-
Notifications
You must be signed in to change notification settings - Fork 265
/
ddl.go
3178 lines (2922 loc) · 86.9 KB
/
ddl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 Matrix Origin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package compile
import (
"context"
"fmt"
"math"
"strings"
"github.com/matrixorigin/matrixone/pkg/catalog"
"github.com/matrixorigin/matrixone/pkg/common/moerr"
"github.com/matrixorigin/matrixone/pkg/compress"
"github.com/matrixorigin/matrixone/pkg/container/batch"
"github.com/matrixorigin/matrixone/pkg/container/types"
"github.com/matrixorigin/matrixone/pkg/container/vector"
"github.com/matrixorigin/matrixone/pkg/defines"
"github.com/matrixorigin/matrixone/pkg/incrservice"
"github.com/matrixorigin/matrixone/pkg/pb/api"
"github.com/matrixorigin/matrixone/pkg/pb/lock"
"github.com/matrixorigin/matrixone/pkg/pb/plan"
"github.com/matrixorigin/matrixone/pkg/sql/colexec/lockop"
"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
plan2 "github.com/matrixorigin/matrixone/pkg/sql/plan"
"github.com/matrixorigin/matrixone/pkg/sql/plan/function"
"github.com/matrixorigin/matrixone/pkg/txn/client"
"github.com/matrixorigin/matrixone/pkg/util/trace"
"github.com/matrixorigin/matrixone/pkg/vm/engine"
"github.com/matrixorigin/matrixone/pkg/vm/process"
"go.uber.org/zap"
"golang.org/x/exp/constraints"
)
func (s *Scope) CreateDatabase(c *Compile) error {
var span trace.Span
c.ctx, span = trace.Start(c.ctx, "CreateDatabase")
defer span.End()
dbName := s.Plan.GetDdl().GetCreateDatabase().GetDatabase()
if _, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator); err == nil {
if s.Plan.GetDdl().GetCreateDatabase().GetIfNotExists() {
return nil
}
return moerr.NewDBAlreadyExists(c.ctx, dbName)
}
if err := lockMoDatabase(c, dbName); err != nil {
return err
}
ctx := context.WithValue(c.ctx, defines.SqlKey{}, s.Plan.GetDdl().GetCreateDatabase().GetSql())
datType := ""
if s.Plan.GetDdl().GetCreateDatabase().SubscriptionOption != nil {
datType = catalog.SystemDBTypeSubscription
}
ctx = context.WithValue(ctx, defines.DatTypKey{}, datType)
return c.e.Create(ctx, dbName, c.proc.TxnOperator)
}
func (s *Scope) DropDatabase(c *Compile) error {
dbName := s.Plan.GetDdl().GetDropDatabase().GetDatabase()
if _, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator); err != nil {
if s.Plan.GetDdl().GetDropDatabase().GetIfExists() {
return nil
}
return moerr.NewErrDropNonExistsDB(c.ctx, dbName)
}
if err := lockMoDatabase(c, dbName); err != nil {
return err
}
sql := s.Plan.GetDdl().GetDropDatabase().GetCheckFKSql()
if len(sql) != 0 {
err := runDetectFkReferToDBSql(c, sql)
if err != nil {
return err
}
}
// whether foreign_key_checks = 0 or 1
err := s.removeFkeysRelationships(c, dbName)
if err != nil {
return err
}
err = c.e.Delete(c.ctx, dbName, c.proc.TxnOperator)
if err != nil {
return err
}
// 1.delete all index object record under the database from mo_catalog.mo_indexes
deleteSql := fmt.Sprintf(deleteMoIndexesWithDatabaseIdFormat, s.Plan.GetDdl().GetDropDatabase().GetDatabaseId())
err = c.runSql(deleteSql)
if err != nil {
return err
}
// 2.delete all partition object record under the database from mo_catalog.mo_table_partitions
deleteSql = fmt.Sprintf(deleteMoTablePartitionsWithDatabaseIdFormat, s.Plan.GetDdl().GetDropDatabase().GetDatabaseId())
err = c.runSql(deleteSql)
if err != nil {
return err
}
//3. delete fks
err = c.runSql(s.Plan.GetDdl().GetDropDatabase().GetUpdateFkSql())
if err != nil {
return err
}
return nil
}
func (s *Scope) removeFkeysRelationships(c *Compile, dbName string) error {
database, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
if err != nil {
return err
}
relations, err := database.Relations(c.ctx)
if err != nil {
return err
}
for _, rel := range relations {
relation, err := database.Relation(c.ctx, rel, nil)
if err != nil {
return err
}
tblId := relation.GetTableID(c.ctx)
fkeys, refChild, err := s.getFkDefs(c, relation)
if err != nil {
return err
}
//remove tblId from the parent table
for _, fkey := range fkeys.Fkeys {
if fkey.ForeignTbl == 0 {
continue
}
_, _, parentTable, err := c.e.GetRelationById(c.ctx, c.proc.TxnOperator, fkey.ForeignTbl)
if err != nil {
return err
}
err = s.removeChildTblIdFromParentTable(c, parentTable, tblId)
if err != nil {
return err
}
}
//remove tblId from the child table
for _, childId := range refChild.Tables {
if childId == 0 {
continue
}
_, _, childTable, err := c.e.GetRelationById(c.ctx, c.proc.TxnOperator, childId)
if err != nil {
return err
}
err = s.removeParentTblIdFromChildTable(c, childTable, tblId)
if err != nil {
return err
}
}
}
return nil
}
// Drop the old view, and create the new view.
func (s *Scope) AlterView(c *Compile) error {
qry := s.Plan.GetDdl().GetAlterView()
dbName := c.db
tblName := qry.GetTableDef().GetName()
dbSource, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
if err != nil {
if qry.GetIfExists() {
return nil
}
return err
}
if _, err = dbSource.Relation(c.ctx, tblName, nil); err != nil {
if qry.GetIfExists() {
return nil
}
return err
}
if err := lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); err != nil {
return err
}
// Drop view table.
if err := dbSource.Delete(c.ctx, tblName); err != nil {
return err
}
// Create view table.
// convert the plan's cols to the execution's cols
planCols := qry.GetTableDef().GetCols()
exeCols := planColsToExeCols(planCols)
// convert the plan's defs to the execution's defs
exeDefs, err := planDefsToExeDefs(qry.GetTableDef())
if err != nil {
return err
}
// if _, err := dbSource.Relation(c.ctx, tblName); err == nil {
// return moerr.NewTableAlreadyExists(c.ctx, tblName)
// }
return dbSource.Create(context.WithValue(c.ctx, defines.SqlKey{}, c.sql), tblName, append(exeCols, exeDefs...))
}
func addAlterKind(alterKind []api.AlterKind, kind api.AlterKind) []api.AlterKind {
for i := range alterKind {
if alterKind[i] == kind {
return alterKind
}
}
alterKind = append(alterKind, kind)
return alterKind
}
func getAddColPos(cols []*plan.ColDef, def *plan.ColDef, colName string, pos int32) ([]*plan.ColDef, int32, error) {
if pos == 0 {
cols = append([]*plan.ColDef{def}, cols...)
return cols, pos, nil
} else if pos == -1 {
length := len(cols)
cols = append(cols, nil)
copy(cols[length:], cols[length-1:])
cols[length-1] = def
return cols, int32(length - 1), nil
}
var idx int
for idx = 0; idx < len(cols); idx++ {
if cols[idx].Name == colName {
cols = append(cols, nil)
copy(cols[idx+2:], cols[idx+1:])
cols[idx+1] = def
return cols, int32(idx + 1), nil
}
}
return nil, 0, moerr.NewInvalidInputNoCtx("column '%s' doesn't exist in table", colName)
}
func (s *Scope) AlterTableInplace(c *Compile) error {
qry := s.Plan.GetDdl().GetAlterTable()
dbName := qry.Database
if dbName == "" {
dbName = c.db
}
tblName := qry.GetTableDef().GetName()
dbSource, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
if err != nil {
return err
}
databaseId := dbSource.GetDatabaseId(c.ctx)
rel, err := dbSource.Relation(c.ctx, tblName, nil)
if err != nil {
return err
}
tblId := rel.GetTableID(c.ctx)
tableDef := plan2.DeepCopyTableDef(qry.TableDef, true)
oldCt, err := GetConstraintDef(c.ctx, rel)
if err != nil {
return err
}
if c.proc.TxnOperator.Txn().IsPessimistic() {
var retryErr error
// 1. lock origin table metadata in catalog
if err = lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); err != nil {
if !moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetry) &&
!moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetryWithDefChanged) {
return err
}
retryErr = err
}
// 2. lock origin table
var partitionTableNames []string
if tableDef.Partition != nil {
partitionTableNames = tableDef.Partition.PartitionTableNames
}
if err = lockTable(c.ctx, c.e, c.proc, rel, dbName, partitionTableNames, true); err != nil {
if !moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetry) &&
!moerr.IsMoErrCode(err, moerr.ErrTxnNeedRetryWithDefChanged) {
return err
}
retryErr = err
}
if retryErr != nil {
return retryErr
}
}
newCt := &engine.ConstraintDef{
Cts: []engine.Constraint{},
}
//added fk in this alter table statement
newAddedFkNames := make(map[string]bool)
/*
collect old fk names.
ForeignKeyDef.Name may be empty in previous design.
So, we only use ForeignKeyDef.Name that is no empty.
*/
oldFkNames := make(map[string]bool)
for _, ct := range oldCt.Cts {
switch t := ct.(type) {
case *engine.ForeignKeyDef:
for _, fkey := range t.Fkeys {
if len(fkey.Name) != 0 {
oldFkNames[fkey.Name] = true
}
}
}
}
removeRefChildTbls := make(map[string]uint64)
var addRefChildTbls []uint64
var newFkeys []*plan.ForeignKeyDef
var addIndex []*plan.IndexDef
var dropIndexMap = make(map[string]bool)
var alterIndex *plan.IndexDef
var alterKinds []api.AlterKind
var comment string
var oldName, newName string
var addCol []*plan.AlterAddColumn
var dropCol []*plan.AlterDropColumn
var changePartitionDef *plan.PartitionByDef
cols := tableDef.Cols
// drop foreign key
for _, action := range qry.Actions {
switch act := action.Action.(type) {
case *plan.AlterTable_Action_Drop:
alterTableDrop := act.Drop
constraintName := alterTableDrop.Name
if alterTableDrop.Typ == plan.AlterTableDrop_FOREIGN_KEY {
//check fk existed in table
if _, has := oldFkNames[constraintName]; !has {
return moerr.NewErrCantDropFieldOrKey(c.ctx, constraintName)
}
alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
for i, fk := range tableDef.Fkeys {
if fk.Name == constraintName {
removeRefChildTbls[constraintName] = fk.ForeignTbl
tableDef.Fkeys = append(tableDef.Fkeys[:i], tableDef.Fkeys[i+1:]...)
break
}
}
} else if alterTableDrop.Typ == plan.AlterTableDrop_INDEX {
alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
var notDroppedIndex []*plan.IndexDef
for _, indexdef := range tableDef.Indexes {
if indexdef.IndexName == constraintName {
dropIndexMap[indexdef.IndexName] = true
//1. drop index table
if indexdef.TableExist {
if _, err = dbSource.Relation(c.ctx, indexdef.IndexTableName, nil); err != nil {
return err
}
if err = dbSource.Delete(c.ctx, indexdef.IndexTableName); err != nil {
return err
}
}
//2. delete index object from mo_catalog.mo_indexes
deleteSql := fmt.Sprintf(deleteMoIndexesWithTableIdAndIndexNameFormat, tableDef.TblId, indexdef.IndexName)
err = c.runSql(deleteSql)
if err != nil {
return err
}
} else {
notDroppedIndex = append(notDroppedIndex, indexdef)
}
}
// Avoid modifying slice directly during iteration
tableDef.Indexes = notDroppedIndex
} else if alterTableDrop.Typ == plan.AlterTableDrop_COLUMN {
alterKinds = append(alterKinds, api.AlterKind_DropColumn)
var idx int
for idx = 0; idx < len(cols); idx++ {
if cols[idx].Name == constraintName {
drop := &plan.AlterDropColumn{
Idx: uint32(idx),
Seq: cols[idx].Seqnum,
}
dropCol = append(dropCol, drop)
copy(cols[idx:], cols[idx+1:])
cols = cols[0 : len(cols)-1]
break
}
}
}
case *plan.AlterTable_Action_AddFk:
//check fk existed in table
if _, has := oldFkNames[act.AddFk.Fkey.Name]; has {
return moerr.NewErrDuplicateKeyName(c.ctx, act.AddFk.Fkey.Name)
}
//check fk existed in this alter table statement
if _, has := newAddedFkNames[act.AddFk.Fkey.Name]; has {
return moerr.NewErrDuplicateKeyName(c.ctx, act.AddFk.Fkey.Name)
}
newAddedFkNames[act.AddFk.Fkey.Name] = true
alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
addRefChildTbls = append(addRefChildTbls, act.AddFk.Fkey.ForeignTbl)
newFkeys = append(newFkeys, act.AddFk.Fkey)
case *plan.AlterTable_Action_AddIndex:
alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
indexInfo := act.AddIndex.IndexInfo // IndexInfo is named same as planner's IndexInfo
indexTableDef := act.AddIndex.IndexInfo.TableDef
// indexName -> meta -> indexDef
// -> centroids -> indexDef
// -> entries -> indexDef
multiTableIndexes := make(map[string]*MultiTableIndex)
for _, indexDef := range indexTableDef.Indexes {
for i := range addIndex {
if indexDef.IndexName == addIndex[i].IndexName {
return moerr.NewDuplicateKey(c.ctx, indexDef.IndexName)
}
}
addIndex = append(addIndex, indexDef)
if indexDef.Unique {
// 1. Unique Index related logic
err = s.handleUniqueIndexTable(c, indexDef, qry.Database, tableDef, indexInfo)
} else if !indexDef.Unique && catalog.IsRegularIndexAlgo(indexDef.IndexAlgo) {
// 2. Regular Secondary index
err = s.handleRegularSecondaryIndexTable(c, indexDef, qry.Database, tableDef, indexInfo)
} else if !indexDef.Unique && catalog.IsMasterIndexAlgo(indexDef.IndexAlgo) {
// 3. Master index
err = s.handleMasterIndexTable(c, indexDef, qry.Database, tableDef, indexInfo)
} else if !indexDef.Unique && catalog.IsIvfIndexAlgo(indexDef.IndexAlgo) {
// 4. IVF indexDefs are aggregated and handled later
if _, ok := multiTableIndexes[indexDef.IndexName]; !ok {
multiTableIndexes[indexDef.IndexName] = &MultiTableIndex{
IndexAlgo: catalog.ToLower(indexDef.IndexAlgo),
IndexDefs: make(map[string]*plan.IndexDef),
}
}
multiTableIndexes[indexDef.IndexName].IndexDefs[catalog.ToLower(indexDef.IndexAlgoTableType)] = indexDef
}
if err != nil {
return err
}
}
for _, multiTableIndex := range multiTableIndexes {
switch multiTableIndex.IndexAlgo { // no need for catalog.ToLower() here
case catalog.MoIndexIvfFlatAlgo.ToString():
err = s.handleVectorIvfFlatIndex(c, multiTableIndex.IndexDefs, qry.Database, tableDef, indexInfo)
}
if err != nil {
return err
}
}
//1. build and update constraint def
for _, indexDef := range indexTableDef.Indexes {
insertSql, err := makeInsertSingleIndexSQL(c.e, c.proc, databaseId, tblId, indexDef)
if err != nil {
return err
}
err = c.runSql(insertSql)
if err != nil {
return err
}
}
case *plan.AlterTable_Action_AlterIndex:
alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
tableAlterIndex := act.AlterIndex
constraintName := tableAlterIndex.IndexName
for i, indexdef := range tableDef.Indexes {
if indexdef.IndexName == constraintName {
alterIndex = indexdef
alterIndex.Visible = tableAlterIndex.Visible
tableDef.Indexes[i].Visible = tableAlterIndex.Visible
// update the index visibility in mo_catalog.mo_indexes
var updateSql string
if alterIndex.Visible {
updateSql = fmt.Sprintf(updateMoIndexesVisibleFormat, 1, tableDef.TblId, indexdef.IndexName)
} else {
updateSql = fmt.Sprintf(updateMoIndexesVisibleFormat, 0, tableDef.TblId, indexdef.IndexName)
}
err = c.runSql(updateSql)
if err != nil {
return err
}
break
}
}
case *plan.AlterTable_Action_AlterReindex:
// NOTE: We hold lock (with retry) during alter reindex, as "alter table" takes an exclusive lock
//in the beginning for pessimistic mode. We need to see how to reduce the critical section.
alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateConstraint)
tableAlterIndex := act.AlterReindex
constraintName := tableAlterIndex.IndexName
multiTableIndexes := make(map[string]*MultiTableIndex)
for i, indexDef := range tableDef.Indexes {
if indexDef.IndexName == constraintName {
alterIndex = indexDef
// 1. Get old AlgoParams
newAlgoParamsMap, err := catalog.IndexParamsStringToMap(alterIndex.IndexAlgoParams)
if err != nil {
return err
}
// 2.a update AlgoParams for the index to be re-indexed
// NOTE: this will throw error if the algo type is not supported for reindex.
// So Step 4. will not be executed if error is thrown here.
indexAlgo := catalog.ToLower(alterIndex.IndexAlgo)
switch catalog.ToLower(indexAlgo) {
case catalog.MoIndexIvfFlatAlgo.ToString():
newAlgoParamsMap[catalog.IndexAlgoParamLists] = fmt.Sprintf("%d", tableAlterIndex.IndexAlgoParamList)
default:
return moerr.NewInternalError(c.ctx, "invalid index algo type for alter reindex")
}
// 2.b generate new AlgoParams string
newAlgoParams, err := catalog.IndexParamsMapToJsonString(newAlgoParamsMap)
if err != nil {
return err
}
// 3.a Update IndexDef and TableDef
alterIndex.IndexAlgoParams = newAlgoParams
tableDef.Indexes[i].IndexAlgoParams = newAlgoParams
// 3.b Update mo_catalog.mo_indexes
updateSql := fmt.Sprintf(updateMoIndexesAlgoParams, newAlgoParams, tableDef.TblId, alterIndex.IndexName)
err = c.runSql(updateSql)
if err != nil {
return err
}
// 4. Add to multiTableIndexes
if _, ok := multiTableIndexes[indexDef.IndexName]; !ok {
multiTableIndexes[indexDef.IndexName] = &MultiTableIndex{
IndexAlgo: catalog.ToLower(indexDef.IndexAlgo),
IndexDefs: make(map[string]*plan.IndexDef),
}
}
multiTableIndexes[indexDef.IndexName].IndexDefs[catalog.ToLower(indexDef.IndexAlgoTableType)] = indexDef
}
}
if len(multiTableIndexes) != 1 {
return moerr.NewInternalError(c.ctx, "invalid index algo type for alter reindex")
}
// update the hidden tables
for _, multiTableIndex := range multiTableIndexes {
switch multiTableIndex.IndexAlgo {
case catalog.MoIndexIvfFlatAlgo.ToString():
err = s.handleVectorIvfFlatIndex(c, multiTableIndex.IndexDefs, qry.Database, tableDef, nil)
}
if err != nil {
return err
}
}
case *plan.AlterTable_Action_AlterComment:
alterKinds = addAlterKind(alterKinds, api.AlterKind_UpdateComment)
comment = act.AlterComment.NewComment
case *plan.AlterTable_Action_AlterName:
alterKinds = addAlterKind(alterKinds, api.AlterKind_RenameTable)
oldName = act.AlterName.OldName
newName = act.AlterName.NewName
case *plan.AlterTable_Action_AddColumn:
alterKinds = append(alterKinds, api.AlterKind_AddColumn)
col := &plan.ColDef{
Name: act.AddColumn.Name,
Alg: plan.CompressType_Lz4,
Typ: act.AddColumn.Type,
}
var pos int32
cols, pos, err = getAddColPos(cols, col, act.AddColumn.PreName, act.AddColumn.Pos)
if err != nil {
return err
}
act.AddColumn.Pos = pos
addCol = append(addCol, act.AddColumn)
case *plan.AlterTable_Action_AddPartition:
alterKinds = append(alterKinds, api.AlterKind_AddPartition)
changePartitionDef = act.AddPartition.PartitionDef
partitionTables := act.AddPartition.GetPartitionTables()
for _, table := range partitionTables {
storageCols := planColsToExeCols(table.GetCols())
storageDefs, err := planDefsToExeDefs(table)
if err != nil {
return err
}
err = dbSource.Create(c.ctx, table.GetName(), append(storageCols, storageDefs...))
if err != nil {
return err
}
}
insertMoTablePartitionSql := genInsertMoTablePartitionsSql(databaseId, tblId, act.AddPartition.PartitionDef, act.AddPartition.Definitions)
err = c.runSql(insertMoTablePartitionSql)
if err != nil {
return err
}
}
}
// reset origin table's constraint
originHasFkDef := false
originHasIndexDef := false
for _, ct := range oldCt.Cts {
switch t := ct.(type) {
case *engine.ForeignKeyDef:
for _, fkey := range t.Fkeys {
//For compatibility, regenerate constraint name for the constraint with empty name.
if len(fkey.Name) == 0 {
fkey.Name = plan2.GenConstraintName()
newFkeys = append(newFkeys, fkey)
} else if _, ok := removeRefChildTbls[fkey.Name]; !ok {
newFkeys = append(newFkeys, fkey)
}
}
t.Fkeys = newFkeys
originHasFkDef = true
newCt.Cts = append(newCt.Cts, t)
case *engine.RefChildTableDef:
newCt.Cts = append(newCt.Cts, t)
case *engine.IndexDef:
originHasIndexDef = true
// NOTE: using map and remainingIndexes slice here to avoid "Modifying a Slice During Iteration".
var remainingIndexes []*plan.IndexDef
for _, idx := range t.Indexes {
if !dropIndexMap[idx.IndexName] {
remainingIndexes = append(remainingIndexes, idx)
}
}
t.Indexes = remainingIndexes
t.Indexes = append(t.Indexes, addIndex...)
if alterIndex != nil {
for i, idx := range t.Indexes {
if alterIndex.IndexName == idx.IndexName {
t.Indexes[i].Visible = alterIndex.Visible
// NOTE: algo param is same for all the indexDefs of the same indexName.
// ie for IVFFLAT: meta, centroids, entries all have same algo params.
// so we don't need multiple `alterIndex`.
t.Indexes[i].IndexAlgoParams = alterIndex.IndexAlgoParams
}
}
}
newCt.Cts = append(newCt.Cts, t)
case *engine.PrimaryKeyDef:
newCt.Cts = append(newCt.Cts, t)
}
}
if !originHasFkDef {
newCt.Cts = append(newCt.Cts, &engine.ForeignKeyDef{
Fkeys: newFkeys,
})
}
if !originHasIndexDef && addIndex != nil {
newCt.Cts = append(newCt.Cts, &engine.IndexDef{
Indexes: addIndex,
})
}
var addColIdx int
var dropColIdx int
constraint := make([][]byte, 0)
for _, kind := range alterKinds {
var req *api.AlterTableReq
switch kind {
case api.AlterKind_UpdateConstraint:
ct, err := newCt.MarshalBinary()
if err != nil {
return err
}
req = api.NewUpdateConstraintReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), string(ct))
case api.AlterKind_UpdateComment:
req = api.NewUpdateCommentReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), comment)
case api.AlterKind_RenameTable:
req = api.NewRenameTableReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), oldName, newName)
case api.AlterKind_AddColumn:
name := addCol[addColIdx].Name
typ := &addCol[addColIdx].Type
pos := addCol[addColIdx].Pos
addColIdx++
req = api.NewAddColumnReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), name, typ, pos)
case api.AlterKind_DropColumn:
req = api.NewRemoveColumnReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), dropCol[dropColIdx].Idx, dropCol[dropColIdx].Seq)
dropColIdx++
case api.AlterKind_AddPartition:
req = api.NewAddPartitionReq(rel.GetDBID(c.ctx), rel.GetTableID(c.ctx), changePartitionDef)
default:
}
tmp, err := req.Marshal()
if err != nil {
return err
}
constraint = append(constraint, tmp)
}
err = rel.AlterTable(c.ctx, newCt, constraint)
if err != nil {
return err
}
// remove refChildTbls for drop foreign key clause
//remove the child table id -- tblId from the parent table -- fkTblId
for _, fkTblId := range removeRefChildTbls {
var fkRelation engine.Relation
if fkTblId == 0 {
//fk self refer
fkRelation = rel
} else {
_, _, fkRelation, err = c.e.GetRelationById(c.ctx, c.proc.TxnOperator, fkTblId)
if err != nil {
return err
}
}
err = s.removeChildTblIdFromParentTable(c, fkRelation, tblId)
if err != nil {
return err
}
}
// append refChildTbls for add foreign key clause
//add the child table id -- tblId into the parent table -- fkTblId
for _, fkTblId := range addRefChildTbls {
if fkTblId == 0 {
//fk self refer
err = AddChildTblIdToParentTable(c.ctx, rel, fkTblId)
if err != nil {
return err
}
} else {
_, _, fkRelation, err := c.e.GetRelationById(c.ctx, c.proc.TxnOperator, fkTblId)
if err != nil {
return err
}
err = AddChildTblIdToParentTable(c.ctx, fkRelation, tblId)
if err != nil {
return err
}
}
}
return nil
}
func (s *Scope) CreateTable(c *Compile) error {
qry := s.Plan.GetDdl().GetCreateTable()
// convert the plan's cols to the execution's cols
planCols := qry.GetTableDef().GetCols()
exeCols := planColsToExeCols(planCols)
// TODO: debug for #11917
if strings.Contains(qry.GetTableDef().GetName(), "sbtest") {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.String("txnID", c.proc.TxnOperator.Txn().DebugString()),
)
}
// convert the plan's defs to the execution's defs
exeDefs, err := planDefsToExeDefs(qry.GetTableDef())
if err != nil {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.Error(err),
)
return err
}
dbName := c.db
if qry.GetDatabase() != "" {
dbName = qry.GetDatabase()
}
tblName := qry.GetTableDef().GetName()
dbSource, err := c.e.Database(c.ctx, dbName, c.proc.TxnOperator)
if err != nil {
if dbName == "" {
// TODO: debug for #11917
if strings.Contains(qry.GetTableDef().GetName(), "sbtest") {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.String("txnID", c.proc.TxnOperator.Txn().DebugString()),
)
}
return moerr.NewNoDB(c.ctx)
}
// TODO: debug for #11917
if strings.Contains(qry.GetTableDef().GetName(), "sbtest") {
getLogger().Info("createTable no exist",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.String("txnID", c.proc.TxnOperator.Txn().DebugString()),
)
}
return err
}
if _, err := dbSource.Relation(c.ctx, tblName, nil); err == nil {
if qry.GetIfNotExists() {
// TODO: debug for #11917
if strings.Contains(qry.GetTableDef().GetName(), "sbtest") {
getLogger().Info("createTable no exist",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.String("txnID", c.proc.TxnOperator.Txn().DebugString()),
)
}
return nil
}
if qry.GetReplace() {
err := c.runSql(fmt.Sprintf("drop view if exists %s", tblName))
if err != nil {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.Error(err),
)
return err
}
} else {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.Error(err),
)
return moerr.NewTableAlreadyExists(c.ctx, tblName)
}
}
// check in EntireEngine.TempEngine, notice that TempEngine may not init
tmpDBSource, err := c.e.Database(c.ctx, defines.TEMPORARY_DBNAME, c.proc.TxnOperator)
if err == nil {
if _, err := tmpDBSource.Relation(c.ctx, engine.GetTempTableName(dbName, tblName), nil); err == nil {
if qry.GetIfNotExists() {
return nil
}
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.Error(err),
)
return moerr.NewTableAlreadyExists(c.ctx, fmt.Sprintf("temporary '%s'", tblName))
}
}
if err := lockMoTable(c, dbName, tblName, lock.LockMode_Exclusive); err != nil {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.Error(err),
)
return err
}
if err := dbSource.Create(context.WithValue(c.ctx, defines.SqlKey{}, c.sql), tblName, append(exeCols, exeDefs...)); err != nil {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.Error(err),
)
return err
}
// TODO: debug for #11917
if strings.Contains(qry.GetTableDef().GetName(), "sbtest") {
getLogger().Info("createTable ok",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.String("txnID", c.proc.TxnOperator.Txn().DebugString()),
)
}
partitionTables := qry.GetPartitionTables()
for _, table := range partitionTables {
storageCols := planColsToExeCols(table.GetCols())
storageDefs, err := planDefsToExeDefs(table)
if err != nil {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.Error(err),
)
return err
}
err = dbSource.Create(c.ctx, table.GetName(), append(storageCols, storageDefs...))
if err != nil {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.Error(err),
)
return err
}
}
//update mo_foreign_keys
for _, sql := range qry.UpdateFkSqls {
err = c.runSql(sql)
if err != nil {
return err
}
}
// handle fk that refers to others tables
fkDbs := qry.GetFkDbs()
if len(fkDbs) > 0 {
fkTables := qry.GetFkTables()
//get the relation of created table above again.
//due to the colId may be changed.
newRelation, err := dbSource.Relation(c.ctx, tblName, nil)
if err != nil {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.Error(err),
)
return err
}
tblId := newRelation.GetTableID(c.ctx)
newTableDef, err := newRelation.TableDefs(c.ctx)
if err != nil {
getLogger().Info("createTable",
zap.String("databaseName", c.db),
zap.String("tableName", qry.GetTableDef().GetName()),
zap.Error(err),
)
return err
}
oldCt := GetConstraintDefFromTableDefs(newTableDef)
//get the columnId of the column from newTableDef
var colNameToId = make(map[string]uint64)
for _, def := range newTableDef {
if attr, ok := def.(*engine.AttributeDef); ok {
colNameToId[attr.Attr.Name] = attr.Attr.ID
}
}
//old colId -> colName
colId2Name := make(map[uint64]string)
for _, col := range planCols {
colId2Name[col.ColId] = col.Name
}
//1. update fk info in child table.
//column ids of column names in child table have changed after
//the table is created by engine.Database.Create.
//refresh column ids of column names in child table.
newFkeys := make([]*plan.ForeignKeyDef, len(qry.GetTableDef().Fkeys))
for i, fkey := range qry.GetTableDef().Fkeys {
newDef := &plan.ForeignKeyDef{
Name: fkey.Name,
Cols: make([]uint64, len(fkey.Cols)),
ForeignTbl: fkey.ForeignTbl,
ForeignCols: make([]uint64, len(fkey.ForeignCols)),
OnDelete: fkey.OnDelete,
OnUpdate: fkey.OnUpdate,
}
copy(newDef.ForeignCols, fkey.ForeignCols)
//if it is fk self, the parent table is same as the child table.
//refresh the ForeignCols also.
if fkey.ForeignTbl == 0 {
for j, colId := range fkey.ForeignCols {
//old colId -> colName
colName := colId2Name[colId]
//colName -> new colId
newDef.ForeignCols[j] = colNameToId[colName]
}