Skip to content

Commit

Permalink
fix(sqlite): Fix ADD COLUMN without typename
Browse files Browse the repository at this point in the history
Use type name 'any' for ALTER TABLE t1 ADD COLUMN c1 where no type
name for c1 is provided. This is the same logic as for CREATE TABLE.

Fixes sqlc-dev#3375
  • Loading branch information
dvob committed May 12, 2024
1 parent 9ec7a68 commit 6e67606
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
24 changes: 24 additions & 0 deletions internal/engine/sqlite/catalog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,30 @@ func TestUpdate(t *testing.T) {
},
},
},
{
`
CREATE TABLE foo (bar text);
ALTER TABLE foo ADD COLUMN baz;
`,
&catalog.Schema{
Name: "main",
Tables: []*catalog.Table{
{
Rel: &ast.TableName{Name: "foo"},
Columns: []*catalog.Column{
{
Name: "bar",
Type: ast.TypeName{Name: "text"},
},
{
Name: "baz",
Type: ast.TypeName{Name: "any"},
},
},
},
},
},
},
{
`
CREATE TABLE foo (bar text);
Expand Down
19 changes: 10 additions & 9 deletions internal/engine/sqlite/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ func identifier(id string) string {
return strings.ToLower(id)
}

func getTypeName(t parser.IType_nameContext) string {
if t == nil {
return "any"
}
return t.GetText()
}

func NewIdentifier(t string) *ast.String {
return &ast.String{Str: identifier(t)}
}
Expand Down Expand Up @@ -72,10 +79,8 @@ func (c *cc) convertAlter_table_stmtContext(n *parser.Alter_table_stmtContext) a
Name: &name,
Subtype: ast.AT_AddColumn,
Def: &ast.ColumnDef{
Colname: name,
TypeName: &ast.TypeName{
Name: def.Type_name().GetText(),
},
Colname: name,
TypeName: &ast.TypeName{Name: getTypeName(def.Type_name())},
IsNotNull: hasNotNullConstraint(def.AllColumn_constraint()),
},
})
Expand Down Expand Up @@ -113,14 +118,10 @@ func (c *cc) convertCreate_table_stmtContext(n *parser.Create_table_stmtContext)
}
for _, idef := range n.AllColumn_def() {
if def, ok := idef.(*parser.Column_defContext); ok {
typeName := "any"
if def.Type_name() != nil {
typeName = def.Type_name().GetText()
}
stmt.Cols = append(stmt.Cols, &ast.ColumnDef{
Colname: identifier(def.Column_name().GetText()),
IsNotNull: hasNotNullConstraint(def.AllColumn_constraint()),
TypeName: &ast.TypeName{Name: typeName},
TypeName: &ast.TypeName{Name: getTypeName(def.Type_name())},
})
}
}
Expand Down

0 comments on commit 6e67606

Please sign in to comment.