Skip to content

Commit fcb7ff8

Browse files
committed
add create table nil default
1 parent 64da230 commit fcb7ff8

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

sql/planbuilder/ddl.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1419,6 +1419,15 @@ func (b *Builder) tableSpecToSchema(inScope, outScope *scope, db sql.Database, t
14191419

14201420
for i, def := range defaults {
14211421
schema[i].Default = b.convertDefaultExpression(outScope, def, schema[i].Type, schema[i].Nullable)
1422+
if schema[i].Default == nil && schema[i].Nullable {
1423+
schema[i].Default = &sql.ColumnDefaultValue{
1424+
Expr: expression.NewLiteral(nil, schema[i].Type),
1425+
OutType: nil,
1426+
Literal: true,
1427+
Parenthesized: false,
1428+
ReturnNil: true,
1429+
}
1430+
}
14221431
err := validateDefaultExprs(schema[i])
14231432
if err != nil {
14241433
b.handleErr(err)

sql/planbuilder/dml.go

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,12 +75,24 @@ func (b *Builder) buildInsert(inScope *scope, i *ast.Insert) (outScope *scope) {
7575
if len(columns) == 0 && len(destScope.cols) > 0 && rt != nil {
7676
schema := rt.Schema()
7777
columns = make([]string, len(schema))
78-
for i, col := range schema {
78+
for index, col := range schema {
7979
// Tables with any generated column must always supply a column list, so this is always an error
8080
if col.Generated != nil {
8181
b.handleErr(sql.ErrGeneratedColumnValue.New(col.Name, rt.Name()))
8282
}
83-
columns[i] = col.Name
83+
columns[index] = col.Name
84+
}
85+
if ir, ok := i.Rows.(*ast.AliasedValues); ok && len(ir.Values[0]) == 0 {
86+
// VALUES() clause is empty in conjunction with empty column list, so we need to
87+
// insert default val for respective columns.
88+
ir.Values[0] = make([]ast.Expr, len(schema))
89+
for j, col := range schema {
90+
if col.Default == nil {
91+
b.handleErr(sql.ErrInsertIntoNonNullableDefaultNullColumn.New(col.Name))
92+
}
93+
94+
ir.Values[0][j] = &ast.Default{}
95+
}
8496
}
8597
}
8698
}
@@ -214,8 +226,6 @@ func (b *Builder) buildInsertValues(inScope *scope, v *ast.AliasedValues, column
214226
literalOnly = true
215227
exprTuples := make([][]sql.Expression, len(v.Values))
216228
for i, vt := range v.Values {
217-
// noExprs is an edge case where we fill VALUES with nil expressions
218-
//noExprs := len(vt) == 0
219229
// triggerUnknownTable is an edge case where we ignored an unresolved
220230
// table error and do not have a schema for resolving defaults
221231
triggerUnknownTable := (len(columnNames) == 0 && len(vt) > 0) && (len(b.TriggerCtx().UnresolvedTables) > 0)

0 commit comments

Comments
 (0)