Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(differ): support to add enum labels if possible (#3804)
rebelicefc6208235214
diff --git a/plugin/parser/ast/add_enum_label_stmt.go b/plugin/parser/ast/add_enum_label_stmt.gonew file mode 100644index 0000000000..c2c69d7b14--- /dev/null+++ b/plugin/parser/ast/add_enum_label_stmt.go@@ -0,0 +1,23 @@+package ast++// PositionType is the type of new label position.+type PositionType int++const (+ // PositionTypeEnd is the type of new label at the end of the list labels. It's default label.+ PositionTypeEnd PositionType = iota+ // PositionTypeAfter is the type of after neighbor label.+ PositionTypeAfter+ // PositionTypeBefore is the type of before neighbor label.+ PositionTypeBefore+)++// AddEnumLabelStmt is the struct of add enum label statements.+type AddEnumLabelStmt struct {+ node++ EnumType *TypeNameDef+ NewLabel string+ Position PositionType+ NeighborLabel string+}diff --git a/plugin/parser/ast/alter_type_stmt.go b/plugin/parser/ast/alter_type_stmt.gonew file mode 100644index 0000000000..f0e65f17b7--- /dev/null+++ b/plugin/parser/ast/alter_type_stmt.go@@ -0,0 +1,9 @@+package ast++// AlterTypeStmt is the struct for ALTER TYPE statements.+type AlterTypeStmt struct {+ ddl++ Type *TypeNameDef+ AlterItemList []Node+}diff --git a/plugin/parser/differ/pg/differ.go b/plugin/parser/differ/pg/differ.goindex 4216c3b144..0f698467ce 100644--- a/plugin/parser/differ/pg/differ.go+++ b/plugin/parser/differ/pg/differ.go@@ -46,6 +46,7 @@ type diffNode struct {// Create nodescreateSchemaList []ast.NodecreateTypeList []ast.Node+ alterTypeList []ast.NodecreateExtensionList []ast.NodecreateFunctionList []ast.NodecreateSequenceList []ast.Node@@ -1025,9 +1026,110 @@ func (diff *diffNode) modifyFunction(oldFunction *ast.CreateFunctionStmt, newFunreturn nil}+func isSubsequenceEnum(oldType ast.UserDefinedType, newType ast.UserDefinedType) bool {+ oldEnum, ok := oldType.(*ast.EnumTypeDef)+ if !ok {+ return false+ }+ newEnum, ok := newType.(*ast.EnumTypeDef)+ if !ok {+ return false+ }++ pos := 0+ for _, oldLabel := range oldEnum.LabelList {+ for {+ if pos >= len(newEnum.LabelList) {+ return false+ }+ if newEnum.LabelList[pos] == oldLabel {+ break+ }+ pos+++ }+ }+ return true+}++func (diff *diffNode) addEnumValue(oldType *ast.CreateTypeStmt, newType *ast.CreateTypeStmt) error {+ oldEnum, ok := oldType.Type.(*ast.EnumTypeDef)+ if !ok {+ // never catch+ return parser.NewConvertErrorf("expected EnumTypeDef but found %t", oldType.Type)+ }+ newEnum, ok := newType.Type.(*ast.EnumTypeDef)+ if !ok {+ // never catch+ return parser.NewConvertErrorf("expected EnumTypeDef but found %t", newType.Type)+ }++ // oldEnum has empty label list, so append newEnum labels.+ if len(oldEnum.LabelList) == 0 {+ for _, label := range newEnum.LabelList {+ diff.alterTypeList = append(diff.alterTypeList, &ast.AlterTypeStmt{+ Type: newType.Type.TypeName(),+ AlterItemList: []ast.Node{&ast.AddEnumLabelStmt{+ EnumType: newType.Type.TypeName(),+ NewLabel: label,+ Position: ast.PositionTypeEnd,+ }},+ })+ }+ return nil+ }++ firstOldLabelPos := 0+ for {+ if newEnum.LabelList[firstOldLabelPos] == oldEnum.LabelList[0] {+ break+ }+ firstOldLabelPos+++ }++ // Add Labels before first equal label by BEFORE.+ for i := firstOldLabelPos - 1; i >= 0; i-- {+ diff.alterTypeList = append(diff.alterTypeList, &ast.AlterTypeStmt{+ Type: newType.Type.TypeName(),+ AlterItemList: []ast.Node{&ast.AddEnumLabelStmt{+ EnumType: newType.Type.TypeName(),+ NewLabel: newEnum.LabelList[i],+ Position: ast.PositionTypeBefore,+ NeighborLabel: newEnum.LabelList[i+1],+ }},+ })+ }++ // Add remaining labels by AFTER.+ oldLabelPos := 1+ for i := firstOldLabelPos + 1; i < len(newEnum.LabelList); i++ {+ newLabel := newEnum.LabelList[i]+ if len(oldEnum.LabelList) > oldLabelPos && newLabel == oldEnum.LabelList[oldLabelPos] {+ oldLabelPos+++ continue+ }+ diff.alterTypeList = append(diff.alterTypeList, &ast.AlterTypeStmt{+ Type: newType.Type.TypeName(),+ AlterItemList: []ast.Node{&ast.AddEnumLabelStmt{+ EnumType: newType.Type.TypeName(),+ NewLabel: newLabel,+ Position: ast.PositionTypeAfter,+ NeighborLabel: newEnum.LabelList[i-1],+ }},+ })+ }++ return nil+}+func (diff *diffNode) modifyType(oldType *ast.CreateTypeStmt, newType *ast.CreateTypeStmt) error {// TODO(rebelice): not use Text(), it only works for pg_dump.if oldType.Text() != newType.Text() {+ // Add enum value.+ if isSubsequenceEnum(oldType.Type, newType.Type) {+ return diff.addEnumValue(oldType, newType)+ }++ // DROP and RE-CREATE.diff.dropTypeList = append(diff.dropTypeList, &ast.DropTypeStmt{TypeNameList: []*ast.TypeNameDef{oldType.Type.TypeName()},})@@ -1298,6 +1400,9 @@ func (diff *diffNode) deparse() (string, error) {if err := printStmtSliceByText(&buf, diff.createTypeList); err != nil {return "", err}+ if err := printStmtSlice(&buf, diff.alterTypeList); err != nil {+ return "", err+ }if err := printStmtSliceByText(&buf, diff.createExtensionList); err != nil {return "", err}diff --git a/plugin/parser/differ/pg/test-data/test_differ_data.yaml b/plugin/parser/differ/pg/test-data/test_differ_data.yamlindex f86e7fa3b4..96bd4cc1c2 100644--- a/plugin/parser/differ/pg/test-data/test_differ_data.yaml+++ b/plugin/parser/differ/pg/test-data/test_differ_data.yaml@@ -318,7 +318,7 @@- oldSchema: |CREATE TYPE public.tp1 AS ENUM ('a', 'b', 'c');CREATE TYPE public.tp2 AS ENUM ('a', 'b', 'c');- CREATE TYPE public.tp3 AS ENUM ('a', 'b', 'c');+ CREATE TYPE public.tp3 AS ENUM ('a', 'b', 'e');CREATE TABLE public.t1(a public.tp1, b public.tp2, c public.tp3)newSchema: |CREATE TYPE public.tp1 AS ENUM ('a', 'b', 'c');@@ -334,3 +334,34 @@ALTER COLUMN "b" SET DATA TYPE public.tp3;ALTER TABLE "public"."t1"ALTER COLUMN "c" SET DATA TYPE public.tp4;+- oldSchema: |+ create type public.enum1 as enum ('a', 'b', 'c');+ create table public.t1 (a enum1);+ newSchema: |+ create type public.enum1 as enum ('1', '2', 'a', '3', '4', 'b', '5', 'c', '6', '7');+ create table public.t1 (a enum1);+ diff: |+ ALTER TYPE "public"."enum1" ADD VALUE '2' BEFORE 'a';+ ALTER TYPE "public"."enum1" ADD VALUE '1' BEFORE '2';+ ALTER TYPE "public"."enum1" ADD VALUE '3' AFTER 'a';+ ALTER TYPE "public"."enum1" ADD VALUE '4' AFTER '3';+ ALTER TYPE "public"."enum1" ADD VALUE '5' AFTER 'b';+ ALTER TYPE "public"."enum1" ADD VALUE '6' AFTER 'c';+ ALTER TYPE "public"."enum1" ADD VALUE '7' AFTER '6';+- oldSchema: |+ create type public.enum1 as enum ();+ create table public.t1 (a enum1);+ newSchema: |+ create type public.enum1 as enum ('1', '2', 'a', '3', '4', 'b', '5', 'c', '6', '7');+ create table public.t1 (a enum1);+ diff: |+ ALTER TYPE "public"."enum1" ADD VALUE '1';+ ALTER TYPE "public"."enum1" ADD VALUE '2';+ ALTER TYPE "public"."enum1" ADD VALUE 'a';+ ALTER TYPE "public"."enum1" ADD VALUE '3';+ ALTER TYPE "public"."enum1" ADD VALUE '4';+ ALTER TYPE "public"."enum1" ADD VALUE 'b';+ ALTER TYPE "public"."enum1" ADD VALUE '5';+ ALTER TYPE "public"."enum1" ADD VALUE 'c';+ ALTER TYPE "public"."enum1" ADD VALUE '6';+ ALTER TYPE "public"."enum1" ADD VALUE '7';diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.goindex 11918b4ada..01d23ecf75 100644--- a/plugin/parser/engine/pg/convert.go+++ b/plugin/parser/engine/pg/convert.go@@ -717,6 +717,36 @@ func convert(node *pgquery.Node, statement parser.SingleSQL) (res ast.Node, err}return &ast.CreateTypeStmt{Type: enumTypeDef}, nil+ case *pgquery.Node_AlterEnumStmt:+ if in.AlterEnumStmt.OldVal == "" {+ schema, name, err := convertObjectName(in.AlterEnumStmt.TypeName)+ if err != nil {+ return nil, err+ }+ typeName := &ast.TypeNameDef{+ Schema: schema,+ Name: name,+ }+ // ADD ENUM VALUE STATEMENT+ addEnumValueStmt := &ast.AddEnumLabelStmt{+ EnumType: typeName,+ NewLabel: in.AlterEnumStmt.NewVal,+ NeighborLabel: in.AlterEnumStmt.NewValNeighbor,+ }+ if in.AlterEnumStmt.NewValNeighbor == "" {+ addEnumValueStmt.Position = ast.PositionTypeEnd+ } else if in.AlterEnumStmt.NewValIsAfter {+ addEnumValueStmt.Position = ast.PositionTypeAfter+ } else {+ addEnumValueStmt.Position = ast.PositionTypeBefore+ }++ return &ast.AlterTypeStmt{+ Type: typeName,+ AlterItemList: []ast.Node{addEnumValueStmt},+ }, nil+ }+ // TODO(rebelice): support RENAME ENUM VALUE statementsdefault:return &ast.UnconvertedStmt{}, nil}diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.goindex 69098c47f5..029edc2c80 100644--- a/plugin/parser/engine/pg/convert_test.go+++ b/plugin/parser/engine/pg/convert_test.go@@ -2930,3 +2930,97 @@ func TestDropType(t *testing.T) {runTests(t, tests)}++func TestAlterType(t *testing.T) {+ tests := []testData{+ {+ stmt: `ALTER TYPE public.bug_status ADD VALUE 'a' BEFORE 'b'`,+ want: []ast.Node{+ &ast.AlterTypeStmt{+ Type: &ast.TypeNameDef{+ Schema: "public",+ Name: "bug_status",+ },+ AlterItemList: []ast.Node{+ &ast.AddEnumLabelStmt{+ EnumType: &ast.TypeNameDef{+ Schema: "public",+ Name: "bug_status",+ },+ NewLabel: "a",+ Position: ast.PositionTypeBefore,+ NeighborLabel: "b",+ },+ },+ },+ },+ statementList: []parser.SingleSQL{+ {++ Text: `ALTER TYPE public.bug_status ADD VALUE 'a' BEFORE 'b'`,+ LastLine: 1,+ },+ },+ },+ {+ stmt: `ALTER TYPE public.bug_status ADD VALUE 'a' AFTER 'b'`,+ want: []ast.Node{+ &ast.AlterTypeStmt{+ Type: &ast.TypeNameDef{+ Schema: "public",+ Name: "bug_status",+ },+ AlterItemList: []ast.Node{+ &ast.AddEnumLabelStmt{+ EnumType: &ast.TypeNameDef{+ Schema: "public",+ Name: "bug_status",+ },+ NewLabel: "a",+ Position: ast.PositionTypeAfter,+ NeighborLabel: "b",+ },+ },+ },+ },+ statementList: []parser.SingleSQL{+ {++ Text: `ALTER TYPE public.bug_status ADD VALUE 'a' AFTER 'b'`,+ LastLine: 1,+ },+ },+ },+ {+ stmt: `ALTER TYPE public.bug_status ADD VALUE 'a'`,+ want: []ast.Node{+ &ast.AlterTypeStmt{+ Type: &ast.TypeNameDef{+ Schema: "public",+ Name: "bug_status",+ },+ AlterItemList: []ast.Node{+ &ast.AddEnumLabelStmt{+ EnumType: &ast.TypeNameDef{+ Schema: "public",+ Name: "bug_status",+ },+ NewLabel: "a",+ Position: ast.PositionTypeEnd,+ NeighborLabel: "",+ },+ },+ },+ },+ statementList: []parser.SingleSQL{+ {++ Text: `ALTER TYPE public.bug_status ADD VALUE 'a'`,+ LastLine: 1,+ },+ },+ },+ }++ runTests(t, tests)+}diff --git a/plugin/parser/engine/pg/deparse.go b/plugin/parser/engine/pg/deparse.goindex 62308925fa..8f3c4c4455 100644--- a/plugin/parser/engine/pg/deparse.go+++ b/plugin/parser/engine/pg/deparse.go@@ -91,6 +91,11 @@ func deparse(context parser.DeparseContext, in ast.Node, buf *strings.Builder) ereturn err}return buf.WriteByte(';')+ case *ast.AlterTypeStmt:+ if err := deparseAlterType(context, node, buf); err != nil {+ return err+ }+ return buf.WriteByte(';')}return errors.Errorf("failed to deparse %T", in)}@@ -1180,6 +1185,56 @@ func deparseFunctionSignature(function *ast.FunctionDef, buf *strings.Builder) ereturn buf.WriteByte(')')}+func deparseAlterType(ctx parser.DeparseContext, in *ast.AlterTypeStmt, buf *strings.Builder) error {+ if _, err := buf.WriteString("ALTER TYPE "); err != nil {+ return err+ }+ if in.Type.Schema != "" {+ if err := writeSurrounding(buf, in.Type.Schema, `"`); err != nil {+ return err+ }+ if err := buf.WriteByte('.'); err != nil {+ return err+ }+ }+ if err := writeSurrounding(buf, in.Type.Name, `"`); err != nil {+ return err+ }+ if err := buf.WriteByte(' '); err != nil {+ return err+ }++ for _, item := range in.AlterItemList {+ if node, ok := item.(*ast.AddEnumLabelStmt); ok {+ // The ADD ENUM VALUE statement use the cannot share the AlterType statement with other alter items.+ return deparseAddEnumValue(ctx, node, buf)+ }+ }+ return nil+}++func deparseAddEnumValue(_ parser.DeparseContext, in *ast.AddEnumLabelStmt, buf *strings.Builder) error {+ if _, err := buf.WriteString("ADD VALUE "); err != nil {+ return err+ }+ if err := writeSurrounding(buf, in.NewLabel, "'"); err != nil {+ return err+ }+ switch in.Position {+ case ast.PositionTypeEnd:+ return nil+ case ast.PositionTypeBefore:+ if _, err := buf.WriteString(" BEFORE "); err != nil {+ return err+ }+ case ast.PositionTypeAfter:+ if _, err := buf.WriteString(" AFTER "); err != nil {+ return err+ }+ }+ return writeSurrounding(buf, in.NeighborLabel, "'")+}+func deparseDropType(ctx parser.DeparseContext, in *ast.DropTypeStmt, buf *strings.Builder) error {if _, err := buf.WriteString("DROP TYPE "); err != nil {return errdiff --git a/plugin/parser/engine/pg/test-data/test_type_data.yaml b/plugin/parser/engine/pg/test-data/test_type_data.yamlindex 9a9c69d5da..26a5b80fb0 100644--- a/plugin/parser/engine/pg/test-data/test_type_data.yaml+++ b/plugin/parser/engine/pg/test-data/test_type_data.yaml@@ -2,3 +2,9 @@want: DROP TYPE IF EXISTS "tp1", "public"."tp2";- stmt: drop type tp1 cascade;want: DROP TYPE "tp1" CASCADE;+- stmt: alter type public.t1 add value 'a';+ want: ALTER TYPE "public"."t1" ADD VALUE 'a';+- stmt: alter type public.t1 add value 'a' after 'd';+ want: ALTER TYPE "public"."t1" ADD VALUE 'a' AFTER 'd';+- stmt: alter type public.t1 add value 'a' before 'x';+ want: ALTER TYPE "public"."t1" ADD VALUE 'a' BEFORE 'x';