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: support Branching and Differ for PostgreSQL COMMENT TABLE/COLUMN (#8647)
rebelice85a9b6403592
diff --git a/backend/plugin/parser/pg/differ.go b/backend/plugin/parser/pg/differ.goindex 9460e61b94..3770a32e12 100644--- a/backend/plugin/parser/pg/differ.go+++ b/backend/plugin/parser/pg/differ.go@@ -54,6 +54,7 @@ type diffNode struct {createTriggerList []ast.NodecreateConstraintExceptFkList []ast.NodecreateForeignKeyList []ast.Node+ setCommentList []ast.Node}type schemaMap map[string]*schemaInfo@@ -93,20 +94,24 @@ func newSchemaInfo(id int, createSchema *ast.CreateSchemaStmt) *schemaInfo {}type tableInfo struct {- id int- existsInNew bool- createTable *ast.CreateTableStmt- constraintMap constraintMap- triggerMap triggerMap+ id int+ existsInNew bool+ createTable *ast.CreateTableStmt+ constraintMap constraintMap+ triggerMap triggerMap+ comment string+ columnCommentMap map[string]string}func newTableInfo(id int, createTable *ast.CreateTableStmt) *tableInfo {return &tableInfo{- id: id,- existsInNew: false,- createTable: createTable,- constraintMap: make(constraintMap),- triggerMap: make(triggerMap),+ id: id,+ existsInNew: false,+ createTable: createTable,+ constraintMap: make(constraintMap),+ triggerMap: make(triggerMap),+ comment: "",+ columnCommentMap: make(map[string]string),}}@@ -407,6 +412,96 @@ func (m schemaMap) getType(schemaName string, typeName string) *typeInfo {return schema.typeMap[typeName]}+func (m schemaMap) addComment(comment *ast.CommentStmt) error {+ switch comment.Type {+ case ast.ObjectTypeTable:+ tableDef, ok := comment.Object.(*ast.TableDef)+ if !ok {+ return errors.Errorf("failed to add comment: expect table def, but found %v", comment.Object)+ }+ schema, exists := m[tableDef.Schema]+ if !exists {+ return errors.Errorf("failed to add comment: schema %s not found", tableDef.Schema)+ }+ table, exists := schema.tableMap[tableDef.Name]+ if !exists {+ return errors.Errorf("failed to add comment: table %s not found", tableDef.Name)+ }+ table.comment = comment.Comment+ return nil+ case ast.ObjectTypeColumn:+ columnNameDef, ok := comment.Object.(*ast.ColumnNameDef)+ if !ok {+ return errors.Errorf("failed to add comment: expect column name def, but found %v", comment.Object)+ }+ schema, exists := m[columnNameDef.Table.Schema]+ if !exists {+ return errors.Errorf("failed to add comment: schema %s not found", columnNameDef.Table.Schema)+ }+ table, exists := schema.tableMap[columnNameDef.Table.Name]+ if !exists {+ return errors.Errorf("failed to add comment: table %s not found", columnNameDef.Table.Name)+ }+ table.columnCommentMap[columnNameDef.ColumnName] = comment.Comment+ return nil+ default:+ // We only support table and column comment.+ return nil+ }+}++func (m schemaMap) getTableComment(schemaName string, tableName string) string {+ schema, exists := m[schemaName]+ if !exists {+ return ""+ }+ table, exists := schema.tableMap[tableName]+ if !exists {+ return ""+ }+ return table.comment+}++func (m schemaMap) removeTableComment(schemaName string, tableName string) {+ schema, exists := m[schemaName]+ if !exists {+ return+ }+ table, exists := schema.tableMap[tableName]+ if !exists {+ return+ }+ table.comment = ""+}++func (m schemaMap) getColumnComment(schemaName string, tableName string, columnName string) string {+ schema, exists := m[schemaName]+ if !exists {+ return ""+ }+ table, exists := schema.tableMap[tableName]+ if !exists {+ return ""+ }+ columnComment, exists := table.columnCommentMap[columnName]+ if !exists {+ return ""+ }+ return columnComment+}++func (m schemaMap) removeColumnComment(schemaName string, tableName string, columnName string) {+ schema, exists := m[schemaName]+ if !exists {+ return+ }+ table, exists := schema.tableMap[tableName]+ if !exists {+ return+ }+ delete(table.columnCommentMap, columnName)+}+func onlySetOwnedBy(sequence *ast.AlterSequenceStmt) bool {return sequence.Type == nil &&sequence.IncrementBy == nil &&@@ -614,6 +709,10 @@ func SchemaDiff(oldStmt, newStmt string, _ bool) (string, error) {if err := oldSchemaMap.addType(i, stmt); err != nil {return "", err}+ case *ast.CommentStmt:+ if err := oldSchemaMap.addComment(stmt); err != nil {+ return "", err+ }// TODO(rebelice): add default back here}}@@ -641,7 +740,7 @@ func SchemaDiff(oldStmt, newStmt string, _ bool) (string, error) {}oldTable.existsInNew = true// Modify the table.- if err := diff.modifyTable(oldTable.createTable, stmt); err != nil {+ if err := diff.modifyTable(oldTable, stmt); err != nil {return "", err}case *ast.CreateSchemaStmt:@@ -809,6 +908,33 @@ func SchemaDiff(oldStmt, newStmt string, _ bool) (string, error) {if err := diff.modifyType(oldType.createType, stmt); err != nil {return "", err}+ case *ast.CommentStmt:+ switch stmt.Type {+ case ast.ObjectTypeTable:+ tableDef, ok := stmt.Object.(*ast.TableDef)+ if !ok {+ return "", errors.Errorf("failed to add comment: expect table def, but found %v", stmt.Object)+ }+ oldComment := oldSchemaMap.getTableComment(tableDef.Schema, tableDef.Name)+ // Set the table comment.+ if oldComment == "" || oldComment != stmt.Comment {+ diff.setCommentList = append(diff.setCommentList, stmt)+ }+ oldSchemaMap.removeTableComment(tableDef.Schema, tableDef.Name)+ case ast.ObjectTypeColumn:+ columnNameDef, ok := stmt.Object.(*ast.ColumnNameDef)+ if !ok {+ return "", errors.Errorf("failed to add comment: expect column name def, but found %v", stmt.Object)+ }+ oldComment := oldSchemaMap.getColumnComment(columnNameDef.Table.Schema, columnNameDef.Table.Name, columnNameDef.ColumnName)+ // Set the column comment.+ if oldComment == "" || oldComment != stmt.Comment {+ diff.setCommentList = append(diff.setCommentList, stmt)+ }+ oldSchemaMap.removeColumnComment(columnNameDef.Table.Schema, columnNameDef.Table.Name, columnNameDef.ColumnName)+ default:+ // We only support table and column comment.+ }}}@@ -921,10 +1047,14 @@ func (diff *diffNode) dropObject(oldSchemaMap schemaMap) error {// Drop the remaining old type.diff.dropTypeStmt(oldSchemaMap)+ // Drop the remaining old comment.+ diff.dropComment(oldSchemaMap)+return nil}-func (diff *diffNode) modifyTableByColumn(oldTable *ast.CreateTableStmt, newTable *ast.CreateTableStmt) error {+func (diff *diffNode) modifyTableByColumn(oldTableInfo *tableInfo, newTable *ast.CreateTableStmt) error {+ oldTable := oldTableInfo.createTabletableName := oldTable.NameaddColumn := &ast.AlterTableStmt{Table: tableName,@@ -957,6 +1087,8 @@ func (diff *diffNode) modifyTableByColumn(oldTable *ast.CreateTableStmt, newTablfor _, oldColumn := range oldTable.ColumnList {if _, exists := oldColumnMap[oldColumn.ColumnName]; exists {+ // No need to drop comment for the column, because we will drop the column.+ delete(oldTableInfo.columnCommentMap, oldColumn.ColumnName)dropColumn.AlterItemList = append(dropColumn.AlterItemList, &ast.DropColumnStmt{Table: tableName,ColumnName: oldColumn.ColumnName,@@ -1013,12 +1145,12 @@ func (diff *diffNode) modifyTableByConstraint(oldTable *ast.CreateTableStmt, newreturn nil}-func (diff *diffNode) modifyTable(oldTable *ast.CreateTableStmt, newTable *ast.CreateTableStmt) error {+func (diff *diffNode) modifyTable(oldTable *tableInfo, newTable *ast.CreateTableStmt) error {if err := diff.modifyTableByColumn(oldTable, newTable); err != nil {return err}- return diff.modifyTableByConstraint(oldTable, newTable)+ return diff.modifyTableByConstraint(oldTable.createTable, newTable)}func isEqualConstraint(oldConstraint *ast.ConstraintDef, newConstraint *ast.ConstraintDef) (bool, error) {@@ -1565,6 +1697,9 @@ func (diff *diffNode) deparse() (string, error) {if err := printStmtSlice(&buf, diff.createForeignKeyList); err != nil {return "", err}+ if err := printStmtSlice(&buf, diff.setCommentList); err != nil {+ return "", err+ }return buf.String(), nil}@@ -1694,6 +1829,60 @@ func dropFunction(m schemaMap) *ast.DropFunctionStmt {return &ast.DropFunctionStmt{FunctionList: functionDefList}}+func (diff *diffNode) dropComment(m schemaMap) {+ var tables []*tableInfo+ for _, schema := range m {+ for _, table := range schema.tableMap {+ if !table.existsInNew {+ // no need to drop, because the comments are dropped when drop table+ continue+ }+ tables = append(tables, table)+ }+ }+ if len(tables) == 0 {+ return+ }+ sort.Slice(tables, func(i, j int) bool {+ return tables[i].id < tables[j].id+ })++ for _, table := range tables {+ if table.comment != "" {+ diff.setCommentList = append(diff.setCommentList, &ast.CommentStmt{+ Comment: "",+ Object: &ast.TableDef{Schema: table.createTable.Name.Schema, Name: table.createTable.Name.Name},+ Type: ast.ObjectTypeTable,+ })+ }++ type commentInfo struct {+ column string+ comment string+ }+ var columnCommentList []commentInfo+ for k, v := range table.columnCommentMap {+ columnCommentList = append(columnCommentList, commentInfo{+ column: k,+ comment: v,+ })+ }+ sort.Slice(columnCommentList, func(i, j int) bool {+ return columnCommentList[i].column < columnCommentList[j].column+ })+ for _, columnComment := range columnCommentList {+ diff.setCommentList = append(diff.setCommentList, &ast.CommentStmt{+ Comment: "",+ Object: &ast.ColumnNameDef{+ Table: &ast.TableDef{Schema: table.createTable.Name.Schema, Name: table.createTable.Name.Name},+ ColumnName: columnComment.column,+ },+ Type: ast.ObjectTypeColumn,+ })+ }+ }+}+func (diff *diffNode) dropTypeStmt(m schemaMap) {var typeList []*typeInfofor _, schema := range m {diff --git a/backend/plugin/parser/pg/pg.go b/backend/plugin/parser/pg/pg.goindex 7183de46ac..c5a761e0cd 100644--- a/backend/plugin/parser/pg/pg.go+++ b/backend/plugin/parser/pg/pg.go@@ -40,13 +40,24 @@ func ParsePostgreSQL(sql string) (antlr.Tree, error) {return tree, nil}-// NormalizePostgreSQLQualifiedNameAsTableName normalizes the given qualified name as table name.-func NormalizePostgreSQLQualifiedNameAsTableName(ctx parser.IQualified_nameContext) (string, string, error) {+// NormalizePostgreSQLAnyName normalizes the given any name.+func NormalizePostgreSQLAnyName(ctx parser.IAny_nameContext) []string {if ctx == nil {- return "", "", nil+ return nil}- list := NormalizePostgreSQLQualifiedName(ctx)+ var result []string+ result = append(result, NormalizePostgreSQLColid(ctx.Colid()))+ if ctx.Attrs() != nil {+ for _, item := range ctx.Attrs().AllAttr_name() {+ result = append(result, normalizePostgreSQLAttrName(item))+ }+ }++ return result+}++func normalizePostgreSQLStringListAsTableName(list []string) (string, string, error) {switch len(list) {case 2:return list[0], list[1], nil@@ -55,10 +66,50 @@ func NormalizePostgreSQLQualifiedNameAsTableName(ctx parser.IQualified_nameContecase 0:return "", "", nildefault:- return "", "", errors.Errorf("Invalid table name: %s", ctx.GetText())+ return "", "", errors.Errorf("Invalid table name: %v", list)}}+// NormalizePostgreSQLAnyNameAsTableName normalizes the given any name as table name.+func NormalizePostgreSQLAnyNameAsTableName(ctx parser.IAny_nameContext) (string, string, error) {+ if ctx == nil {+ return "", "", nil+ }++ list := NormalizePostgreSQLAnyName(ctx)+ return normalizePostgreSQLStringListAsTableName(list)+}++// NormalizePostgreSQLAnyNameAsColumnName normalizes the given any name as column name.+func NormalizePostgreSQLAnyNameAsColumnName(ctx parser.IAny_nameContext) (string, string, string, error) {+ if ctx == nil {+ return "", "", "", nil+ }++ list := NormalizePostgreSQLAnyName(ctx)++ switch len(list) {+ case 3:+ return list[0], list[1], list[2], nil+ case 2:+ return "", list[0], list[1], nil+ case 1:+ return "", "", list[0], nil+ default:+ return "", "", "", errors.Errorf("Invalid column name: %v", list)+ }+}++// NormalizePostgreSQLQualifiedNameAsTableName normalizes the given qualified name as table name.+func NormalizePostgreSQLQualifiedNameAsTableName(ctx parser.IQualified_nameContext) (string, string, error) {+ if ctx == nil {+ return "", "", nil+ }++ list := NormalizePostgreSQLQualifiedName(ctx)+ return normalizePostgreSQLStringListAsTableName(list)+}+// ParsePostgreSQLStatement parses the given SQL and returns the AST tree.func NormalizePostgreSQLQualifiedName(ctx parser.IQualified_nameContext) []string {if ctx == nil {diff --git a/backend/plugin/parser/pg/test-data/test_differ_data.yaml b/backend/plugin/parser/pg/test-data/test_differ_data.yamlindex a86cfb9da6..8b9c7bc7a4 100644--- a/backend/plugin/parser/pg/test-data/test_differ_data.yaml+++ b/backend/plugin/parser/pg/test-data/test_differ_data.yaml@@ -449,3 +449,43 @@"a" integer);+- oldSchema: |-+ create table "public"."t1" ("a" int);+ comment on table "public"."t1" is 'comment with ''; test escape';+ create table "public"."t2" ("a" int);+ comment on table "public"."t2" is 'comment with ''; test escape';+ create table "public"."t3" ("a" int);+ create table "public"."t4" ("a" int);+ comment on table "public"."t4" is 'comment with ''; test escape';+ newSchema: |-+ create table "public"."t1" ("a" int);+ create table "public"."t2" ("a" int);+ comment on table "public"."t2" is 'comment with ''; test escape';+ create table "public"."t3" ("a" int);+ comment on table "public"."t3" is 'comment with ''; test escape';+ create table "public"."t4" ("a" int);+ comment on table "public"."t4" is 'comment with ''; test escape for t4';+ diff: |++ COMMENT ON TABLE "public"."t3" IS 'comment with ''; test escape';++ COMMENT ON TABLE "public"."t4" IS 'comment with ''; test escape for t4';++ COMMENT ON TABLE "public"."t1" IS '';++- oldSchema: |-+ create table "public"."t1" ("a" int, b int, c int, d int);+ comment on column public.t1.a is 'comment with ''; test escape';+ comment on column public.t1.b is 'comment with ''; test escape for b';+ comment on column public.t1.d is 'comment with ''; test escape';+ newSchema: |-+ create table "public"."t1" ("a" int, b int, c int, d int);+ comment on column public.t1.c is 'comment with ''; test escape for c';+ comment on column public.t1.b is 'comment with ''; test escape for b';+ comment on column public.t1.d is 'comment with ''; test escape for d';+ diff: |++ COMMENT ON COLUMN "public"."t1"."c" IS 'comment with ''; test escape for c';++ COMMENT ON COLUMN "public"."t1"."d" IS 'comment with ''; test escape for d';++ COMMENT ON COLUMN "public"."t1"."a" IS '';+diff --git a/backend/plugin/parser/sql/engine/pg/convert.go b/backend/plugin/parser/sql/engine/pg/convert.goindex dd138837b4..f30c4a2b7f 100644--- a/backend/plugin/parser/sql/engine/pg/convert.go+++ b/backend/plugin/parser/sql/engine/pg/convert.go@@ -653,7 +653,8 @@ func convert(node *pgquery.Node, statement base.SingleSQL) (res ast.Node, err erreturn ©Stmt, nilcase *pgquery.Node_CommentStmt:commentStmt := ast.CommentStmt{- Comment: in.CommentStmt.Comment,+ // unescape single quote+ Comment: strings.ReplaceAll(in.CommentStmt.Comment, "''", "'"),}switch in.CommentStmt.Objtype {diff --git a/backend/plugin/parser/sql/engine/pg/convert_test.go b/backend/plugin/parser/sql/engine/pg/convert_test.goindex e0cd824267..412ba19053 100644--- a/backend/plugin/parser/sql/engine/pg/convert_test.go+++ b/backend/plugin/parser/sql/engine/pg/convert_test.go@@ -2222,15 +2222,15 @@ func TestUnconvertStmt(t *testing.T) {func TestCommentStmt(t *testing.T) {tests := []testData{{- stmt: "COMMENT ON TABLE public.tech_book IS 'This is a comment.'",+ stmt: "COMMENT ON TABLE public.tech_book IS 'This is a comment with ''.'",want: []ast.Node{&ast.CommentStmt{Type: ast.ObjectTypeTable,Object: &ast.TableDef{Schema: "public", Name: "tech_book"},- Comment: "This is a comment.",+ Comment: "This is a comment with '.",}},statementList: []base.SingleSQL{{- Text: "COMMENT ON TABLE public.tech_book IS 'This is a comment.'",+ Text: "COMMENT ON TABLE public.tech_book IS 'This is a comment with ''.'",LastLine: 1,},},diff --git a/backend/plugin/parser/sql/engine/pg/deparse.go b/backend/plugin/parser/sql/engine/pg/deparse.goindex 0fa3234d54..751eb8e0c0 100644--- a/backend/plugin/parser/sql/engine/pg/deparse.go+++ b/backend/plugin/parser/sql/engine/pg/deparse.go@@ -100,10 +100,88 @@ func deparseImpl(context DeparseContext, in ast.Node, buf *strings.Builder) erroreturn err}return buf.WriteByte(';')+ case *ast.CommentStmt:+ if err := deparseComment(context, node, buf); err != nil {+ return err+ }+ return buf.WriteByte(';')}return errors.Errorf("failed to deparse %T", in)}+func deparseComment(context DeparseContext, in *ast.CommentStmt, buf *strings.Builder) error {+ if err := context.WriteIndent(buf, deparseIndentString); err != nil {+ return err+ }++ switch in.Type {+ case ast.ObjectTypeTable:+ if _, err := buf.WriteString("COMMENT ON TABLE \""); err != nil {+ return err+ }+ tableDef, ok := in.Object.(*ast.TableDef)+ if !ok {+ return errors.Errorf("expect *ast.TableDef, but got %T", in.Object)+ }+ if tableDef.Schema != "" {+ if _, err := buf.WriteString(tableDef.Schema); err != nil {+ return err+ }+ if _, err := buf.WriteString("\".\""); err != nil {+ return err+ }+ }+ if _, err := buf.WriteString(tableDef.Name); err != nil {+ return err+ }+ if _, err := buf.WriteString("\" IS '"); err != nil {+ return err+ }+ escapeComment := strings.ReplaceAll(in.Comment, "'", "''")+ if _, err := buf.WriteString(escapeComment); err != nil {+ return err+ }+ _, err := buf.WriteString("'")+ return err+ case ast.ObjectTypeColumn:+ if _, err := buf.WriteString("COMMENT ON COLUMN \""); err != nil {+ return err+ }+ columnNameDef, ok := in.Object.(*ast.ColumnNameDef)+ if !ok {+ return errors.Errorf("expect *ast.ColumnNameDef, but got %T", in.Object)+ }+ if columnNameDef.Table.Schema != "" {+ if _, err := buf.WriteString(columnNameDef.Table.Schema); err != nil {+ return err+ }+ if _, err := buf.WriteString("\".\""); err != nil {+ return err+ }+ }+ if _, err := buf.WriteString(columnNameDef.Table.Name); err != nil {+ return err+ }+ if _, err := buf.WriteString("\".\""); err != nil {+ return err+ }+ if _, err := buf.WriteString(columnNameDef.ColumnName); err != nil {+ return err+ }+ if _, err := buf.WriteString("\" IS '"); err != nil {+ return err+ }+ escapeComment := strings.ReplaceAll(in.Comment, "'", "''")+ if _, err := buf.WriteString(escapeComment); err != nil {+ return err+ }+ _, err := buf.WriteString("'")+ return err+ default:+ return errors.Errorf("failed to deparse comment for type %v", in.Type)+ }+}+func deparseDropIndex(context DeparseContext, in *ast.DropIndexStmt, buf *strings.Builder) error {if err := context.WriteIndent(buf, deparseIndentString); err != nil {return errdiff --git a/backend/plugin/parser/sql/engine/pg/deparse_test.go b/backend/plugin/parser/sql/engine/pg/deparse_test.goindex ae7a74d560..6e36cbabb5 100644--- a/backend/plugin/parser/sql/engine/pg/deparse_test.go+++ b/backend/plugin/parser/sql/engine/pg/deparse_test.go@@ -76,6 +76,8 @@ func TestDeparse(t *testing.T) {"test_trigger_data.yaml",// Type"test_type_data.yaml",+ // Comment+ "test_comment_data.yaml",}for _, test := range testFileList {runDeparseTest(t, test, false /* record */)diff --git a/backend/plugin/parser/sql/engine/pg/test-data/test_comment_data.yaml b/backend/plugin/parser/sql/engine/pg/test-data/test_comment_data.yamlnew file mode 100644index 0000000000..162b5bbbd6--- /dev/null+++ b/backend/plugin/parser/sql/engine/pg/test-data/test_comment_data.yaml@@ -0,0 +1,4 @@+- stmt: COMMENT ON COLUMN public.t4.c IS 'comment with ''; test escape';+ want: COMMENT ON COLUMN "public"."t4"."c" IS 'comment with ''; test escape';+- stmt: COMMENT ON TABLE public.t4 IS 'comment with ''; test escape';+ want: COMMENT ON TABLE "public"."t4" IS 'comment with ''; test escape';diff --git a/backend/plugin/schema-engine/pg/structurer.go b/backend/plugin/schema-engine/pg/structurer.goindex 8e0080102c..9980ce57ca 100644--- a/backend/plugin/schema-engine/pg/structurer.go+++ b/backend/plugin/schema-engine/pg/structurer.go@@ -623,12 +623,25 @@ func (i *indexState) toString(buf *strings.Builder, schemaName, tableName string}type columnState struct {- id int- name string- tp string- defaultValue *string- comment string- nullable bool+ // ignore means this column is already in the target schema.+ // But we need the columnState to deal with the comment statement.+ // So we cannot delete the columnState, instead we set ignore to true.+ ignore bool+ // ignoreComment means this column is already in the target schema.+ ignoreComment bool+ id int+ name string+ tp string+ defaultValue *string+ comment string+ nullable bool+}++func (c *columnState) commentToString(buf *strings.Builder, schemaName, tableName string) error {+ if _, err := buf.WriteString(fmt.Sprintf("COMMENT ON COLUMN \"%s\".\"%s\".\"%s\" IS '%s';\n", schemaName, tableName, c.name, escapePostgreSQLString(c.comment))); err != nil {+ return err+ }+ return nil}func (c *columnState) toString(buf *strings.Builder) error {@@ -736,6 +749,26 @@ func GetDesignSchema(baselineSchema string, to *v1pb.DatabaseMetadata) (string,if err := tableState.toString(&listener.result, schema.Name); err != nil {return "", err}++ if _, err := listener.result.WriteString("\n"); err != nil {+ return "", err+ }++ for _, column := range table.Columns {+ columnState, exists := tableState.columns[column.Name]+ if !exists {+ continue+ }++ if column.Comment != "" && !columnState.ignoreComment {+ if err := columnState.commentToString(&listener.result, schema.Name, table.Name); err != nil {+ return "", err+ }+ if _, err := listener.result.WriteString("\n"); err != nil {+ return "", err+ }+ }+ }}}@@ -806,6 +839,9 @@ func (g *designSchemaGenerator) ExitCreatestmt(ctx *postgres.CreatestmtContext)var columnList []*columnStatefor _, column := range g.currentTable.columns {+ if column.ignore {+ continue+ }columnList = append(columnList, column)}sort.Slice(columnList, func(i, j int) bool {@@ -1108,6 +1144,131 @@ func (g *designSchemaGenerator) EnterTablelikeclause(ctx *postgres.Tablelikeclau}}+func (g *designSchemaGenerator) EnterCommentstmt(ctx *postgres.CommentstmtContext) {+ if g.err != nil {+ return+ }+ if _, err := g.result.WriteString(ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{+ Start: g.lastTokenIndex,+ Stop: ctx.GetStart().GetTokenIndex() - 1,+ })); err != nil {+ g.err = err+ return+ }++ g.lastTokenIndex = skipFollowingSemiIndex(ctx.GetParser().GetTokenStream(), ctx.GetStop().GetTokenIndex()+1)+ endTokenIndex := g.lastTokenIndex - 1++ if ctx.Object_type_any_name() != nil {+ if ctx.Object_type_any_name().TABLE() != nil && ctx.Object_type_any_name().FOREIGN() == nil {+ schemaName, tableName, err := pgparser.NormalizePostgreSQLAnyNameAsTableName(ctx.Any_name())+ if err != nil {+ g.err = err+ return+ }+ schema, exists := g.to.schemas[schemaName]+ if !exists {+ // Skip not found schema.+ return+ }+ _, exists = schema.tables[tableName]+ if !exists {+ // Skip not found table.+ return+ }+ }+ }++ if ctx.COLUMN() == nil {+ // Keep other comment statements.+ if _, err := g.result.WriteString(ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{+ Start: ctx.GetStart().GetTokenIndex(),+ Stop: endTokenIndex,+ })); err != nil {+ g.err = err+ return+ }+ return+ }++ schemaName, tableName, columnName, err := pgparser.NormalizePostgreSQLAnyNameAsColumnName(ctx.Any_name())+ if err != nil {+ g.err = err+ return+ }+ schema, exists := g.to.schemas[schemaName]+ if !exists {+ // Skip not found schema.+ return+ }+ table, exists := schema.tables[tableName]+ if !exists {+ // Skip not found table.+ return+ }+ column, exists := table.columns[columnName]+ if !exists {+ // Skip not found column.+ return+ }+ equal := false+ column.ignoreComment = true+ if ctx.Comment_text().NULL_P() != nil {+ equal = len(column.comment) == 0+ } else {+ if len(column.comment) == 0 {+ // Skip for empty comment string.+ return+ }+ commentText := ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{+ Start: ctx.Comment_text().GetStart().GetTokenIndex(),+ Stop: ctx.Comment_text().GetStop().GetTokenIndex(),+ })+ if len(commentText) > 2 && commentText[0] == '\'' && commentText[len(commentText)-1] == '\'' {+ commentText = unescapePostgreSQLString(commentText[1 : len(commentText)-1])+ }++ equal = commentText == column.comment+ }++ if equal {+ if _, err := g.result.WriteString(ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{+ Start: ctx.GetStart().GetTokenIndex(),+ Stop: endTokenIndex,+ })); err != nil {+ g.err = err+ return+ }+ } else {+ if _, err := g.result.WriteString(ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{+ Start: ctx.GetStart().GetTokenIndex(),+ Stop: ctx.Comment_text().GetStart().GetTokenIndex() - 1,+ })); err != nil {+ g.err = err+ return+ }+ if _, err := g.result.WriteString(fmt.Sprintf("'%s'", escapePostgreSQLString(column.comment))); err != nil {+ g.err = err+ return+ }+ if _, err := g.result.WriteString(ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{+ Start: ctx.Comment_text().GetStop().GetTokenIndex() + 1,+ Stop: endTokenIndex,+ })); err != nil {+ g.err = err+ return+ }+ }+}++func escapePostgreSQLString(s string) string {+ return strings.ReplaceAll(s, "'", "''")+}++func unescapePostgreSQLString(s string) string {+ return strings.ReplaceAll(s, "''", "'")+}+func (g *designSchemaGenerator) EnterColumnDef(ctx *postgres.ColumnDefContext) {if g.err != nil || g.currentTable == nil {return@@ -1118,7 +1279,7 @@ func (g *designSchemaGenerator) EnterColumnDef(ctx *postgres.ColumnDefContext) {if !exists {return}- delete(g.currentTable.columns, columnName)+ column.ignore = trueif g.firstElementInTable {g.firstElementInTable = falsediff --git a/backend/plugin/schema-engine/pg/testdata/get_design_schema.yaml b/backend/plugin/schema-engine/pg/testdata/get_design_schema.yamlindex 87879028bd..04551aad49 100644--- a/backend/plugin/schema-engine/pg/testdata/get_design_schema.yaml+++ b/backend/plugin/schema-engine/pg/testdata/get_design_schema.yaml@@ -3,6 +3,7 @@"a" int,CONSTRAINT t_a_check CHECK ("a" > 0));+ COMMENT ON COLUMN public.t.a IS 'this is a comment';ALTER TABLE public."t" ADD CONSTRAINT fk_t_a_t2_b FOREIGN KEY ("a") REFERENCES public."t2" ("b");CREATE TABLE public."t3" ("a" int@@ -13,6 +14,7 @@d int,e char(10) NOT NULL DEFAULT 'NULL');+ COMMENT ON COLUMN public.t4.c IS 'comment with ''; test escape';ALTER TABLE public.t4 ADD CONSTRAINT pk_t4_a_c_d PRIMARY KEY (a, c, d);ALTER TABLE public.t4 ADD CONSTRAINT fk_t4_a_t2_b FOREIGN KEY (a) REFERENCES public.t2 (b);target:@@ -55,7 +57,7 @@type: varchar(10)characterset: ""collation: ""- comment: this is comment, aha+ comment: this is comment', ahaclassification: ""usercomment: ""effectivemaskinglevel: 0@@ -77,7 +79,7 @@type: intcharacterset: ""collation: ""- comment: ""+ comment: comment with '; test escapeclassification: ""usercomment: ""effectivemaskinglevel: 0@@ -192,14 +194,20 @@CONSTRAINT t_a_check CHECK ("a" > 0));+CREATE TABLE public.t4 (a varchar(10) NOT NULL DEFAULT 'default value',c int NOT NULL,e int ,"b" char(10) NOT NULL);+ COMMENT ON COLUMN public.t4.c IS 'comment with ''; test escape';ALTER TABLE public.t4 ADD CONSTRAINT pk_t4_a_c_d PRIMARY KEY ("a", "b", "c");- ALTER TABLE public.t4 ADD CONSTRAINT fk_t4_a_t2_b FOREIGN KEY ("b") REFERENCES "public"."t2"("b");CREATE TABLE "public"."t2" (+ ALTER TABLE public.t4 ADD CONSTRAINT fk_t4_a_t2_b FOREIGN KEY ("b") REFERENCES "public"."t2"("b");++ COMMENT ON COLUMN "public"."t4"."a" IS 'this is comment'', aha';++ CREATE TABLE "public"."t2" ("b" int NULL,"a" int NULL);@@ -209,3 +217,4 @@ALTER TABLE ONLY "public"."t2"ADD CONSTRAINT "fk_t2_b_t4_b" FOREIGN KEY ("b") REFERENCES "public"."t4"("b");+