forked from dolthub/go-mysql-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ddl.go
622 lines (522 loc) · 15.5 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
// Copyright 2020-2021 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 plan
import (
"fmt"
"strings"
"gopkg.in/src-d/go-errors.v1"
"github.com/Sndav/go-mysql-server/sql"
"github.com/Sndav/go-mysql-server/sql/expression"
)
// ErrCreateTable is thrown when the database doesn't support table creation
var ErrCreateTableNotSupported = errors.NewKind("tables cannot be created on database %s")
// ErrDropTableNotSupported is thrown when the database doesn't support dropping tables
var ErrDropTableNotSupported = errors.NewKind("tables cannot be dropped on database %s")
// ErrRenameTableNotSupported is thrown when the database doesn't support renaming tables
var ErrRenameTableNotSupported = errors.NewKind("tables cannot be renamed on database %s")
// ErrAlterTableNotSupported is thrown when the database doesn't support ALTER TABLE statements
var ErrAlterTableNotSupported = errors.NewKind("table %s cannot be altered on database %s")
// ErrNullDefault is thrown when a non-null column is added with a null default
var ErrNullDefault = errors.NewKind("column declared not null must have a non-null default value")
// ErrTableCreatedNotFound is thrown when a table is created from CREATE TABLE but cannot be found immediately afterward
var ErrTableCreatedNotFound = errors.NewKind("table was created but could not be found")
type IfNotExistsOption bool
const (
IfNotExists IfNotExistsOption = true
IfNotExistsAbsent IfNotExistsOption = false
)
type TempTableOption bool
const (
IsTempTable TempTableOption = true
IsTempTableAbsent TempTableOption = false
)
// Ddl nodes have a reference to a database, but no children and a nil schema.
type ddlNode struct {
db sql.Database
}
// Resolved implements the Resolvable interface.
func (c *ddlNode) Resolved() bool {
_, ok := c.db.(sql.UnresolvedDatabase)
return !ok
}
// Database implements the sql.Databaser interface.
func (c *ddlNode) Database() sql.Database {
return c.db
}
// Schema implements the Node interface.
func (*ddlNode) Schema() sql.Schema { return nil }
// Children implements the Node interface.
func (c *ddlNode) Children() []sql.Node { return nil }
type IndexDefinition struct {
IndexName string
Using sql.IndexUsing
Constraint sql.IndexConstraint
Columns []sql.IndexColumn
Comment string
}
func (i *IndexDefinition) String() string {
return i.IndexName
}
// TableSpec is a node describing the schema of a table.
type TableSpec struct {
Schema sql.Schema
FkDefs []*sql.ForeignKeyConstraint
ChDefs []*sql.CheckConstraint
IdxDefs []*IndexDefinition
}
func (c *TableSpec) WithSchema(schema sql.Schema) *TableSpec {
nc := *c
nc.Schema = schema
return &nc
}
func (c *TableSpec) WithForeignKeys(fkDefs []*sql.ForeignKeyConstraint) *TableSpec {
nc := *c
nc.FkDefs = fkDefs
return &nc
}
func (c *TableSpec) WithCheckConstraints(chDefs []*sql.CheckConstraint) *TableSpec {
nc := *c
nc.ChDefs = chDefs
return &nc
}
func (c *TableSpec) WithIndices(idxDefs []*IndexDefinition) *TableSpec {
nc := *c
nc.IdxDefs = idxDefs
return &nc
}
// CreateTable is a node describing the creation of some table.
type CreateTable struct {
ddlNode
name string
schema sql.Schema
ifNotExists IfNotExistsOption
fkDefs []*sql.ForeignKeyConstraint
chDefs []*sql.CheckConstraint
idxDefs []*IndexDefinition
like sql.Node
temporary TempTableOption
selectNode sql.Node
}
var _ sql.Databaser = (*CreateTable)(nil)
var _ sql.Node = (*CreateTable)(nil)
var _ sql.Expressioner = (*CreateTable)(nil)
// NewCreateTable creates a new CreateTable node
func NewCreateTable(db sql.Database, name string, ifn IfNotExistsOption, temp TempTableOption, tableSpec *TableSpec) *CreateTable {
for _, s := range tableSpec.Schema {
s.Source = name
}
return &CreateTable{
ddlNode: ddlNode{db},
name: name,
schema: tableSpec.Schema,
fkDefs: tableSpec.FkDefs,
chDefs: tableSpec.ChDefs,
idxDefs: tableSpec.IdxDefs,
ifNotExists: ifn,
temporary: temp,
}
}
// NewCreateTableLike creates a new CreateTable node for CREATE TABLE LIKE statements
func NewCreateTableLike(db sql.Database, name string, likeTable sql.Node, ifn IfNotExistsOption, temp TempTableOption) *CreateTable {
return &CreateTable{
ddlNode: ddlNode{db},
name: name,
ifNotExists: ifn,
like: likeTable,
temporary: temp,
}
}
// NewCreateTableSelect create a new CreateTable node for CREATE TABLE [AS] SELECT
func NewCreateTableSelect(db sql.Database, name string, selectNode sql.Node, tableSpec *TableSpec, ifn IfNotExistsOption, temp TempTableOption) *CreateTable {
for _, s := range tableSpec.Schema {
s.Source = name
}
return &CreateTable{
ddlNode: ddlNode{db: db},
schema: tableSpec.Schema,
fkDefs: tableSpec.FkDefs,
chDefs: tableSpec.ChDefs,
idxDefs: tableSpec.IdxDefs,
name: name,
selectNode: selectNode,
ifNotExists: ifn,
temporary: temp,
}
}
// WithDatabase implements the sql.Databaser interface.
func (c *CreateTable) WithDatabase(db sql.Database) (sql.Node, error) {
nc := *c
nc.db = db
return &nc, nil
}
// Schema implements the sql.Node interface.
func (c *CreateTable) Schema() sql.Schema {
return c.schema
}
// Resolved implements the Resolvable interface.
func (c *CreateTable) Resolved() bool {
resolved := c.ddlNode.Resolved()
for _, col := range c.schema {
resolved = resolved && col.Default.Resolved()
}
return resolved
}
// RowIter implements the Node interface.
func (c *CreateTable) RowIter(ctx *sql.Context, row sql.Row) (sql.RowIter, error) {
var err error
if c.temporary == IsTempTable {
creatable, ok := c.db.(sql.TemporaryTableCreator)
if !ok {
return sql.RowsToRowIter(), sql.ErrTemporaryTableNotSupported.New()
}
if err := c.validateDefaultPosition(); err != nil {
return sql.RowsToRowIter(), err
}
err = creatable.CreateTemporaryTable(ctx, c.name, c.schema)
} else {
creatable, ok := c.db.(sql.TableCreator)
if !ok {
return sql.RowsToRowIter(), ErrCreateTableNotSupported.New(c.db.Name())
}
if err := c.validateDefaultPosition(); err != nil {
return sql.RowsToRowIter(), err
}
err = creatable.CreateTable(ctx, c.name, c.schema)
}
if err != nil && !(sql.ErrTableAlreadyExists.Is(err) && (c.ifNotExists == IfNotExists)) {
return sql.RowsToRowIter(), err
}
//TODO: in the event that foreign keys or indexes aren't supported, you'll be left with a created table and no foreign keys/indexes
//this also means that if a foreign key or index fails, you'll only have what was declared up to the failure
tableNode, ok, err := c.db.GetTableInsensitive(ctx, c.name)
if err != nil {
return sql.RowsToRowIter(), err
}
if !ok {
return sql.RowsToRowIter(), ErrTableCreatedNotFound.New()
}
if len(c.idxDefs) > 0 {
err = c.createIndexes(ctx, tableNode)
if err != nil {
return sql.RowsToRowIter(), err
}
}
if len(c.fkDefs) > 0 {
err = c.createForeignKeys(ctx, tableNode)
if err != nil {
return sql.RowsToRowIter(), err
}
}
if len(c.chDefs) > 0 {
err = c.createChecks(ctx, tableNode)
if err != nil {
return sql.RowsToRowIter(), err
}
}
return sql.RowsToRowIter(), nil
}
func (c *CreateTable) createIndexes(ctx *sql.Context, tableNode sql.Table) error {
idxAlterable, ok := tableNode.(sql.IndexAlterableTable)
if !ok {
return ErrNotIndexable.New()
}
for _, idxDef := range c.idxDefs {
err := idxAlterable.CreateIndex(ctx, idxDef.IndexName, idxDef.Using, idxDef.Constraint, idxDef.Columns, idxDef.Comment)
if err != nil {
return err
}
}
return nil
}
func (c *CreateTable) createForeignKeys(ctx *sql.Context, tableNode sql.Table) error {
fkAlterable, ok := tableNode.(sql.ForeignKeyAlterableTable)
if !ok {
return ErrNoForeignKeySupport.New(c.name)
}
for _, fkDef := range c.fkDefs {
refTbl, ok, err := c.db.GetTableInsensitive(ctx, fkDef.ReferencedTable)
if err != nil {
return err
}
if !ok {
return sql.ErrTableNotFound.New(fkDef.ReferencedTable)
}
err = executeCreateForeignKey(ctx, fkAlterable, refTbl, fkDef)
if err != nil {
return err
}
}
return nil
}
func (c *CreateTable) createChecks(ctx *sql.Context, tableNode sql.Table) error {
chAlterable, ok := tableNode.(sql.CheckAlterableTable)
if !ok {
return ErrNoCheckConstraintSupport.New(c.name)
}
for _, ch := range c.chDefs {
check, err := NewCheckDefinition(ctx, ch)
if err != nil {
return err
}
err = chAlterable.CreateCheck(ctx, check)
if err != nil {
return err
}
}
return nil
}
// Children implements the Node interface.
func (c *CreateTable) Children() []sql.Node {
if c.like != nil {
return []sql.Node{c.like}
} else if c.selectNode != nil {
return []sql.Node{c.selectNode}
}
return nil
}
// WithChildren implements the Node interface.
func (c *CreateTable) WithChildren(children ...sql.Node) (sql.Node, error) {
if len(children) == 0 {
return c, nil
} else if len(children) == 1 {
child := children[0]
nc := *c
switch child.(type) {
case *Project, *Limit:
nc.selectNode = child
default:
nc.like = child
}
return &nc, nil
} else {
return nil, sql.ErrInvalidChildrenNumber.New(c, len(children), 1)
}
}
func (c *CreateTable) String() string {
ifNotExists := ""
if c.ifNotExists {
ifNotExists = "if not exists "
}
return fmt.Sprintf("Create table %s%s", ifNotExists, c.name)
}
func (c *CreateTable) DebugString() string {
ifNotExists := ""
if c.ifNotExists {
ifNotExists = "if not exists "
}
p := sql.NewTreePrinter()
p.WriteNode("Create table %s%s", ifNotExists, c.name)
var children []string
children = append(children, c.schemaDebugString())
if len(c.fkDefs) > 0 {
children = append(children, c.foreignKeysDebugString())
}
if len(c.idxDefs) > 0 {
children = append(children, c.indexesDebugString())
}
if len(c.chDefs) > 0 {
children = append(children, c.checkConstraintsDebugString())
}
p.WriteChildren(children...)
return p.String()
}
func (c *CreateTable) foreignKeysDebugString() string {
p := sql.NewTreePrinter()
p.WriteNode("ForeignKeys")
var children []string
for _, def := range c.fkDefs {
children = append(children, sql.DebugString(def))
}
p.WriteChildren(children...)
return p.String()
}
func (c *CreateTable) indexesDebugString() string {
p := sql.NewTreePrinter()
p.WriteNode("Indexes")
var children []string
for _, def := range c.idxDefs {
children = append(children, sql.DebugString(def))
}
p.WriteChildren(children...)
return p.String()
}
func (c *CreateTable) checkConstraintsDebugString() string {
p := sql.NewTreePrinter()
p.WriteNode("CheckConstraints")
var children []string
for _, def := range c.chDefs {
children = append(children, sql.DebugString(def))
}
p.WriteChildren(children...)
return p.String()
}
func (c *CreateTable) schemaDebugString() string {
p := sql.NewTreePrinter()
p.WriteNode("Columns")
var children []string
for _, col := range c.schema {
children = append(children, sql.DebugString(col))
}
p.WriteChildren(children...)
return p.String()
}
func (c *CreateTable) Expressions() []sql.Expression {
exprs := make([]sql.Expression, len(c.schema)+len(c.chDefs))
i := 0
for _, col := range c.schema {
exprs[i] = expression.WrapExpression(col.Default)
i++
}
for _, ch := range c.chDefs {
exprs[i] = ch.Expr
i++
}
return exprs
}
func (c *CreateTable) Like() sql.Node {
return c.like
}
func (c *CreateTable) Select() sql.Node {
return c.selectNode
}
func (c *CreateTable) TableSpec() *TableSpec {
tableSpec := TableSpec{}
ret := tableSpec.WithSchema(c.schema)
ret = tableSpec.WithForeignKeys(c.fkDefs)
ret = tableSpec.WithIndices(c.idxDefs)
ret = tableSpec.WithCheckConstraints(c.chDefs)
return ret
}
func (c *CreateTable) Name() string {
return c.name
}
func (c *CreateTable) IfNotExists() IfNotExistsOption {
return c.ifNotExists
}
func (c *CreateTable) Temporary() TempTableOption {
return c.temporary
}
func (c *CreateTable) WithExpressions(exprs ...sql.Expression) (sql.Node, error) {
if len(exprs) != len(c.schema)+len(c.chDefs) {
return nil, sql.ErrInvalidChildrenNumber.New(c, len(exprs), len(c.schema)+len(c.chDefs))
}
nc := *c
i := 0
for ; i < len(c.schema); i++ {
unwrappedColDefVal, ok := exprs[i].(*expression.Wrapper).Unwrap().(*sql.ColumnDefaultValue)
if ok {
nc.schema[i].Default = unwrappedColDefVal
} else { // nil fails type check
nc.schema[i].Default = nil
}
}
for ; i < len(c.chDefs)+len(c.schema); i++ {
nc.chDefs[i-len(c.schema)].Expr = exprs[i]
}
return &nc, nil
}
func (c *CreateTable) validateDefaultPosition() error {
colsAfterThis := make(map[string]*sql.Column)
for i := len(c.schema) - 1; i >= 0; i-- {
col := c.schema[i]
colsAfterThis[col.Name] = col
if err := inspectDefaultForInvalidColumns(col, colsAfterThis); err != nil {
return err
}
}
return nil
}
// DropTable is a node describing dropping one or more tables
type DropTable struct {
ddlNode
names []string
ifExists bool
triggerNames []string
}
var _ sql.Node = (*DropTable)(nil)
var _ sql.Databaser = (*DropTable)(nil)
// NewDropTable creates a new DropTable node
func NewDropTable(db sql.Database, ifExists bool, tableNames ...string) *DropTable {
return &DropTable{
ddlNode: ddlNode{db},
names: tableNames,
ifExists: ifExists,
}
}
// WithDatabase implements the sql.Databaser interface.
func (d *DropTable) WithDatabase(db sql.Database) (sql.Node, error) {
nc := *d
nc.db = db
return &nc, nil
}
// WithTriggers returns this node but with the given triggers.
func (d *DropTable) WithTriggers(triggers []string) sql.Node {
nd := *d
nd.triggerNames = triggers
return &nd
}
// TableNames returns the names of the tables to drop.
func (d *DropTable) TableNames() []string {
return d.names
}
// RowIter implements the Node interface.
func (d *DropTable) RowIter(ctx *sql.Context, row sql.Row) (sql.RowIter, error) {
droppable, ok := d.db.(sql.TableDropper)
if !ok {
return nil, ErrDropTableNotSupported.New(d.db.Name())
}
var err error
for _, tableName := range d.names {
tbl, ok, err := d.db.GetTableInsensitive(ctx, tableName)
if err != nil {
return nil, err
}
if !ok {
if d.ifExists {
continue
}
return nil, sql.ErrTableNotFound.New(tableName)
}
err = droppable.DropTable(ctx, tbl.Name())
if err != nil {
return nil, err
}
}
if len(d.triggerNames) > 0 {
//TODO: if dropping any triggers fail, then we'll be left in a state where triggers exist for a table that was dropped
triggerDb, ok := d.db.(sql.TriggerDatabase)
if !ok {
return nil, fmt.Errorf(`tables %v are referenced in triggers %v, but database does not support triggers`, d.names, d.triggerNames)
}
for _, trigger := range d.triggerNames {
err = triggerDb.DropTrigger(ctx, trigger)
if err != nil {
return nil, err
}
}
}
return sql.RowsToRowIter(), err
}
// WithChildren implements the Node interface.
func (d *DropTable) WithChildren(children ...sql.Node) (sql.Node, error) {
return NillaryWithChildren(d, children...)
}
func (d *DropTable) String() string {
ifExists := ""
names := strings.Join(d.names, ", ")
if d.ifExists {
ifExists = "if exists "
}
return fmt.Sprintf("Drop table %s%s", ifExists, names)
}