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 sync function (#3770)
rebelice8e0a0acb352a
diff --git a/plugin/parser/differ/pg/differ.go b/plugin/parser/differ/pg/differ.goindex 89817a7432..8d54f89afc 100644--- a/plugin/parser/differ/pg/differ.go+++ b/plugin/parser/differ/pg/differ.go@@ -37,12 +37,14 @@ type diffNode struct {dropColumnList []ast.NodedropTableList []ast.NodedropSequenceList []ast.Node+ dropFunctionList []ast.NodedropExtensionList []ast.NodedropSchemaList []ast.Node// Create nodescreateSchemaList []ast.NodecreateExtensionList []ast.Node+ createFunctionList []ast.NodecreateSequenceList []ast.NodealterSequenceExceptOwnedByList []ast.NodecreateTableList []ast.Node@@ -61,6 +63,7 @@ type constraintMap map[string]*constraintInfotype indexMap map[string]*indexInfotype sequenceMap map[string]*sequenceInfotype extensionMap map[string]*extensionInfo+type functionMap map[string]*functionInfotype schemaInfo struct {id int@@ -70,6 +73,7 @@ type schemaInfo struct {indexMap indexMapsequenceMap sequenceMapextensionMap extensionMap+ functionMap functionMap}func newSchemaInfo(id int, createSchema *ast.CreateSchemaStmt) *schemaInfo {@@ -81,6 +85,7 @@ func newSchemaInfo(id int, createSchema *ast.CreateSchemaStmt) *schemaInfo {indexMap: make(indexMap),sequenceMap: make(sequenceMap),extensionMap: make(extensionMap),+ functionMap: make(functionMap),}}@@ -171,6 +176,20 @@ func newExtensionInfo(id int, createExtension *ast.CreateExtensionStmt) *extensi}}+type functionInfo struct {+ id int+ existsInNew bool+ createFunction *ast.CreateFunctionStmt+}++func newFunctionInfo(id int, createFunction *ast.CreateFunctionStmt) *functionInfo {+ return &functionInfo{+ id: id,+ existsInNew: false,+ createFunction: createFunction,+ }+}+func (m schemaMap) addTable(id int, table *ast.CreateTableStmt) error {schema, exists := m[table.Name.Schema]if !exists {@@ -234,6 +253,27 @@ func (m schemaMap) getExtension(schemaName string, extensionName string) *extensreturn schema.extensionMap[extensionName]}+func (m schemaMap) addFunction(id int, function *ast.CreateFunctionStmt) error {+ schema, exists := m[function.Function.Schema]+ if !exists {+ return errors.Errorf("failed to add function: schema %s not found", function.Function.Schema)+ }+ signature, err := functionSignature(function.Function)+ if err != nil {+ return err+ }+ schema.functionMap[signature] = newFunctionInfo(id, function)+ return nil+}++func (m schemaMap) getFunction(schemaName string, signature string) *functionInfo {+ schema, exists := m[schemaName]+ if !exists {+ return nil+ }+ return schema.functionMap[signature]+}+func (m schemaMap) addIndex(id int, index *ast.CreateIndexStmt) error {schema, exists := m[index.Index.Table.Schema]if !exists {@@ -413,6 +453,10 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {if err := oldSchemaMap.addExtension(i, stmt); err != nil {return "", err}+ case *ast.CreateFunctionStmt:+ if err := oldSchemaMap.addFunction(i, stmt); err != nil {+ return "", err+ }// TODO(rebelice): add default back here}}@@ -519,6 +563,22 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {if err := diff.modifyExtension(oldExtension.createExtension, stmt); err != nil {return "", err}+ case *ast.CreateFunctionStmt:+ signature, err := functionSignature(stmt.Function)+ if err != nil {+ return "", err+ }+ oldFunction := oldSchemaMap.getFunction(stmt.Function.Schema, signature)+ // Add the function.+ if oldFunction == nil {+ diff.createFunctionList = append(diff.createFunctionList, stmt)+ continue+ }+ oldFunction.existsInNew = true+ // Modify the function.+ if err := diff.modifyFunction(oldFunction.createFunction, stmt); err != nil {+ return "", err+ }}}@@ -620,6 +680,11 @@ func (diff *diffNode) dropObject(oldSchemaMap schemaMap) error {diff.dropExtensionList = append(diff.dropExtensionList, dropExtensionStmt)}+ // Drop the remaining old function.+ if dropFunctionStmt := dropFunction(oldSchemaMap); dropFunctionStmt != nil {+ diff.dropFunctionList = append(diff.dropFunctionList, dropFunctionStmt)+ }+return nil}@@ -831,6 +896,17 @@ func (diff *diffNode) modifyExtension(oldExtension *ast.CreateExtensionStmt, newreturn nil}+func (diff *diffNode) modifyFunction(oldFunction *ast.CreateFunctionStmt, newFunction *ast.CreateFunctionStmt) error {+ // TODO(rebelice): not use Text(), it only works for pg_dump.+ if oldFunction.Text() != newFunction.Text() {+ diff.dropFunctionList = append(diff.dropFunctionList, &ast.DropFunctionStmt{+ FunctionList: []*ast.FunctionDef{oldFunction.Function},+ })+ diff.createFunctionList = append(diff.createFunctionList, newFunction)+ }+ return nil+}+func (diff *diffNode) modifyIndex(oldIndex *ast.CreateIndexStmt, newIndex *ast.CreateIndexStmt) error {// TODO(rebelice): not use Text(), it only works for pg_dump.if oldIndex.Text() != newIndex.Text() {@@ -1059,6 +1135,9 @@ func (diff *diffNode) deparse() (string, error) {if err := printStmtSlice(&buf, diff.dropSequenceList); err != nil {return "", err}+ if err := printStmtSlice(&buf, diff.dropFunctionList); err != nil {+ return "", err+ }if err := printStmtSlice(&buf, diff.dropExtensionList); err != nil {return "", err}@@ -1073,6 +1152,9 @@ func (diff *diffNode) deparse() (string, error) {if err := printStmtSliceByText(&buf, diff.createExtensionList); err != nil {return "", err}+ if err := printStmtSliceByText(&buf, diff.createFunctionList); err != nil {+ return "", err+ }if err := printStmtSlice(&buf, diff.createSequenceList); err != nil {return "", err}@@ -1207,6 +1289,31 @@ func dropExtension(m schemaMap) *ast.DropExtensionStmt {}}+func dropFunction(m schemaMap) *ast.DropFunctionStmt {+ var functionList []*functionInfo+ for _, schema := range m {+ for _, function := range schema.functionMap {+ if function.existsInNew {+ // no need to drop+ continue+ }+ functionList = append(functionList, function)+ }+ }+ if len(functionList) == 0 {+ return nil+ }+ sort.Slice(functionList, func(i, j int) bool {+ return functionList[i].id < functionList[j].id+ })++ var functionDefList []*ast.FunctionDef+ for _, function := range functionList {+ functionDefList = append(functionDefList, function.createFunction.Function)+ }+ return &ast.DropFunctionStmt{FunctionList: functionDefList}+}+func dropIndex(m schemaMap) *ast.DropIndexStmt {var indexList []*indexInfofor _, schema := range m {@@ -1304,3 +1411,10 @@ func writeStringWithNewLine(out io.Writer, str string) error {}return nil}++// use DROP FUNCTION statement as the function signature.+func functionSignature(function *ast.FunctionDef) (string, error) {+ return parser.Deparse(parser.Postgres, parser.DeparseContext{}, &ast.DropFunctionStmt{+ FunctionList: []*ast.FunctionDef{function},+ })+}diff --git a/plugin/parser/differ/pg/test-data/test_differ_data.yaml b/plugin/parser/differ/pg/test-data/test_differ_data.yamlindex a49559e889..39aafc825f 100644--- a/plugin/parser/differ/pg/test-data/test_differ_data.yaml+++ b/plugin/parser/differ/pg/test-data/test_differ_data.yaml@@ -199,3 +199,72 @@DROP INDEX "public"."trgm_idx2";DROP INDEX "public"."trgm_idx3";CREATE INDEX trgm_idx2 ON public.test_trgm USING gin (t2 public.gin_trgm_ops);+- oldSchema: |+ CREATE FUNCTION public.trigger_update_updated_ts() RETURNS trigger+ LANGUAGE plpgsql+ AS $$+ BEGIN+ NEW.updated_ts = extract(epoch from now());+ RETURN NEW;+ END;+ $$;+ CREATE FUNCTION public.f1() RETURNS trigger+ LANGUAGE plpgsql+ AS $$+ BEGIN+ NEW.updated_ts = extract(epoch from now());+ RETURN NEW;+ END;+ $$;+ CREATE FUNCTION public.f1(int) RETURNS trigger+ LANGUAGE plpgsql+ AS $$+ BEGIN+ NEW.updated_ts = extract(epoch from now());+ RETURN NEW;+ END;+ $$;+ newSchema: |+ CREATE FUNCTION public.trigger_update_updated_ts() RETURNS trigger+ LANGUAGE plpgsql+ AS $$+ BEGIN+ NEW.updated_ts = extract(epoch from now());+ RETURN NEW;+ END;+ $$;+ CREATE FUNCTION public.f1(int, int, int) RETURNS trigger+ LANGUAGE plpgsql+ AS $$+ BEGIN+ NEW.updated_ts = extract(epoch from now());+ RETURN NEW;+ END;+ $$;+ CREATE FUNCTION public.f1(int) RETURNS trigger+ LANGUAGE plpgsql+ AS $$+ BEGIN+ NEW.ts = extract(epoch from now());+ RETURN NEW;+ END;+ $$;+ diff: |+ DROP FUNCTION "public"."f1"(integer);+ DROP FUNCTION "public"."f1"();+ CREATE FUNCTION public.f1(int, int, int) RETURNS trigger+ LANGUAGE plpgsql+ AS $$+ BEGIN+ NEW.updated_ts = extract(epoch from now());+ RETURN NEW;+ END;+ $$;+ CREATE FUNCTION public.f1(int) RETURNS trigger+ LANGUAGE plpgsql+ AS $$+ BEGIN+ NEW.ts = extract(epoch from now());+ RETURN NEW;+ END;+ $$;diff --git a/plugin/parser/engine/pg/deparse.go b/plugin/parser/engine/pg/deparse.goindex 2d166612a0..0ec47482f6 100644--- a/plugin/parser/engine/pg/deparse.go+++ b/plugin/parser/engine/pg/deparse.go@@ -76,6 +76,11 @@ func deparse(context parser.DeparseContext, in ast.Node, buf *strings.Builder) ereturn err}return buf.WriteByte(';')+ case *ast.DropFunctionStmt:+ if err := deparseDropFunction(context, node, buf); err != nil {+ return err+ }+ return buf.WriteByte(';')}return errors.Errorf("failed to deparse %T", in)}@@ -1110,6 +1115,61 @@ func deparseAlterSequence(ctx parser.DeparseContext, in *ast.AlterSequenceStmt,return nil}+func deparseDropFunction(ctx parser.DeparseContext, in *ast.DropFunctionStmt, buf *strings.Builder) error {+ if _, err := buf.WriteString("DROP FUNCTION "); err != nil {+ return err+ }+ if in.IfExists {+ if _, err := buf.WriteString("IF EXISTS "); err != nil {+ return err+ }+ }+ for i, function := range in.FunctionList {+ if i != 0 {+ if _, err := buf.WriteString(", "); err != nil {+ return err+ }+ }+ if err := deparseFunctionSignature(function, buf); err != nil {+ return err+ }+ }+ return deparseDropBehavior(ctx, in.Behavior, buf)+}++func deparseFunctionSignature(function *ast.FunctionDef, buf *strings.Builder) error {+ if function.Schema != "" {+ if err := writeSurrounding(buf, function.Schema, `"`); err != nil {+ return err+ }+ if err := buf.WriteByte('.'); err != nil {+ return err+ }+ }+ if err := writeSurrounding(buf, function.Name, `"`); err != nil {+ return err+ }+ if err := buf.WriteByte('('); err != nil {+ return err+ }+ total := 0+ for _, parameter := range function.ParameterList {+ if parameter.Mode == ast.FunctionParameterModeOut {+ continue+ }+ if total != 0 {+ if _, err := buf.WriteString(", "); err != nil {+ return err+ }+ }+ total+++ if err := deparseDataType(parser.DeparseContext{}, parameter.Type, buf); err != nil {+ return err+ }+ }+ return buf.WriteByte(')')+}+func deparseDropExtension(ctx parser.DeparseContext, in *ast.DropExtensionStmt, buf *strings.Builder) error {if _, err := buf.WriteString("DROP EXTENSION "); err != nil {return errdiff --git a/plugin/parser/engine/pg/deparse_test.go b/plugin/parser/engine/pg/deparse_test.goindex 16ad099ce6..08315d9041 100644--- a/plugin/parser/engine/pg/deparse_test.go+++ b/plugin/parser/engine/pg/deparse_test.go@@ -73,6 +73,8 @@ func TestDeparse(t *testing.T) {"test_drop_sequence_data.yaml",// Extension"test_extension_data.yaml",+ // Function+ "test_function_data.yaml",}for _, test := range testFileList {runDeparseTest(t, test, false /* record */)diff --git a/plugin/parser/engine/pg/test-data/test_function_data.yaml b/plugin/parser/engine/pg/test-data/test_function_data.yamlnew file mode 100644index 0000000000..bcad4621e2--- /dev/null+++ b/plugin/parser/engine/pg/test-data/test_function_data.yaml@@ -0,0 +1,4 @@+- stmt: drop function func1(a int, b int, c int);+ want: DROP FUNCTION "func1"(integer, integer, integer);+- stmt: drop function if exists public.func1(a int), func2(OUT int);+ want: DROP FUNCTION IF EXISTS "public"."func1"(integer), "func2"();