Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions server/ast/alter_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,22 @@ func nodeAlterTableCmds(
return nil, nil, err
}
vitessDdlCmds = append(vitessDdlCmds, statement)

// Postgres (unlike MySQL) allows an inline FK constraint
// when altering a table to add a column. GMS doesn't support
// this directly in the ALTER TABLE ADD COLUMN DDL command,
// so we break this out into a separate DDL command.
if len(statement.TableSpec.Constraints) > 0 {
vitessDdlCmds = append(vitessDdlCmds,
&vitess.DDL{
Action: "alter",
ConstraintAction: "add",
Table: tableName,
IfExists: ifExists,
TableSpec: statement.TableSpec,
})
}

case *tree.AlterTableDropColumn:
statement, err = nodeAlterTableDropColumn(ctx, cmd, tableName, ifExists)
if err != nil {
Expand Down Expand Up @@ -217,6 +233,14 @@ func nodeAlterTableAddColumn(ctx *Context, node *tree.AlterTableAddColumn, table
tableSpec := &vitess.TableSpec{}
tableSpec.AddColumn(vitessColumnDef)

if node.ColumnDef.References.Table != nil {
constraintDef, err := nodeForeignKeyDefinitionFromColumnTableDef(ctx, node.ColumnDef.Name, node.ColumnDef)
if err != nil {
return nil, err
}
tableSpec.AddConstraint(&vitess.ConstraintDefinition{Details: constraintDef})
}

return &vitess.DDL{
Action: "alter",
ColumnAction: "add",
Expand Down
21 changes: 21 additions & 0 deletions testing/go/alter_table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,27 @@ func TestAlterTable(t *testing.T) {
},
},
},
{
Name: "ALTER TABLE ADD COLUMN with inline FK constraint",
SetUpScript: []string{
"create table t (v varchar(100));",
"create table parent (id int primary key);",
},
Assertions: []ScriptTestAssertion{
{
Query: "ALTER TABLE t ADD COLUMN c1 int REFERENCES parent(id);",
Expected: []sql.Row{},
},
{
Query: "SELECT conname AS constraint_name, pg_get_constraintdef(oid) AS constraint_definition FROM pg_constraint WHERE conrelid = 't'::regclass AND contype='f';",
Expected: []sql.Row{{"t_c1_fkey", "FOREIGN KEY t_c1_fkey (c1) REFERENCES parent (id)"}},
},
{
Query: "INSERT INTO t VALUES ('abc', 123);",
ExpectedErr: "Foreign key violation on fk: `t_c1_fkey`",
},
},
},
{
Name: "Rename table",
SetUpScript: []string{
Expand Down
Loading