github.com/matrixorigin/matrixone@v1.2.0/pkg/sql/compile/ddl.go (about)

     1  // Copyright 2021 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package compile
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"math"
    21  	"strings"
    22  
    23  	"github.com/matrixorigin/matrixone/pkg/catalog"
    24  	"github.com/matrixorigin/matrixone/pkg/common/moerr"
    25  	"github.com/matrixorigin/matrixone/pkg/compress"
    26  	"github.com/matrixorigin/matrixone/pkg/container/batch"
    27  	"github.com/matrixorigin/matrixone/pkg/container/types"
    28  	"github.com/matrixorigin/matrixone/pkg/container/vector"
    29  	"github.com/matrixorigin/matrixone/pkg/defines"
    30  	"github.com/matrixorigin/matrixone/pkg/incrservice"
    31  	"github.com/matrixorigin/matrixone/pkg/pb/api"
    32  	"github.com/matrixorigin/matrixone/pkg/pb/lock"
    33  	"github.com/matrixorigin/matrixone/pkg/pb/plan"
    34  	"github.com/matrixorigin/matrixone/pkg/sql/colexec/lockop"
    35  	"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
    36  	plan2 "github.com/matrixorigin/matrixone/pkg/sql/plan"
    37  	"github.com/matrixorigin/matrixone/pkg/sql/plan/function"
    38  	"github.com/matrixorigin/matrixone/pkg/txn/client"
    39  	"github.com/matrixorigin/matrixone/pkg/util/trace"
    40  	"github.com/matrixorigin/matrixone/pkg/vm/engine"
    41  	"github.com/matrixorigin/matrixone/pkg/vm/process"
    42  	"go.uber.org/zap"
    43  	"golang.org/x/exp/constraints"
    44  )
    45  
    46  func (s *Scope) CreateDatabase(c *Compile) error {
    47  	var span trace.Span
    48  	c.ctx, span = trace.Start(c.ctx, "CreateDatabase")
    49  	defer span.End()
    50  	dbName := s.Plan.GetDdl().GetCreateDatabase().GetDatabase()
    51  	if _, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator); err == nil {
    52  		if s.Plan.GetDdl().GetCreateDatabase().GetIfNotExists() {
    53  			return nil
    54  		}
    55  		return moerr.NewDBAlreadyExists(c.ctx, dbName)
    56  	}
    57  
    58  	if err := lockMoDatabase(c, dbName); err != nil {
    59  		return err
    60  	}
    61  
    62  	ctx := context.WithValue(c.ctx, defines.SqlKey{}, s.Plan.GetDdl().GetCreateDatabase().GetSql())
    63  	datType := ""
    64  	if s.Plan.GetDdl().GetCreateDatabase().SubscriptionOption != nil {
    65  		datType = catalog.SystemDBTypeSubscription
    66  	}
    67  	ctx = context.WithValue(ctx, defines.DatTypKey{}, datType)
    68  	return c.e.Create(ctx, dbName, c.proc.TxnOperator)
    69  }
    70  
    71  func (s *Scope) DropDatabase(c *Compile) error {
    72  	dbName := s.Plan.GetDdl().GetDropDatabase().GetDatabase()
    73  	if _, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator); err != nil {
    74  		if s.Plan.GetDdl().GetDropDatabase().GetIfExists() {
    75  			return nil
    76  		}
    77  		return moerr.NewErrDropNonExistsDB(c.ctx, dbName)
    78  	}
    79  
    80  	if err := lockMoDatabase(c, dbName); err != nil {
    81  		return err
    82  	}
    83  
    84  	sql := s.Plan.GetDdl().GetDropDatabase().GetCheckFKSql()
    85  	if len(sql) != 0 {
    86  		err := runDetectFkReferToDBSql(c, sql)
    87  		if err != nil {
    88  			return err
    89  		}
    90  	}
    91  
    92  	// whether foreign_key_checks = 0 or 1
    93  	err := s.removeFkeysRelationships(c, dbName)
    94  	if err != nil {
    95  		return err
    96  	}
    97  
    98  	err = c.e.Delete(c.ctx, dbName, c.proc.TxnOperator)
    99  	if err != nil {
   100  		return err
   101  	}
   102  
   103  	// 1.delete all index object record under the database from mo_catalog.mo_indexes
   104  	deleteSql := fmt.Sprintf(deleteMoIndexesWithDatabaseIdFormat, s.Plan.GetDdl().GetDropDatabase().GetDatabaseId())
   105  	err = c.runSql(deleteSql)
   106  	if err != nil {
   107  		return err
   108  	}
   109  
   110  	// 2.delete all partition object record under the database from mo_catalog.mo_table_partitions
   111  	deleteSql = fmt.Sprintf(deleteMoTablePartitionsWithDatabaseIdFormat, s.Plan.GetDdl().GetDropDatabase().GetDatabaseId())
   112  	err = c.runSql(deleteSql)
   113  	if err != nil {
   114  		return err
   115  	}
   116  
   117  	//3. delete fks
   118  	err = c.runSql(s.Plan.GetDdl().GetDropDatabase().GetUpdateFkSql())
   119  	if err != nil {
   120  		return err
   121  	}
   122  	return nil
   123  }
   124  
   125  func (s *Scope) removeFkeysRelationships(c *Compile, dbName string) error {
   126  	database, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
   127  	if err != nil {
   128  		return err
   129  	}
   130  
   131  	relations, err := database.Relations(c.ctx)
   132  	if err != nil {
   133  		return err
   134  	}
   135  	for _, rel := range relations {
   136  		relation, err := database.Relation(c.ctx, rel, nil)
   137  		if err != nil {
   138  			return err
   139  		}
   140  		tblId := relation.GetTableID(c.ctx)
   141  		fkeys, refChild, err := s.getFkDefs(c, relation)
   142  		if err != nil {
   143  			return err
   144  		}
   145  		//remove tblId from the parent table
   146  		for _, fkey := range fkeys.Fkeys {
   147  			if fkey.ForeignTbl == 0 {
   148  				continue
   149  			}
   150  
   151  			_, _, parentTable, err := c.e.GetRelationById(c.ctx, c.proc.TxnOperator, fkey.ForeignTbl)
   152  			if err != nil {
   153  				return err
   154  			}
   155  			err = s.removeChildTblIdFromParentTable(c, parentTable, tblId)
   156  			if err != nil {
   157  				return err
   158  			}
   159  		}
   160  		//remove tblId from the child table
   161  		for _, childId := range refChild.Tables {
   162  			if childId == 0 {
   163  				continue
   164  			}
   165  			_, _, childTable, err := c.e.GetRelationById(c.ctx, c.proc.TxnOperator, childId)
   166  			if err != nil {
   167  				return err
   168  			}
   169  			err = s.removeParentTblIdFromChildTable(c, childTable, tblId)
   170  			if err != nil {
   171  				return err
   172  			}
   173  		}
   174  	}
   175  	return nil
   176  }
   177  
   178  // Drop the old view, and create the new view.
   179  func (s *Scope) AlterView(c *Compile) error {
   180  	qry := s.Plan.GetDdl().GetAlterView()
   181  
   182  	dbName := c.db
   183  	tblName := qry.GetTableDef().GetName()
   184  
   185  	dbSource, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
   186  	if err != nil {
   187  		if qry.GetIfExists() {
   188  			return nil
   189  		}
   190  		return err
   191  	}
   192  	if _, err = dbSource.Relation(c.ctx, tblName, nil); err != nil {
   193  		if qry.GetIfExists() {
   194  			return nil
   195  		}
   196  		return err
   197  	}
   198  
   199  	if err := lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); err != nil {
   200  		return err
   201  	}
   202  
   203  	// Drop view table.
   204  	if err := dbSource.Delete(c.ctx, tblName); err != nil {
   205  		return err
   206  	}
   207  
   208  	// Create view table.
   209  	// convert the plan's cols to the execution's cols
   210  	planCols := qry.GetTableDef().GetCols()
   211  	exeCols := planColsToExeCols(planCols)
   212  
   213  	// convert the plan's defs to the execution's defs
   214  	exeDefs, err := planDefsToExeDefs(qry.GetTableDef())
   215  	if err != nil {
   216  		return err
   217  	}
   218  
   219  	// if _, err := dbSource.Relation(c.ctx, tblName); err == nil {
   220  	//  	 return moerr.NewTableAlreadyExists(c.ctx, tblName)
   221  	// }
   222  
   223  	return dbSource.Create(context.WithValue(c.ctx, defines.SqlKey{}, c.sql), tblName, append(exeCols, exeDefs...))
   224  }
   225  
   226  func addAlterKind(alterKind []api.AlterKind, kind api.AlterKind) []api.AlterKind {
   227  	for i := range alterKind {
   228  		if alterKind[i] == kind {
   229  			return alterKind
   230  		}
   231  	}
   232  	alterKind = append(alterKind, kind)
   233  	return alterKind
   234  }
   235  
   236  func getAddColPos(cols []*plan.ColDef, def *plan.ColDef, colName string, pos int32) ([]*plan.ColDef, int32, error) {
   237  	if pos == 0 {
   238  		cols = append([]*plan.ColDef{def}, cols...)
   239  		return cols, pos, nil
   240  	} else if pos == -1 {
   241  		length := len(cols)
   242  		cols = append(cols, nil)
   243  		copy(cols[length:], cols[length-1:])
   244  		cols[length-1] = def
   245  		return cols, int32(length - 1), nil
   246  	}
   247  	var idx int
   248  	for idx = 0; idx < len(cols); idx++ {
   249  		if cols[idx].Name == colName {
   250  			cols = append(cols, nil)
   251  			copy(cols[idx+2:], cols[idx+1:])
   252  			cols[idx+1] = def
   253  			return cols, int32(idx + 1), nil
   254  		}
   255  	}
   256  	return nil, 0, moerr.NewInvalidInputNoCtx("column '%s' doesn't exist in table", colName)
   257  }
   258  
   259  func (s *Scope) AlterTableInplace(c *Compile) error {
   260  	qry := s.Plan.GetDdl().GetAlterTable()
   261  	dbName := qry.Database
   262  	if dbName == "" {
   263  		dbName = c.db
   264  	}
   265  
   266  	tblName := qry.GetTableDef().GetName()
   267  
   268  	dbSource, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
   269  	if err != nil {
   270  		return err
   271  	}
   272  	databaseId := dbSource.GetDatabaseId(c.ctx)
   273  
   274  	rel, err := dbSource.Relation(c.ctx, tblName, nil)
   275  	if err != nil {
   276  		return err
   277  	}
   278  	tblId := rel.GetTableID(c.ctx)
   279  
   280  	tableDef := plan2.DeepCopyTableDef(qry.TableDef, true)
   281  	oldCt, err := GetConstraintDef(c.ctx, rel)
   282  	if err != nil {
   283  		return err
   284  	}
   285  
   286  	if c.proc.TxnOperator.Txn().IsPessimistic() {
   287  		var retryErr error
   288  		// 1. lock origin table metadata in catalog
   289  		if err = lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); err != nil {
   290  			if !moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetry) &&
   291  				!moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetryWithDefChanged) {
   292  				return err
   293  			}
   294  			retryErr = err
   295  		}
   296  
   297  		// 2. lock origin table
   298  		var partitionTableNames []string
   299  		if tableDef.Partition != nil {
   300  			partitionTableNames = tableDef.Partition.PartitionTableNames
   301  		}
   302  		if err = lockTable(c.ctx, c.e, c.proc, rel, dbName, partitionTableNames, true); err != nil {
   303  			if !moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetry) &&
   304  				!moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetryWithDefChanged) {
   305  				return err
   306  			}
   307  			retryErr = err
   308  		}
   309  		if retryErr != nil {
   310  			return retryErr
   311  		}
   312  	}
   313  	newCt := &engine.ConstraintDef{
   314  		Cts: []engine.Constraint{},
   315  	}
   316  
   317  	//added fk in this alter table statement
   318  	newAddedFkNames := make(map[string]bool)
   319  	/*
   320  		collect old fk names.
   321  		ForeignKeyDef.Name may be empty in previous design.
   322  		So, we only use ForeignKeyDef.Name that is no empty.
   323  	*/
   324  	oldFkNames := make(map[string]bool)
   325  	for _, ct := range oldCt.Cts {
   326  		switch t := ct.(type) {
   327  		case *engine.ForeignKeyDef:
   328  			for _, fkey := range t.Fkeys {
   329  				if len(fkey.Name) != 0 {
   330  					oldFkNames[fkey.Name] = true
   331  				}
   332  			}
   333  		}
   334  	}
   335  
   336  	removeRefChildTbls := make(map[string]uint64)
   337  	var addRefChildTbls []uint64
   338  	var newFkeys []*plan.ForeignKeyDef
   339  
   340  	var addIndex []*plan.IndexDef
   341  	var dropIndexMap = make(map[string]bool)
   342  	var alterIndex *plan.IndexDef
   343  
   344  	var alterKinds []api.AlterKind
   345  	var comment string
   346  	var oldName, newName string
   347  	var addCol []*plan.AlterAddColumn
   348  	var dropCol []*plan.AlterDropColumn
   349  	var changePartitionDef *plan.PartitionByDef
   350  
   351  	cols := tableDef.Cols
   352  	// drop foreign key
   353  	for _, action := range qry.Actions {
   354  		switch act := action.Action.(type) {
   355  		case *plan.AlterTable_Action_Drop:
   356  			alterTableDrop := act.Drop
   357  			constraintName := alterTableDrop.Name
   358  			if alterTableDrop.Typ == plan.AlterTableDrop_FOREIGN_KEY {
   359  				//check fk existed in table
   360  				if _, has := oldFkNames[constraintName]; !has {
   361  					return moerr.NewErrCantDropFieldOrKey(c.ctx, constraintName)
   362  				}
   363  				alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
   364  				for i, fk := range tableDef.Fkeys {
   365  					if fk.Name == constraintName {
   366  						removeRefChildTbls[constraintName] = fk.ForeignTbl
   367  						tableDef.Fkeys = append(tableDef.Fkeys[:i], tableDef.Fkeys[i+1:]...)
   368  						break
   369  					}
   370  				}
   371  			} else if alterTableDrop.Typ == plan.AlterTableDrop_INDEX {
   372  				alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
   373  				var notDroppedIndex []*plan.IndexDef
   374  				for _, indexdef := range tableDef.Indexes {
   375  					if indexdef.IndexName == constraintName {
   376  						dropIndexMap[indexdef.IndexName] = true
   377  
   378  						//1. drop index table
   379  						if indexdef.TableExist {
   380  							if _, err = dbSource.Relation(c.ctx, indexdef.IndexTableName, nil); err != nil {
   381  								return err
   382  							}
   383  							if err = dbSource.Delete(c.ctx, indexdef.IndexTableName); err != nil {
   384  								return err
   385  							}
   386  						}
   387  						//2. delete index object from mo_catalog.mo_indexes
   388  						deleteSql := fmt.Sprintf(deleteMoIndexesWithTableIdAndIndexNameFormat, tableDef.TblId, indexdef.IndexName)
   389  						err = c.runSql(deleteSql)
   390  						if err != nil {
   391  							return err
   392  						}
   393  					} else {
   394  						notDroppedIndex = append(notDroppedIndex, indexdef)
   395  					}
   396  				}
   397  				// Avoid modifying slice directly during iteration
   398  				tableDef.Indexes = notDroppedIndex
   399  			} else if alterTableDrop.Typ == plan.AlterTableDrop_COLUMN {
   400  				alterKinds = append(alterKinds, api.AlterKind_DropColumn)
   401  				var idx int
   402  				for idx = 0; idx < len(cols); idx++ {
   403  					if cols[idx].Name == constraintName {
   404  						drop := &plan.AlterDropColumn{
   405  							Idx: uint32(idx),
   406  							Seq: cols[idx].Seqnum,
   407  						}
   408  						dropCol = append(dropCol, drop)
   409  						copy(cols[idx:], cols[idx+1:])
   410  						cols = cols[0 : len(cols)-1]
   411  						break
   412  					}
   413  				}
   414  			}
   415  		case *plan.AlterTable_Action_AddFk:
   416  			//check fk existed in table
   417  			if _, has := oldFkNames[act.AddFk.Fkey.Name]; has {
   418  				return moerr.NewErrDuplicateKeyName(c.ctx, act.AddFk.Fkey.Name)
   419  			}
   420  			//check fk existed in this alter table statement
   421  			if _, has := newAddedFkNames[act.AddFk.Fkey.Name]; has {
   422  				return moerr.NewErrDuplicateKeyName(c.ctx, act.AddFk.Fkey.Name)
   423  			}
   424  			newAddedFkNames[act.AddFk.Fkey.Name] = true
   425  			alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
   426  			addRefChildTbls = append(addRefChildTbls, act.AddFk.Fkey.ForeignTbl)
   427  			newFkeys = append(newFkeys, act.AddFk.Fkey)
   428  		case *plan.AlterTable_Action_AddIndex:
   429  			alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
   430  
   431  			indexInfo := act.AddIndex.IndexInfo // IndexInfo is named same as planner's IndexInfo
   432  			indexTableDef := act.AddIndex.IndexInfo.TableDef
   433  
   434  			// indexName -> meta      -> indexDef
   435  			//     		 -> centroids -> indexDef
   436  			//     		 -> entries   -> indexDef
   437  			multiTableIndexes := make(map[string]*MultiTableIndex)
   438  			for _, indexDef := range indexTableDef.Indexes {
   439  
   440  				for i := range addIndex {
   441  					if indexDef.IndexName == addIndex[i].IndexName {
   442  						return moerr.NewDuplicateKey(c.ctx, indexDef.IndexName)
   443  					}
   444  				}
   445  				addIndex = append(addIndex, indexDef)
   446  
   447  				if indexDef.Unique {
   448  					// 1. Unique Index related logic
   449  					err = s.handleUniqueIndexTable(c, indexDef, qry.Database, tableDef, indexInfo)
   450  				} else if !indexDef.Unique && catalog.IsRegularIndexAlgo(indexDef.IndexAlgo) {
   451  					// 2. Regular Secondary index
   452  					err = s.handleRegularSecondaryIndexTable(c, indexDef, qry.Database, tableDef, indexInfo)
   453  				} else if !indexDef.Unique && catalog.IsMasterIndexAlgo(indexDef.IndexAlgo) {
   454  					// 3. Master index
   455  					err = s.handleMasterIndexTable(c, indexDef, qry.Database, tableDef, indexInfo)
   456  				} else if !indexDef.Unique && catalog.IsIvfIndexAlgo(indexDef.IndexAlgo) {
   457  					// 4. IVF indexDefs are aggregated and handled later
   458  					if _, ok := multiTableIndexes[indexDef.IndexName]; !ok {
   459  						multiTableIndexes[indexDef.IndexName] = &MultiTableIndex{
   460  							IndexAlgo: catalog.ToLower(indexDef.IndexAlgo),
   461  							IndexDefs: make(map[string]*plan.IndexDef),
   462  						}
   463  					}
   464  					multiTableIndexes[indexDef.IndexName].IndexDefs[catalog.ToLower(indexDef.IndexAlgoTableType)] = indexDef
   465  
   466  				}
   467  				if err != nil {
   468  					return err
   469  				}
   470  			}
   471  			for _, multiTableIndex := range multiTableIndexes {
   472  				switch multiTableIndex.IndexAlgo { // no need for catalog.ToLower() here
   473  				case catalog.MoIndexIvfFlatAlgo.ToString():
   474  					err = s.handleVectorIvfFlatIndex(c, multiTableIndex.IndexDefs, qry.Database, tableDef, indexInfo)
   475  				}
   476  
   477  				if err != nil {
   478  					return err
   479  				}
   480  			}
   481  
   482  			//1. build and update constraint def
   483  			for _, indexDef := range indexTableDef.Indexes {
   484  				insertSql, err := makeInsertSingleIndexSQL(c.e, c.proc, databaseId, tblId, indexDef)
   485  				if err != nil {
   486  					return err
   487  				}
   488  				err = c.runSql(insertSql)
   489  				if err != nil {
   490  					return err
   491  				}
   492  			}
   493  		case *plan.AlterTable_Action_AlterIndex:
   494  			alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
   495  			tableAlterIndex := act.AlterIndex
   496  			constraintName := tableAlterIndex.IndexName
   497  			for i, indexdef := range tableDef.Indexes {
   498  				if indexdef.IndexName == constraintName {
   499  					alterIndex = indexdef
   500  					alterIndex.Visible = tableAlterIndex.Visible
   501  					tableDef.Indexes[i].Visible = tableAlterIndex.Visible
   502  					// update the index visibility in mo_catalog.mo_indexes
   503  					var updateSql string
   504  					if alterIndex.Visible {
   505  						updateSql = fmt.Sprintf(updateMoIndexesVisibleFormat, 1, tableDef.TblId, indexdef.IndexName)
   506  					} else {
   507  						updateSql = fmt.Sprintf(updateMoIndexesVisibleFormat, 0, tableDef.TblId, indexdef.IndexName)
   508  					}
   509  					err = c.runSql(updateSql)
   510  					if err != nil {
   511  						return err
   512  					}
   513  
   514  					break
   515  				}
   516  			}
   517  		case *plan.AlterTable_Action_AlterReindex:
   518  			// NOTE: We hold lock (with retry) during alter reindex, as "alter table" takes an exclusive lock
   519  			//in the beginning for pessimistic mode. We need to see how to reduce the critical section.
   520  			alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
   521  			tableAlterIndex := act.AlterReindex
   522  			constraintName := tableAlterIndex.IndexName
   523  			multiTableIndexes := make(map[string]*MultiTableIndex)
   524  
   525  			for i, indexDef := range tableDef.Indexes {
   526  				if indexDef.IndexName == constraintName {
   527  					alterIndex = indexDef
   528  
   529  					// 1. Get old AlgoParams
   530  					newAlgoParamsMap, err := catalog.IndexParamsStringToMap(alterIndex.IndexAlgoParams)
   531  					if err != nil {
   532  						return err
   533  					}
   534  
   535  					// 2.a update AlgoParams for the index to be re-indexed
   536  					// NOTE: this will throw error if the algo type is not supported for reindex.
   537  					// So Step 4. will not be executed if error is thrown here.
   538  					indexAlgo := catalog.ToLower(alterIndex.IndexAlgo)
   539  					switch catalog.ToLower(indexAlgo) {
   540  					case catalog.MoIndexIvfFlatAlgo.ToString():
   541  						newAlgoParamsMap[catalog.IndexAlgoParamLists] = fmt.Sprintf("%d", tableAlterIndex.IndexAlgoParamList)
   542  					default:
   543  						return moerr.NewInternalError(c.ctx, "invalid index algo type for alter reindex")
   544  					}
   545  
   546  					// 2.b generate new AlgoParams string
   547  					newAlgoParams, err := catalog.IndexParamsMapToJsonString(newAlgoParamsMap)
   548  					if err != nil {
   549  						return err
   550  					}
   551  
   552  					// 3.a Update IndexDef and TableDef
   553  					alterIndex.IndexAlgoParams = newAlgoParams
   554  					tableDef.Indexes[i].IndexAlgoParams = newAlgoParams
   555  
   556  					// 3.b Update mo_catalog.mo_indexes
   557  					updateSql := fmt.Sprintf(updateMoIndexesAlgoParams, newAlgoParams, tableDef.TblId, alterIndex.IndexName)
   558  					err = c.runSql(updateSql)
   559  					if err != nil {
   560  						return err
   561  					}
   562  
   563  					// 4. Add to multiTableIndexes
   564  					if _, ok := multiTableIndexes[indexDef.IndexName]; !ok {
   565  						multiTableIndexes[indexDef.IndexName] = &MultiTableIndex{
   566  							IndexAlgo: catalog.ToLower(indexDef.IndexAlgo),
   567  							IndexDefs: make(map[string]*plan.IndexDef),
   568  						}
   569  					}
   570  					multiTableIndexes[indexDef.IndexName].IndexDefs[catalog.ToLower(indexDef.IndexAlgoTableType)] = indexDef
   571  				}
   572  			}
   573  
   574  			if len(multiTableIndexes) != 1 {
   575  				return moerr.NewInternalError(c.ctx, "invalid index algo type for alter reindex")
   576  			}
   577  
   578  			// update the hidden tables
   579  			for _, multiTableIndex := range multiTableIndexes {
   580  				switch multiTableIndex.IndexAlgo {
   581  				case catalog.MoIndexIvfFlatAlgo.ToString():
   582  					err = s.handleVectorIvfFlatIndex(c, multiTableIndex.IndexDefs, qry.Database, tableDef, nil)
   583  				}
   584  
   585  				if err != nil {
   586  					return err
   587  				}
   588  			}
   589  		case *plan.AlterTable_Action_AlterComment:
   590  			alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateComment)
   591  			comment = act.AlterComment.NewComment
   592  		case *plan.AlterTable_Action_AlterName:
   593  			alterKinds = addAlterKind(alterKinds, api.AlterKind_RenameTable)
   594  			oldName = act.AlterName.OldName
   595  			newName = act.AlterName.NewName
   596  		case *plan.AlterTable_Action_AddColumn:
   597  			alterKinds = append(alterKinds, api.AlterKind_AddColumn)
   598  			col := &plan.ColDef{
   599  				Name: act.AddColumn.Name,
   600  				Alg:  plan.CompressType_Lz4,
   601  				Typ:  act.AddColumn.Type,
   602  			}
   603  			var pos int32
   604  			cols, pos, err = getAddColPos(cols, col, act.AddColumn.PreName, act.AddColumn.Pos)
   605  			if err != nil {
   606  				return err
   607  			}
   608  			act.AddColumn.Pos = pos
   609  			addCol = append(addCol, act.AddColumn)
   610  		case *plan.AlterTable_Action_AddPartition:
   611  			alterKinds = append(alterKinds, api.AlterKind_AddPartition)
   612  			changePartitionDef = act.AddPartition.PartitionDef
   613  			partitionTables := act.AddPartition.GetPartitionTables()
   614  			for _, table := range partitionTables {
   615  				storageCols := planColsToExeCols(table.GetCols())
   616  				storageDefs, err := planDefsToExeDefs(table)
   617  				if err != nil {
   618  					return err
   619  				}
   620  				err = dbSource.Create(c.ctx, table.GetName(), append(storageCols, storageDefs...))
   621  				if err != nil {
   622  					return err
   623  				}
   624  			}
   625  
   626  			insertMoTablePartitionSql := genInsertMoTablePartitionsSql(databaseId, tblId, act.AddPartition.PartitionDef, act.AddPartition.Definitions)
   627  			err = c.runSql(insertMoTablePartitionSql)
   628  			if err != nil {
   629  				return err
   630  			}
   631  		}
   632  	}
   633  
   634  	// reset origin table's constraint
   635  	originHasFkDef := false
   636  	originHasIndexDef := false
   637  	for _, ct := range oldCt.Cts {
   638  		switch t := ct.(type) {
   639  		case *engine.ForeignKeyDef:
   640  			for _, fkey := range t.Fkeys {
   641  				//For compatibility, regenerate constraint name for the constraint with empty name.
   642  				if len(fkey.Name) == 0 {
   643  					fkey.Name = plan2.GenConstraintName()
   644  					newFkeys = append(newFkeys, fkey)
   645  				} else if _, ok := removeRefChildTbls[fkey.Name]; !ok {
   646  					newFkeys = append(newFkeys, fkey)
   647  				}
   648  			}
   649  			t.Fkeys = newFkeys
   650  			originHasFkDef = true
   651  			newCt.Cts = append(newCt.Cts, t)
   652  		case *engine.RefChildTableDef:
   653  			newCt.Cts = append(newCt.Cts, t)
   654  		case *engine.IndexDef:
   655  			originHasIndexDef = true
   656  			// NOTE: using map and remainingIndexes slice here to avoid "Modifying a Slice During Iteration".
   657  			var remainingIndexes []*plan.IndexDef
   658  			for _, idx := range t.Indexes {
   659  				if !dropIndexMap[idx.IndexName] {
   660  					remainingIndexes = append(remainingIndexes, idx)
   661  				}
   662  			}
   663  			t.Indexes = remainingIndexes
   664  
   665  			t.Indexes = append(t.Indexes, addIndex...)
   666  			if alterIndex != nil {
   667  				for i, idx := range t.Indexes {
   668  					if alterIndex.IndexName == idx.IndexName {
   669  						t.Indexes[i].Visible = alterIndex.Visible
   670  						// NOTE: algo param is same for all the indexDefs of the same indexName.
   671  						// ie for IVFFLAT: meta, centroids, entries all have same algo params.
   672  						// so we don't need multiple `alterIndex`.
   673  						t.Indexes[i].IndexAlgoParams = alterIndex.IndexAlgoParams
   674  					}
   675  				}
   676  			}
   677  			newCt.Cts = append(newCt.Cts, t)
   678  		case *engine.PrimaryKeyDef:
   679  			newCt.Cts = append(newCt.Cts, t)
   680  		}
   681  	}
   682  	if !originHasFkDef {
   683  		newCt.Cts = append(newCt.Cts, &engine.ForeignKeyDef{
   684  			Fkeys: newFkeys,
   685  		})
   686  	}
   687  	if !originHasIndexDef && addIndex != nil {
   688  		newCt.Cts = append(newCt.Cts, &engine.IndexDef{
   689  			Indexes: addIndex,
   690  		})
   691  	}
   692  
   693  	var addColIdx int
   694  	var dropColIdx int
   695  	constraint := make([][]byte, 0)
   696  	for _, kind := range alterKinds {
   697  		var req *api.AlterTableReq
   698  		switch kind {
   699  		case api.AlterKind_UpdateConstraint:
   700  			ct, err := newCt.MarshalBinary()
   701  			if err != nil {
   702  				return err
   703  			}
   704  			req = api.NewUpdateConstraintReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), string(ct))
   705  		case api.AlterKind_UpdateComment:
   706  			req = api.NewUpdateCommentReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), comment)
   707  		case api.AlterKind_RenameTable:
   708  			req = api.NewRenameTableReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), oldName, newName)
   709  		case api.AlterKind_AddColumn:
   710  			name := addCol[addColIdx].Name
   711  			typ := &addCol[addColIdx].Type
   712  			pos := addCol[addColIdx].Pos
   713  			addColIdx++
   714  			req = api.NewAddColumnReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), name, typ, pos)
   715  		case api.AlterKind_DropColumn:
   716  			req = api.NewRemoveColumnReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), dropCol[dropColIdx].Idx, dropCol[dropColIdx].Seq)
   717  			dropColIdx++
   718  		case api.AlterKind_AddPartition:
   719  			req = api.NewAddPartitionReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), changePartitionDef)
   720  		default:
   721  		}
   722  		tmp, err := req.Marshal()
   723  		if err != nil {
   724  			return err
   725  		}
   726  		constraint = append(constraint, tmp)
   727  	}
   728  
   729  	err = rel.AlterTable(c.ctx, newCt, constraint)
   730  	if err != nil {
   731  		return err
   732  	}
   733  
   734  	// remove refChildTbls for drop foreign key clause
   735  	//remove the child table id -- tblId from the parent table -- fkTblId
   736  	for _, fkTblId := range removeRefChildTbls {
   737  		var fkRelation engine.Relation
   738  		if fkTblId == 0 {
   739  			//fk self refer
   740  			fkRelation = rel
   741  		} else {
   742  			_, _, fkRelation, err = c.e.GetRelationById(c.ctx, c.proc.TxnOperator, fkTblId)
   743  			if err != nil {
   744  				return err
   745  			}
   746  		}
   747  
   748  		err = s.removeChildTblIdFromParentTable(c, fkRelation, tblId)
   749  		if err != nil {
   750  			return err
   751  		}
   752  	}
   753  
   754  	// append refChildTbls for add foreign key clause
   755  	//add the child table id -- tblId into the parent table -- fkTblId
   756  	for _, fkTblId := range addRefChildTbls {
   757  		if fkTblId == 0 {
   758  			//fk self refer
   759  			err = AddChildTblIdToParentTable(c.ctx, rel, fkTblId)
   760  			if err != nil {
   761  				return err
   762  			}
   763  		} else {
   764  			_, _, fkRelation, err := c.e.GetRelationById(c.ctx, c.proc.TxnOperator, fkTblId)
   765  			if err != nil {
   766  				return err
   767  			}
   768  			err = AddChildTblIdToParentTable(c.ctx, fkRelation, tblId)
   769  			if err != nil {
   770  				return err
   771  			}
   772  		}
   773  	}
   774  	return nil
   775  }
   776  
   777  func (s *Scope) CreateTable(c *Compile) error {
   778  	qry := s.Plan.GetDdl().GetCreateTable()
   779  	// convert the plan's cols to the execution's cols
   780  	planCols := qry.GetTableDef().GetCols()
   781  	exeCols := planColsToExeCols(planCols)
   782  	// TODO: debug for #11917
   783  	if strings.Contains(qry.GetTableDef().GetName(), "sbtest") {
   784  		getLogger().Info("createTable",
   785  			zap.String("databaseName", c.db),
   786  			zap.String("tableName", qry.GetTableDef().GetName()),
   787  			zap.String("txnID", c.proc.TxnOperator.Txn().DebugString()),
   788  		)
   789  	}
   790  
   791  	// convert the plan's defs to the execution's defs
   792  	exeDefs, err := planDefsToExeDefs(qry.GetTableDef())
   793  	if err != nil {
   794  		getLogger().Info("createTable",
   795  			zap.String("databaseName", c.db),
   796  			zap.String("tableName", qry.GetTableDef().GetName()),
   797  			zap.Error(err),
   798  		)
   799  		return err
   800  	}
   801  
   802  	dbName := c.db
   803  	if qry.GetDatabase() != "" {
   804  		dbName = qry.GetDatabase()
   805  	}
   806  	tblName := qry.GetTableDef().GetName()
   807  
   808  	dbSource, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
   809  	if err != nil {
   810  		if dbName == "" {
   811  			// TODO: debug for #11917
   812  			if strings.Contains(qry.GetTableDef().GetName(), "sbtest") {
   813  				getLogger().Info("createTable",
   814  					zap.String("databaseName", c.db),
   815  					zap.String("tableName", qry.GetTableDef().GetName()),
   816  					zap.String("txnID", c.proc.TxnOperator.Txn().DebugString()),
   817  				)
   818  			}
   819  			return moerr.NewNoDB(c.ctx)
   820  		}
   821  		// TODO: debug for #11917
   822  		if strings.Contains(qry.GetTableDef().GetName(), "sbtest") {
   823  			getLogger().Info("createTable no exist",
   824  				zap.String("databaseName", c.db),
   825  				zap.String("tableName", qry.GetTableDef().GetName()),
   826  				zap.String("txnID", c.proc.TxnOperator.Txn().DebugString()),
   827  			)
   828  		}
   829  		return err
   830  	}
   831  	if _, err := dbSource.Relation(c.ctx, tblName, nil); err == nil {
   832  		if qry.GetIfNotExists() {
   833  			// TODO: debug for #11917
   834  			if strings.Contains(qry.GetTableDef().GetName(), "sbtest") {
   835  				getLogger().Info("createTable no exist",
   836  					zap.String("databaseName", c.db),
   837  					zap.String("tableName", qry.GetTableDef().GetName()),
   838  					zap.String("txnID", c.proc.TxnOperator.Txn().DebugString()),
   839  				)
   840  			}
   841  			return nil
   842  		}
   843  		if qry.GetReplace() {
   844  			err := c.runSql(fmt.Sprintf("drop view if exists %s", tblName))
   845  			if err != nil {
   846  				getLogger().Info("createTable",
   847  					zap.String("databaseName", c.db),
   848  					zap.String("tableName", qry.GetTableDef().GetName()),
   849  					zap.Error(err),
   850  				)
   851  				return err
   852  			}
   853  		} else {
   854  			getLogger().Info("createTable",
   855  				zap.String("databaseName", c.db),
   856  				zap.String("tableName", qry.GetTableDef().GetName()),
   857  				zap.Error(err),
   858  			)
   859  			return moerr.NewTableAlreadyExists(c.ctx, tblName)
   860  		}
   861  	}
   862  
   863  	// check in EntireEngine.TempEngine, notice that TempEngine may not init
   864  	tmpDBSource, err := c.e.Database(c.ctx, defines.TEMPORARY_DBNAME, c.proc.TxnOperator)
   865  	if err == nil {
   866  		if _, err := tmpDBSource.Relation(c.ctx, engine.GetTempTableName(dbName, tblName), nil); err == nil {
   867  			if qry.GetIfNotExists() {
   868  				return nil
   869  			}
   870  			getLogger().Info("createTable",
   871  				zap.String("databaseName", c.db),
   872  				zap.String("tableName", qry.GetTableDef().GetName()),
   873  				zap.Error(err),
   874  			)
   875  			return moerr.NewTableAlreadyExists(c.ctx, fmt.Sprintf("temporary '%s'", tblName))
   876  		}
   877  	}
   878  
   879  	if err := lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); err != nil {
   880  		getLogger().Info("createTable",
   881  			zap.String("databaseName", c.db),
   882  			zap.String("tableName", qry.GetTableDef().GetName()),
   883  			zap.Error(err),
   884  		)
   885  		return err
   886  	}
   887  
   888  	if err := dbSource.Create(context.WithValue(c.ctx, defines.SqlKey{}, c.sql), tblName, append(exeCols, exeDefs...)); err != nil {
   889  		getLogger().Info("createTable",
   890  			zap.String("databaseName", c.db),
   891  			zap.String("tableName", qry.GetTableDef().GetName()),
   892  			zap.Error(err),
   893  		)
   894  		return err
   895  	}
   896  	// TODO: debug for #11917
   897  	if strings.Contains(qry.GetTableDef().GetName(), "sbtest") {
   898  		getLogger().Info("createTable ok",
   899  			zap.String("databaseName", c.db),
   900  			zap.String("tableName", qry.GetTableDef().GetName()),
   901  			zap.String("txnID", c.proc.TxnOperator.Txn().DebugString()),
   902  		)
   903  	}
   904  
   905  	partitionTables := qry.GetPartitionTables()
   906  	for _, table := range partitionTables {
   907  		storageCols := planColsToExeCols(table.GetCols())
   908  		storageDefs, err := planDefsToExeDefs(table)
   909  		if err != nil {
   910  			getLogger().Info("createTable",
   911  				zap.String("databaseName", c.db),
   912  				zap.String("tableName", qry.GetTableDef().GetName()),
   913  				zap.Error(err),
   914  			)
   915  			return err
   916  		}
   917  		err = dbSource.Create(c.ctx, table.GetName(), append(storageCols, storageDefs...))
   918  		if err != nil {
   919  			getLogger().Info("createTable",
   920  				zap.String("databaseName", c.db),
   921  				zap.String("tableName", qry.GetTableDef().GetName()),
   922  				zap.Error(err),
   923  			)
   924  			return err
   925  		}
   926  	}
   927  
   928  	//update mo_foreign_keys
   929  	for _, sql := range qry.UpdateFkSqls {
   930  		err = c.runSql(sql)
   931  		if err != nil {
   932  			return err
   933  		}
   934  	}
   935  
   936  	// handle fk that refers to others tables
   937  	fkDbs := qry.GetFkDbs()
   938  	if len(fkDbs) > 0 {
   939  		fkTables := qry.GetFkTables()
   940  		//get the relation of created table above again.
   941  		//due to the colId may be changed.
   942  		newRelation, err := dbSource.Relation(c.ctx, tblName, nil)
   943  		if err != nil {
   944  			getLogger().Info("createTable",
   945  				zap.String("databaseName", c.db),
   946  				zap.String("tableName", qry.GetTableDef().GetName()),
   947  				zap.Error(err),
   948  			)
   949  			return err
   950  		}
   951  		tblId := newRelation.GetTableID(c.ctx)
   952  
   953  		newTableDef, err := newRelation.TableDefs(c.ctx)
   954  		if err != nil {
   955  			getLogger().Info("createTable",
   956  				zap.String("databaseName", c.db),
   957  				zap.String("tableName", qry.GetTableDef().GetName()),
   958  				zap.Error(err),
   959  			)
   960  			return err
   961  		}
   962  
   963  		oldCt := GetConstraintDefFromTableDefs(newTableDef)
   964  		//get the columnId of the column from newTableDef
   965  		var colNameToId = make(map[string]uint64)
   966  		for _, def := range newTableDef {
   967  			if attr, ok := def.(*engine.AttributeDef); ok {
   968  				colNameToId[attr.Attr.Name] = attr.Attr.ID
   969  			}
   970  		}
   971  		//old colId -> colName
   972  		colId2Name := make(map[uint64]string)
   973  		for _, col := range planCols {
   974  			colId2Name[col.ColId] = col.Name
   975  		}
   976  		//1. update fk info in child table.
   977  		//column ids of column names in child table have changed after
   978  		//the table is created by engine.Database.Create.
   979  		//refresh column ids of column names in child table.
   980  		newFkeys := make([]*plan.ForeignKeyDef, len(qry.GetTableDef().Fkeys))
   981  		for i, fkey := range qry.GetTableDef().Fkeys {
   982  			newDef := &plan.ForeignKeyDef{
   983  				Name:        fkey.Name,
   984  				Cols:        make([]uint64, len(fkey.Cols)),
   985  				ForeignTbl:  fkey.ForeignTbl,
   986  				ForeignCols: make([]uint64, len(fkey.ForeignCols)),
   987  				OnDelete:    fkey.OnDelete,
   988  				OnUpdate:    fkey.OnUpdate,
   989  			}
   990  			copy(newDef.ForeignCols, fkey.ForeignCols)
   991  
   992  			//if it is fk self, the parent table is same as the child table.
   993  			//refresh the ForeignCols also.
   994  			if fkey.ForeignTbl == 0 {
   995  				for j, colId := range fkey.ForeignCols {
   996  					//old colId -> colName
   997  					colName := colId2Name[colId]
   998  					//colName -> new colId
   999  					newDef.ForeignCols[j] = colNameToId[colName]
  1000  				}
  1001  			} else {
  1002  				copy(newDef.ForeignCols, fkey.ForeignCols)
  1003  			}
  1004  
  1005  			//refresh child table column id
  1006  			for idx, colName := range qry.GetFkCols()[i].Cols {
  1007  				newDef.Cols[idx] = colNameToId[colName]
  1008  			}
  1009  			newFkeys[i] = newDef
  1010  		}
  1011  		// remove old fk settings
  1012  		newCt, err := MakeNewCreateConstraint(oldCt, &engine.ForeignKeyDef{
  1013  			Fkeys: newFkeys,
  1014  		})
  1015  		if err != nil {
  1016  			getLogger().Info("createTable",
  1017  				zap.String("databaseName", c.db),
  1018  				zap.String("tableName", qry.GetTableDef().GetName()),
  1019  				zap.Error(err),
  1020  			)
  1021  			return err
  1022  		}
  1023  		err = newRelation.UpdateConstraint(c.ctx, newCt)
  1024  		if err != nil {
  1025  			getLogger().Info("createTable",
  1026  				zap.String("databaseName", c.db),
  1027  				zap.String("tableName", qry.GetTableDef().GetName()),
  1028  				zap.Error(err),
  1029  			)
  1030  			return err
  1031  		}
  1032  
  1033  		//2. need to append TableId to parent's TableDef.RefChildTbls
  1034  		for i, fkTableName := range fkTables {
  1035  			fkDbName := fkDbs[i]
  1036  			fkey := qry.GetTableDef().Fkeys[i]
  1037  			if fkey.ForeignTbl == 0 {
  1038  				//fk self refer
  1039  				//add current table to parent's children table
  1040  				err = AddChildTblIdToParentTable(c.ctx, newRelation, 0)
  1041  				if err != nil {
  1042  					getLogger().Info("createTable",
  1043  						zap.String("databaseName", c.db),
  1044  						zap.String("tableName", qry.GetTableDef().GetName()),
  1045  						zap.Error(err),
  1046  					)
  1047  					return err
  1048  				}
  1049  				continue
  1050  			}
  1051  			fkDbSource, err := c.e.Database(c.ctx, fkDbName, c.proc.TxnOperator)
  1052  			if err != nil {
  1053  				getLogger().Info("createTable",
  1054  					zap.String("databaseName", c.db),
  1055  					zap.String("tableName", qry.GetTableDef().GetName()),
  1056  					zap.Error(err),
  1057  				)
  1058  				return err
  1059  			}
  1060  			fkRelation, err := fkDbSource.Relation(c.ctx, fkTableName, nil)
  1061  			if err != nil {
  1062  				getLogger().Info("createTable",
  1063  					zap.String("databaseName", c.db),
  1064  					zap.String("tableName", qry.GetTableDef().GetName()),
  1065  					zap.Error(err),
  1066  				)
  1067  				return err
  1068  			}
  1069  			//add current table to parent's children table
  1070  			err = AddChildTblIdToParentTable(c.ctx, fkRelation, tblId)
  1071  			if err != nil {
  1072  				getLogger().Info("createTable",
  1073  					zap.String("databaseName", c.db),
  1074  					zap.String("tableName", qry.GetTableDef().GetName()),
  1075  					zap.Error(err),
  1076  				)
  1077  				return err
  1078  			}
  1079  		}
  1080  	}
  1081  
  1082  	// handle fk forward reference
  1083  	fkRefersToMe := qry.GetFksReferToMe()
  1084  	if len(fkRefersToMe) > 0 {
  1085  		//1. get the relation of created table above again.
  1086  		//get the relation of created table above again.
  1087  		//due to the colId may be changed.
  1088  		newRelation, err := dbSource.Relation(c.ctx, tblName, nil)
  1089  		if err != nil {
  1090  			getLogger().Info("createTable",
  1091  				zap.String("databaseName", c.db),
  1092  				zap.String("tableName", qry.GetTableDef().GetName()),
  1093  				zap.Error(err),
  1094  			)
  1095  			return err
  1096  		}
  1097  		tblId := newRelation.GetTableID(c.ctx)
  1098  
  1099  		newTableDef, err := newRelation.TableDefs(c.ctx)
  1100  		if err != nil {
  1101  			getLogger().Info("createTable",
  1102  				zap.String("databaseName", c.db),
  1103  				zap.String("tableName", qry.GetTableDef().GetName()),
  1104  				zap.Error(err),
  1105  			)
  1106  			return err
  1107  		}
  1108  		//get the columnId of the column from newTableDef
  1109  		var colNameToId = make(map[string]uint64)
  1110  		for _, def := range newTableDef {
  1111  			if attr, ok := def.(*engine.AttributeDef); ok {
  1112  				colNameToId[attr.Attr.Name] = attr.Attr.ID
  1113  			}
  1114  		}
  1115  		//1.1 update the column id of the column names in this table.
  1116  		//2. update fk info in the child table.
  1117  		for _, info := range fkRefersToMe {
  1118  			//update foreignCols in fk
  1119  			newDef := &plan.ForeignKeyDef{
  1120  				Name:        info.Def.Name,
  1121  				Cols:        make([]uint64, len(info.Def.Cols)),
  1122  				ForeignTbl:  tblId,
  1123  				ForeignCols: make([]uint64, len(info.Def.ForeignCols)),
  1124  				OnDelete:    info.Def.OnDelete,
  1125  				OnUpdate:    info.Def.OnUpdate,
  1126  			}
  1127  			//child table column ids of the child table
  1128  			copy(newDef.Cols, info.Def.Cols)
  1129  			//parent table column ids of the parent table
  1130  			for j, colReferred := range info.ColsReferred.Cols {
  1131  				//colName -> new colId
  1132  				if id, has := colNameToId[colReferred]; has {
  1133  					newDef.ForeignCols[j] = id
  1134  				} else {
  1135  					err := moerr.NewInternalError(c.ctx, "no column %s", colReferred)
  1136  					getLogger().Info("createTable",
  1137  						zap.String("databaseName", c.db),
  1138  						zap.String("tableName", qry.GetTableDef().GetName()),
  1139  						zap.Error(err),
  1140  					)
  1141  					return err
  1142  				}
  1143  			}
  1144  
  1145  			// add the fk def into the child table
  1146  			childDb, err := c.e.Database(c.ctx, info.Db, c.proc.TxnOperator)
  1147  			if err != nil {
  1148  				getLogger().Info("createTable",
  1149  					zap.String("databaseName", c.db),
  1150  					zap.String("tableName", qry.GetTableDef().GetName()),
  1151  					zap.Error(err),
  1152  				)
  1153  				return err
  1154  			}
  1155  			childTable, err := childDb.Relation(c.ctx, info.Table, nil)
  1156  			if err != nil {
  1157  				getLogger().Info("createTable",
  1158  					zap.String("databaseName", c.db),
  1159  					zap.String("tableName", qry.GetTableDef().GetName()),
  1160  					zap.Error(err),
  1161  				)
  1162  				return err
  1163  			}
  1164  			err = AddFkeyToRelation(c.ctx, childTable, newDef)
  1165  			if err != nil {
  1166  				getLogger().Info("createTable",
  1167  					zap.String("databaseName", c.db),
  1168  					zap.String("tableName", qry.GetTableDef().GetName()),
  1169  					zap.Error(err),
  1170  				)
  1171  				return err
  1172  			}
  1173  			// add the child table id -- tblId into the current table -- refChildDef
  1174  			err = AddChildTblIdToParentTable(c.ctx, newRelation, childTable.GetTableID(c.ctx))
  1175  			if err != nil {
  1176  				getLogger().Info("createTable",
  1177  					zap.String("databaseName", c.db),
  1178  					zap.String("tableName", qry.GetTableDef().GetName()),
  1179  					zap.Error(err),
  1180  				)
  1181  				return err
  1182  			}
  1183  		}
  1184  	}
  1185  
  1186  	// build index table
  1187  	for _, def := range qry.IndexTables {
  1188  		planCols = def.GetCols()
  1189  		exeCols = planColsToExeCols(planCols)
  1190  		exeDefs, err = planDefsToExeDefs(def)
  1191  		if err != nil {
  1192  			getLogger().Info("createTable",
  1193  				zap.String("databaseName", c.db),
  1194  				zap.String("tableName", qry.GetTableDef().GetName()),
  1195  				zap.Error(err),
  1196  			)
  1197  			return err
  1198  		}
  1199  		if _, err := dbSource.Relation(c.ctx, def.Name, nil); err == nil {
  1200  			getLogger().Info("createTable",
  1201  				zap.String("databaseName", c.db),
  1202  				zap.String("tableName", qry.GetTableDef().GetName()),
  1203  				zap.Error(err),
  1204  			)
  1205  			return moerr.NewTableAlreadyExists(c.ctx, def.Name)
  1206  		}
  1207  		if err := dbSource.Create(c.ctx, def.Name, append(exeCols, exeDefs...)); err != nil {
  1208  			getLogger().Info("createTable",
  1209  				zap.String("databaseName", c.db),
  1210  				zap.String("tableName", qry.GetTableDef().GetName()),
  1211  				zap.Error(err),
  1212  			)
  1213  			return err
  1214  		}
  1215  
  1216  		var initSQL string
  1217  		switch def.TableType {
  1218  		case catalog.SystemSI_IVFFLAT_TblType_Metadata:
  1219  			initSQL = fmt.Sprintf("insert into `%s`.`%s` (`%s`, `%s`) VALUES('version', '0');",
  1220  				qry.Database,
  1221  				def.Name,
  1222  				catalog.SystemSI_IVFFLAT_TblCol_Metadata_key,
  1223  				catalog.SystemSI_IVFFLAT_TblCol_Metadata_val,
  1224  			)
  1225  
  1226  		case catalog.SystemSI_IVFFLAT_TblType_Centroids:
  1227  			initSQL = fmt.Sprintf("insert into `%s`.`%s` (`%s`, `%s`, `%s`) VALUES(0,1,NULL);",
  1228  				qry.Database,
  1229  				def.Name,
  1230  				catalog.SystemSI_IVFFLAT_TblCol_Centroids_version,
  1231  				catalog.SystemSI_IVFFLAT_TblCol_Centroids_id,
  1232  				catalog.SystemSI_IVFFLAT_TblCol_Centroids_centroid,
  1233  			)
  1234  		}
  1235  		err = c.runSql(initSQL)
  1236  		if err != nil {
  1237  			return err
  1238  		}
  1239  
  1240  	}
  1241  
  1242  	if checkIndexInitializable(dbName, tblName) {
  1243  		newRelation, err := dbSource.Relation(c.ctx, tblName, nil)
  1244  		if err != nil {
  1245  			getLogger().Info("createTable",
  1246  				zap.String("databaseName", c.db),
  1247  				zap.String("tableName", qry.GetTableDef().GetName()),
  1248  				zap.Error(err),
  1249  			)
  1250  			return err
  1251  		}
  1252  		insertSQL, err := makeInsertMultiIndexSQL(c.e, c.ctx, c.proc, dbSource, newRelation)
  1253  		if err != nil {
  1254  			getLogger().Info("createTable",
  1255  				zap.String("databaseName", c.db),
  1256  				zap.String("tableName", qry.GetTableDef().GetName()),
  1257  				zap.Error(err),
  1258  			)
  1259  			return err
  1260  		}
  1261  		err = c.runSql(insertSQL)
  1262  		if err != nil {
  1263  			getLogger().Info("createTable",
  1264  				zap.String("databaseName", c.db),
  1265  				zap.String("tableName", qry.GetTableDef().GetName()),
  1266  				zap.Error(err),
  1267  			)
  1268  			return err
  1269  		}
  1270  
  1271  		insertSQL2, err := makeInsertTablePartitionsSQL(c.ctx, dbSource, newRelation)
  1272  		if err != nil {
  1273  			getLogger().Info("createTable",
  1274  				zap.String("databaseName", c.db),
  1275  				zap.String("tableName", qry.GetTableDef().GetName()),
  1276  				zap.Error(err),
  1277  			)
  1278  			return err
  1279  		}
  1280  		err = c.runSql(insertSQL2)
  1281  		if err != nil {
  1282  			getLogger().Info("createTable",
  1283  				zap.String("databaseName", c.db),
  1284  				zap.String("tableName", qry.GetTableDef().GetName()),
  1285  				zap.Error(err),
  1286  			)
  1287  			return err
  1288  		}
  1289  
  1290  	}
  1291  
  1292  	return maybeCreateAutoIncrement(
  1293  		c.ctx,
  1294  		dbSource,
  1295  		qry.GetTableDef(),
  1296  		c.proc.TxnOperator,
  1297  		nil)
  1298  }
  1299  
  1300  func checkIndexInitializable(dbName string, tblName string) bool {
  1301  	if dbName == catalog.MOTaskDB {
  1302  		return false
  1303  	} else if dbName == catalog.MO_CATALOG && strings.HasPrefix(tblName, catalog.MO_INDEXES) {
  1304  		// NOTE: this HasPrefix is very critical.
  1305  		// 1. When we do "alter table mo_index add col1, col2 after type",
  1306  		// 2. we create a new temporary mo_index_temp table. This mo_index_temp is same as mo_index table, with the new columns.
  1307  		// 3. Since the mo_index_temp is same as mo_index, it will have PrimaryKey(id, column_name), and this will result in a recursive behavior on mo_index table.
  1308  		// 4. Technically PrimaryKey(id, column_name) will be populated using genInsertMOIndexesSql which already contains both the 2 new columns that will be soon added by Sql based upgradeLogic.
  1309  		// 5. So, we need to skip the index table insert here.
  1310  		// TODO: verify if this logic is correct.
  1311  		return false
  1312  	}
  1313  	return true
  1314  }
  1315  
  1316  func (s *Scope) CreateTempTable(c *Compile) error {
  1317  	qry := s.Plan.GetDdl().GetCreateTable()
  1318  	// convert the plan's cols to the execution's cols
  1319  	planCols := qry.GetTableDef().GetCols()
  1320  	exeCols := planColsToExeCols(planCols)
  1321  
  1322  	// convert the plan's defs to the execution's defs
  1323  	exeDefs, err := planDefsToExeDefs(qry.GetTableDef())
  1324  	if err != nil {
  1325  		return err
  1326  	}
  1327  
  1328  	// Temporary table names and persistent table names are not allowed to be duplicated
  1329  	// So before create temporary table, need to check if it exists a table has same name
  1330  	dbName := c.db
  1331  	if qry.GetDatabase() != "" {
  1332  		dbName = qry.GetDatabase()
  1333  	}
  1334  
  1335  	// check in EntireEngine.TempEngine
  1336  	tmpDBSource, err := c.e.Database(c.ctx, defines.TEMPORARY_DBNAME, c.proc.TxnOperator)
  1337  	if err != nil {
  1338  		return err
  1339  	}
  1340  	tblName := qry.GetTableDef().GetName()
  1341  	if _, err := tmpDBSource.Relation(c.ctx, engine.GetTempTableName(dbName, tblName), nil); err == nil {
  1342  		if qry.GetIfNotExists() {
  1343  			return nil
  1344  		}
  1345  		return moerr.NewTableAlreadyExists(c.ctx, fmt.Sprintf("temporary '%s'", tblName))
  1346  	}
  1347  
  1348  	// check in EntireEngine.Engine
  1349  	dbSource, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
  1350  	if err != nil {
  1351  		return err
  1352  	}
  1353  	if _, err := dbSource.Relation(c.ctx, tblName, nil); err == nil {
  1354  		if qry.GetIfNotExists() {
  1355  			return nil
  1356  		}
  1357  		return moerr.NewTableAlreadyExists(c.ctx, tblName)
  1358  	}
  1359  
  1360  	// create temporary table
  1361  	if err := tmpDBSource.Create(c.ctx, engine.GetTempTableName(dbName, tblName), append(exeCols, exeDefs...)); err != nil {
  1362  		return err
  1363  	}
  1364  
  1365  	// build index table
  1366  	for _, def := range qry.IndexTables {
  1367  		planCols = def.GetCols()
  1368  		exeCols = planColsToExeCols(planCols)
  1369  		exeDefs, err = planDefsToExeDefs(def)
  1370  		if err != nil {
  1371  			return err
  1372  		}
  1373  		if _, err := tmpDBSource.Relation(c.ctx, def.Name, nil); err == nil {
  1374  			return moerr.NewTableAlreadyExists(c.ctx, def.Name)
  1375  		}
  1376  
  1377  		if err := tmpDBSource.Create(c.ctx, engine.GetTempTableName(dbName, def.Name), append(exeCols, exeDefs...)); err != nil {
  1378  			return err
  1379  		}
  1380  	}
  1381  
  1382  	return maybeCreateAutoIncrement(
  1383  		c.ctx,
  1384  		tmpDBSource,
  1385  		qry.GetTableDef(),
  1386  		c.proc.TxnOperator,
  1387  		func() string {
  1388  			return engine.GetTempTableName(dbName, tblName)
  1389  		})
  1390  }
  1391  
  1392  func (s *Scope) CreateIndex(c *Compile) error {
  1393  	qry := s.Plan.GetDdl().GetCreateIndex()
  1394  
  1395  	{
  1396  		// lockMoTable will lock Table  mo_catalog.mo_tables
  1397  		// for the row with db_name=dbName & table_name = tblName。
  1398  		dbName := c.db
  1399  		if qry.GetDatabase() != "" {
  1400  			dbName = qry.GetDatabase()
  1401  		}
  1402  		tblName := qry.GetTableDef().GetName()
  1403  		if err := lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); err != nil {
  1404  			return err
  1405  		}
  1406  	}
  1407  
  1408  	d, err := c.e.Database(c.ctx, qry.Database, c.proc.TxnOperator)
  1409  	if err != nil {
  1410  		return err
  1411  	}
  1412  	databaseId := d.GetDatabaseId(c.ctx)
  1413  
  1414  	r, err := d.Relation(c.ctx, qry.Table, nil)
  1415  	if err != nil {
  1416  		return err
  1417  	}
  1418  	tableId := r.GetTableID(c.ctx)
  1419  
  1420  	originalTableDef := plan2.DeepCopyTableDef(qry.TableDef, true)
  1421  	indexInfo := qry.GetIndex() // IndexInfo is named same as planner's IndexInfo
  1422  	indexTableDef := indexInfo.GetTableDef()
  1423  
  1424  	// indexName -> meta      -> indexDef[0]
  1425  	//     		 -> centroids -> indexDef[1]
  1426  	//     		 -> entries   -> indexDef[2]
  1427  	multiTableIndexes := make(map[string]*MultiTableIndex)
  1428  	for _, indexDef := range indexTableDef.Indexes {
  1429  
  1430  		indexAlgo := indexDef.IndexAlgo
  1431  		if indexDef.Unique {
  1432  			// 1. Unique Index related logic
  1433  			err = s.handleUniqueIndexTable(c, indexDef, qry.Database, originalTableDef, indexInfo)
  1434  		} else if !indexDef.Unique && catalog.IsRegularIndexAlgo(indexAlgo) {
  1435  			// 2. Regular Secondary index
  1436  			err = s.handleRegularSecondaryIndexTable(c, indexDef, qry.Database, originalTableDef, indexInfo)
  1437  		} else if !indexDef.Unique && catalog.IsMasterIndexAlgo(indexAlgo) {
  1438  			// 3. Master index
  1439  			err = s.handleMasterIndexTable(c, indexDef, qry.Database, originalTableDef, indexInfo)
  1440  		} else if !indexDef.Unique && catalog.IsIvfIndexAlgo(indexAlgo) {
  1441  			// 4. IVF indexDefs are aggregated and handled later
  1442  			if _, ok := multiTableIndexes[indexDef.IndexName]; !ok {
  1443  				multiTableIndexes[indexDef.IndexName] = &MultiTableIndex{
  1444  					IndexAlgo: catalog.ToLower(indexDef.IndexAlgo),
  1445  					IndexDefs: make(map[string]*plan.IndexDef),
  1446  				}
  1447  			}
  1448  			multiTableIndexes[indexDef.IndexName].IndexDefs[catalog.ToLower(indexDef.IndexAlgoTableType)] = indexDef
  1449  		}
  1450  		if err != nil {
  1451  			return err
  1452  		}
  1453  	}
  1454  
  1455  	for _, multiTableIndex := range multiTableIndexes {
  1456  		switch multiTableIndex.IndexAlgo {
  1457  		case catalog.MoIndexIvfFlatAlgo.ToString():
  1458  			err = s.handleVectorIvfFlatIndex(c, multiTableIndex.IndexDefs, qry.Database, originalTableDef, indexInfo)
  1459  		}
  1460  
  1461  		if err != nil {
  1462  			return err
  1463  		}
  1464  	}
  1465  
  1466  	// build and update constraint def (no need to handle IVF related logic here)
  1467  	defs, err := planDefsToExeDefs(indexTableDef)
  1468  	if err != nil {
  1469  		return err
  1470  	}
  1471  	ct := defs[0].(*engine.ConstraintDef)
  1472  
  1473  	oldCt, err := GetConstraintDef(c.ctx, r)
  1474  	if err != nil {
  1475  		return err
  1476  	}
  1477  	newCt, err := MakeNewCreateConstraint(oldCt, ct.Cts[0])
  1478  	if err != nil {
  1479  		return err
  1480  	}
  1481  	err = r.UpdateConstraint(c.ctx, newCt)
  1482  	if err != nil {
  1483  		return err
  1484  	}
  1485  
  1486  	// generate inserts into mo_indexes metadata
  1487  	for _, indexDef := range indexTableDef.Indexes {
  1488  		sql, err := makeInsertSingleIndexSQL(c.e, c.proc, databaseId, tableId, indexDef)
  1489  		if err != nil {
  1490  			return err
  1491  		}
  1492  		err = c.runSql(sql)
  1493  		if err != nil {
  1494  			return err
  1495  		}
  1496  	}
  1497  	return nil
  1498  }
  1499  
  1500  func (s *Scope) handleVectorIvfFlatIndex(c *Compile, indexDefs map[string]*plan.IndexDef, qryDatabase string, originalTableDef *plan.TableDef, indexInfo *plan.CreateTable) error {
  1501  	if ok, err := s.isExperimentalEnabled(c, ivfFlatIndexFlag); err != nil {
  1502  		return err
  1503  	} else if !ok {
  1504  		return moerr.NewInternalErrorNoCtx("IVF index is not enabled")
  1505  	}
  1506  
  1507  	// 1. static check
  1508  	if len(indexDefs) != 3 {
  1509  		return moerr.NewInternalErrorNoCtx("invalid ivf index table definition")
  1510  	} else if len(indexDefs[catalog.SystemSI_IVFFLAT_TblType_Metadata].Parts) != 1 {
  1511  		return moerr.NewInternalErrorNoCtx("invalid ivf index table definition")
  1512  	}
  1513  
  1514  	// 2. create hidden tables
  1515  	if indexInfo != nil {
  1516  
  1517  		tables := make([]string, 3)
  1518  		tables[0] = genCreateIndexTableSqlForIvfIndex(indexInfo.GetIndexTables()[0], indexDefs[catalog.SystemSI_IVFFLAT_TblType_Metadata], qryDatabase)
  1519  		tables[1] = genCreateIndexTableSqlForIvfIndex(indexInfo.GetIndexTables()[1], indexDefs[catalog.SystemSI_IVFFLAT_TblType_Centroids], qryDatabase)
  1520  		tables[2] = genCreateIndexTableSqlForIvfIndex(indexInfo.GetIndexTables()[2], indexDefs[catalog.SystemSI_IVFFLAT_TblType_Entries], qryDatabase)
  1521  
  1522  		for _, createTableSql := range tables {
  1523  			err := c.runSql(createTableSql)
  1524  			if err != nil {
  1525  				return err
  1526  			}
  1527  		}
  1528  	}
  1529  
  1530  	// 3. get count of secondary index column in original table
  1531  	totalCnt, err := s.handleIndexColCount(c, indexDefs[catalog.SystemSI_IVFFLAT_TblType_Metadata], qryDatabase, originalTableDef)
  1532  	if err != nil {
  1533  		return err
  1534  	}
  1535  
  1536  	// 4.a populate meta table
  1537  	err = s.handleIvfIndexMetaTable(c, indexDefs[catalog.SystemSI_IVFFLAT_TblType_Metadata], qryDatabase)
  1538  	if err != nil {
  1539  		return err
  1540  	}
  1541  
  1542  	// 4.b populate centroids table
  1543  	err = s.handleIvfIndexCentroidsTable(c, indexDefs[catalog.SystemSI_IVFFLAT_TblType_Centroids], qryDatabase, originalTableDef,
  1544  		totalCnt,
  1545  		indexDefs[catalog.SystemSI_IVFFLAT_TblType_Metadata].IndexTableName)
  1546  	if err != nil {
  1547  		return err
  1548  	}
  1549  
  1550  	// 4.c populate entries table
  1551  	err = s.handleIvfIndexEntriesTable(c, indexDefs[catalog.SystemSI_IVFFLAT_TblType_Entries], qryDatabase, originalTableDef,
  1552  		indexDefs[catalog.SystemSI_IVFFLAT_TblType_Metadata].IndexTableName,
  1553  		indexDefs[catalog.SystemSI_IVFFLAT_TblType_Centroids].IndexTableName)
  1554  	if err != nil {
  1555  		return err
  1556  	}
  1557  
  1558  	// 4.d delete older entries in index table.
  1559  	err = s.handleIvfIndexDeleteOldEntries(c,
  1560  		indexDefs[catalog.SystemSI_IVFFLAT_TblType_Metadata].IndexTableName,
  1561  		indexDefs[catalog.SystemSI_IVFFLAT_TblType_Centroids].IndexTableName,
  1562  		indexDefs[catalog.SystemSI_IVFFLAT_TblType_Entries].IndexTableName,
  1563  		qryDatabase)
  1564  	if err != nil {
  1565  		return err
  1566  	}
  1567  
  1568  	return nil
  1569  
  1570  }
  1571  
  1572  func (s *Scope) DropIndex(c *Compile) error {
  1573  	qry := s.Plan.GetDdl().GetDropIndex()
  1574  	d, err := c.e.Database(c.ctx, qry.Database, c.proc.TxnOperator)
  1575  	if err != nil {
  1576  		return err
  1577  	}
  1578  	r, err := d.Relation(c.ctx, qry.Table, nil)
  1579  	if err != nil {
  1580  		return err
  1581  	}
  1582  
  1583  	//1. build and update constraint def
  1584  	oldCt, err := GetConstraintDef(c.ctx, r)
  1585  	if err != nil {
  1586  		return err
  1587  	}
  1588  	newCt, err := makeNewDropConstraint(oldCt, qry.GetIndexName())
  1589  	if err != nil {
  1590  		return err
  1591  	}
  1592  	err = r.UpdateConstraint(c.ctx, newCt)
  1593  	if err != nil {
  1594  		return err
  1595  	}
  1596  
  1597  	//2. drop index table
  1598  	if qry.IndexTableName != "" {
  1599  		if _, err = d.Relation(c.ctx, qry.IndexTableName, nil); err != nil {
  1600  			return err
  1601  		}
  1602  		if err = d.Delete(c.ctx, qry.IndexTableName); err != nil {
  1603  			return err
  1604  		}
  1605  	}
  1606  
  1607  	//3. delete index object from mo_catalog.mo_indexes
  1608  	deleteSql := fmt.Sprintf(deleteMoIndexesWithTableIdAndIndexNameFormat, r.GetTableID(c.ctx), qry.IndexName)
  1609  	err = c.runSql(deleteSql)
  1610  	if err != nil {
  1611  		return err
  1612  	}
  1613  	return nil
  1614  }
  1615  
  1616  func makeNewDropConstraint(oldCt *engine.ConstraintDef, dropName string) (*engine.ConstraintDef, error) {
  1617  	// must fount dropName because of being checked in plan
  1618  	for i, ct := range oldCt.Cts {
  1619  		switch def := ct.(type) {
  1620  		case *engine.ForeignKeyDef:
  1621  			for idx, fkDef := range def.Fkeys {
  1622  				if fkDef.Name == dropName {
  1623  					def.Fkeys = append(def.Fkeys[:idx], def.Fkeys[idx+1:]...)
  1624  					oldCt.Cts = append(oldCt.Cts[:i], oldCt.Cts[i+1:]...)
  1625  					oldCt.Cts = append(oldCt.Cts, def)
  1626  					break
  1627  				}
  1628  			}
  1629  		case *engine.IndexDef:
  1630  			for idx, index := range def.Indexes {
  1631  				if index.IndexName == dropName {
  1632  					def.Indexes = append(def.Indexes[:idx], def.Indexes[idx+1:]...)
  1633  					oldCt.Cts = append(oldCt.Cts[:i], oldCt.Cts[i+1:]...)
  1634  					oldCt.Cts = append(oldCt.Cts, def)
  1635  					break
  1636  				}
  1637  			}
  1638  		}
  1639  	}
  1640  	return oldCt, nil
  1641  }
  1642  
  1643  func MakeNewCreateConstraint(oldCt *engine.ConstraintDef, c engine.Constraint) (*engine.ConstraintDef, error) {
  1644  	// duplication has checked in plan
  1645  	if oldCt == nil {
  1646  		return &engine.ConstraintDef{
  1647  			Cts: []engine.Constraint{c},
  1648  		}, nil
  1649  	}
  1650  	switch t := c.(type) {
  1651  	case *engine.ForeignKeyDef:
  1652  		ok := false
  1653  		for i, ct := range oldCt.Cts {
  1654  			if _, ok = ct.(*engine.ForeignKeyDef); ok {
  1655  				oldCt.Cts = append(oldCt.Cts[:i], oldCt.Cts[i+1:]...)
  1656  				oldCt.Cts = append(oldCt.Cts, t)
  1657  				break
  1658  			}
  1659  		}
  1660  		if !ok {
  1661  			oldCt.Cts = append(oldCt.Cts, c)
  1662  		}
  1663  
  1664  	case *engine.RefChildTableDef:
  1665  		ok := false
  1666  		for i, ct := range oldCt.Cts {
  1667  			if _, ok = ct.(*engine.RefChildTableDef); ok {
  1668  				oldCt.Cts = append(oldCt.Cts[:i], oldCt.Cts[i+1:]...)
  1669  				oldCt.Cts = append(oldCt.Cts, t)
  1670  				break
  1671  			}
  1672  		}
  1673  		if !ok {
  1674  			oldCt.Cts = append(oldCt.Cts, c)
  1675  		}
  1676  
  1677  	case *engine.IndexDef:
  1678  		ok := false
  1679  		var indexdef *engine.IndexDef
  1680  		for i, ct := range oldCt.Cts {
  1681  			if indexdef, ok = ct.(*engine.IndexDef); ok {
  1682  				//TODO: verify if this is correct @ouyuanning & @qingx
  1683  				indexdef.Indexes = append(indexdef.Indexes, t.Indexes...)
  1684  				oldCt.Cts = append(oldCt.Cts[:i], oldCt.Cts[i+1:]...)
  1685  				oldCt.Cts = append(oldCt.Cts, indexdef)
  1686  				break
  1687  			}
  1688  		}
  1689  		if !ok {
  1690  			oldCt.Cts = append(oldCt.Cts, c)
  1691  		}
  1692  	}
  1693  	return oldCt, nil
  1694  }
  1695  
  1696  func AddChildTblIdToParentTable(ctx context.Context, fkRelation engine.Relation, tblId uint64) error {
  1697  	oldCt, err := GetConstraintDef(ctx, fkRelation)
  1698  	if err != nil {
  1699  		return err
  1700  	}
  1701  	var oldRefChildDef *engine.RefChildTableDef
  1702  	for _, ct := range oldCt.Cts {
  1703  		if old, ok := ct.(*engine.RefChildTableDef); ok {
  1704  			oldRefChildDef = old
  1705  		}
  1706  	}
  1707  	if oldRefChildDef == nil {
  1708  		oldRefChildDef = &engine.RefChildTableDef{}
  1709  	}
  1710  	oldRefChildDef.Tables = append(oldRefChildDef.Tables, tblId)
  1711  	newCt, err := MakeNewCreateConstraint(oldCt, oldRefChildDef)
  1712  	if err != nil {
  1713  		return err
  1714  	}
  1715  	return fkRelation.UpdateConstraint(ctx, newCt)
  1716  }
  1717  
  1718  func AddFkeyToRelation(ctx context.Context, fkRelation engine.Relation, fkey *plan.ForeignKeyDef) error {
  1719  	oldCt, err := GetConstraintDef(ctx, fkRelation)
  1720  	if err != nil {
  1721  		return err
  1722  	}
  1723  	var oldFkeys *engine.ForeignKeyDef
  1724  	for _, ct := range oldCt.Cts {
  1725  		if old, ok := ct.(*engine.ForeignKeyDef); ok {
  1726  			oldFkeys = old
  1727  		}
  1728  	}
  1729  	if oldFkeys == nil {
  1730  		oldFkeys = &engine.ForeignKeyDef{}
  1731  	}
  1732  	oldFkeys.Fkeys = append(oldFkeys.Fkeys, fkey)
  1733  	newCt, err := MakeNewCreateConstraint(oldCt, oldFkeys)
  1734  	if err != nil {
  1735  		return err
  1736  	}
  1737  	return fkRelation.UpdateConstraint(ctx, newCt)
  1738  }
  1739  
  1740  // removeChildTblIdFromParentTable removes the tblId from the tableDef of fkRelation.
  1741  // input the fkRelation as the parameter instead of retrieving it again
  1742  // to embrace the fk self refer situation
  1743  func (s *Scope) removeChildTblIdFromParentTable(c *Compile, fkRelation engine.Relation, tblId uint64) error {
  1744  	oldCt, err := GetConstraintDef(c.ctx, fkRelation)
  1745  	if err != nil {
  1746  		return err
  1747  	}
  1748  	for _, ct := range oldCt.Cts {
  1749  		if def, ok := ct.(*engine.RefChildTableDef); ok {
  1750  			for idx, refTable := range def.Tables {
  1751  				if refTable == tblId {
  1752  					def.Tables = append(def.Tables[:idx], def.Tables[idx+1:]...)
  1753  					break
  1754  				}
  1755  			}
  1756  			break
  1757  		}
  1758  	}
  1759  	return fkRelation.UpdateConstraint(c.ctx, oldCt)
  1760  }
  1761  
  1762  func (s *Scope) removeParentTblIdFromChildTable(c *Compile, fkRelation engine.Relation, tblId uint64) error {
  1763  	oldCt, err := GetConstraintDef(c.ctx, fkRelation)
  1764  	if err != nil {
  1765  		return err
  1766  	}
  1767  	var oldFkeys *engine.ForeignKeyDef
  1768  	for _, ct := range oldCt.Cts {
  1769  		if old, ok := ct.(*engine.ForeignKeyDef); ok {
  1770  			oldFkeys = old
  1771  		}
  1772  	}
  1773  	if oldFkeys == nil {
  1774  		oldFkeys = &engine.ForeignKeyDef{}
  1775  	}
  1776  	newFkeys := &engine.ForeignKeyDef{}
  1777  	for _, fkey := range oldFkeys.Fkeys {
  1778  		if fkey.ForeignTbl != tblId {
  1779  			newFkeys.Fkeys = append(newFkeys.Fkeys, fkey)
  1780  		}
  1781  	}
  1782  	newCt, err := MakeNewCreateConstraint(oldCt, newFkeys)
  1783  	if err != nil {
  1784  		return err
  1785  	}
  1786  	return fkRelation.UpdateConstraint(c.ctx, newCt)
  1787  }
  1788  
  1789  func (s *Scope) getFkDefs(c *Compile, fkRelation engine.Relation) (*engine.ForeignKeyDef, *engine.RefChildTableDef, error) {
  1790  	var oldFkeys *engine.ForeignKeyDef
  1791  	var oldRefChild *engine.RefChildTableDef
  1792  	oldCt, err := GetConstraintDef(c.ctx, fkRelation)
  1793  	if err != nil {
  1794  		return nil, nil, err
  1795  	}
  1796  	for _, ct := range oldCt.Cts {
  1797  		if old, ok := ct.(*engine.ForeignKeyDef); ok {
  1798  			oldFkeys = old
  1799  		} else if refChild, ok := ct.(*engine.RefChildTableDef); ok {
  1800  			oldRefChild = refChild
  1801  		}
  1802  	}
  1803  	if oldFkeys == nil {
  1804  		oldFkeys = &engine.ForeignKeyDef{}
  1805  	}
  1806  	if oldRefChild == nil {
  1807  		oldRefChild = &engine.RefChildTableDef{}
  1808  	}
  1809  	return oldFkeys, oldRefChild, nil
  1810  }
  1811  
  1812  // Truncation operations cannot be performed if the session holds an active table lock.
  1813  func (s *Scope) TruncateTable(c *Compile) error {
  1814  	var dbSource engine.Database
  1815  	var rel engine.Relation
  1816  	var err error
  1817  	var isTemp bool
  1818  	var newId uint64
  1819  
  1820  	tqry := s.Plan.GetDdl().GetTruncateTable()
  1821  	dbName := tqry.GetDatabase()
  1822  	tblName := tqry.GetTable()
  1823  	oldId := tqry.GetTableId()
  1824  	keepAutoIncrement := false
  1825  	affectedRows := uint64(0)
  1826  
  1827  	dbSource, err = c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
  1828  	if err != nil {
  1829  		return err
  1830  	}
  1831  
  1832  	if rel, err = dbSource.Relation(c.ctx, tblName, nil); err != nil {
  1833  		var e error // avoid contamination of error messages
  1834  		dbSource, e = c.e.Database(c.ctx, defines.TEMPORARY_DBNAME, c.proc.TxnOperator)
  1835  		if e != nil {
  1836  			return err
  1837  		}
  1838  		rel, e = dbSource.Relation(c.ctx, engine.GetTempTableName(dbName, tblName), nil)
  1839  		if e != nil {
  1840  			return err
  1841  		}
  1842  		isTemp = true
  1843  	}
  1844  
  1845  	if !isTemp && c.proc.TxnOperator.Txn().IsPessimistic() {
  1846  		var err error
  1847  		if e := lockMoTable(c, dbName, tblName, lock.LockMode_Shared); e != nil {
  1848  			if !moerr.IsMoErrCode(e, moerr.ErrTxnNeedRetry) &&
  1849  				!moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetryWithDefChanged) {
  1850  				return e
  1851  			}
  1852  			err = e
  1853  		}
  1854  		// before dropping table, lock it.
  1855  		if e := lockTable(c.ctx, c.e, c.proc, rel, dbName, tqry.PartitionTableNames, false); e != nil {
  1856  			if !moerr.IsMoErrCode(e, moerr.ErrTxnNeedRetry) &&
  1857  				!moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetryWithDefChanged) {
  1858  				return e
  1859  			}
  1860  			err = e
  1861  		}
  1862  		if err != nil {
  1863  			return err
  1864  		}
  1865  	}
  1866  
  1867  	if tqry.IsDelete {
  1868  		keepAutoIncrement = true
  1869  		affectedRows, err = rel.Rows(c.ctx)
  1870  		if err != nil {
  1871  			return err
  1872  		}
  1873  	}
  1874  
  1875  	if isTemp {
  1876  		// memoryengine truncate always return 0, so for temporary table, just use origin tableId as newId
  1877  		_, err = dbSource.Truncate(c.ctx, engine.GetTempTableName(dbName, tblName))
  1878  		newId = rel.GetTableID(c.ctx)
  1879  	} else {
  1880  		newId, err = dbSource.Truncate(c.ctx, tblName)
  1881  	}
  1882  
  1883  	if err != nil {
  1884  		return err
  1885  	}
  1886  
  1887  	// Truncate Index Tables if needed
  1888  	for _, name := range tqry.IndexTableNames {
  1889  		var err error
  1890  		if isTemp {
  1891  			_, err = dbSource.Truncate(c.ctx, engine.GetTempTableName(dbName, name))
  1892  		} else {
  1893  			_, err = dbSource.Truncate(c.ctx, name)
  1894  		}
  1895  		if err != nil {
  1896  			return err
  1897  		}
  1898  	}
  1899  
  1900  	//Truncate Partition subtable if needed
  1901  	for _, name := range tqry.PartitionTableNames {
  1902  		var err error
  1903  		if isTemp {
  1904  			_, err = dbSource.Truncate(c.ctx, engine.GetTempTableName(dbName, name))
  1905  		} else {
  1906  			_, err = dbSource.Truncate(c.ctx, name)
  1907  		}
  1908  		if err != nil {
  1909  			return err
  1910  		}
  1911  	}
  1912  
  1913  	// update tableDef of foreign key's table with new table id
  1914  	for _, ftblId := range tqry.ForeignTbl {
  1915  		_, _, fkRelation, err := c.e.GetRelationById(c.ctx, c.proc.TxnOperator, ftblId)
  1916  		if err != nil {
  1917  			return err
  1918  		}
  1919  		oldCt, err := GetConstraintDef(c.ctx, fkRelation)
  1920  		if err != nil {
  1921  			return err
  1922  		}
  1923  		for _, ct := range oldCt.Cts {
  1924  			if def, ok := ct.(*engine.RefChildTableDef); ok {
  1925  				for idx, refTable := range def.Tables {
  1926  					if refTable == oldId {
  1927  						def.Tables[idx] = newId
  1928  						break
  1929  					}
  1930  				}
  1931  				break
  1932  			}
  1933  		}
  1934  		err = fkRelation.UpdateConstraint(c.ctx, oldCt)
  1935  		if err != nil {
  1936  			return err
  1937  		}
  1938  
  1939  	}
  1940  
  1941  	if isTemp {
  1942  		oldId = rel.GetTableID(c.ctx)
  1943  	}
  1944  	err = incrservice.GetAutoIncrementService(c.ctx).Reset(
  1945  		c.ctx,
  1946  		oldId,
  1947  		newId,
  1948  		keepAutoIncrement,
  1949  		c.proc.TxnOperator)
  1950  	if err != nil {
  1951  		return err
  1952  	}
  1953  
  1954  	// update index information in mo_catalog.mo_indexes
  1955  	updateSql := fmt.Sprintf(updateMoIndexesTruncateTableFormat, newId, oldId)
  1956  	err = c.runSql(updateSql)
  1957  	if err != nil {
  1958  		return err
  1959  	}
  1960  	c.addAffectedRows(uint64(affectedRows))
  1961  	return nil
  1962  }
  1963  
  1964  func (s *Scope) DropSequence(c *Compile) error {
  1965  	qry := s.Plan.GetDdl().GetDropSequence()
  1966  	dbName := qry.GetDatabase()
  1967  	var dbSource engine.Database
  1968  	var err error
  1969  
  1970  	tblName := qry.GetTable()
  1971  	dbSource, err = c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
  1972  	if err != nil {
  1973  		if qry.GetIfExists() {
  1974  			return nil
  1975  		}
  1976  		return err
  1977  	}
  1978  
  1979  	var rel engine.Relation
  1980  	if rel, err = dbSource.Relation(c.ctx, tblName, nil); err != nil {
  1981  		if qry.GetIfExists() {
  1982  			return nil
  1983  		}
  1984  		return err
  1985  	}
  1986  
  1987  	if err := lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); err != nil {
  1988  		return err
  1989  	}
  1990  
  1991  	// Delete the stored session value.
  1992  	c.proc.SessionInfo.SeqDeleteKeys = append(c.proc.SessionInfo.SeqDeleteKeys, rel.GetTableID(c.ctx))
  1993  
  1994  	return dbSource.Delete(c.ctx, tblName)
  1995  }
  1996  
  1997  func (s *Scope) DropTable(c *Compile) error {
  1998  	qry := s.Plan.GetDdl().GetDropTable()
  1999  	dbName := qry.GetDatabase()
  2000  	tblName := qry.GetTable()
  2001  	isView := qry.GetIsView()
  2002  	var isSource = false
  2003  	if qry.TableDef != nil {
  2004  		isSource = qry.TableDef.TableType == catalog.SystemSourceRel
  2005  	}
  2006  	var dbSource engine.Database
  2007  	var rel engine.Relation
  2008  	var err error
  2009  	var isTemp bool
  2010  
  2011  	tblId := qry.GetTableId()
  2012  
  2013  	dbSource, err = c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
  2014  	if err != nil {
  2015  		if qry.GetIfExists() {
  2016  			return nil
  2017  		}
  2018  		return err
  2019  	}
  2020  
  2021  	if rel, err = dbSource.Relation(c.ctx, tblName, nil); err != nil {
  2022  		var e error // avoid contamination of error messages
  2023  		dbSource, e = c.e.Database(c.ctx, defines.TEMPORARY_DBNAME, c.proc.TxnOperator)
  2024  		if dbSource == nil && qry.GetIfExists() {
  2025  			return nil
  2026  		} else if e != nil {
  2027  			return err
  2028  		}
  2029  		rel, e = dbSource.Relation(c.ctx, engine.GetTempTableName(dbName, tblName), nil)
  2030  		if e != nil {
  2031  			if qry.GetIfExists() {
  2032  				return nil
  2033  			} else {
  2034  				return err
  2035  			}
  2036  		}
  2037  		isTemp = true
  2038  	}
  2039  
  2040  	if !isTemp && !isView && !isSource && c.proc.TxnOperator.Txn().IsPessimistic() {
  2041  		var err error
  2042  		if e := lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); e != nil {
  2043  			if !moerr.IsMoErrCode(e, moerr.ErrTxnNeedRetry) &&
  2044  				!moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetryWithDefChanged) {
  2045  				return e
  2046  			}
  2047  			err = e
  2048  		}
  2049  		// before dropping table, lock it.
  2050  		if e := lockTable(c.ctx, c.e, c.proc, rel, dbName, qry.PartitionTableNames, false); e != nil {
  2051  			if !moerr.IsMoErrCode(e, moerr.ErrTxnNeedRetry) &&
  2052  				!moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetryWithDefChanged) {
  2053  				return e
  2054  			}
  2055  			err = e
  2056  		}
  2057  		if err != nil {
  2058  			return err
  2059  		}
  2060  	}
  2061  
  2062  	if len(qry.UpdateFkSqls) > 0 {
  2063  		for _, sql := range qry.UpdateFkSqls {
  2064  			if err = c.runSql(sql); err != nil {
  2065  				return err
  2066  			}
  2067  		}
  2068  	}
  2069  
  2070  	// update tableDef of foreign key's table
  2071  	//remove the child table id -- tblId from the parent table -- fkTblId
  2072  	for _, fkTblId := range qry.ForeignTbl {
  2073  		if fkTblId == 0 {
  2074  			//fk self refer
  2075  			continue
  2076  		}
  2077  		_, _, fkRelation, err := c.e.GetRelationById(c.ctx, c.proc.TxnOperator, fkTblId)
  2078  		if err != nil {
  2079  			return err
  2080  		}
  2081  
  2082  		err = s.removeChildTblIdFromParentTable(c, fkRelation, tblId)
  2083  		if err != nil {
  2084  			return err
  2085  		}
  2086  	}
  2087  
  2088  	//remove parent table id from the child table (when foreign_key_checks is disabled)
  2089  	for _, childTblId := range qry.FkChildTblsReferToMe {
  2090  		if childTblId == 0 {
  2091  			continue
  2092  		}
  2093  		_, _, childRelation, err := c.e.GetRelationById(c.ctx, c.proc.TxnOperator, childTblId)
  2094  		if err != nil {
  2095  			return err
  2096  		}
  2097  		err = s.removeParentTblIdFromChildTable(c, childRelation, tblId)
  2098  		if err != nil {
  2099  			return err
  2100  		}
  2101  	}
  2102  
  2103  	// delete all index objects record of the table in mo_catalog.mo_indexes
  2104  	if !qry.IsView && qry.Database != catalog.MO_CATALOG && qry.Table != catalog.MO_INDEXES {
  2105  		if qry.GetTableDef().Pkey != nil || len(qry.GetTableDef().Indexes) > 0 {
  2106  			deleteSql := fmt.Sprintf(deleteMoIndexesWithTableIdFormat, qry.GetTableDef().TblId)
  2107  			err = c.runSql(deleteSql)
  2108  			if err != nil {
  2109  				return err
  2110  			}
  2111  		}
  2112  	}
  2113  
  2114  	// delete all partition objects record of the table in mo_catalog.mo_table_partitions
  2115  	if !qry.IsView && qry.Database != catalog.MO_CATALOG && qry.Table != catalog.MO_TABLE_PARTITIONS {
  2116  		if qry.TableDef.Partition != nil {
  2117  			deleteSql := fmt.Sprintf(deleteMoTablePartitionsWithTableIdFormat, qry.GetTableDef().TblId)
  2118  			err = c.runSql(deleteSql)
  2119  			if err != nil {
  2120  				return err
  2121  			}
  2122  		}
  2123  	}
  2124  
  2125  	if isTemp {
  2126  		if err := dbSource.Delete(c.ctx, engine.GetTempTableName(dbName, tblName)); err != nil {
  2127  			return err
  2128  		}
  2129  		for _, name := range qry.IndexTableNames {
  2130  			if err := dbSource.Delete(c.ctx, name); err != nil {
  2131  				return err
  2132  			}
  2133  		}
  2134  
  2135  		//delete partition table
  2136  		for _, name := range qry.GetPartitionTableNames() {
  2137  			if err = dbSource.Delete(c.ctx, name); err != nil {
  2138  				return err
  2139  			}
  2140  		}
  2141  
  2142  		if dbName != catalog.MO_CATALOG && tblName != catalog.MO_INDEXES {
  2143  			err := incrservice.GetAutoIncrementService(c.ctx).Delete(
  2144  				c.ctx,
  2145  				rel.GetTableID(c.ctx),
  2146  				c.proc.TxnOperator)
  2147  			if err != nil {
  2148  				return err
  2149  			}
  2150  		}
  2151  
  2152  	} else {
  2153  		if err := dbSource.Delete(c.ctx, tblName); err != nil {
  2154  			return err
  2155  		}
  2156  		for _, name := range qry.IndexTableNames {
  2157  			if err := dbSource.Delete(c.ctx, name); err != nil {
  2158  				return err
  2159  			}
  2160  		}
  2161  
  2162  		// delete partition subtable
  2163  		for _, name := range qry.GetPartitionTableNames() {
  2164  			if err = dbSource.Delete(c.ctx, name); err != nil {
  2165  				return err
  2166  			}
  2167  		}
  2168  
  2169  		if dbName != catalog.MO_CATALOG && tblName != catalog.MO_INDEXES {
  2170  			// When drop table 'mo_catalog.mo_indexes', there is no need to delete the auto increment data
  2171  			err := incrservice.GetAutoIncrementService(c.ctx).Delete(
  2172  				c.ctx,
  2173  				rel.GetTableID(c.ctx),
  2174  				c.proc.TxnOperator)
  2175  			if err != nil {
  2176  				return err
  2177  			}
  2178  		}
  2179  	}
  2180  	return nil
  2181  }
  2182  
  2183  func planDefsToExeDefs(tableDef *plan.TableDef) ([]engine.TableDef, error) {
  2184  	planDefs := tableDef.GetDefs()
  2185  	var exeDefs []engine.TableDef
  2186  	c := new(engine.ConstraintDef)
  2187  	for _, def := range planDefs {
  2188  		switch defVal := def.GetDef().(type) {
  2189  		case *plan.TableDef_DefType_Properties:
  2190  			properties := make([]engine.Property, len(defVal.Properties.GetProperties()))
  2191  			for i, p := range defVal.Properties.GetProperties() {
  2192  				properties[i] = engine.Property{
  2193  					Key:   p.GetKey(),
  2194  					Value: p.GetValue(),
  2195  				}
  2196  			}
  2197  			exeDefs = append(exeDefs, &engine.PropertiesDef{
  2198  				Properties: properties,
  2199  			})
  2200  			c.Cts = append(c.Cts, &engine.StreamConfigsDef{
  2201  				Configs: defVal.Properties.GetProperties(),
  2202  			})
  2203  		}
  2204  	}
  2205  
  2206  	if tableDef.Indexes != nil {
  2207  		c.Cts = append(c.Cts, &engine.IndexDef{
  2208  			Indexes: tableDef.Indexes,
  2209  		})
  2210  	}
  2211  
  2212  	if tableDef.Partition != nil {
  2213  		bytes, err := tableDef.Partition.MarshalPartitionInfo()
  2214  		if err != nil {
  2215  			return nil, err
  2216  		}
  2217  		exeDefs = append(exeDefs, &engine.PartitionDef{
  2218  			Partitioned: 1,
  2219  			Partition:   string(bytes),
  2220  		})
  2221  	}
  2222  
  2223  	if tableDef.ViewSql != nil {
  2224  		exeDefs = append(exeDefs, &engine.ViewDef{
  2225  			View: tableDef.ViewSql.View,
  2226  		})
  2227  	}
  2228  
  2229  	if len(tableDef.Fkeys) > 0 {
  2230  		c.Cts = append(c.Cts, &engine.ForeignKeyDef{
  2231  			Fkeys: tableDef.Fkeys,
  2232  		})
  2233  	}
  2234  
  2235  	if tableDef.Pkey != nil {
  2236  		c.Cts = append(c.Cts, &engine.PrimaryKeyDef{
  2237  			Pkey: tableDef.Pkey,
  2238  		})
  2239  	}
  2240  
  2241  	if len(tableDef.RefChildTbls) > 0 {
  2242  		c.Cts = append(c.Cts, &engine.RefChildTableDef{
  2243  			Tables: tableDef.RefChildTbls,
  2244  		})
  2245  	}
  2246  
  2247  	if len(c.Cts) > 0 {
  2248  		exeDefs = append(exeDefs, c)
  2249  	}
  2250  
  2251  	if tableDef.ClusterBy != nil {
  2252  		exeDefs = append(exeDefs, &engine.ClusterByDef{
  2253  			Name: tableDef.ClusterBy.Name,
  2254  		})
  2255  	}
  2256  	return exeDefs, nil
  2257  }
  2258  
  2259  func planColsToExeCols(planCols []*plan.ColDef) []engine.TableDef {
  2260  	exeCols := make([]engine.TableDef, len(planCols))
  2261  	for i, col := range planCols {
  2262  		var alg compress.T
  2263  		switch col.Alg {
  2264  		case plan.CompressType_None:
  2265  			alg = compress.None
  2266  		case plan.CompressType_Lz4:
  2267  			alg = compress.Lz4
  2268  		}
  2269  		colTyp := col.GetTyp()
  2270  		exeCols[i] = &engine.AttributeDef{
  2271  			Attr: engine.Attribute{
  2272  				Name:          col.Name,
  2273  				Alg:           alg,
  2274  				Type:          types.New(types.T(colTyp.GetId()), colTyp.GetWidth(), colTyp.GetScale()),
  2275  				Default:       planCols[i].GetDefault(),
  2276  				OnUpdate:      planCols[i].GetOnUpdate(),
  2277  				Primary:       col.GetPrimary(),
  2278  				Comment:       col.GetComment(),
  2279  				ClusterBy:     col.ClusterBy,
  2280  				AutoIncrement: col.Typ.GetAutoIncr(),
  2281  				IsHidden:      col.Hidden,
  2282  				Seqnum:        uint16(col.Seqnum),
  2283  				EnumVlaues:    colTyp.GetEnumvalues(),
  2284  			},
  2285  		}
  2286  	}
  2287  	return exeCols
  2288  }
  2289  
  2290  func (s *Scope) CreateSequence(c *Compile) error {
  2291  	qry := s.Plan.GetDdl().GetCreateSequence()
  2292  	// convert the plan's cols to the execution's cols
  2293  	planCols := qry.GetTableDef().GetCols()
  2294  	exeCols := planColsToExeCols(planCols)
  2295  
  2296  	// convert the plan's defs to the execution's defs
  2297  	exeDefs, err := planDefsToExeDefs(qry.GetTableDef())
  2298  	if err != nil {
  2299  		return err
  2300  	}
  2301  
  2302  	dbName := c.db
  2303  	if qry.GetDatabase() != "" {
  2304  		dbName = qry.GetDatabase()
  2305  	}
  2306  	tblName := qry.GetTableDef().GetName()
  2307  
  2308  	dbSource, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
  2309  	if err != nil {
  2310  		if dbName == "" {
  2311  			return moerr.NewNoDB(c.ctx)
  2312  		}
  2313  		return err
  2314  	}
  2315  
  2316  	if _, err := dbSource.Relation(c.ctx, tblName, nil); err == nil {
  2317  		if qry.GetIfNotExists() {
  2318  			return nil
  2319  		}
  2320  		// Just report table exists error.
  2321  		return moerr.NewTableAlreadyExists(c.ctx, tblName)
  2322  	}
  2323  
  2324  	if err := lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); err != nil {
  2325  		return err
  2326  	}
  2327  
  2328  	if err := dbSource.Create(context.WithValue(c.ctx, defines.SqlKey{}, c.sql), tblName, append(exeCols, exeDefs...)); err != nil {
  2329  		return err
  2330  	}
  2331  
  2332  	// Init the only row of sequence.
  2333  	if rel, err := dbSource.Relation(c.ctx, tblName, nil); err == nil {
  2334  		if rel == nil {
  2335  			return moerr.NewTableAlreadyExists(c.ctx, tblName)
  2336  		}
  2337  		bat, err := makeSequenceInitBatch(c.ctx, c.stmt.(*tree.CreateSequence), qry.GetTableDef(), c.proc)
  2338  		defer func() {
  2339  			if bat != nil {
  2340  				bat.Clean(c.proc.Mp())
  2341  			}
  2342  		}()
  2343  		if err != nil {
  2344  			return err
  2345  		}
  2346  		err = rel.Write(c.proc.Ctx, bat)
  2347  		if err != nil {
  2348  			return err
  2349  		}
  2350  	}
  2351  	return nil
  2352  }
  2353  
  2354  func (s *Scope) AlterSequence(c *Compile) error {
  2355  	var values []interface{}
  2356  	var curval string
  2357  	qry := s.Plan.GetDdl().GetAlterSequence()
  2358  	// convert the plan's cols to the execution's cols
  2359  	planCols := qry.GetTableDef().GetCols()
  2360  	exeCols := planColsToExeCols(planCols)
  2361  
  2362  	// convert the plan's defs to the execution's defs
  2363  	exeDefs, err := planDefsToExeDefs(qry.GetTableDef())
  2364  	if err != nil {
  2365  		return err
  2366  	}
  2367  
  2368  	dbName := c.db
  2369  	if qry.GetDatabase() != "" {
  2370  		dbName = qry.GetDatabase()
  2371  	}
  2372  	tblName := qry.GetTableDef().GetName()
  2373  
  2374  	dbSource, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
  2375  	if err != nil {
  2376  		if dbName == "" {
  2377  			return moerr.NewNoDB(c.ctx)
  2378  		}
  2379  		return err
  2380  	}
  2381  
  2382  	if rel, err := dbSource.Relation(c.ctx, tblName, nil); err == nil {
  2383  		// sequence table exists
  2384  		// get pre sequence table row values
  2385  		values, err = c.proc.SessionInfo.SqlHelper.ExecSql(fmt.Sprintf("select * from `%s`.`%s`", dbName, tblName))
  2386  		if err != nil {
  2387  			return err
  2388  		}
  2389  		if values == nil {
  2390  			return moerr.NewInternalError(c.ctx, "Failed to get sequence meta data.")
  2391  		}
  2392  
  2393  		// get pre curval
  2394  
  2395  		curval = c.proc.SessionInfo.SeqCurValues[rel.GetTableID(c.ctx)]
  2396  		// dorp the pre sequence
  2397  		err = c.runSql(fmt.Sprintf("drop sequence %s", tblName))
  2398  		if err != nil {
  2399  			return err
  2400  		}
  2401  	} else {
  2402  		// sequence table not exists
  2403  		if qry.GetIfExists() {
  2404  			return nil
  2405  		}
  2406  		return moerr.NewInternalError(c.ctx, "sequence %s not exists", tblName)
  2407  	}
  2408  
  2409  	if err := lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); err != nil {
  2410  		return err
  2411  	}
  2412  
  2413  	if err := dbSource.Create(context.WithValue(c.ctx, defines.SqlKey{}, c.sql), tblName, append(exeCols, exeDefs...)); err != nil {
  2414  		return err
  2415  	}
  2416  
  2417  	//Init the only row of sequence.
  2418  	if rel, err := dbSource.Relation(c.ctx, tblName, nil); err == nil {
  2419  		if rel == nil {
  2420  			return moerr.NewLockTableNotFound(c.ctx)
  2421  		}
  2422  		bat, err := makeSequenceAlterBatch(c.ctx, c.stmt.(*tree.AlterSequence), qry.GetTableDef(), c.proc, values, curval)
  2423  		defer func() {
  2424  			if bat != nil {
  2425  				bat.Clean(c.proc.Mp())
  2426  			}
  2427  		}()
  2428  		if err != nil {
  2429  			return err
  2430  		}
  2431  		err = rel.Write(c.proc.Ctx, bat)
  2432  		if err != nil {
  2433  			return err
  2434  		}
  2435  	}
  2436  	return nil
  2437  }
  2438  
  2439  /*
  2440  Sequence table got 1 row and 7 columns(besides row_id).
  2441  -----------------------------------------------------------------------------------
  2442  last_seq_num | min_value| max_value| start_value| increment_value| cycle| is_called |
  2443  -----------------------------------------------------------------------------------
  2444  
  2445  ------------------------------------------------------------------------------------
  2446  */
  2447  
  2448  func makeSequenceAlterBatch(ctx context.Context, stmt *tree.AlterSequence, tableDef *plan.TableDef, proc *process.Process, result []interface{}, curval string) (*batch.Batch, error) {
  2449  	var bat batch.Batch
  2450  	bat.Ro = true
  2451  	bat.Cnt = 0
  2452  	bat.SetRowCount(1)
  2453  	attrs := make([]string, len(plan2.Sequence_cols_name))
  2454  	for i := range attrs {
  2455  		attrs[i] = plan2.Sequence_cols_name[i]
  2456  	}
  2457  	bat.Attrs = attrs
  2458  
  2459  	// typ is sequenece's type now
  2460  	typ := plan2.MakeTypeByPlan2Type(tableDef.Cols[0].Typ)
  2461  	vecs := make([]*vector.Vector, len(plan2.Sequence_cols_name))
  2462  
  2463  	switch typ.Oid {
  2464  	case types.T_int16:
  2465  		lastV, incr, minV, maxV, startN, cycle, err := makeAlterSequenceParam[int16](ctx, stmt, result, curval)
  2466  		if err != nil {
  2467  			return nil, err
  2468  		}
  2469  		if maxV < 0 {
  2470  			maxV = math.MaxInt16
  2471  		}
  2472  		err = valueCheckOut(maxV, minV, startN, ctx)
  2473  		if err != nil {
  2474  			return nil, err
  2475  		}
  2476  		err = makeAlterSequenceVecs(vecs, typ, proc, incr, lastV, minV, maxV, startN, cycle)
  2477  		if err != nil {
  2478  			return nil, err
  2479  		}
  2480  	case types.T_int32:
  2481  		lastV, incr, minV, maxV, startN, cycle, err := makeAlterSequenceParam[int32](ctx, stmt, result, curval)
  2482  		if err != nil {
  2483  			return nil, err
  2484  		}
  2485  		if maxV < 0 {
  2486  			maxV = math.MaxInt32
  2487  		}
  2488  		err = valueCheckOut(maxV, minV, startN, ctx)
  2489  		if err != nil {
  2490  			return nil, err
  2491  		}
  2492  		err = makeAlterSequenceVecs(vecs, typ, proc, incr, lastV, minV, maxV, startN, cycle)
  2493  		if err != nil {
  2494  			return nil, err
  2495  		}
  2496  	case types.T_int64:
  2497  		lastV, incr, minV, maxV, startN, cycle, err := makeAlterSequenceParam[int64](ctx, stmt, result, curval)
  2498  		if err != nil {
  2499  			return nil, err
  2500  		}
  2501  		if maxV < 0 {
  2502  			maxV = math.MaxInt64
  2503  		}
  2504  		err = valueCheckOut(maxV, minV, startN, ctx)
  2505  		if err != nil {
  2506  			return nil, err
  2507  		}
  2508  		err = makeAlterSequenceVecs(vecs, typ, proc, incr, lastV, minV, maxV, startN, cycle)
  2509  		if err != nil {
  2510  			return nil, err
  2511  		}
  2512  	case types.T_uint16:
  2513  		lastV, incr, minV, maxV, startN, cycle, err := makeAlterSequenceParam[uint16](ctx, stmt, result, curval)
  2514  		if err != nil {
  2515  			return nil, err
  2516  		}
  2517  		err = valueCheckOut(maxV, minV, startN, ctx)
  2518  		if err != nil {
  2519  			return nil, err
  2520  		}
  2521  		err = makeAlterSequenceVecs(vecs, typ, proc, incr, lastV, minV, maxV, startN, cycle)
  2522  		if err != nil {
  2523  			return nil, err
  2524  		}
  2525  	case types.T_uint32:
  2526  		lastV, incr, minV, maxV, startN, cycle, err := makeAlterSequenceParam[uint32](ctx, stmt, result, curval)
  2527  		if err != nil {
  2528  			return nil, err
  2529  		}
  2530  		err = valueCheckOut(maxV, minV, startN, ctx)
  2531  		if err != nil {
  2532  			return nil, err
  2533  		}
  2534  		err = makeAlterSequenceVecs(vecs, typ, proc, incr, lastV, minV, maxV, startN, cycle)
  2535  		if err != nil {
  2536  			return nil, err
  2537  		}
  2538  	case types.T_uint64:
  2539  		lastV, incr, minV, maxV, startN, cycle, err := makeAlterSequenceParam[uint64](ctx, stmt, result, curval)
  2540  		if err != nil {
  2541  			return nil, err
  2542  		}
  2543  		err = valueCheckOut(maxV, minV, startN, ctx)
  2544  		if err != nil {
  2545  			return nil, err
  2546  		}
  2547  		err = makeAlterSequenceVecs(vecs, typ, proc, incr, lastV, minV, maxV, startN, cycle)
  2548  		if err != nil {
  2549  			return nil, err
  2550  		}
  2551  	default:
  2552  		return nil, moerr.NewNotSupported(ctx, "Unsupported type for sequence")
  2553  	}
  2554  	bat.Vecs = vecs
  2555  	return &bat, nil
  2556  }
  2557  
  2558  func makeSequenceInitBatch(ctx context.Context, stmt *tree.CreateSequence, tableDef *plan.TableDef, proc *process.Process) (*batch.Batch, error) {
  2559  	var bat batch.Batch
  2560  	bat.Ro = true
  2561  	bat.Cnt = 0
  2562  	bat.SetRowCount(1)
  2563  	attrs := make([]string, len(plan2.Sequence_cols_name))
  2564  	for i := range attrs {
  2565  		attrs[i] = plan2.Sequence_cols_name[i]
  2566  	}
  2567  	bat.Attrs = attrs
  2568  
  2569  	typ := plan2.MakeTypeByPlan2Type(tableDef.Cols[0].Typ)
  2570  	sequence_cols_num := 7
  2571  	vecs := make([]*vector.Vector, sequence_cols_num)
  2572  
  2573  	// Make sequence vecs.
  2574  	switch typ.Oid {
  2575  	case types.T_int16:
  2576  		incr, minV, maxV, startN, err := makeSequenceParam[int16](ctx, stmt)
  2577  		if err != nil {
  2578  			return nil, err
  2579  		}
  2580  		if stmt.MaxValue == nil {
  2581  			if incr > 0 {
  2582  				maxV = math.MaxInt16
  2583  			} else {
  2584  				maxV = -1
  2585  			}
  2586  		}
  2587  		if stmt.MinValue == nil && incr < 0 {
  2588  			minV = math.MinInt16
  2589  		}
  2590  		if stmt.StartWith == nil {
  2591  			if incr > 0 {
  2592  				startN = minV
  2593  			} else {
  2594  				startN = maxV
  2595  			}
  2596  		}
  2597  		err = valueCheckOut(maxV, minV, startN, ctx)
  2598  		if err != nil {
  2599  			return nil, err
  2600  		}
  2601  		err = makeSequenceVecs(vecs, stmt, typ, proc, incr, minV, maxV, startN)
  2602  		if err != nil {
  2603  			return nil, err
  2604  		}
  2605  	case types.T_int32:
  2606  		incr, minV, maxV, startN, err := makeSequenceParam[int32](ctx, stmt)
  2607  		if err != nil {
  2608  			return nil, err
  2609  		}
  2610  		if stmt.MaxValue == nil {
  2611  			if incr > 0 {
  2612  				maxV = math.MaxInt32
  2613  			} else {
  2614  				maxV = -1
  2615  			}
  2616  		}
  2617  		if stmt.MinValue == nil && incr < 0 {
  2618  			minV = math.MinInt32
  2619  		}
  2620  		if stmt.StartWith == nil {
  2621  			if incr > 0 {
  2622  				startN = minV
  2623  			} else {
  2624  				startN = maxV
  2625  			}
  2626  		}
  2627  		err = valueCheckOut(maxV, minV, startN, ctx)
  2628  		if err != nil {
  2629  			return nil, err
  2630  		}
  2631  		err = makeSequenceVecs(vecs, stmt, typ, proc, incr, minV, maxV, startN)
  2632  		if err != nil {
  2633  			return nil, err
  2634  		}
  2635  	case types.T_int64:
  2636  		incr, minV, maxV, startN, err := makeSequenceParam[int64](ctx, stmt)
  2637  		if err != nil {
  2638  			return nil, err
  2639  		}
  2640  		if stmt.MaxValue == nil {
  2641  			if incr > 0 {
  2642  				maxV = math.MaxInt64
  2643  			} else {
  2644  				maxV = -1
  2645  			}
  2646  		}
  2647  		if stmt.MinValue == nil && incr < 0 {
  2648  			minV = math.MinInt64
  2649  		}
  2650  		if stmt.StartWith == nil {
  2651  			if incr > 0 {
  2652  				startN = minV
  2653  			} else {
  2654  				startN = maxV
  2655  			}
  2656  		}
  2657  		err = valueCheckOut(maxV, minV, startN, ctx)
  2658  		if err != nil {
  2659  			return nil, err
  2660  		}
  2661  		err = makeSequenceVecs(vecs, stmt, typ, proc, incr, minV, maxV, startN)
  2662  		if err != nil {
  2663  			return nil, err
  2664  		}
  2665  	case types.T_uint16:
  2666  		incr, minV, maxV, startN, err := makeSequenceParam[uint16](ctx, stmt)
  2667  		if err != nil {
  2668  			return nil, err
  2669  		}
  2670  		if stmt.MaxValue == nil {
  2671  			maxV = math.MaxUint16
  2672  		}
  2673  		if stmt.MinValue == nil && incr < 0 {
  2674  			minV = 0
  2675  		}
  2676  		if stmt.StartWith == nil {
  2677  			if incr > 0 {
  2678  				startN = minV
  2679  			} else {
  2680  				startN = maxV
  2681  			}
  2682  		}
  2683  		err = valueCheckOut(maxV, minV, startN, ctx)
  2684  		if err != nil {
  2685  			return nil, err
  2686  		}
  2687  		err = makeSequenceVecs(vecs, stmt, typ, proc, incr, minV, maxV, startN)
  2688  		if err != nil {
  2689  			return nil, err
  2690  		}
  2691  	case types.T_uint32:
  2692  		incr, minV, maxV, startN, err := makeSequenceParam[uint32](ctx, stmt)
  2693  		if err != nil {
  2694  			return nil, err
  2695  		}
  2696  		if stmt.MaxValue == nil {
  2697  			maxV = math.MaxUint32
  2698  		}
  2699  		if stmt.MinValue == nil && incr < 0 {
  2700  			minV = 0
  2701  		}
  2702  		if stmt.StartWith == nil {
  2703  			if incr > 0 {
  2704  				startN = minV
  2705  			} else {
  2706  				startN = maxV
  2707  			}
  2708  		}
  2709  		err = valueCheckOut(maxV, minV, startN, ctx)
  2710  		if err != nil {
  2711  			return nil, err
  2712  		}
  2713  		err = makeSequenceVecs(vecs, stmt, typ, proc, incr, minV, maxV, startN)
  2714  		if err != nil {
  2715  			return nil, err
  2716  		}
  2717  	case types.T_uint64:
  2718  		incr, minV, maxV, startN, err := makeSequenceParam[uint64](ctx, stmt)
  2719  		if err != nil {
  2720  			return nil, err
  2721  		}
  2722  		if stmt.MaxValue == nil {
  2723  			maxV = math.MaxUint64
  2724  		}
  2725  		if stmt.MinValue == nil && incr < 0 {
  2726  			minV = 0
  2727  		}
  2728  		if stmt.StartWith == nil {
  2729  			if incr > 0 {
  2730  				startN = minV
  2731  			} else {
  2732  				startN = maxV
  2733  			}
  2734  		}
  2735  		err = valueCheckOut(maxV, minV, startN, ctx)
  2736  		if err != nil {
  2737  			return nil, err
  2738  		}
  2739  		err = makeSequenceVecs(vecs, stmt, typ, proc, incr, minV, maxV, startN)
  2740  		if err != nil {
  2741  			return nil, err
  2742  		}
  2743  	default:
  2744  		return nil, moerr.NewNotSupported(ctx, "Unsupported type for sequence")
  2745  	}
  2746  
  2747  	bat.Vecs = vecs
  2748  	return &bat, nil
  2749  }
  2750  
  2751  func makeSequenceVecs[T constraints.Integer](vecs []*vector.Vector, stmt *tree.CreateSequence, typ types.Type, proc *process.Process, incr int64, minV, maxV, startN T) (err error) {
  2752  	defer func() {
  2753  		if err != nil {
  2754  			for _, v := range vecs {
  2755  				if v != nil {
  2756  					v.Free(proc.Mp())
  2757  				}
  2758  			}
  2759  		}
  2760  	}()
  2761  
  2762  	if vecs[0], err = vector.NewConstFixed(typ, startN, 1, proc.Mp()); err != nil {
  2763  		return err
  2764  	}
  2765  	if vecs[1], err = vector.NewConstFixed(typ, minV, 1, proc.Mp()); err != nil {
  2766  		return err
  2767  	}
  2768  	if vecs[2], err = vector.NewConstFixed(typ, maxV, 1, proc.Mp()); err != nil {
  2769  		return err
  2770  	}
  2771  	if vecs[3], err = vector.NewConstFixed(typ, startN, 1, proc.Mp()); err != nil {
  2772  		return err
  2773  	}
  2774  	if vecs[4], err = vector.NewConstFixed(types.T_int64.ToType(), incr, 1, proc.Mp()); err != nil {
  2775  		return err
  2776  	}
  2777  	if stmt.Cycle {
  2778  		vecs[5], err = vector.NewConstFixed(types.T_bool.ToType(), true, 1, proc.Mp())
  2779  	} else {
  2780  		vecs[5], err = vector.NewConstFixed(types.T_bool.ToType(), false, 1, proc.Mp())
  2781  	}
  2782  	if err != nil {
  2783  		return err
  2784  	}
  2785  	vecs[6], err = vector.NewConstFixed(types.T_bool.ToType(), false, 1, proc.Mp())
  2786  	return err
  2787  }
  2788  
  2789  func makeAlterSequenceVecs[T constraints.Integer](vecs []*vector.Vector, typ types.Type, proc *process.Process, incr int64, lastV, minV, maxV, startN T, cycle bool) (err error) {
  2790  	defer func() {
  2791  		if err != nil {
  2792  			for _, v := range vecs {
  2793  				if v != nil {
  2794  					v.Free(proc.Mp())
  2795  				}
  2796  			}
  2797  		}
  2798  	}()
  2799  
  2800  	if vecs[0], err = vector.NewConstFixed(typ, lastV, 1, proc.Mp()); err != nil {
  2801  		return err
  2802  	}
  2803  	if vecs[1], err = vector.NewConstFixed(typ, minV, 1, proc.Mp()); err != nil {
  2804  		return err
  2805  	}
  2806  	if vecs[2], err = vector.NewConstFixed(typ, maxV, 1, proc.Mp()); err != nil {
  2807  		return err
  2808  	}
  2809  	if vecs[3], err = vector.NewConstFixed(typ, startN, 1, proc.Mp()); err != nil {
  2810  		return err
  2811  	}
  2812  	if vecs[4], err = vector.NewConstFixed(types.T_int64.ToType(), incr, 1, proc.Mp()); err != nil {
  2813  		return err
  2814  	}
  2815  	if vecs[5], err = vector.NewConstFixed(types.T_bool.ToType(), cycle, 1, proc.Mp()); err != nil {
  2816  		return err
  2817  	}
  2818  	vecs[6], err = vector.NewConstFixed(types.T_bool.ToType(), false, 1, proc.Mp())
  2819  	return err
  2820  }
  2821  
  2822  func makeSequenceParam[T constraints.Integer](ctx context.Context, stmt *tree.CreateSequence) (int64, T, T, T, error) {
  2823  	var minValue, maxValue, startNum T
  2824  	incrNum := int64(1)
  2825  	if stmt.IncrementBy != nil {
  2826  		switch stmt.IncrementBy.Num.(type) {
  2827  		case uint64:
  2828  			return 0, 0, 0, 0, moerr.NewInvalidInput(ctx, "incr value's data type is int64")
  2829  		}
  2830  		incrNum = getValue[int64](stmt.IncrementBy.Minus, stmt.IncrementBy.Num)
  2831  	}
  2832  	if incrNum == 0 {
  2833  		return 0, 0, 0, 0, moerr.NewInvalidInput(ctx, "Incr value for sequence must not be 0")
  2834  	}
  2835  
  2836  	if stmt.MinValue == nil {
  2837  		if incrNum > 0 {
  2838  			minValue = 1
  2839  		} else {
  2840  			// Value here is wrong.
  2841  			// We will get real value later.
  2842  			minValue = 0
  2843  		}
  2844  	} else {
  2845  		minValue = getValue[T](stmt.MinValue.Minus, stmt.MinValue.Num)
  2846  	}
  2847  
  2848  	if stmt.MaxValue == nil {
  2849  		// Value here is wrong.
  2850  		// We will get real value later.
  2851  		maxValue = 0
  2852  	} else {
  2853  		maxValue = getValue[T](stmt.MaxValue.Minus, stmt.MaxValue.Num)
  2854  	}
  2855  
  2856  	if stmt.StartWith == nil {
  2857  		// The value may be wrong.
  2858  		if incrNum > 0 {
  2859  			startNum = minValue
  2860  		} else {
  2861  			startNum = maxValue
  2862  		}
  2863  	} else {
  2864  		startNum = getValue[T](stmt.StartWith.Minus, stmt.StartWith.Num)
  2865  	}
  2866  
  2867  	return incrNum, minValue, maxValue, startNum, nil
  2868  }
  2869  
  2870  func makeAlterSequenceParam[T constraints.Integer](ctx context.Context, stmt *tree.AlterSequence, result []interface{}, curval string) (T, int64, T, T, T, bool, error) {
  2871  	var minValue, maxValue, startNum, lastNum T
  2872  	var incrNum int64
  2873  	var cycle bool
  2874  
  2875  	if incr, ok := result[4].(int64); ok {
  2876  		incrNum = incr
  2877  	}
  2878  
  2879  	// if alter increment value
  2880  	if stmt.IncrementBy != nil {
  2881  		switch stmt.IncrementBy.Num.(type) {
  2882  		case uint64:
  2883  			return 0, 0, 0, 0, 0, false, moerr.NewInvalidInput(ctx, "incr value's data type is int64")
  2884  		}
  2885  		incrNum = getValue[int64](stmt.IncrementBy.Minus, stmt.IncrementBy.Num)
  2886  	}
  2887  	if incrNum == 0 {
  2888  		return 0, 0, 0, 0, 0, false, moerr.NewInvalidInput(ctx, "Incr value for sequence must not be 0")
  2889  	}
  2890  
  2891  	// if alter minValue of sequence
  2892  	preMinValue := result[1]
  2893  	if stmt.MinValue != nil {
  2894  		minValue = getValue[T](stmt.MinValue.Minus, stmt.MinValue.Num)
  2895  	} else {
  2896  		minValue = getInterfaceValue[T](preMinValue)
  2897  	}
  2898  
  2899  	// if alter maxValue of sequence
  2900  	preMaxValue := result[2]
  2901  	if stmt.MaxValue != nil {
  2902  		maxValue = getValue[T](stmt.MaxValue.Minus, stmt.MaxValue.Num)
  2903  	} else {
  2904  		maxValue = getInterfaceValue[T](preMaxValue)
  2905  	}
  2906  
  2907  	preLastSeq := result[0]
  2908  	preLastSeqNum := getInterfaceValue[T](preLastSeq)
  2909  	// if alter startWith value of sequence
  2910  	preStartWith := preLastSeqNum
  2911  	if stmt.StartWith != nil {
  2912  		startNum = getValue[T](stmt.StartWith.Minus, stmt.StartWith.Num)
  2913  		if startNum < preStartWith {
  2914  			startNum = preStartWith
  2915  		}
  2916  	} else {
  2917  		startNum = getInterfaceValue[T](preStartWith)
  2918  	}
  2919  	if len(curval) != 0 {
  2920  		lastNum = preLastSeqNum + T(incrNum)
  2921  		if lastNum < startNum+T(incrNum) {
  2922  			lastNum = startNum + T(incrNum)
  2923  		}
  2924  	} else {
  2925  		lastNum = preLastSeqNum
  2926  	}
  2927  
  2928  	// if alter cycle state of sequence
  2929  	preCycle := result[5]
  2930  	if preCycleVal, ok := preCycle.(bool); ok {
  2931  		if stmt.Cycle != nil {
  2932  			cycle = stmt.Cycle.Cycle
  2933  		} else {
  2934  			cycle = preCycleVal
  2935  		}
  2936  	}
  2937  
  2938  	return lastNum, incrNum, minValue, maxValue, startNum, cycle, nil
  2939  }
  2940  
  2941  // Checkout values.
  2942  func valueCheckOut[T constraints.Integer](maxValue, minValue, startNum T, ctx context.Context) error {
  2943  	if maxValue <= minValue {
  2944  		return moerr.NewInvalidInput(ctx, "MAXVALUE (%d) of sequence must be bigger than MINVALUE (%d) of it", maxValue, minValue)
  2945  	}
  2946  	if startNum < minValue || startNum > maxValue {
  2947  		return moerr.NewInvalidInput(ctx, "STARTVALUE (%d) for sequence must between MINVALUE (%d) and MAXVALUE (%d)", startNum, minValue, maxValue)
  2948  	}
  2949  	return nil
  2950  }
  2951  
  2952  func getValue[T constraints.Integer](minus bool, num any) T {
  2953  	var v T
  2954  	switch num := num.(type) {
  2955  	case uint64:
  2956  		v = T(num)
  2957  	case int64:
  2958  		if minus {
  2959  			v = -T(num)
  2960  		} else {
  2961  			v = T(num)
  2962  		}
  2963  	}
  2964  	return v
  2965  }
  2966  
  2967  func getInterfaceValue[T constraints.Integer](val interface{}) T {
  2968  	switch val := val.(type) {
  2969  	case int16:
  2970  		return T(val)
  2971  	case int32:
  2972  		return T(val)
  2973  	case int64:
  2974  		return T(val)
  2975  	case uint16:
  2976  		return T(val)
  2977  	case uint32:
  2978  		return T(val)
  2979  	case uint64:
  2980  		return T(val)
  2981  	}
  2982  	return 0
  2983  }
  2984  
  2985  func doLockTable(
  2986  	eng engine.Engine,
  2987  	proc *process.Process,
  2988  	rel engine.Relation,
  2989  	defChanged bool) error {
  2990  	id := rel.GetTableID(proc.Ctx)
  2991  	defs, err := rel.GetPrimaryKeys(proc.Ctx)
  2992  	if err != nil {
  2993  		return err
  2994  	}
  2995  
  2996  	if len(defs) != 1 {
  2997  		panic("invalid primary keys")
  2998  	}
  2999  
  3000  	err = lockop.LockTable(
  3001  		eng,
  3002  		proc,
  3003  		id,
  3004  		defs[0].Type,
  3005  		defChanged)
  3006  
  3007  	return err
  3008  }
  3009  
  3010  func lockTable(
  3011  	ctx context.Context,
  3012  	eng engine.Engine,
  3013  	proc *process.Process,
  3014  	rel engine.Relation,
  3015  	dbName string,
  3016  	partitionTableNames []string,
  3017  	defChanged bool) error {
  3018  
  3019  	if len(partitionTableNames) == 0 {
  3020  		return doLockTable(eng, proc, rel, defChanged)
  3021  	}
  3022  
  3023  	dbSource, err := eng.Database(ctx, dbName, proc.TxnOperator)
  3024  	if err != nil {
  3025  		return err
  3026  	}
  3027  
  3028  	for _, tableName := range partitionTableNames {
  3029  		pRel, pErr := dbSource.Relation(ctx, tableName, nil)
  3030  		if pErr != nil {
  3031  			return pErr
  3032  		}
  3033  		err = doLockTable(eng, proc, pRel, defChanged)
  3034  		if err != nil {
  3035  			return err
  3036  		}
  3037  	}
  3038  	return nil
  3039  }
  3040  
  3041  func lockRows(
  3042  	eng engine.Engine,
  3043  	proc *process.Process,
  3044  	rel engine.Relation,
  3045  	vec *vector.Vector,
  3046  	lockMode lock.LockMode,
  3047  	sharding lock.Sharding,
  3048  	group uint32) error {
  3049  	if vec == nil || vec.Length() == 0 {
  3050  		panic("lock rows is empty")
  3051  	}
  3052  
  3053  	id := rel.GetTableID(proc.Ctx)
  3054  
  3055  	err := lockop.LockRows(
  3056  		eng,
  3057  		proc,
  3058  		rel,
  3059  		id,
  3060  		vec,
  3061  		*vec.GetType(),
  3062  		lockMode,
  3063  		sharding,
  3064  		group)
  3065  	return err
  3066  }
  3067  
  3068  func maybeCreateAutoIncrement(
  3069  	ctx context.Context,
  3070  	db engine.Database,
  3071  	def *plan.TableDef,
  3072  	txnOp client.TxnOperator,
  3073  	nameResolver func() string) error {
  3074  	name := def.Name
  3075  	if nameResolver != nil {
  3076  		name = nameResolver()
  3077  	}
  3078  	tb, err := db.Relation(ctx, name, nil)
  3079  	if err != nil {
  3080  		return err
  3081  	}
  3082  	def.TblId = tb.GetTableID(ctx)
  3083  
  3084  	cols := incrservice.GetAutoColumnFromDef(def)
  3085  	if len(cols) == 0 {
  3086  		return nil
  3087  	}
  3088  	return incrservice.GetAutoIncrementService(ctx).Create(
  3089  		ctx,
  3090  		def.TblId,
  3091  		cols,
  3092  		txnOp)
  3093  }
  3094  
  3095  func getRelFromMoCatalog(c *Compile, tblName string) (engine.Relation, error) {
  3096  	dbSource, err := c.e.Database(c.ctx, catalog.MO_CATALOG, c.proc.TxnOperator)
  3097  	if err != nil {
  3098  		return nil, err
  3099  	}
  3100  
  3101  	rel, err := dbSource.Relation(c.ctx, tblName, nil)
  3102  	if err != nil {
  3103  		return nil, err
  3104  	}
  3105  
  3106  	return rel, nil
  3107  }
  3108  
  3109  func getLockVector(proc *process.Process, accountId uint32, names []string) (*vector.Vector, error) {
  3110  	vecs := make([]*vector.Vector, len(names)+1)
  3111  	defer func() {
  3112  		for _, v := range vecs {
  3113  			if v != nil {
  3114  				proc.PutVector(v)
  3115  			}
  3116  		}
  3117  	}()
  3118  
  3119  	// append account_id
  3120  	accountIdVec := proc.GetVector(types.T_uint32.ToType())
  3121  	err := vector.AppendFixed(accountIdVec, accountId, false, proc.GetMPool())
  3122  	if err != nil {
  3123  		return nil, err
  3124  	}
  3125  	vecs[0] = accountIdVec
  3126  	// append names
  3127  	for i, name := range names {
  3128  		nameVec := proc.GetVector(types.T_varchar.ToType())
  3129  		err := vector.AppendBytes(nameVec, []byte(name), false, proc.GetMPool())
  3130  		if err != nil {
  3131  			return nil, err
  3132  		}
  3133  		vecs[i+1] = nameVec
  3134  	}
  3135  
  3136  	vec, err := function.RunFunctionDirectly(proc, function.SerialFunctionEncodeID, vecs, 1)
  3137  	if err != nil {
  3138  		return nil, err
  3139  	}
  3140  	return vec, nil
  3141  }
  3142  
  3143  func lockMoDatabase(c *Compile, dbName string) error {
  3144  	dbRel, err := getRelFromMoCatalog(c, catalog.MO_DATABASE)
  3145  	if err != nil {
  3146  		return err
  3147  	}
  3148  	vec, err := getLockVector(c.proc, c.proc.SessionInfo.AccountId, []string{dbName})
  3149  	if err != nil {
  3150  		return err
  3151  	}
  3152  	defer vec.Free(c.proc.Mp())
  3153  	if err := lockRows(c.e, c.proc, dbRel, vec, lock.LockMode_Exclusive, lock.Sharding_ByRow, c.proc.SessionInfo.AccountId); err != nil {
  3154  		return err
  3155  	}
  3156  	return nil
  3157  }
  3158  
  3159  func lockMoTable(
  3160  	c *Compile,
  3161  	dbName string,
  3162  	tblName string,
  3163  	lockMode lock.LockMode) error {
  3164  	dbRel, err := getRelFromMoCatalog(c, catalog.MO_TABLES)
  3165  	if err != nil {
  3166  		return err
  3167  	}
  3168  	vec, err := getLockVector(c.proc, c.proc.SessionInfo.AccountId, []string{dbName, tblName})
  3169  	if err != nil {
  3170  		return err
  3171  	}
  3172  	defer vec.Free(c.proc.Mp())
  3173  
  3174  	if err := lockRows(c.e, c.proc, dbRel, vec, lockMode, lock.Sharding_ByRow, c.proc.SessionInfo.AccountId); err != nil {
  3175  		return err
  3176  	}
  3177  	return nil
  3178  }