/
ddl.go
1608 lines (1459 loc) · 48.7 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 2023 Dolthub, Inc.
//
// 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 planbuilder
import (
"fmt"
"strconv"
"strings"
"github.com/dolthub/vitess/go/mysql"
ast "github.com/dolthub/vitess/go/vt/sqlparser"
"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/expression"
"github.com/dolthub/go-mysql-server/sql/expression/function"
"github.com/dolthub/go-mysql-server/sql/mysql_db"
"github.com/dolthub/go-mysql-server/sql/plan"
"github.com/dolthub/go-mysql-server/sql/types"
)
func (b *Builder) resolveDb(name string) sql.Database {
if name == "" {
err := sql.ErrNoDatabaseSelected.New()
b.handleErr(err)
}
database, err := b.cat.Database(b.ctx, name)
if err != nil {
b.handleErr(err)
}
// todo show tables as of expects privileged
//if privilegedDatabase, ok := database.(mysql_db.PrivilegedDatabase); ok {
// database = privilegedDatabase.Unwrap()
//}
return database
}
// buildAlterTable converts AlterTable AST nodes. If there is a single clause in the statement, it is returned as
// the appropriate node type. Otherwise, a plan.Block is returned with children representing all the various clauses.
// Our validation rules for what counts as a legal set of alter clauses differs from mysql's here. MySQL seems to apply
// some form of precedence rules to the clauses in an ALTER TABLE so that e.g. DROP COLUMN always happens before other
// kinds of statements. So in MySQL, statements like `ALTER TABLE t ADD KEY (a), DROP COLUMN a` fails, whereas our
// analyzer happily produces a plan that adds an index and then drops that column. We do this in part for simplicity,
// and also because we construct more than one node per clause in some cases and really want them executed in a
// particular order in that case.
func (b *Builder) buildAlterTable(inScope *scope, query string, c *ast.AlterTable) (outScope *scope) {
b.multiDDL = true
defer func() {
b.multiDDL = false
}()
statements := make([]sql.Node, 0, len(c.Statements))
for i := 0; i < len(c.Statements); i++ {
scopes := b.buildAlterTableClause(inScope, c.Statements[i])
for _, scope := range scopes {
statements = append(statements, scope.node)
}
}
if len(statements) == 1 {
outScope = inScope.push()
outScope.node = statements[0]
return outScope
}
outScope = inScope.push()
outScope.node = plan.NewBlock(statements)
return
}
func (b *Builder) buildDDL(inScope *scope, query string, c *ast.DDL) (outScope *scope) {
outScope = inScope.push()
switch strings.ToLower(c.Action) {
case ast.CreateStr:
if c.TriggerSpec != nil {
return b.buildCreateTrigger(inScope, query, c)
}
if c.ProcedureSpec != nil {
return b.buildCreateProcedure(inScope, query, c)
}
if c.EventSpec != nil {
return b.buildCreateEvent(inScope, query, c)
}
if c.ViewSpec != nil {
return b.buildCreateView(inScope, query, c)
}
return b.buildCreateTable(inScope, c)
case ast.DropStr:
// get database
if c.TriggerSpec != nil {
dbName := c.TriggerSpec.TrigName.Qualifier.String()
if dbName == "" {
dbName = b.ctx.GetCurrentDatabase()
}
trigName := c.TriggerSpec.TrigName.Name.String()
outScope.node = plan.NewDropTrigger(b.resolveDb(dbName), trigName, c.IfExists)
return
}
if c.ProcedureSpec != nil {
dbName := c.ProcedureSpec.ProcName.Qualifier.String()
if dbName == "" {
dbName = b.ctx.GetCurrentDatabase()
}
procName := c.ProcedureSpec.ProcName.Name.String()
outScope.node = plan.NewDropProcedure(b.resolveDb(dbName), procName, c.IfExists)
return
}
if c.EventSpec != nil {
dbName := c.EventSpec.EventName.Qualifier.String()
if dbName == "" {
dbName = b.ctx.GetCurrentDatabase()
}
eventName := c.EventSpec.EventName.Name.String()
outScope.node = plan.NewDropEvent(b.resolveDb(dbName), eventName, c.IfExists)
return
}
if len(c.FromViews) != 0 {
plans := make([]sql.Node, len(c.FromViews))
for i, v := range c.FromViews {
plans[i] = plan.NewSingleDropView(b.currentDb(), v.Name.String())
}
outScope.node = plan.NewDropView(plans, c.IfExists)
return
}
return b.buildDropTable(inScope, c)
case ast.AlterStr:
if c.EventSpec != nil {
return b.buildAlterEvent(inScope, query, c)
} else if !c.User.IsEmpty() {
return b.buildAlterUser(inScope, query, c)
}
b.handleErr(sql.ErrUnsupportedFeature.New(ast.String(c)))
case ast.RenameStr:
return b.buildRenameTable(inScope, c)
case ast.TruncateStr:
return b.buildTruncateTable(inScope, c)
default:
b.handleErr(sql.ErrUnsupportedSyntax.New(ast.String(c)))
}
return
}
func (b *Builder) buildDropTable(inScope *scope, c *ast.DDL) (outScope *scope) {
outScope = inScope.push()
var dropTables []sql.Node
dbName := c.FromTables[0].Qualifier.String()
if dbName == "" {
dbName = b.currentDb().Name()
}
for _, t := range c.FromTables {
if t.Qualifier.String() != "" && t.Qualifier.String() != dbName {
err := sql.ErrUnsupportedFeature.New("dropping tables on multiple databases in the same statement")
b.handleErr(err)
}
tableName := strings.ToLower(t.Name.String())
if c.IfExists {
_, _, err := b.cat.Table(b.ctx, dbName, tableName)
if sql.ErrTableNotFound.Is(err) && b.ctx != nil && b.ctx.Session != nil {
b.ctx.Session.Warn(&sql.Warning{
Level: "Note",
Code: mysql.ERBadTable,
Message: fmt.Sprintf("Unknown table '%s'", tableName),
})
continue
} else if err != nil {
b.handleErr(err)
}
}
tableScope, ok := b.buildResolvedTable(inScope, dbName, tableName, nil)
if ok {
dropTables = append(dropTables, tableScope.node)
} else if !c.IfExists {
err := sql.ErrTableNotFound.New(tableName)
b.handleErr(err)
}
}
outScope.node = plan.NewDropTable(dropTables, c.IfExists)
return
}
func (b *Builder) buildTruncateTable(inScope *scope, c *ast.DDL) (outScope *scope) {
outScope = inScope.push()
dbName := c.Table.Qualifier.String()
tabName := c.Table.Name.String()
tableScope, ok := b.buildResolvedTable(inScope, dbName, tabName, nil)
if !ok {
b.handleErr(sql.ErrTableNotFound.New(tabName))
}
outScope.node = plan.NewTruncate(
c.Table.Qualifier.String(),
tableScope.node,
)
return
}
func (b *Builder) buildCreateTable(inScope *scope, c *ast.DDL) (outScope *scope) {
outScope = inScope.push()
if c.OptLike != nil {
return b.buildCreateTableLike(inScope, c)
}
qualifier := c.Table.Qualifier.String()
if qualifier == "" {
qualifier = b.ctx.GetCurrentDatabase()
}
database := b.resolveDb(qualifier)
// In the case that no table spec is given but a SELECT Statement return the CREATE TABLE node.
// if the table spec != nil it will get parsed below.
if c.TableSpec == nil && c.OptSelect != nil {
tableSpec := &plan.TableSpec{}
selectScope := b.buildSelectStmt(inScope, c.OptSelect.Select)
outScope.node = plan.NewCreateTableSelect(database, c.Table.Name.String(), c.IfNotExists, c.Temporary, selectScope.node, tableSpec)
return outScope
}
idxDefs := b.buildIndexDefs(inScope, c.TableSpec)
schema, collation, tblOpts := b.tableSpecToSchema(inScope, outScope, database, strings.ToLower(c.Table.Name.String()), c.TableSpec, false)
fkDefs, chDefs := b.buildConstraintsDefs(outScope, c.Table, c.TableSpec)
schema.Schema = assignColumnIndexesInSchema(schema.Schema)
chDefs = assignColumnIndexesInCheckDefs(chDefs, schema.Schema)
if privDb, ok := database.(mysql_db.PrivilegedDatabase); ok {
if sv, ok := privDb.Unwrap().(sql.SchemaValidator); ok {
if err := sv.ValidateSchema(schema.PhysicalSchema()); err != nil {
b.handleErr(err)
}
}
} else {
if sv, ok := database.(sql.SchemaValidator); ok {
if err := sv.ValidateSchema(schema.PhysicalSchema()); err != nil {
b.handleErr(err)
}
}
}
tableSpec := &plan.TableSpec{
Schema: schema,
IdxDefs: idxDefs,
FkDefs: fkDefs,
ChDefs: chDefs,
Collation: collation,
TableOpts: tblOpts,
}
if c.OptSelect != nil {
selectScope := b.buildSelectStmt(inScope, c.OptSelect.Select)
outScope.node = plan.NewCreateTableSelect(database, c.Table.Name.String(), c.IfNotExists, c.Temporary, selectScope.node, tableSpec)
} else {
outScope.node = plan.NewCreateTable(
database, c.Table.Name.String(), c.IfNotExists, c.Temporary, tableSpec)
}
return
}
func assignColumnIndexesInCheckDefs(defs []*sql.CheckConstraint, schema sql.Schema) []*sql.CheckConstraint {
newDefs := make([]*sql.CheckConstraint, len(defs))
for i, def := range defs {
newDefs[i] = def
newDefs[i].Expr = assignColumnIndexes(def.Expr, schema).(sql.Expression)
}
return newDefs
}
func assignColumnIndexesInSchema(schema sql.Schema) sql.Schema {
newSch := make(sql.Schema, len(schema))
for i, col := range schema {
newSch[i] = col
if col.Default != nil {
newSch[i].Default = assignColumnIndexes(col.Default, schema).(*sql.ColumnDefaultValue)
}
if col.Generated != nil {
newSch[i].Generated = assignColumnIndexes(col.Generated, schema).(*sql.ColumnDefaultValue)
}
}
return newSch
}
func (b *Builder) buildCreateTableLike(inScope *scope, ct *ast.DDL) *scope {
tableName := ct.OptLike.LikeTable.Name.String()
likeDbName := ct.OptLike.LikeTable.Qualifier.String()
if likeDbName == "" {
likeDbName = b.ctx.GetCurrentDatabase()
}
outScope, ok := b.buildTablescan(inScope, likeDbName, tableName, nil)
if !ok {
b.handleErr(sql.ErrTableNotFound.New(tableName))
}
likeTable, ok := outScope.node.(*plan.ResolvedTable)
if !ok {
err := fmt.Errorf("expected resolved table: %s", tableName)
b.handleErr(err)
}
newTableName := strings.ToLower(ct.Table.Name.String())
outScope.setTableAlias(newTableName)
var idxDefs sql.IndexDefs
if indexableTable, ok := likeTable.Table.(sql.IndexAddressableTable); ok {
indexes, err := indexableTable.GetIndexes(b.ctx)
if err != nil {
b.handleErr(err)
}
for _, index := range indexes {
if index.IsGenerated() {
continue
}
constraint := sql.IndexConstraint_None
if index.IsUnique() {
if index.ID() == "PRIMARY" {
constraint = sql.IndexConstraint_Primary
} else {
constraint = sql.IndexConstraint_Unique
}
}
columns := make([]sql.IndexColumn, len(index.Expressions()))
for i, col := range index.Expressions() {
//TODO: find a better way to get only the column name if the table is present
col = strings.TrimPrefix(col, indexableTable.Name()+".")
columns[i] = sql.IndexColumn{Name: col}
}
idxDefs = append(idxDefs, &sql.IndexDef{
Name: index.ID(),
Storage: sql.IndexUsing_Default,
Constraint: constraint,
Columns: columns,
Comment: index.Comment(),
})
}
}
origSch := likeTable.Schema()
newSch := make(sql.Schema, len(origSch))
for i, col := range origSch {
tempCol := *col
tempCol.Source = newTableName
newSch[i] = &tempCol
}
var pkOrdinals []int
if pkTable, ok := likeTable.Table.(sql.PrimaryKeyTable); ok {
pkOrdinals = pkTable.PrimaryKeySchema().PkOrdinals
}
var checkDefs []*sql.CheckConstraint
if checksTable, ok := likeTable.Table.(sql.CheckTable); ok {
checks, err := checksTable.GetChecks(b.ctx)
if err != nil {
b.handleErr(err)
}
for _, check := range checks {
checkConstraint := b.buildCheckConstraint(outScope, &check)
if err != nil {
b.handleErr(err)
}
// Prevent a name collision between old and new checks.
// New check will be assigned a name during building.
checkConstraint.Name = ""
checkDefs = append(checkDefs, checkConstraint)
}
}
pkSchema := sql.NewPrimaryKeySchema(newSch, pkOrdinals...)
pkSchema.Schema = b.resolveSchemaDefaults(outScope, pkSchema.Schema)
tableSpec := &plan.TableSpec{
Schema: pkSchema,
IdxDefs: idxDefs,
ChDefs: checkDefs,
Collation: likeTable.Collation(),
Comment: likeTable.Comment(),
}
qualifier := ct.Table.Qualifier.String()
if qualifier == "" {
qualifier = b.ctx.GetCurrentDatabase()
}
database := b.resolveDb(qualifier)
outScope.node = plan.NewCreateTable(database, newTableName, ct.IfNotExists, ct.Temporary, tableSpec)
return outScope
}
func (b *Builder) buildRenameTable(inScope *scope, ddl *ast.DDL) (outScope *scope) {
outScope = inScope
if len(ddl.FromTables) != len(ddl.ToTables) {
panic("Expected from tables and to tables of equal length")
}
var fromTables, toTables []string
for _, table := range ddl.FromTables {
fromTables = append(fromTables, table.Name.String())
}
for _, table := range ddl.ToTables {
toTables = append(toTables, table.Name.String())
}
outScope.node = plan.NewRenameTable(b.currentDb(), fromTables, toTables, b.multiDDL)
return
}
func (b *Builder) isUniqueColumn(tableSpec *ast.TableSpec, columnName string) bool {
for _, column := range tableSpec.Columns {
if column.Name.String() == columnName {
return column.Type.KeyOpt == colKeyUnique ||
column.Type.KeyOpt == colKeyUniqueKey
}
}
err := fmt.Errorf("unknown column name %s", columnName)
b.handleErr(err)
return false
}
func (b *Builder) buildAlterTableClause(inScope *scope, ddl *ast.DDL) []*scope {
outScopes := make([]*scope, 0, 1)
// RENAME a to b, c to d ..
if ddl.Action == ast.RenameStr {
outScopes = append(outScopes, b.buildRenameTable(inScope, ddl))
} else {
dbName := ddl.Table.Qualifier.String()
tableName := ddl.Table.Name.String()
var ok bool
tableScope, ok := b.buildResolvedTable(inScope, dbName, tableName, nil)
if !ok {
b.handleErr(sql.ErrTableNotFound.New(tableName))
}
rt, ok := tableScope.node.(*plan.ResolvedTable)
if !ok {
err := fmt.Errorf("expected resolved table: %s", tableName)
b.handleErr(err)
}
if ddl.ColumnAction != "" {
columnActionOutscope := b.buildAlterTableColumnAction(tableScope, ddl, rt)
outScopes = append(outScopes, columnActionOutscope)
if ddl.TableSpec != nil {
if len(ddl.TableSpec.Columns) != 1 {
err := sql.ErrUnsupportedFeature.New("unexpected number of columns in a single alter column clause")
b.handleErr(err)
}
column := ddl.TableSpec.Columns[0]
isUnique := b.isUniqueColumn(ddl.TableSpec, column.Name.String())
if isUnique {
createIndex := plan.NewAlterCreateIndex(
rt.Database(),
rt,
column.Name.String(),
sql.IndexUsing_BTree,
sql.IndexConstraint_Unique,
[]sql.IndexColumn{{Name: column.Name.String()}},
"",
)
createIndexScope := inScope.push()
createIndexScope.node = createIndex
outScopes = append(outScopes, createIndexScope)
}
}
}
if ddl.ConstraintAction != "" {
if len(ddl.TableSpec.Constraints) != 1 {
b.handleErr(sql.ErrUnsupportedFeature.New("unexpected number of constraints in a single alter constraint clause"))
}
outScopes = append(outScopes, b.buildAlterConstraint(tableScope, ddl, rt))
}
if ddl.IndexSpec != nil {
outScopes = append(outScopes, b.buildAlterIndex(tableScope, ddl, rt))
}
if ddl.AutoIncSpec != nil {
outScopes = append(outScopes, b.buildAlterAutoIncrement(tableScope, ddl, rt))
}
if ddl.DefaultSpec != nil {
outScopes = append(outScopes, b.buildAlterDefault(tableScope, ddl, rt))
}
if ddl.AlterCollationSpec != nil {
outScopes = append(outScopes, b.buildAlterCollationSpec(tableScope, ddl, rt))
}
for _, s := range outScopes {
if ts, ok := s.node.(sql.SchemaTarget); ok {
s.node = b.modifySchemaTarget(s, ts, rt)
}
}
pkt, _ := rt.Table.(sql.PrimaryKeyTable)
if pkt != nil {
for _, s := range outScopes {
if ts, ok := s.node.(sql.PrimaryKeySchemaTarget); ok {
s.node = b.modifySchemaTarget(inScope, ts, rt)
ts.WithPrimaryKeySchema(pkt.PrimaryKeySchema())
}
}
}
}
return outScopes
}
func (b *Builder) buildAlterTableColumnAction(inScope *scope, ddl *ast.DDL, table *plan.ResolvedTable) (outScope *scope) {
outScope = inScope
switch strings.ToLower(ddl.ColumnAction) {
case ast.AddStr:
sch, _, _ := b.tableSpecToSchema(inScope, outScope, table.Database(), ddl.Table.Name.String(), ddl.TableSpec, true)
outScope.node = plan.NewAddColumnResolved(table, *sch.Schema[0], columnOrderToColumnOrder(ddl.ColumnOrder))
case ast.DropStr:
drop := plan.NewDropColumnResolved(table, ddl.Column.String())
checks := b.loadChecksFromTable(outScope, table.Table)
outScope.node = drop.WithChecks(checks)
case ast.RenameStr:
rename := plan.NewRenameColumnResolved(table, ddl.Column.String(), ddl.ToColumn.String())
checks := b.loadChecksFromTable(outScope, table.Table)
outScope.node = rename.WithChecks(checks)
case ast.ModifyStr, ast.ChangeStr:
// modify adds a new column maybe with same name
// make new hierarchy so it resolves before old column
outScope = inScope.push()
sch, _, _ := b.tableSpecToSchema(inScope, outScope, table.Database(), ddl.Table.Name.String(), ddl.TableSpec, true)
modifyCol := plan.NewModifyColumnResolved(table, ddl.Column.String(), *sch.Schema[0], columnOrderToColumnOrder(ddl.ColumnOrder))
outScope.node = modifyCol
default:
err := sql.ErrUnsupportedFeature.New(ast.String(ddl))
b.handleErr(err)
}
return outScope
}
func (b *Builder) buildAlterConstraint(inScope *scope, ddl *ast.DDL, table *plan.ResolvedTable) (outScope *scope) {
outScope = inScope
parsedConstraint := b.convertConstraintDefinition(inScope, ddl.TableSpec.Constraints[0])
switch strings.ToLower(ddl.ConstraintAction) {
case ast.AddStr:
switch c := parsedConstraint.(type) {
case *sql.ForeignKeyConstraint:
c.Database = table.SqlDatabase.Name()
c.Table = table.Name()
alterFk := plan.NewAlterAddForeignKey(c)
alterFk.DbProvider = b.cat
outScope.node = alterFk
case *sql.CheckConstraint:
outScope.node = plan.NewAlterAddCheck(table, c)
default:
err := sql.ErrUnsupportedFeature.New(ast.String(ddl))
b.handleErr(err)
}
case ast.DropStr:
switch c := parsedConstraint.(type) {
case *sql.ForeignKeyConstraint:
database := table.SqlDatabase.Name()
dropFk := plan.NewAlterDropForeignKey(database, table.Name(), c.Name)
dropFk.DbProvider = b.cat
outScope.node = dropFk
case *sql.CheckConstraint:
outScope.node = plan.NewAlterDropCheck(table, c.Name)
case namedConstraint:
outScope.node = &plan.DropConstraint{
UnaryNode: plan.UnaryNode{Child: table},
Name: c.name,
}
default:
err := sql.ErrUnsupportedFeature.New(ast.String(ddl))
b.handleErr(err)
}
}
return
}
func (b *Builder) buildConstraintsDefs(inScope *scope, tname ast.TableName, spec *ast.TableSpec) (fks []*sql.ForeignKeyConstraint, checks []*sql.CheckConstraint) {
for _, unknownConstraint := range spec.Constraints {
parsedConstraint := b.convertConstraintDefinition(inScope, unknownConstraint)
switch constraint := parsedConstraint.(type) {
case *sql.ForeignKeyConstraint:
constraint.Database = tname.Qualifier.String()
constraint.Table = tname.Name.String()
if constraint.Database == "" {
constraint.Database = b.ctx.GetCurrentDatabase()
}
fks = append(fks, constraint)
case *sql.CheckConstraint:
checks = append(checks, constraint)
default:
err := sql.ErrUnknownConstraintDefinition.New(unknownConstraint.Name, unknownConstraint)
b.handleErr(err)
}
}
return
}
func columnOrderToColumnOrder(order *ast.ColumnOrder) *sql.ColumnOrder {
if order == nil {
return nil
}
if order.First {
return &sql.ColumnOrder{First: true}
} else {
return &sql.ColumnOrder{AfterColumn: order.AfterColumn.String()}
}
}
func (b *Builder) buildIndexDefs(_ *scope, spec *ast.TableSpec) (idxDefs sql.IndexDefs) {
for _, idxDef := range spec.Indexes {
constraint := sql.IndexConstraint_None
if idxDef.Info.Primary {
constraint = sql.IndexConstraint_Primary
} else if idxDef.Info.Unique {
constraint = sql.IndexConstraint_Unique
} else if idxDef.Info.Spatial {
constraint = sql.IndexConstraint_Spatial
} else if idxDef.Info.Fulltext {
constraint = sql.IndexConstraint_Fulltext
}
columns := b.gatherIndexColumns(idxDef.Columns)
var comment string
for _, option := range idxDef.Options {
if strings.ToLower(option.Name) == strings.ToLower(ast.KeywordString(ast.COMMENT_KEYWORD)) {
comment = string(option.Value.Val)
}
}
idxDefs = append(idxDefs, &sql.IndexDef{
Name: idxDef.Info.Name.String(),
Storage: sql.IndexUsing_Default, //TODO: add vitess support for USING
Constraint: constraint,
Columns: columns,
Comment: comment,
})
}
for _, colDef := range spec.Columns {
if colDef.Type.KeyOpt == colKeyFulltextKey {
idxDefs = append(idxDefs, &sql.IndexDef{
Storage: sql.IndexUsing_Default,
Constraint: sql.IndexConstraint_Fulltext,
Columns: []sql.IndexColumn{
{
Name: colDef.Name.String(),
},
},
})
continue
}
if colDef.Type.KeyOpt == colKeyUnique || colDef.Type.KeyOpt == colKeyUniqueKey {
idxDefs = append(idxDefs, &sql.IndexDef{
Storage: sql.IndexUsing_Default,
Constraint: sql.IndexConstraint_Unique,
Columns: []sql.IndexColumn{
{
Name: colDef.Name.String(),
},
},
})
}
}
return
}
type namedConstraint struct {
name string
}
func (b *Builder) convertConstraintDefinition(inScope *scope, cd *ast.ConstraintDefinition) interface{} {
if fkConstraint, ok := cd.Details.(*ast.ForeignKeyDefinition); ok {
columns := make([]string, len(fkConstraint.Source))
for i, col := range fkConstraint.Source {
columns[i] = col.String()
}
refColumns := make([]string, len(fkConstraint.ReferencedColumns))
for i, col := range fkConstraint.ReferencedColumns {
refColumns[i] = col.String()
}
refDatabase := fkConstraint.ReferencedTable.Qualifier.String()
if refDatabase == "" {
refDatabase = b.ctx.GetCurrentDatabase()
}
// The database and table are set in the calling function
return &sql.ForeignKeyConstraint{
Name: cd.Name,
Columns: columns,
ParentDatabase: refDatabase,
ParentTable: fkConstraint.ReferencedTable.Name.String(),
ParentColumns: refColumns,
OnUpdate: b.buildReferentialAction(fkConstraint.OnUpdate),
OnDelete: b.buildReferentialAction(fkConstraint.OnDelete),
IsResolved: false,
}
} else if chConstraint, ok := cd.Details.(*ast.CheckConstraintDefinition); ok {
var c sql.Expression
if chConstraint.Expr != nil {
c = b.buildScalar(inScope, chConstraint.Expr)
}
return &sql.CheckConstraint{
Name: cd.Name,
Expr: c,
Enforced: chConstraint.Enforced,
}
} else if len(cd.Name) > 0 && cd.Details == nil {
return namedConstraint{cd.Name}
}
err := sql.ErrUnknownConstraintDefinition.New(cd.Name, cd)
b.handleErr(err)
return nil
}
func (b *Builder) buildReferentialAction(action ast.ReferenceAction) sql.ForeignKeyReferentialAction {
switch action {
case ast.Restrict:
return sql.ForeignKeyReferentialAction_Restrict
case ast.Cascade:
return sql.ForeignKeyReferentialAction_Cascade
case ast.NoAction:
return sql.ForeignKeyReferentialAction_NoAction
case ast.SetNull:
return sql.ForeignKeyReferentialAction_SetNull
case ast.SetDefault:
return sql.ForeignKeyReferentialAction_SetDefault
default:
return sql.ForeignKeyReferentialAction_DefaultAction
}
}
func (b *Builder) buildAlterIndex(inScope *scope, ddl *ast.DDL, table *plan.ResolvedTable) (outScope *scope) {
outScope = inScope
switch strings.ToLower(ddl.IndexSpec.Action) {
case ast.CreateStr:
var using sql.IndexUsing
switch ddl.IndexSpec.Using.Lowered() {
case "", "btree":
using = sql.IndexUsing_BTree
case "hash":
using = sql.IndexUsing_Hash
default:
return b.buildExternalCreateIndex(inScope, ddl)
}
var constraint sql.IndexConstraint
switch ddl.IndexSpec.Type {
case ast.UniqueStr:
constraint = sql.IndexConstraint_Unique
case ast.FulltextStr:
constraint = sql.IndexConstraint_Fulltext
case ast.SpatialStr:
constraint = sql.IndexConstraint_Spatial
case ast.PrimaryStr:
constraint = sql.IndexConstraint_Primary
default:
constraint = sql.IndexConstraint_None
}
columns := b.gatherIndexColumns(ddl.IndexSpec.Columns)
var comment string
for _, option := range ddl.IndexSpec.Options {
if strings.ToLower(option.Name) == strings.ToLower(ast.KeywordString(ast.COMMENT_KEYWORD)) {
comment = string(option.Value.Val)
}
}
if constraint == sql.IndexConstraint_Primary {
outScope.node = plan.NewAlterCreatePk(table.SqlDatabase, table, columns)
return
}
indexName := ddl.IndexSpec.ToName.String()
if strings.ToLower(indexName) == ast.PrimaryStr {
err := sql.ErrInvalidIndexName.New(indexName)
b.handleErr(err)
}
createIndex := plan.NewAlterCreateIndex(table.SqlDatabase, table, ddl.IndexSpec.ToName.String(), using, constraint, columns, comment)
outScope.node = b.modifySchemaTarget(inScope, createIndex, table)
return
case ast.DropStr:
if ddl.IndexSpec.Type == ast.PrimaryStr {
outScope.node = plan.NewAlterDropPk(table.SqlDatabase, table)
return
}
outScope.node = plan.NewAlterDropIndex(table.Database(), table, ddl.IndexSpec.ToName.String())
return
case ast.RenameStr:
outScope.node = plan.NewAlterRenameIndex(table.Database(), table, ddl.IndexSpec.FromName.String(), ddl.IndexSpec.ToName.String())
return
case "disable":
outScope.node = plan.NewAlterDisableEnableKeys(table.SqlDatabase, table, true)
return
case "enable":
outScope.node = plan.NewAlterDisableEnableKeys(table.SqlDatabase, table, false)
return
default:
err := sql.ErrUnsupportedFeature.New(ast.String(ddl))
b.handleErr(err)
}
return
}
func (b *Builder) gatherIndexColumns(cols []*ast.IndexColumn) []sql.IndexColumn {
out := make([]sql.IndexColumn, len(cols))
for i, col := range cols {
var length int64
var err error
if col.Length != nil && col.Length.Type == ast.IntVal {
length, err = strconv.ParseInt(string(col.Length.Val), 10, 64)
if err != nil {
b.handleErr(err)
}
if length < 1 {
err := sql.ErrKeyZero.New(col.Column)
b.handleErr(err)
}
}
out[i] = sql.IndexColumn{
Name: col.Column.String(),
Length: length,
}
}
return out
}
func (b *Builder) buildAlterAutoIncrement(inScope *scope, ddl *ast.DDL, table *plan.ResolvedTable) (outScope *scope) {
outScope = inScope
val, ok := ddl.AutoIncSpec.Value.(*ast.SQLVal)
if !ok {
err := sql.ErrInvalidSQLValType.New(ddl.AutoIncSpec.Value)
b.handleErr(err)
}
var autoVal uint64
if val.Type == ast.IntVal {
i, err := strconv.ParseUint(string(val.Val), 10, 64)
if err != nil {
b.handleErr(err)
}
autoVal = i
} else if val.Type == ast.FloatVal {
f, err := strconv.ParseFloat(string(val.Val), 10)
if err != nil {
b.handleErr(err)
}
autoVal = uint64(f)
} else {
err := sql.ErrInvalidSQLValType.New(ddl.AutoIncSpec.Value)
b.handleErr(err)
}
outScope.node = plan.NewAlterAutoIncrement(table.Database(), table, autoVal)
return
}
func (b *Builder) buildAlterDefault(inScope *scope, ddl *ast.DDL, table *plan.ResolvedTable) (outScope *scope) {
outScope = inScope
switch strings.ToLower(ddl.DefaultSpec.Action) {
case ast.SetStr:
for _, c := range table.Schema() {
if strings.EqualFold(c.Name, ddl.DefaultSpec.Column.String()) {
defaultExpr := b.convertDefaultExpression(inScope, ddl.DefaultSpec.Value, c.Type, c.Nullable)
defSet := plan.NewAlterDefaultSet(table.Database(), table, ddl.DefaultSpec.Column.String(), defaultExpr)
outScope.node = b.modifySchemaTarget(inScope, defSet, table)
return
}
}
err := sql.ErrTableColumnNotFound.New(table.Name(), ddl.DefaultSpec.Column.String())
b.handleErr(err)
return
case ast.DropStr:
outScope.node = plan.NewAlterDefaultDrop(table.Database(), table, ddl.DefaultSpec.Column.String())
return
default:
err := sql.ErrUnsupportedFeature.New(ast.String(ddl))
b.handleErr(err)
}
return
}
func (b *Builder) buildAlterCollationSpec(inScope *scope, ddl *ast.DDL, table *plan.ResolvedTable) (outScope *scope) {
outScope = inScope
collation, err := sql.ParseCollation(ddl.AlterCollationSpec.CharacterSet, ddl.AlterCollationSpec.Collation, false)
if err != nil {
b.handleErr(err)
}
outScope.node = plan.NewAlterTableCollationResolved(table, collation)
return
}
func (b *Builder) buildDefaultExpression(inScope *scope, defaultExpr ast.Expr) *sql.ColumnDefaultValue {
if defaultExpr == nil {
return nil
}
parsedExpr := b.buildScalar(inScope, defaultExpr)
// Function expressions must be enclosed in parentheses (except for current_timestamp() and now())
_, isParenthesized := defaultExpr.(*ast.ParenExpr)
isLiteral := !isParenthesized
// A literal will never have children, thus we can also check for that.
if unaryExpr, is := defaultExpr.(*ast.UnaryExpr); is {
if _, lit := unaryExpr.Expr.(*ast.SQLVal); lit {
isLiteral = true
}
} else if !isParenthesized {
if f, ok := parsedExpr.(*expression.UnresolvedFunction); ok {
// Datetime and Timestamp columns allow now and current_timestamp to not be enclosed in parens,
// but they still need to be treated as function expressions
switch strings.ToLower(f.Name()) {
case "now", "current_timestamp", "localtime", "localtimestamp":
isLiteral = false
default:
err := sql.ErrSyntaxError.New("column default function expressions must be enclosed in parentheses")
b.handleErr(err)
}
}
}
return ExpressionToColumnDefaultValue(parsedExpr, isLiteral, isParenthesized)
}
// ExpressionToColumnDefaultValue takes in an Expression and returns the equivalent ColumnDefaultValue if the expression
// is valid for a default value. If the expression represents a literal (and not an expression that returns a literal, so "5"
// rather than "(5)"), then the parameter "isLiteral" should be true.
func ExpressionToColumnDefaultValue(inputExpr sql.Expression, isLiteral, isParenthesized bool) *sql.ColumnDefaultValue {
return &sql.ColumnDefaultValue{
Expr: inputExpr,
OutType: nil,
Literal: isLiteral,
ReturnNil: true,
Parenthesized: isParenthesized,
}
}
func (b *Builder) buildExternalCreateIndex(inScope *scope, ddl *ast.DDL) (outScope *scope) {
config := make(map[string]string)
for _, option := range ddl.IndexSpec.Options {
if option.Using != "" {
config[option.Name] = option.Using
} else {
config[option.Name] = string(option.Value.Val)
}
}
dbName := strings.ToLower(ddl.Table.Qualifier.String())
tblName := strings.ToLower(ddl.Table.Name.String())
var ok bool
outScope, ok = b.buildTablescan(inScope, dbName, tblName, nil)
if !ok {
b.handleErr(sql.ErrTableNotFound.New(tblName))
}
table, ok := outScope.node.(*plan.ResolvedTable)
if !ok {
err := fmt.Errorf("expected resolved table: %s", tblName)
b.handleErr(err)
}
tableId := outScope.tables[tblName]
cols := make([]sql.Expression, len(ddl.IndexSpec.Columns))
for i, col := range ddl.IndexSpec.Columns {
colName := strings.ToLower(col.Column.String())
c, ok := inScope.resolveColumn(dbName, tblName, colName, true, false)
if !ok {
b.handleErr(sql.ErrColumnNotFound.New(colName))
}
cols[i] = expression.NewGetFieldWithTable(int(c.id), int(tableId), c.typ, c.db, c.table, c.col, c.nullable)
}
createIndex := plan.NewCreateIndex(
ddl.IndexSpec.ToName.String(),
table,
cols,
ddl.IndexSpec.Using.Lowered(),
config,
)
createIndex.Catalog = b.cat
outScope.node = createIndex