Skip to content

Commit ebf955b

Browse files
committed
add create table nil default
1 parent e9900ff commit ebf955b

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-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: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,29 @@ 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 {
79-
columns[i] = col.Name
78+
for index, col := range schema {
79+
// Tables with any generated column must always supply a column list, so this is always an error
80+
if col.Generated != nil {
81+
b.handleErr(sql.ErrGeneratedColumnValue.New(col.Name, rt.Name()))
82+
}
83+
columns[index] = col.Name
84+
}
85+
if ir, ok := i.Rows.(*ast.AliasedValues); ok {
86+
// Handle any empty VALUES() tuples when no column list was specified
87+
for valueIdx, valueRow := range ir.Values {
88+
if len(valueRow) == 0 {
89+
// VALUES() clause is empty in conjunction with empty column list, so we need to
90+
// insert default val for respective columns.
91+
ir.Values[valueIdx] = make([]ast.Expr, len(schema))
92+
for j, col := range schema {
93+
if col.Default == nil && !col.AutoIncrement {
94+
b.handleErr(sql.ErrInsertIntoNonNullableDefaultNullColumn.New(col.Name))
95+
}
96+
97+
ir.Values[valueIdx][j] = &ast.Default{}
98+
}
99+
}
100+
}
80101
}
81102
}
82103
}
@@ -210,8 +231,6 @@ func (b *Builder) buildInsertValues(inScope *scope, v *ast.AliasedValues, column
210231
literalOnly = true
211232
exprTuples := make([][]sql.Expression, len(v.Values))
212233
for i, vt := range v.Values {
213-
// noExprs is an edge case where we fill VALUES with nil expressions
214-
//noExprs := len(vt) == 0
215234
// triggerUnknownTable is an edge case where we ignored an unresolved
216235
// table error and do not have a schema for resolving defaults
217236
triggerUnknownTable := (len(columnNames) == 0 && len(vt) > 0) && (len(b.TriggerCtx().UnresolvedTables) > 0)

0 commit comments

Comments
 (0)