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
50 changes: 50 additions & 0 deletions internal/catalog/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,56 @@ func Update(c *pg.Catalog, stmt nodes.Node) error {

switch n := raw.Stmt.(type) {

case nodes.AlterEnumStmt:
fqn, err := ParseList(n.TypeName)
if err != nil {
return err
}
schema, exists := c.Schemas[fqn.Schema]
if !exists {
return wrap(pg.ErrorSchemaDoesNotExist(fqn.Schema), raw.StmtLocation)
}
typ, exists := schema.Types[fqn.Rel]
if !exists {
return wrap(pg.ErrorRelationDoesNotExist(fqn.Rel), raw.StmtLocation)
}
enum, ok := typ.(pg.Enum)
if !ok {
return wrap(pg.ErrorRelationDoesNotExist(fqn.Rel), raw.StmtLocation)
}
oldIndex := -1
newIndex := -1
for i, val := range enum.Vals {
if n.OldVal != nil && val == *n.OldVal {
oldIndex = i
}
if n.NewVal != nil && val == *n.NewVal {
newIndex = i
}
}
if n.OldVal != nil {
// RENAME TYPE
if oldIndex < 0 {
return fmt.Errorf("type %s does not have value %s", fqn.Rel, *n.OldVal)
}
if newIndex >= 0 {
return fmt.Errorf("type %s already has value %s", fqn.Rel, *n.NewVal)
}
enum.Vals[oldIndex] = *n.NewVal
schema.Types[fqn.Rel] = enum
} else {
// ADD VALUE
if newIndex >= 0 {
if !n.SkipIfNewValExists {
return fmt.Errorf("type %s already has value %s", fqn.Rel, *n.NewVal)
} else {
return nil
}
}
enum.Vals = append(enum.Vals, *n.NewVal)
schema.Types[fqn.Rel] = enum
}

case nodes.AlterObjectSchemaStmt:
switch n.ObjectType {

Expand Down
58 changes: 58 additions & 0 deletions internal/catalog/build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,43 @@ func TestUpdate(t *testing.T) {
},
},
},
{
`
CREATE TYPE status AS ENUM ('open', 'closed');
ALTER TYPE status RENAME VALUE 'closed' TO 'shut';
`,
pg.Catalog{
Schemas: map[string]pg.Schema{
"public": {
Types: map[string]pg.Type{
"status": pg.Enum{
Name: "status",
Vals: []string{"open", "shut"},
},
},
},
},
},
},
{
`
CREATE TYPE status AS ENUM ('open', 'closed');
ALTER TYPE status ADD VALUE 'unknown';
ALTER TYPE status ADD VALUE IF NOT EXISTS 'unknown';
`,
pg.Catalog{
Schemas: map[string]pg.Schema{
"public": {
Types: map[string]pg.Type{
"status": pg.Enum{
Name: "status",
Vals: []string{"open", "closed", "unknown"},
},
},
},
},
},
},
{
"CREATE TABLE venues ();",
pg.Catalog{
Expand Down Expand Up @@ -240,6 +277,27 @@ func TestUpdate(t *testing.T) {
},
},
},
/*
{
`
CREATE TYPE status AS ENUM ('open', 'closed');
ALTER TYPE status RENAME VALUE 'closed' TO 'shut';
`,
pg.Catalog{
Schemas: map[string]pg.Schema{
"public": {
Types: map[string]pg.Type{
"status": pg.Enum{
Name: "status",
Vals: []string{"open", "shut"},
},
},
Tables: map[string]pg.Table{},
},
},
},
},
*/
{
`
CREATE TABLE venues ();
Expand Down
Loading