Skip to content

Commit

Permalink
insert: return error if field doesn't exist in strict table. Fixes #472
Browse files Browse the repository at this point in the history
  • Loading branch information
asdine committed Oct 29, 2023
1 parent ff9b9e8 commit d5bccbd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
19 changes: 14 additions & 5 deletions internal/query/statement/insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ func (stmt *InsertStmt) Prepare(c *Context) (Statement, error) {
var s *stream.Stream

if stmt.Values != nil {
ti, err := c.Catalog.GetTableInfo(stmt.TableName)
if err != nil {
return nil, err
}

// if no fields have been specified, we need to inject the fields from the defined table info
if len(stmt.Fields) == 0 {
ti, err := c.Catalog.GetTableInfo(stmt.TableName)
if err != nil {
return nil, err
}

for i := range stmt.Values {
kvs, ok := stmt.Values[i].(*expr.KVPairs)
if !ok {
Expand All @@ -61,6 +61,15 @@ func (stmt *InsertStmt) Prepare(c *Context) (Statement, error) {
}
}
}
} else {
if !ti.FieldConstraints.AllowExtraFields {
for i := range stmt.Fields {
_, ok := ti.FieldConstraints.ByField[stmt.Fields[i]]
if !ok {
return nil, errors.Errorf("table has no field %s", stmt.Fields[i])
}
}
}
}
s = stream.New(docs.Emit(stmt.Values...))
} else {
Expand Down
5 changes: 5 additions & 0 deletions sqltests/INSERT/values.sql
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ SELECT pk(), * FROM test;
}
*/

-- test: VALUES, with too many fields
CREATE TABLE test (a TEXT, b TEXT, c TEXT);
INSERT INTO test (b, a, c, d) VALUES ('b', 'a', 'c', 'd');
-- error: table has no field d

-- test: variadic, VALUES, with all fields
CREATE TABLE test (a TEXT, b TEXT, c TEXT, ...);
INSERT INTO test (a, b, c) VALUES ('a', 'b', 'c');
Expand Down

0 comments on commit d5bccbd

Please sign in to comment.