github.com/matrixorigin/matrixone@v1.2.0/pkg/vm/engine/disttae/tools.go (about) 1 // Copyright 2022 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 disttae 16 17 import ( 18 "context" 19 "fmt" 20 "time" 21 22 "github.com/matrixorigin/matrixone/pkg/catalog" 23 "github.com/matrixorigin/matrixone/pkg/common/moerr" 24 "github.com/matrixorigin/matrixone/pkg/common/mpool" 25 "github.com/matrixorigin/matrixone/pkg/container/batch" 26 "github.com/matrixorigin/matrixone/pkg/container/types" 27 "github.com/matrixorigin/matrixone/pkg/container/vector" 28 "github.com/matrixorigin/matrixone/pkg/defines" 29 "github.com/matrixorigin/matrixone/pkg/fileservice" 30 "github.com/matrixorigin/matrixone/pkg/logutil" 31 "github.com/matrixorigin/matrixone/pkg/objectio" 32 "github.com/matrixorigin/matrixone/pkg/pb/api" 33 "github.com/matrixorigin/matrixone/pkg/pb/metadata" 34 "github.com/matrixorigin/matrixone/pkg/pb/plan" 35 "github.com/matrixorigin/matrixone/pkg/pb/timestamp" 36 "github.com/matrixorigin/matrixone/pkg/pb/txn" 37 "github.com/matrixorigin/matrixone/pkg/txn/client" 38 "github.com/matrixorigin/matrixone/pkg/txn/trace" 39 "github.com/matrixorigin/matrixone/pkg/vm/engine" 40 "github.com/matrixorigin/matrixone/pkg/vm/process" 41 ) 42 43 func genCreateDatabaseTuple(sql string, accountId, userId, roleId uint32, 44 name string, databaseId uint64, typ string, m *mpool.MPool) (*batch.Batch, error) { 45 bat := batch.NewWithSize(len(catalog.MoDatabaseSchema)) 46 bat.Attrs = append(bat.Attrs, catalog.MoDatabaseSchema...) 47 bat.SetRowCount(1) 48 49 var err error 50 defer func() { 51 if err != nil { 52 bat.Clean(m) 53 } 54 }() 55 56 { 57 idx := catalog.MO_DATABASE_DAT_ID_IDX 58 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // dat_id 59 if err = vector.AppendFixed(bat.Vecs[idx], databaseId, false, m); err != nil { 60 return nil, err 61 } 62 idx = catalog.MO_DATABASE_DAT_NAME_IDX 63 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // datname 64 if err = vector.AppendBytes(bat.Vecs[idx], []byte(name), false, m); err != nil { 65 return nil, err 66 } 67 idx = catalog.MO_DATABASE_DAT_CATALOG_NAME_IDX 68 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // dat_catalog_name 69 if err = vector.AppendBytes(bat.Vecs[idx], []byte(catalog.MO_CATALOG), false, m); err != nil { 70 return nil, err 71 } 72 idx = catalog.MO_DATABASE_CREATESQL_IDX 73 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // dat_createsql 74 if err = vector.AppendBytes(bat.Vecs[idx], []byte(sql), false, m); err != nil { // TODO 75 return nil, err 76 } 77 idx = catalog.MO_DATABASE_OWNER_IDX 78 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // owner 79 if err = vector.AppendFixed(bat.Vecs[idx], roleId, false, m); err != nil { 80 return nil, err 81 } 82 idx = catalog.MO_DATABASE_CREATOR_IDX 83 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // creator 84 if err = vector.AppendFixed(bat.Vecs[idx], userId, false, m); err != nil { 85 return nil, err 86 } 87 idx = catalog.MO_DATABASE_CREATED_TIME_IDX 88 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // created_time 89 if err = vector.AppendFixed(bat.Vecs[idx], types.Timestamp(time.Now().UnixMicro()+types.GetUnixEpochSecs()), false, m); err != nil { 90 return nil, err 91 } 92 idx = catalog.MO_DATABASE_ACCOUNT_ID_IDX 93 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // account_id 94 if err = vector.AppendFixed(bat.Vecs[idx], accountId, false, m); err != nil { 95 return nil, err 96 } 97 idx = catalog.MO_DATABASE_DAT_TYPE_IDX 98 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // dat_type 99 if err = vector.AppendBytes(bat.Vecs[idx], []byte(typ), false, m); err != nil { // TODO 100 return nil, err 101 } 102 } 103 return bat, nil 104 } 105 106 func genDropDatabaseTuple(rowid types.Rowid, id uint64, name string, m *mpool.MPool) (*batch.Batch, error) { 107 bat := batch.NewWithSize(2) 108 bat.Attrs = append(bat.Attrs, catalog.MoDatabaseSchema[:2]...) 109 bat.SetRowCount(1) 110 111 var err error 112 defer func() { 113 if err != nil { 114 bat.Clean(m) 115 } 116 }() 117 118 { 119 idx := catalog.MO_DATABASE_DAT_ID_IDX 120 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // dat_id 121 if err = vector.AppendFixed(bat.Vecs[idx], id, false, m); err != nil { 122 return nil, err 123 } 124 idx = catalog.MO_DATABASE_DAT_NAME_IDX 125 bat.Vecs[idx] = vector.NewVec(catalog.MoDatabaseTypes[idx]) // datname 126 if err = vector.AppendBytes(bat.Vecs[idx], []byte(name), false, m); err != nil { 127 return nil, err 128 } 129 } 130 //add the rowid vector as the first one in the batch 131 vec := vector.NewVec(types.T_Rowid.ToType()) 132 if err = vector.AppendFixed(vec, rowid, false, m); err != nil { 133 return nil, err 134 } 135 bat.Vecs = append([]*vector.Vector{vec}, bat.Vecs...) 136 bat.Attrs = append([]string{catalog.Row_ID}, bat.Attrs...) 137 return bat, nil 138 } 139 140 func genTableConstraintTuple(tblId, dbId uint64, tblName, dbName string, constraint []byte, 141 m *mpool.MPool) (*batch.Batch, error) { 142 bat := batch.NewWithSize(5) 143 bat.Attrs = append(bat.Attrs, catalog.MoTablesSchema[:4]...) 144 bat.Attrs = append(bat.Attrs, catalog.SystemRelAttr_Constraint) 145 bat.SetRowCount(1) 146 147 var err error 148 defer func() { 149 if err != nil { 150 bat.Clean(m) 151 } 152 }() 153 154 { 155 idx := catalog.MO_TABLES_REL_ID_IDX 156 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // rel_id 157 if err = vector.AppendFixed(bat.Vecs[idx], tblId, false, m); err != nil { 158 return nil, err 159 } 160 idx = catalog.MO_TABLES_REL_NAME_IDX 161 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // relname 162 if err = vector.AppendBytes(bat.Vecs[idx], []byte(tblName), false, m); err != nil { 163 return nil, err 164 } 165 idx = catalog.MO_TABLES_RELDATABASE_IDX 166 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // reldatabase 167 if err = vector.AppendBytes(bat.Vecs[idx], []byte(dbName), false, m); err != nil { 168 return nil, err 169 } 170 idx = catalog.MO_TABLES_RELDATABASE_ID_IDX 171 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // reldatabase_id 172 if err = vector.AppendFixed(bat.Vecs[idx], dbId, false, m); err != nil { 173 return nil, err 174 } 175 idx = catalog.MO_TABLES_UPDATE_CONSTRAINT 176 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[catalog.MO_TABLES_CONSTRAINT_IDX]) // constraint 177 if err = vector.AppendBytes(bat.Vecs[idx], constraint, false, m); err != nil { 178 return nil, err 179 } 180 } 181 return bat, nil 182 } 183 184 func genTableAlterTuple(constraint [][]byte, m *mpool.MPool) (*batch.Batch, error) { 185 bat := batch.NewWithSize(1) 186 bat.Attrs = append(bat.Attrs, catalog.SystemRelAttr_Constraint) 187 bat.SetRowCount(1) 188 189 var err error 190 defer func() { 191 if err != nil { 192 bat.Clean(m) 193 } 194 }() 195 196 idx := catalog.MO_TABLES_ALTER_TABLE 197 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[catalog.MO_TABLES_CONSTRAINT_IDX]) // constraint 198 for i := 0; i < len(constraint); i++ { 199 if err = vector.AppendBytes(bat.Vecs[idx], constraint[i], false, m); err != nil { 200 return nil, err 201 } 202 } 203 return bat, nil 204 } 205 206 // genCreateTableTuple yields a batch for insertion into mo_tables. 207 // rowid: rowid of the row. 208 // needRowid: true -- there is a rowid vector in position 0 of the batch. 209 func genCreateTableTuple(tbl *txnTable, sql string, accountId, userId, roleId uint32, name string, 210 tableId uint64, databaseId uint64, databaseName string, rowid types.Rowid, needRowid bool, m *mpool.MPool) (*batch.Batch, error) { 211 _ = sql //TODO delete this param if not required 212 bat := batch.NewWithSize(len(catalog.MoTablesSchema)) 213 bat.Attrs = append(bat.Attrs, catalog.MoTablesSchema...) 214 bat.SetRowCount(1) 215 216 var err error 217 defer func() { 218 if err != nil { 219 bat.Clean(m) 220 } 221 }() 222 223 { 224 idx := catalog.MO_TABLES_REL_ID_IDX 225 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // rel_id 226 if err = vector.AppendFixed(bat.Vecs[idx], tableId, false, m); err != nil { 227 return nil, err 228 } 229 idx = catalog.MO_TABLES_REL_NAME_IDX 230 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // relname 231 if err = vector.AppendBytes(bat.Vecs[idx], []byte(name), false, m); err != nil { 232 return nil, err 233 } 234 idx = catalog.MO_TABLES_RELDATABASE_IDX 235 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // reldatabase 236 if err = vector.AppendBytes(bat.Vecs[idx], []byte(databaseName), false, m); err != nil { 237 return nil, err 238 } 239 idx = catalog.MO_TABLES_RELDATABASE_ID_IDX 240 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // reldatabase_id 241 if err = vector.AppendFixed(bat.Vecs[idx], databaseId, false, m); err != nil { 242 return nil, err 243 } 244 idx = catalog.MO_TABLES_RELPERSISTENCE_IDX 245 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // relpersistence 246 if err = vector.AppendBytes(bat.Vecs[idx], []byte(""), false, m); err != nil { 247 return nil, err 248 } 249 idx = catalog.MO_TABLES_RELKIND_IDX 250 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // relkind 251 if err = vector.AppendBytes(bat.Vecs[idx], []byte(tbl.relKind), false, m); err != nil { 252 return nil, err 253 } 254 idx = catalog.MO_TABLES_REL_COMMENT_IDX 255 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // rel_comment 256 if err = vector.AppendBytes(bat.Vecs[idx], []byte(tbl.comment), false, m); err != nil { 257 return nil, err 258 } 259 idx = catalog.MO_TABLES_REL_CREATESQL_IDX 260 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // rel_createsql 261 if err = vector.AppendBytes(bat.Vecs[idx], []byte(tbl.createSql), false, m); err != nil { 262 return nil, err 263 } 264 idx = catalog.MO_TABLES_CREATED_TIME_IDX 265 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // created_time 266 if err = vector.AppendFixed(bat.Vecs[idx], types.Timestamp(time.Now().Unix()), false, m); err != nil { 267 return nil, err 268 } 269 idx = catalog.MO_TABLES_CREATOR_IDX 270 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // creator 271 if err = vector.AppendFixed(bat.Vecs[idx], userId, false, m); err != nil { 272 return nil, err 273 } 274 idx = catalog.MO_TABLES_OWNER_IDX 275 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // owner 276 if err = vector.AppendFixed(bat.Vecs[idx], roleId, false, m); err != nil { 277 return nil, err 278 } 279 idx = catalog.MO_TABLES_ACCOUNT_ID_IDX 280 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // account_id 281 if err = vector.AppendFixed(bat.Vecs[idx], accountId, false, m); err != nil { 282 return nil, err 283 } 284 idx = catalog.MO_TABLES_PARTITIONED_IDX 285 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // partitioned 286 if err = vector.AppendFixed(bat.Vecs[idx], tbl.partitioned, false, m); err != nil { 287 return nil, err 288 } 289 idx = catalog.MO_TABLES_PARTITION_INFO_IDX 290 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // partition_info 291 if err = vector.AppendBytes(bat.Vecs[idx], []byte(tbl.partition), false, m); err != nil { 292 return nil, err 293 } 294 idx = catalog.MO_TABLES_VIEWDEF_IDX 295 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // viewdef 296 if err := vector.AppendBytes(bat.Vecs[idx], []byte(tbl.viewdef), false, m); err != nil { 297 return nil, err 298 } 299 idx = catalog.MO_TABLES_CONSTRAINT_IDX 300 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // constraint 301 if err = vector.AppendBytes(bat.Vecs[idx], tbl.constraint, false, m); err != nil { 302 return nil, err 303 } 304 idx = catalog.MO_TABLES_VERSION_IDX 305 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // schema_version 306 if err = vector.AppendFixed(bat.Vecs[idx], uint32(0), false, m); err != nil { 307 return nil, err 308 } 309 idx = catalog.MO_TABLES_CATALOG_VERSION_IDX 310 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // catalog version 311 if err = vector.AppendFixed(bat.Vecs[idx], catalog.CatalogVersion_Curr, false, m); err != nil { 312 return nil, err 313 } 314 } 315 if needRowid { 316 //add the rowid vector as the first one in the batch 317 vec := vector.NewVec(types.T_Rowid.ToType()) 318 if err = vector.AppendFixed(vec, rowid, false, m); err != nil { 319 return nil, err 320 } 321 bat.Vecs = append([]*vector.Vector{vec}, bat.Vecs...) 322 bat.Attrs = append([]string{catalog.Row_ID}, bat.Attrs...) 323 } 324 return bat, nil 325 } 326 327 // genCreateColumnTuple yields a batch for insertion into mo_columns. 328 // rowid: rowid of the row. 329 // needRowid: true -- there is a rowid vector in position 0 of the batch. 330 func genCreateColumnTuple(col column, rowid types.Rowid, needRowid bool, m *mpool.MPool) (*batch.Batch, error) { 331 bat := batch.NewWithSize(len(catalog.MoColumnsSchema)) 332 bat.Attrs = append(bat.Attrs, catalog.MoColumnsSchema...) 333 bat.SetRowCount(1) 334 335 var err error 336 defer func() { 337 if err != nil { 338 bat.Clean(m) 339 } 340 }() 341 342 { 343 idx := catalog.MO_COLUMNS_ATT_UNIQ_NAME_IDX 344 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_uniq_name 345 if err = vector.AppendBytes(bat.Vecs[idx], []byte(genColumnPrimaryKey(col.tableId, col.name)), 346 false, m); err != nil { 347 return nil, err 348 } 349 idx = catalog.MO_COLUMNS_ACCOUNT_ID_IDX 350 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // account_id 351 if err = vector.AppendFixed(bat.Vecs[idx], col.accountId, false, m); err != nil { 352 return nil, err 353 } 354 idx = catalog.MO_COLUMNS_ATT_DATABASE_ID_IDX 355 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_database_id 356 if err = vector.AppendFixed(bat.Vecs[idx], col.databaseId, false, m); err != nil { 357 return nil, err 358 } 359 idx = catalog.MO_COLUMNS_ATT_DATABASE_IDX 360 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_database 361 if err = vector.AppendBytes(bat.Vecs[idx], []byte(col.databaseName), false, m); err != nil { 362 return nil, err 363 } 364 idx = catalog.MO_COLUMNS_ATT_RELNAME_ID_IDX 365 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_relname_id 366 if err = vector.AppendFixed(bat.Vecs[idx], col.tableId, false, m); err != nil { 367 return nil, err 368 } 369 idx = catalog.MO_COLUMNS_ATT_RELNAME_IDX 370 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_relname 371 if err = vector.AppendBytes(bat.Vecs[idx], []byte(col.tableName), false, m); err != nil { 372 return nil, err 373 } 374 idx = catalog.MO_COLUMNS_ATTNAME_IDX 375 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // attname 376 if err = vector.AppendBytes(bat.Vecs[idx], []byte(col.name), false, m); err != nil { 377 return nil, err 378 } 379 idx = catalog.MO_COLUMNS_ATTTYP_IDX 380 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // atttyp 381 if err = vector.AppendBytes(bat.Vecs[idx], col.typ, false, m); err != nil { 382 return nil, err 383 } 384 idx = catalog.MO_COLUMNS_ATTNUM_IDX 385 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // attnum 386 if err = vector.AppendFixed(bat.Vecs[idx], col.num, false, m); err != nil { 387 return nil, err 388 } 389 idx = catalog.MO_COLUMNS_ATT_LENGTH_IDX 390 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_length 391 if err = vector.AppendFixed(bat.Vecs[idx], col.typLen, false, m); err != nil { 392 return nil, err 393 } 394 idx = catalog.MO_COLUMNS_ATTNOTNULL_IDX 395 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // attnotnul 396 if err = vector.AppendFixed(bat.Vecs[idx], col.notNull, false, m); err != nil { 397 return nil, err 398 } 399 idx = catalog.MO_COLUMNS_ATTHASDEF_IDX 400 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // atthasdef 401 if err = vector.AppendFixed(bat.Vecs[idx], col.hasDef, false, m); err != nil { 402 return nil, err 403 } 404 idx = catalog.MO_COLUMNS_ATT_DEFAULT_IDX 405 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_default 406 if err = vector.AppendBytes(bat.Vecs[idx], col.defaultExpr, false, m); err != nil { 407 return nil, err 408 } 409 idx = catalog.MO_COLUMNS_ATTISDROPPED_IDX 410 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // attisdropped 411 if err = vector.AppendFixed(bat.Vecs[idx], int8(0), false, m); err != nil { 412 return nil, err 413 } 414 idx = catalog.MO_COLUMNS_ATT_CONSTRAINT_TYPE_IDX 415 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_constraint_type 416 if err = vector.AppendBytes(bat.Vecs[idx], []byte(col.constraintType), false, m); err != nil { 417 return nil, err 418 } 419 idx = catalog.MO_COLUMNS_ATT_IS_UNSIGNED_IDX 420 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_is_unsigned 421 if err = vector.AppendFixed(bat.Vecs[idx], int8(0), false, m); err != nil { 422 return nil, err 423 } 424 idx = catalog.MO_COLUMNS_ATT_IS_AUTO_INCREMENT_IDX 425 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_is_auto_increment 426 if err = vector.AppendFixed(bat.Vecs[idx], col.isAutoIncrement, false, m); err != nil { 427 return nil, err 428 } 429 idx = catalog.MO_COLUMNS_ATT_COMMENT_IDX 430 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_comment 431 if err = vector.AppendBytes(bat.Vecs[idx], []byte(col.comment), false, m); err != nil { 432 return nil, err 433 } 434 idx = catalog.MO_COLUMNS_ATT_IS_HIDDEN_IDX 435 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_is_hidden 436 if err = vector.AppendFixed(bat.Vecs[idx], col.isHidden, false, m); err != nil { 437 return nil, err 438 } 439 idx = catalog.MO_COLUMNS_ATT_HAS_UPDATE_IDX 440 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_has_update 441 if err = vector.AppendFixed(bat.Vecs[idx], col.hasUpdate, false, m); err != nil { 442 return nil, err 443 } 444 idx = catalog.MO_COLUMNS_ATT_UPDATE_IDX 445 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_update 446 if err = vector.AppendBytes(bat.Vecs[idx], col.updateExpr, false, m); err != nil { 447 return nil, err 448 } 449 idx = catalog.MO_COLUMNS_ATT_IS_CLUSTERBY 450 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_constraint_type 451 if err = vector.AppendFixed(bat.Vecs[idx], col.isClusterBy, false, m); err != nil { 452 return nil, err 453 } 454 idx = catalog.MO_COLUMNS_ATT_SEQNUM_IDX 455 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_seqnum 456 if err = vector.AppendFixed(bat.Vecs[idx], col.seqnum, false, m); err != nil { 457 return nil, err 458 } 459 idx = catalog.MO_COLUMNS_ATT_ENUM_IDX 460 bat.Vecs[idx] = vector.NewVec(catalog.MoColumnsTypes[idx]) // att_enum 461 if err = vector.AppendBytes(bat.Vecs[idx], []byte(col.enumValues), false, m); err != nil { 462 return nil, err 463 } 464 } 465 if needRowid { 466 //add the rowid vector as the first one in the batch 467 vec := vector.NewVec(types.T_Rowid.ToType()) 468 if err = vector.AppendFixed(vec, rowid, false, m); err != nil { 469 return nil, err 470 } 471 bat.Vecs = append([]*vector.Vector{vec}, bat.Vecs...) 472 bat.Attrs = append([]string{catalog.Row_ID}, bat.Attrs...) 473 } 474 return bat, nil 475 } 476 477 // genDropColumnTuple generates the batch for deletion on mo_columns. 478 // the batch has rowid vector. 479 func genDropColumnTuple(rowid types.Rowid, m *mpool.MPool) (*batch.Batch, error) { 480 bat := batch.NewWithSize(1) 481 bat.Attrs = []string{catalog.Row_ID} 482 bat.SetRowCount(1) 483 484 var err error 485 defer func() { 486 if err != nil { 487 bat.Clean(m) 488 } 489 }() 490 491 //add the rowid vector as the first one in the batch 492 vec := vector.NewVec(types.T_Rowid.ToType()) 493 if err = vector.AppendFixed(vec, rowid, false, m); err != nil { 494 return nil, err 495 } 496 bat.Vecs[0] = vec 497 return bat, nil 498 } 499 500 // genDropTableTuple generates the batch for deletion on mo_tables. 501 // the batch has rowid vector. 502 func genDropTableTuple(rowid types.Rowid, id, databaseId uint64, name, databaseName string, 503 m *mpool.MPool) (*batch.Batch, error) { 504 bat := batch.NewWithSize(4) 505 bat.Attrs = append(bat.Attrs, catalog.MoTablesSchema[:4]...) 506 bat.SetRowCount(1) 507 508 var err error 509 defer func() { 510 if err != nil { 511 bat.Clean(m) 512 } 513 }() 514 515 { 516 idx := catalog.MO_TABLES_REL_ID_IDX 517 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // rel_id 518 if err = vector.AppendFixed(bat.Vecs[idx], id, false, m); err != nil { 519 return nil, err 520 } 521 idx = catalog.MO_TABLES_REL_NAME_IDX 522 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // relname 523 if err = vector.AppendBytes(bat.Vecs[idx], []byte(name), false, m); err != nil { 524 return nil, err 525 } 526 idx = catalog.MO_TABLES_RELDATABASE_IDX 527 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // reldatabase 528 if err = vector.AppendBytes(bat.Vecs[idx], []byte(databaseName), false, m); err != nil { 529 return nil, err 530 } 531 idx = catalog.MO_TABLES_RELDATABASE_ID_IDX 532 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // reldatabase_id 533 if err = vector.AppendFixed(bat.Vecs[idx], databaseId, false, m); err != nil { 534 return nil, err 535 } 536 } 537 //add the rowid vector as the first one in the batch 538 vec := vector.NewVec(types.T_Rowid.ToType()) 539 if err = vector.AppendFixed(vec, rowid, false, m); err != nil { 540 return nil, err 541 } 542 bat.Vecs = append([]*vector.Vector{vec}, bat.Vecs...) 543 bat.Attrs = append([]string{catalog.Row_ID}, bat.Attrs...) 544 return bat, nil 545 } 546 547 // genTruncateTableTuple generates the batch for the trunacte. 548 // it needs deletion on mo_tables. the batch has rowid vector. 549 func genTruncateTableTuple(rowid types.Rowid, id, databaseId uint64, name, databaseName string, 550 m *mpool.MPool) (*batch.Batch, error) { 551 bat := batch.NewWithSize(4) 552 bat.Attrs = append(bat.Attrs, catalog.MoTablesSchema[:4]...) 553 bat.SetRowCount(1) 554 555 var err error 556 defer func() { 557 if err != nil { 558 bat.Clean(m) 559 } 560 }() 561 562 { 563 idx := catalog.MO_TABLES_REL_ID_IDX 564 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // rel_id 565 if err = vector.AppendFixed(bat.Vecs[idx], id, false, m); err != nil { 566 return nil, err 567 } 568 idx = catalog.MO_TABLES_REL_NAME_IDX 569 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // relname 570 if err = vector.AppendBytes(bat.Vecs[idx], []byte(name), false, m); err != nil { 571 return nil, err 572 } 573 idx = catalog.MO_TABLES_RELDATABASE_IDX 574 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // reldatabase 575 if err = vector.AppendBytes(bat.Vecs[idx], []byte(databaseName), false, m); err != nil { 576 return nil, err 577 } 578 idx = catalog.MO_TABLES_RELDATABASE_ID_IDX 579 bat.Vecs[idx] = vector.NewVec(catalog.MoTablesTypes[idx]) // reldatabase_id 580 if err = vector.AppendFixed(bat.Vecs[idx], databaseId, false, m); err != nil { 581 return nil, err 582 } 583 } 584 //add the rowid vector as the first one in the batch 585 vec := vector.NewVec(types.T_Rowid.ToType()) 586 if err = vector.AppendFixed(vec, rowid, false, m); err != nil { 587 return nil, err 588 } 589 bat.Vecs = append([]*vector.Vector{vec}, bat.Vecs...) 590 bat.Attrs = append([]string{catalog.Row_ID}, bat.Attrs...) 591 return bat, nil 592 } 593 594 /* 595 func genDropColumnsTuple(name string) *batch.Batch { 596 return &batch.Batch{} 597 } 598 */ 599 600 // genDatabaseIdExpr generate an expression to find database info 601 // by database name and accountId 602 /* 603 func genDatabaseIdExpr(ctx context.Context, accountId uint32, name string) *plan.Expr { 604 var left, right *plan.Expr 605 606 { 607 var args []*plan.Expr 608 609 args = append(args, newColumnExpr(MO_DATABASE_ID_NAME_IDX, types.T_varchar, 610 catalog.MoDatabaseSchema[catalog.MO_DATABASE_DAT_NAME_IDX])) 611 args = append(args, newStringConstVal(name)) 612 left = plantool.MakeExpr(ctx, "=", args) 613 } 614 { 615 var args []*plan.Expr 616 617 args = append(args, newColumnExpr(MO_DATABASE_ID_ACCOUNT_IDX, types.T_uint32, 618 catalog.MoDatabaseSchema[catalog.MO_DATABASE_ACCOUNT_ID_IDX])) 619 args = append(args, newIntConstVal(accountId)) 620 right = plantool.MakeExpr(ctx, "=", args) 621 } 622 return plantool.MakeExpr(ctx, "and", []*plan.Expr{left, right}) 623 } 624 */ 625 626 /* 627 // genDatabaseIdExpr generate an expression to find database list 628 // by accountId 629 func genDatabaseListExpr(ctx context.Context, accountId uint32) *plan.Expr { 630 var args []*plan.Expr 631 632 args = append(args, newColumnExpr(MO_DATABASE_LIST_ACCOUNT_IDX, types.T_uint32, 633 catalog.MoDatabaseSchema[catalog.MO_DATABASE_ACCOUNT_ID_IDX])) 634 args = append(args, newIntConstVal(accountId)) 635 return plantool.MakeExpr(ctx, "=", args) 636 } 637 638 // genTableInfoExpr generate an expression to find table info 639 // by database id and table name and accountId 640 func genTableInfoExpr(ctx context.Context, accountId uint32, databaseId uint64, name string) *plan.Expr { 641 var left, right *plan.Expr 642 643 { 644 var args []*plan.Expr 645 646 args = append(args, newColumnExpr(catalog.MO_TABLES_REL_NAME_IDX, types.T_varchar, 647 catalog.MoTablesSchema[catalog.MO_TABLES_REL_NAME_IDX])) 648 args = append(args, newStringConstVal(name)) 649 left = plantool.MakeExpr(ctx, "=", args) 650 } 651 { 652 var args []*plan.Expr 653 654 args = append(args, newColumnExpr(catalog.MO_TABLES_RELDATABASE_ID_IDX, types.T_uint64, 655 catalog.MoTablesSchema[catalog.MO_TABLES_RELDATABASE_ID_IDX])) 656 args = append(args, newIntConstVal(databaseId)) 657 right = plantool.MakeExpr(ctx, "=", args) 658 left = plantool.MakeExpr(ctx, "and", []*plan.Expr{left, right}) 659 } 660 { 661 var args []*plan.Expr 662 663 args = append(args, newColumnExpr(catalog.MO_TABLES_ACCOUNT_ID_IDX, types.T_uint32, 664 catalog.MoTablesSchema[catalog.MO_TABLES_ACCOUNT_ID_IDX])) 665 args = append(args, newIntConstVal(accountId)) 666 right = plantool.MakeExpr(ctx, "=", args) 667 } 668 return plantool.MakeExpr(ctx, "and", []*plan.Expr{left, right}) 669 } 670 671 // genTableIdExpr generate an expression to find table info 672 // by database id and table name and accountId 673 func genTableIdExpr(ctx context.Context, accountId uint32, databaseId uint64, name string) *plan.Expr { 674 var left, right *plan.Expr 675 676 { 677 var args []*plan.Expr 678 679 args = append(args, newColumnExpr(MO_TABLE_ID_NAME_IDX, types.T_varchar, 680 catalog.MoTablesSchema[catalog.MO_TABLES_REL_NAME_IDX])) 681 args = append(args, newStringConstVal(name)) 682 left = plantool.MakeExpr(ctx, "=", args) 683 } 684 { 685 var args []*plan.Expr 686 687 args = append(args, newColumnExpr(MO_TABLE_ID_DATABASE_ID_IDX, types.T_uint64, 688 catalog.MoTablesSchema[catalog.MO_TABLES_RELDATABASE_ID_IDX])) 689 args = append(args, newIntConstVal(databaseId)) 690 right = plantool.MakeExpr(ctx, "=", args) 691 left = plantool.MakeExpr(ctx, "and", []*plan.Expr{left, right}) 692 } 693 { 694 var args []*plan.Expr 695 696 args = append(args, newColumnExpr(MO_TABLE_ID_ACCOUNT_IDX, types.T_uint32, 697 catalog.MoTablesSchema[catalog.MO_TABLES_ACCOUNT_ID_IDX])) 698 args = append(args, newIntConstVal(accountId)) 699 right = plantool.MakeExpr(ctx, "=", args) 700 } 701 return plantool.MakeExpr(ctx, "and", []*plan.Expr{left, right}) 702 } 703 704 // genTableListExpr generate an expression to find table list 705 // by database id and accountId 706 func genTableListExpr(ctx context.Context, accountId uint32, databaseId uint64) *plan.Expr { 707 var left, right *plan.Expr 708 709 { 710 var args []*plan.Expr 711 712 args = append(args, newColumnExpr(MO_TABLE_LIST_DATABASE_ID_IDX, types.T_uint64, 713 catalog.MoTablesSchema[catalog.MO_TABLES_RELDATABASE_ID_IDX])) 714 args = append(args, newIntConstVal(databaseId)) 715 left = plantool.MakeExpr(ctx, "=", args) 716 } 717 { 718 var args []*plan.Expr 719 720 args = append(args, newColumnExpr(MO_TABLE_LIST_ACCOUNT_IDX, types.T_uint32, 721 catalog.MoTablesSchema[catalog.MO_TABLES_ACCOUNT_ID_IDX])) 722 args = append(args, newIntConstVal(accountId)) 723 right = plantool.MakeExpr(ctx, "=", args) 724 } 725 return plantool.MakeExpr(ctx, "and", []*plan.Expr{left, right}) 726 } 727 728 // genColumnInfoExpr generate an expression to find column info list 729 // by database id and table id and accountId 730 func genColumnInfoExpr(ctx context.Context, accountId uint32, databaseId, tableId uint64) *plan.Expr { 731 var left, right *plan.Expr 732 733 { 734 var args []*plan.Expr 735 736 args = append(args, newColumnExpr(catalog.MO_COLUMNS_ATT_DATABASE_ID_IDX, types.T_uint64, 737 catalog.MoColumnsSchema[catalog.MO_COLUMNS_ATT_DATABASE_ID_IDX])) 738 args = append(args, newIntConstVal(databaseId)) 739 left = plantool.MakeExpr(ctx, "=", args) 740 } 741 { 742 var args []*plan.Expr 743 744 args = append(args, newColumnExpr(catalog.MO_COLUMNS_ATT_RELNAME_ID_IDX, types.T_uint64, 745 catalog.MoTablesSchema[catalog.MO_COLUMNS_ATT_RELNAME_ID_IDX])) 746 args = append(args, newIntConstVal(tableId)) 747 right = plantool.MakeExpr(ctx, "=", args) 748 left = plantool.MakeExpr(ctx, "and", []*plan.Expr{left, right}) 749 } 750 { 751 var args []*plan.Expr 752 753 args = append(args, newColumnExpr(catalog.MO_COLUMNS_ACCOUNT_ID_IDX, types.T_uint32, 754 catalog.MoTablesSchema[catalog.MO_COLUMNS_ACCOUNT_ID_IDX])) 755 args = append(args, newIntConstVal(accountId)) 756 right = plantool.MakeExpr(ctx, "=", args) 757 } 758 return plantool.MakeExpr(ctx, "and", []*plan.Expr{left, right}) 759 } 760 761 // genInsertExpr used to generate an expression to partition table data 762 func genInsertExpr(ctx context.Context, defs []engine.TableDef, dnNum int) *plan.Expr { 763 var args []*plan.Expr 764 765 i := 0 766 for _, def := range defs { 767 if attr, ok := def.(*engine.AttributeDef); ok { 768 if attr.Attr.Primary { 769 args = append(args, newColumnExpr(i, attr.Attr.Type.Oid, attr.Attr.Name)) 770 } 771 i++ 772 } 773 } 774 if len(args) == 0 { 775 return nil 776 } 777 return plantool.MakeExpr(ctx, "hash_value", args) 778 } 779 */ 780 781 /* 782 func newIntConstVal(v any) *plan.Expr { 783 var val int64 784 785 switch x := v.(type) { 786 case int32: 787 val = int64(x) 788 case int64: 789 val = int64(x) 790 case uint32: 791 val = int64(x) 792 case uint64: 793 val = int64(x) 794 } 795 return plantool.MakePlan2Int64ConstExprWithType(val) 796 } 797 798 func newStringConstVal(v string) *plan.Expr { 799 return &plan.Expr{ 800 Typ: types.NewProtoType(types.T_varchar), 801 Expr: &plan.Expr_C{ 802 C: &plan.Const{ 803 Value: &plan.Literal_Sval{Sval: v}, 804 }, 805 }, 806 } 807 } 808 */ 809 810 func newColumnExpr(pos int, typ plan.Type, name string) *plan.Expr { 811 return &plan.Expr{ 812 Typ: typ, 813 Expr: &plan.Expr_Col{ 814 Col: &plan.ColRef{ 815 Name: name, 816 ColPos: int32(pos), 817 }, 818 }, 819 } 820 } 821 822 func genWriteReqs(ctx context.Context, writes []Entry, op client.TxnOperator) ([]txn.TxnRequest, error) { 823 mq := make(map[string]DNStore) 824 mp := make(map[string][]*api.Entry) 825 v := ctx.Value(defines.PkCheckByTN{}) 826 for _, e := range writes { 827 // `DELETE_TXN` and `INSERT_TXN` are only used for CN workspace consumption, not sent to DN 828 if e.typ == DELETE_TXN || e.typ == INSERT_TXN { 829 continue 830 } 831 832 //SKIP update/delete on mo_columns 833 //The TN does not counsume the update/delete on mo_columns. 834 //there are update/delete entries on mo_columns just after one on mo_tables. 835 //case 1: (DELETE,MO_TABLES),(UPDATE/DELETE,MO_COLUMNS),(UPDATE/DELETE,MO_COLUMNS),... 836 //there is none update/delete entries on mo_columns just after one on mo_tables. 837 //case 2: (DELETE,MO_TABLES),... 838 if (e.typ == DELETE || e.typ == UPDATE) && 839 e.databaseId == catalog.MO_CATALOG_ID && 840 e.tableId == catalog.MO_COLUMNS_ID { 841 continue 842 } 843 if e.bat == nil || e.bat.IsEmpty() { 844 continue 845 } 846 if e.tableId == catalog.MO_TABLES_ID && (e.typ == INSERT || e.typ == INSERT_TXN) { 847 logutil.Infof("precommit: create table: %s-%v", 848 op.Txn().DebugString(), 849 vector.MustStrCol(e.bat.GetVector(1+catalog.MO_TABLES_REL_NAME_IDX))) 850 } 851 if v != nil { 852 e.pkChkByTN = v.(int8) 853 } 854 pe, err := toPBEntry(e) 855 if err != nil { 856 return nil, err 857 } 858 mp[e.tnStore.ServiceID] = append(mp[e.tnStore.ServiceID], pe) 859 if _, ok := mq[e.tnStore.ServiceID]; !ok { 860 mq[e.tnStore.ServiceID] = e.tnStore 861 } 862 } 863 reqs := make([]txn.TxnRequest, 0, len(mp)) 864 for k := range mp { 865 trace.GetService().TxnCommit(op, mp[k]) 866 payload, err := types.Encode(&api.PrecommitWriteCmd{EntryList: mp[k]}) 867 if err != nil { 868 return nil, err 869 } 870 tn := mq[k] 871 for _, info := range tn.Shards { 872 reqs = append(reqs, txn.TxnRequest{ 873 CNRequest: &txn.CNOpRequest{ 874 OpCode: uint32(api.OpCode_OpPreCommit), 875 Payload: payload, 876 Target: metadata.TNShard{ 877 TNShardRecord: metadata.TNShardRecord{ 878 ShardID: info.ShardID, 879 }, 880 ReplicaID: info.ReplicaID, 881 Address: tn.TxnServiceAddress, 882 }, 883 }, 884 Options: &txn.TxnRequestOptions{ 885 RetryCodes: []int32{ 886 // tn shard not found 887 int32(moerr.ErrTNShardNotFound), 888 }, 889 RetryInterval: int64(time.Second), 890 }, 891 }) 892 } 893 } 894 return reqs, nil 895 } 896 897 func toPBEntry(e Entry) (*api.Entry, error) { 898 var ebat *batch.Batch 899 900 if e.typ == INSERT { 901 ebat = batch.NewWithSize(0) 902 if e.bat.Attrs[0] == catalog.BlockMeta_MetaLoc { 903 ebat.Vecs = e.bat.Vecs 904 ebat.Attrs = e.bat.Attrs 905 } else { 906 //e.bat.Vecs[0] is rowid vector 907 ebat.Vecs = e.bat.Vecs[1:] 908 ebat.Attrs = e.bat.Attrs[1:] 909 } 910 } else { 911 ebat = e.bat 912 } 913 typ := api.Entry_Insert 914 if e.typ == DELETE { 915 typ = api.Entry_Delete 916 if e.tableId != catalog.MO_TABLES_ID && 917 e.tableId != catalog.MO_DATABASE_ID { 918 ebat = batch.NewWithSize(0) 919 //ebat.Vecs = e.bat.Vecs[:1] 920 //ebat.Attrs = e.bat.Attrs[:1] 921 if e.fileName == "" { 922 if len(e.bat.Vecs) != 2 { 923 panic(fmt.Sprintf("e.bat should contain 2 vectors, "+ 924 "one is rowid vector, the other is pk vector,"+ 925 "database name = %s, table name = %s", e.databaseName, e.tableName)) 926 } 927 ebat.Vecs = e.bat.Vecs[:2] 928 ebat.Attrs = e.bat.Attrs[:2] 929 } else { 930 ebat.Vecs = e.bat.Vecs[:1] 931 ebat.Attrs = e.bat.Attrs[:1] 932 } 933 934 } 935 } else if e.typ == UPDATE { 936 typ = api.Entry_Update 937 } else if e.typ == ALTER { 938 typ = api.Entry_Alter 939 } 940 bat, err := toPBBatch(ebat) 941 if err != nil { 942 return nil, err 943 } 944 return &api.Entry{ 945 Bat: bat, 946 EntryType: typ, 947 TableId: e.tableId, 948 DatabaseId: e.databaseId, 949 TableName: e.tableName, 950 DatabaseName: e.databaseName, 951 FileName: e.fileName, 952 PkCheckByTn: int32(e.pkChkByTN), 953 }, nil 954 } 955 956 func toPBBatch(bat *batch.Batch) (*api.Batch, error) { 957 rbat := new(api.Batch) 958 rbat.Attrs = bat.Attrs 959 for _, vec := range bat.Vecs { 960 pbVector, err := vector.VectorToProtoVector(vec) 961 if err != nil { 962 return nil, err 963 } 964 rbat.Vecs = append(rbat.Vecs, pbVector) 965 } 966 return rbat, nil 967 } 968 969 func getTableComment(defs []engine.TableDef) string { 970 for _, def := range defs { 971 if cdef, ok := def.(*engine.CommentDef); ok { 972 return cdef.Comment 973 } 974 } 975 return "" 976 } 977 978 /* 979 func genTableDefOfComment(comment string) engine.TableDef { 980 return &engine.CommentDef{ 981 Comment: comment, 982 } 983 } 984 985 func getColumnsFromRows(rows [][]any) []column { 986 cols := make([]column, len(rows)) 987 for i, row := range rows { 988 cols[i].name = string(row[catalog.MO_COLUMNS_ATTNAME_IDX].([]byte)) 989 cols[i].comment = string(row[catalog.MO_COLUMNS_ATT_COMMENT_IDX].([]byte)) 990 cols[i].isHidden = row[catalog.MO_COLUMNS_ATT_IS_HIDDEN_IDX].(int8) 991 cols[i].isAutoIncrement = row[catalog.MO_COLUMNS_ATT_IS_AUTO_INCREMENT_IDX].(int8) 992 cols[i].constraintType = string(row[catalog.MO_COLUMNS_ATT_CONSTRAINT_TYPE_IDX].([]byte)) 993 cols[i].typ = row[catalog.MO_COLUMNS_ATTTYP_IDX].([]byte) 994 cols[i].hasDef = row[catalog.MO_COLUMNS_ATTHASDEF_IDX].(int8) 995 cols[i].defaultExpr = row[catalog.MO_COLUMNS_ATT_DEFAULT_IDX].([]byte) 996 cols[i].hasUpdate = row[catalog.MO_COLUMNS_ATT_HAS_UPDATE_IDX].(int8) 997 cols[i].updateExpr = row[catalog.MO_COLUMNS_ATT_UPDATE_IDX].([]byte) 998 cols[i].num = row[catalog.MO_COLUMNS_ATTNUM_IDX].(int32) 999 cols[i].isClusterBy = row[catalog.MO_COLUMNS_ATT_IS_CLUSTERBY].(int8) 1000 } 1001 sort.Sort(Columns(cols)) 1002 return cols 1003 } 1004 1005 func genTableDefOfColumn(col column) engine.TableDef { 1006 var attr engine.Attribute 1007 1008 attr.ID = uint64(col.num) 1009 attr.Name = col.name 1010 attr.Alg = compress.Lz4 1011 attr.Comment = col.comment 1012 attr.IsHidden = col.isHidden == 1 1013 attr.AutoIncrement = col.isAutoIncrement == 1 1014 if err := types.Decode(col.typ, &attr.Type); err != nil { 1015 panic(err) 1016 } 1017 if col.hasDef == 1 { 1018 attr.Default = new(plan.Default) 1019 if err := types.Decode(col.defaultExpr, attr.Default); err != nil { 1020 panic(err) 1021 } 1022 } 1023 if col.hasUpdate == 1 { 1024 attr.OnUpdate = new(plan.OnUpdate) 1025 if err := types.Decode(col.updateExpr, attr.OnUpdate); err != nil { 1026 panic(err) 1027 } 1028 } 1029 if col.constraintType == catalog.SystemColPKConstraint { 1030 attr.Primary = true 1031 } 1032 if col.isClusterBy == 1 { 1033 attr.ClusterBy = true 1034 } 1035 return &engine.AttributeDef{Attr: attr} 1036 } 1037 */ 1038 1039 func genColumns(accountId uint32, tableName, databaseName string, 1040 tableId, databaseId uint64, defs []engine.TableDef) ([]column, error) { 1041 { // XXX Why not store PrimaryIndexDef and 1042 // then use PrimaryIndexDef for all primary key constraints. 1043 mp := make(map[string]int) 1044 for i, def := range defs { 1045 if attr, ok := def.(*engine.AttributeDef); ok { 1046 mp[attr.Attr.Name] = i 1047 } 1048 } 1049 for _, def := range defs { 1050 if constraintDef, ok := def.(*engine.ConstraintDef); ok { 1051 for _, ct := range constraintDef.Cts { 1052 if pkdef, ok2 := ct.(*engine.PrimaryKeyDef); ok2 { 1053 pos := mp[pkdef.Pkey.PkeyColName] 1054 attr, _ := defs[pos].(*engine.AttributeDef) 1055 attr.Attr.Primary = true 1056 } 1057 } 1058 } 1059 1060 if clusterByDef, ok := def.(*engine.ClusterByDef); ok { 1061 attr, _ := defs[mp[clusterByDef.Name]].(*engine.AttributeDef) 1062 attr.Attr.ClusterBy = true 1063 } 1064 } 1065 } 1066 var num int32 = 1 1067 cols := make([]column, 0, len(defs)) 1068 for _, def := range defs { 1069 attrDef, ok := def.(*engine.AttributeDef) 1070 if !ok { 1071 continue 1072 } 1073 typ, err := types.Encode(&attrDef.Attr.Type) 1074 if err != nil { 1075 return nil, err 1076 } 1077 col := column{ 1078 typ: typ, 1079 typLen: int32(len(typ)), 1080 accountId: accountId, 1081 tableId: tableId, 1082 databaseId: databaseId, 1083 name: attrDef.Attr.Name, 1084 tableName: tableName, 1085 databaseName: databaseName, 1086 num: num, 1087 comment: attrDef.Attr.Comment, 1088 seqnum: uint16(num - 1), 1089 enumValues: attrDef.Attr.EnumVlaues, 1090 } 1091 attrDef.Attr.ID = uint64(num) 1092 attrDef.Attr.Seqnum = uint16(num - 1) 1093 col.hasDef = 0 1094 if attrDef.Attr.Default != nil { 1095 defaultExpr, err := types.Encode(attrDef.Attr.Default) 1096 if err != nil { 1097 return nil, err 1098 } 1099 if len(defaultExpr) > 0 { 1100 col.hasDef = 1 1101 col.defaultExpr = defaultExpr 1102 } 1103 } 1104 if attrDef.Attr.OnUpdate != nil { 1105 expr, err := types.Encode(attrDef.Attr.OnUpdate) 1106 if err != nil { 1107 return nil, err 1108 } 1109 if len(expr) > 0 { 1110 col.hasUpdate = 1 1111 col.updateExpr = expr 1112 } 1113 } 1114 if attrDef.Attr.IsHidden { 1115 col.isHidden = 1 1116 } 1117 if attrDef.Attr.AutoIncrement { 1118 col.isAutoIncrement = 1 1119 } 1120 if attrDef.Attr.Primary { 1121 col.constraintType = catalog.SystemColPKConstraint 1122 } else { 1123 col.constraintType = catalog.SystemColNoConstraint 1124 } 1125 if attrDef.Attr.ClusterBy { 1126 col.isClusterBy = 1 1127 } 1128 1129 cols = append(cols, col) 1130 num++ 1131 } 1132 return cols, nil 1133 } 1134 1135 func getSql(ctx context.Context) string { 1136 if v := ctx.Value(defines.SqlKey{}); v != nil { 1137 return v.(string) 1138 } 1139 return "" 1140 } 1141 func getTyp(ctx context.Context) string { 1142 if v := ctx.Value(defines.DatTypKey{}); v != nil { 1143 return v.(string) 1144 } 1145 return "" 1146 } 1147 1148 func getAccessInfo(ctx context.Context) (uint32, uint32, uint32, error) { 1149 var accountId, userId, roleId uint32 1150 var err error 1151 1152 accountId, err = defines.GetAccountId(ctx) 1153 if err != nil { 1154 return 0, 0, 0, err 1155 } 1156 userId = defines.GetUserId(ctx) 1157 roleId = defines.GetRoleId(ctx) 1158 return accountId, userId, roleId, nil 1159 } 1160 1161 /* 1162 func partitionBatch(bat *batch.Batch, expr *plan.Expr, proc *process.Process, dnNum int) ([]*batch.Batch, error) { 1163 pvec, err := colexec.EvalExpr(bat, proc, expr) 1164 if err != nil { 1165 return nil, err 1166 } 1167 defer pvec.Free(proc.Mp()) 1168 bats := make([]*batch.Batch, dnNum) 1169 for i := range bats { 1170 bats[i] = batch.New(true, bat.Attrs) 1171 for j := range bats[i].Vecs { 1172 bats[i].SetVector(int32(j), vector.NewVec(*bat.GetVector(int32(j)).GetType())) 1173 } 1174 } 1175 vs := vector.MustFixedCol[int64](pvec) 1176 for i := range bat.Vecs { 1177 vec := bat.GetVector(int32(i)) 1178 for j, v := range vs { 1179 idx := uint64(v) % uint64(dnNum) 1180 if err := bats[idx].GetVector(int32(i)).UnionOne(vec, int64(j), proc.Mp()); err != nil { 1181 for _, bat := range bats { 1182 bat.Clean(proc.Mp()) 1183 } 1184 return nil, err 1185 } 1186 } 1187 } 1188 for i := range bats { 1189 bats[i].SetZs(bats[i].GetVector(0).Length(), proc.Mp()) 1190 } 1191 return bats, nil 1192 } 1193 */ 1194 1195 // func partitionDeleteBatch(tbl *txnTable, bat *batch.Batch) ([]*batch.Batch, error) { 1196 // txn := tbl.db.txn 1197 // parts := tbl.getParts() 1198 // bats := make([]*batch.Batch, len(parts)) 1199 // for i := range bats { 1200 // bats[i] = batch.New(true, bat.Attrs) 1201 // for j := range bats[i].Vecs { 1202 // bats[i].SetVector(int32(j), vector.NewVec(*bat.GetVector(int32(j)).GetType())) 1203 // } 1204 // } 1205 // vec := bat.GetVector(0) 1206 // vs := vector.MustFixedCol[types.Rowid](vec) 1207 // for i, v := range vs { 1208 // for j, part := range parts { 1209 // var blks []BlockMeta 1210 1211 // if tbl.meta != nil { 1212 // blks = tbl.meta.blocks[j] 1213 // } 1214 // if inPartition(v, part, txn.meta.SnapshotTS, blks) { 1215 // if err := bats[j].GetVector(0).UnionOne(vec, int64(i), txn.proc.Mp()); err != nil { 1216 // for _, bat := range bats { 1217 // bat.Clean(txn.proc.Mp()) 1218 // } 1219 // return nil, err 1220 // } 1221 // break 1222 // } 1223 // } 1224 // } 1225 // for i := range bats { 1226 // bats[i].SetZs(bats[i].GetVector(0).RowCount(), txn.proc.Mp()) 1227 // } 1228 // return bats, nil 1229 // } 1230 1231 func genDatabaseKey(id uint32, name string) databaseKey { 1232 return databaseKey{ 1233 name: name, 1234 accountId: id, 1235 } 1236 } 1237 1238 func genTableKey(id uint32, name string, databaseId uint64) tableKey { 1239 return tableKey{ 1240 name: name, 1241 databaseId: databaseId, 1242 accountId: id, 1243 } 1244 } 1245 1246 func genMetaTableName(id uint64) string { 1247 return fmt.Sprintf("_%v_meta", id) 1248 } 1249 1250 func genInsertBatch(bat *batch.Batch, m *mpool.MPool) (*api.Batch, error) { 1251 var attrs []string 1252 vecs := make([]*vector.Vector, 0, 2) 1253 1254 { 1255 vec := vector.NewVec(types.T_Rowid.ToType()) 1256 for i := 0; i < bat.RowCount(); i++ { 1257 val := types.RandomRowid() 1258 if err := vector.AppendFixed(vec, val, false, m); err != nil { 1259 vec.Free(m) 1260 return nil, err 1261 } 1262 } 1263 vecs = append(vecs, vec) 1264 attrs = append(attrs, "rowid") 1265 } 1266 { 1267 var val types.TS 1268 1269 vec := vector.NewVec(types.T_TS.ToType()) 1270 for i := 0; i < bat.RowCount(); i++ { 1271 if err := vector.AppendFixed(vec, val, false, m); err != nil { 1272 vecs[0].Free(m) 1273 vec.Free(m) 1274 return nil, err 1275 } 1276 } 1277 vecs = append(vecs, vec) 1278 attrs = append(attrs, "timestamp") 1279 } 1280 bat.Vecs = append(vecs, bat.Vecs...) 1281 bat.Attrs = append(attrs, bat.Attrs...) 1282 return batch.BatchToProtoBatch(bat) 1283 } 1284 1285 func genColumnPrimaryKey(tableId uint64, name string) string { 1286 return fmt.Sprintf("%v-%v", tableId, name) 1287 } 1288 1289 // func inPartition(v types.Rowid, part *PartitionState, 1290 // ts timestamp.Timestamp, blocks []BlockMeta) bool { 1291 // if part.RowExists(v, types.TimestampToTS(ts)) { 1292 // return true 1293 // } 1294 // if len(blocks) == 0 { 1295 // return false 1296 // } 1297 // blkId := v.GetBlockid() 1298 // for _, blk := range blocks { 1299 // if blk.Info.BlockID == blkId { 1300 // return true 1301 // } 1302 // } 1303 // return false 1304 // } 1305 1306 func transferIval[T int32 | int64](v T, oid types.T) (bool, any) { 1307 switch oid { 1308 case types.T_bit: 1309 return true, uint64(v) 1310 case types.T_int8: 1311 return true, int8(v) 1312 case types.T_int16: 1313 return true, int16(v) 1314 case types.T_int32: 1315 return true, int32(v) 1316 case types.T_int64: 1317 return true, int64(v) 1318 case types.T_uint8: 1319 return true, uint8(v) 1320 case types.T_uint16: 1321 return true, uint16(v) 1322 case types.T_uint32: 1323 return true, uint32(v) 1324 case types.T_uint64: 1325 return true, uint64(v) 1326 case types.T_float32: 1327 return true, float32(v) 1328 case types.T_float64: 1329 return true, float64(v) 1330 default: 1331 return false, nil 1332 } 1333 } 1334 1335 func transferUval[T uint32 | uint64](v T, oid types.T) (bool, any) { 1336 switch oid { 1337 case types.T_bit: 1338 return true, uint64(v) 1339 case types.T_int8: 1340 return true, int8(v) 1341 case types.T_int16: 1342 return true, int16(v) 1343 case types.T_int32: 1344 return true, int32(v) 1345 case types.T_int64: 1346 return true, int64(v) 1347 case types.T_uint8: 1348 return true, uint8(v) 1349 case types.T_uint16: 1350 return true, uint16(v) 1351 case types.T_uint32: 1352 return true, uint32(v) 1353 case types.T_uint64: 1354 return true, uint64(v) 1355 case types.T_float32: 1356 return true, float32(v) 1357 case types.T_float64: 1358 return true, float64(v) 1359 default: 1360 return false, nil 1361 } 1362 } 1363 1364 func transferFval(v float32, oid types.T) (bool, any) { 1365 switch oid { 1366 case types.T_float32: 1367 return true, float32(v) 1368 case types.T_float64: 1369 return true, float64(v) 1370 default: 1371 return false, nil 1372 } 1373 } 1374 1375 func transferDval(v float64, oid types.T) (bool, any) { 1376 switch oid { 1377 case types.T_float32: 1378 return true, float32(v) 1379 case types.T_float64: 1380 return true, float64(v) 1381 default: 1382 return false, nil 1383 } 1384 } 1385 1386 func transferSval(v string, oid types.T) (bool, any) { 1387 switch oid { 1388 case types.T_json: 1389 return true, []byte(v) 1390 case types.T_char, types.T_varchar: 1391 return true, []byte(v) 1392 case types.T_text, types.T_blob: 1393 return true, []byte(v) 1394 case types.T_binary, types.T_varbinary: 1395 return true, []byte(v) 1396 case types.T_uuid: 1397 var uv types.Uuid 1398 copy(uv[:], []byte(v)[:]) 1399 return true, uv 1400 //TODO: should we add T_array for this code? 1401 default: 1402 return false, nil 1403 } 1404 } 1405 1406 func transferBval(v bool, oid types.T) (bool, any) { 1407 switch oid { 1408 case types.T_bool: 1409 return true, v 1410 default: 1411 return false, nil 1412 } 1413 } 1414 1415 func transferDateval(v int32, oid types.T) (bool, any) { 1416 switch oid { 1417 case types.T_date: 1418 return true, types.Date(v) 1419 default: 1420 return false, nil 1421 } 1422 } 1423 1424 func transferTimeval(v int64, oid types.T) (bool, any) { 1425 switch oid { 1426 case types.T_time: 1427 return true, types.Time(v) 1428 default: 1429 return false, nil 1430 } 1431 } 1432 1433 func transferDatetimeval(v int64, oid types.T) (bool, any) { 1434 switch oid { 1435 case types.T_datetime: 1436 return true, types.Datetime(v) 1437 default: 1438 return false, nil 1439 } 1440 } 1441 1442 func transferTimestampval(v int64, oid types.T) (bool, any) { 1443 switch oid { 1444 case types.T_timestamp: 1445 return true, types.Timestamp(v) 1446 default: 1447 return false, nil 1448 } 1449 } 1450 1451 func transferDecimal64val(v int64, oid types.T) (bool, any) { 1452 switch oid { 1453 case types.T_decimal64: 1454 return true, types.Decimal64(v) 1455 default: 1456 return false, nil 1457 } 1458 } 1459 1460 func transferDecimal128val(a, b int64, oid types.T) (bool, any) { 1461 switch oid { 1462 case types.T_decimal128: 1463 return true, types.Decimal128{B0_63: uint64(a), B64_127: uint64(b)} 1464 default: 1465 return false, nil 1466 } 1467 } 1468 1469 func groupBlocksToObjects(blkInfos []*objectio.BlockInfo, dop int) ([][]*objectio.BlockInfo, []int) { 1470 var infos [][]*objectio.BlockInfo 1471 objMap := make(map[string]int) 1472 lenObjs := 0 1473 for _, blkInfo := range blkInfos { 1474 //block := catalog.DecodeBlockInfo(blkInfos[i]) 1475 objName := blkInfo.MetaLocation().Name().String() 1476 if idx, ok := objMap[objName]; ok { 1477 infos[idx] = append(infos[idx], blkInfo) 1478 } else { 1479 objMap[objName] = lenObjs 1480 lenObjs++ 1481 infos = append(infos, []*objectio.BlockInfo{blkInfo}) 1482 } 1483 } 1484 steps := make([]int, len(infos)) 1485 currentBlocks := 0 1486 for i := range infos { 1487 steps[i] = (currentBlocks-PREFETCH_THRESHOLD)/dop - PREFETCH_ROUNDS 1488 if steps[i] < 0 { 1489 steps[i] = 0 1490 } 1491 currentBlocks += len(infos[i]) 1492 } 1493 return infos, steps 1494 } 1495 1496 func newBlockReaders(ctx context.Context, fs fileservice.FileService, tblDef *plan.TableDef, 1497 ts timestamp.Timestamp, num int, expr *plan.Expr, 1498 proc *process.Process) []*blockReader { 1499 rds := make([]*blockReader, num) 1500 for i := 0; i < num; i++ { 1501 rds[i] = newBlockReader( 1502 ctx, tblDef, ts, nil, expr, fs, proc, 1503 ) 1504 } 1505 return rds 1506 } 1507 1508 func distributeBlocksToBlockReaders(rds []*blockReader, numOfReaders int, numOfBlocks int, infos [][]*objectio.BlockInfo, steps []int) []*blockReader { 1509 readerIndex := 0 1510 for i := range infos { 1511 //distribute objects and steps for prefetch 1512 rds[readerIndex].steps = append(rds[readerIndex].steps, steps[i]) 1513 rds[readerIndex].infos = append(rds[readerIndex].infos, infos[i]) 1514 for j := range infos[i] { 1515 //distribute block 1516 rds[readerIndex].blks = append(rds[readerIndex].blks, infos[i][j]) 1517 readerIndex++ 1518 readerIndex = readerIndex % numOfReaders 1519 } 1520 } 1521 scanType := NORMAL 1522 if numOfBlocks < numOfReaders*SMALLSCAN_THRESHOLD { 1523 scanType = SMALL 1524 } else if (numOfReaders * LARGESCAN_THRESHOLD) <= numOfBlocks { 1525 scanType = LARGE 1526 } 1527 for i := range rds { 1528 rds[i].scanType = scanType 1529 } 1530 return rds 1531 }