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(schema-editor): deparse `DatabaseEdit` to DDL statement for postgres (#4066)
boojack9051eb36dbee
diff --git a/api/database.go b/api/database.goindex f086954789..4c8b80ec5e 100644--- a/api/database.go+++ b/api/database.go@@ -137,6 +137,7 @@ type DatabaseEdit struct {// CreateTableContext is the edit database context to create a table.type CreateTableContext struct {+ Schema string `json:"schema"`Name string `json:"name"`Type string `json:"type"`Engine string `json:"engine"`@@ -151,7 +152,8 @@ type CreateTableContext struct {// AlterTableContext is the edit database context to alter a table.type AlterTableContext struct {- Name string `json:"name"`+ Schema string `json:"schema"`+ Name string `json:"name"`// ColumnNameList should be the final order of columns in UI editor and is used to confirm column positions.ColumnNameList []string `json:"columnNameList"`@@ -161,6 +163,7 @@ type AlterTableContext struct {DropColumnList []*DropColumnContext `json:"dropColumnList"`// TODO(steven): diff schemas in backend, so we don't need this flag.DropPrimaryKey bool `json:"dropPrimaryKey"`+ DropPrimaryKeyList []string `json:"dropPrimaryKeyList"`PrimaryKeyList *[]string `json:"primaryKeyList"`DropForeignKeyList []string `json:"dropForeignKeyList"`AddForeignKeyList []*AddForeignKeyContext `json:"addForeignKeyList"`@@ -168,13 +171,15 @@ type AlterTableContext struct {// RenameTableContext is the edit database context to rename a table.type RenameTableContext struct {+ Schema string `json:"schema"`OldName string `json:"oldName"`NewName string `json:"newName"`}// DropTableContext is the edit database context to drop a table.type DropTableContext struct {- Name string `json:"name"`+ Schema string `json:"schema"`+ Name string `json:"name"`}// AddColumnContext is the create/alter table context to add a column.@@ -208,6 +213,7 @@ type DropColumnContext struct {// AddForeignKeyContext is the add foreign key context.type AddForeignKeyContext struct {ColumnList []string `json:"columnList"`+ ReferencedSchema string `json:"referencedSchema"`ReferencedTable string `json:"referencedTable"`ReferencedColumnList []string `json:"referencedColumnList"`}diff --git a/plugin/parser/edit/mysql/deparse.go b/plugin/parser/edit/mysql/deparse.goindex ff78e61b85..e42de114db 100644--- a/plugin/parser/edit/mysql/deparse.go+++ b/plugin/parser/edit/mysql/deparse.go@@ -23,12 +23,10 @@ func (*SchemaEditor) DeparseDatabaseEdit(databaseEdit *api.DatabaseEdit) (stringif err != nil {return "", err}-stmt, err := restoreASTNode(createTableStmt)if err != nil {return "", err}-stmtList = append(stmtList, stmt)}for _, renameTableContext := range databaseEdit.RenameTableList {@@ -37,7 +35,6 @@ func (*SchemaEditor) DeparseDatabaseEdit(databaseEdit *api.DatabaseEdit) (stringif err != nil {return "", err}-stmtList = append(stmtList, stmt)}for _, alterTableContext := range databaseEdit.AlterTableList {@@ -45,12 +42,10 @@ func (*SchemaEditor) DeparseDatabaseEdit(databaseEdit *api.DatabaseEdit) (stringif err != nil {return "", err}-stmt, err := restoreASTNode(alterTableStmt)if err != nil {return "", err}-stmtList = append(stmtList, stmt)}for _, dropTableContext := range databaseEdit.DropTableList {diff --git a/plugin/parser/edit/mysql/deparse_test.go b/plugin/parser/edit/mysql/deparse_test.goindex f349b8d4d9..f76d04a325 100644--- a/plugin/parser/edit/mysql/deparse_test.go+++ b/plugin/parser/edit/mysql/deparse_test.go@@ -6,6 +6,9 @@ import ("github.com/stretchr/testify/assert""github.com/bytebase/bytebase/api"++ // Register pingcap parser driver.+ _ "github.com/pingcap/tidb/types/parser_driver")func TestDeparseCreateTable(t *testing.T) {@@ -124,6 +127,8 @@ func TestDeparseCreateTable(t *testing.T) {}func TestDeparseAlterTable(t *testing.T) {+ var defaultValue = "0"+tests := []struct {name stringdatabaseEdit *api.DatabaseEdit@@ -220,6 +225,42 @@ func TestDeparseAlterTable(t *testing.T) {},want: "ALTER TABLE `t1` DROP COLUMN `email`, ADD COLUMN (`id` INT NOT NULL), CHANGE COLUMN `id_card` `id_card2` INT COMMENT 'ID Card' NOT NULL;\n",},+ {+ name: "alter table t1 and add column id, id_card",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ AlterTableList: []*api.AlterTableContext{+ {+ Name: "t1",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ },+ {+ Name: "id_card",+ Type: "int",+ },+ },+ DropColumnList: []*api.DropColumnContext{+ {+ Name: "name",+ },+ },+ ChangeColumnList: []*api.ChangeColumnContext{+ {+ OldName: "address",+ NewName: "address",+ Type: "int",+ Nullable: false,+ Default: &defaultValue,+ },+ },+ },+ },+ },+ want: "ALTER TABLE `t1` DROP COLUMN `name`, ADD COLUMN (`id` INT NOT NULL, `id_card` INT NOT NULL), CHANGE COLUMN `address` `address` INT NOT NULL DEFAULT '0';\n",+ },}mysqlEditor := &SchemaEditor{}@@ -271,7 +312,7 @@ func TestDeparseAlterAndRenameTable(t *testing.T) {DatabaseID: api.UnknownID,AlterTableList: []*api.AlterTableContext{{- Name: "t1",+ Name: "t2",AddColumnList: []*api.AddColumnContext{{Name: "id",@@ -291,7 +332,7 @@ func TestDeparseAlterAndRenameTable(t *testing.T) {},},},- want: "RENAME TABLE `t1` TO `t2`;\n\nALTER TABLE `t1` ADD COLUMN (`id` INT NOT NULL, `id_card` INT NOT NULL);\n",+ want: "RENAME TABLE `t1` TO `t2`;\n\nALTER TABLE `t2` ADD COLUMN (`id` INT NOT NULL, `id_card` INT NOT NULL);\n",},}diff --git a/plugin/parser/edit/mysql/edit.go b/plugin/parser/edit/mysql/edit.goindex 1a737c7a15..47cf02a35d 100644--- a/plugin/parser/edit/mysql/edit.go+++ b/plugin/parser/edit/mysql/edit.go@@ -5,8 +5,6 @@ import (bbparser "github.com/bytebase/bytebase/plugin/parser""github.com/bytebase/bytebase/plugin/parser/edit"- // Register pingcap parser driver.- _ "github.com/pingcap/tidb/types/parser_driver")var (diff --git a/plugin/parser/edit/pg/deparse.go b/plugin/parser/edit/pg/deparse.gonew file mode 100644index 0000000000..3471360254--- /dev/null+++ b/plugin/parser/edit/pg/deparse.go@@ -0,0 +1,349 @@+package pg++import (+ "fmt"+ "strings"++ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/plugin/parser"+ "github.com/bytebase/bytebase/plugin/parser/ast"+)++// DeparseContext is the context including walkthrough nodes and comment statements.+type DeparseContext struct {+ NodeList []ast.Node+ // StmtList mainly contains column comment statements.+ StmtList []string+}++// DeparseDatabaseEdit deparses DatabaseEdit to DDL statement.+func (*SchemaEditor) DeparseDatabaseEdit(databaseEdit *api.DatabaseEdit) (string, error) {+ ctx := &DeparseContext{+ NodeList: []ast.Node{},+ StmtList: []string{},+ }+ for _, createTableContext := range databaseEdit.CreateTableList {+ err := transformCreateTableContext(ctx, createTableContext)+ if err != nil {+ return "", err+ }+ }+ for _, renameTableContext := range databaseEdit.RenameTableList {+ transformRenameTableContext(ctx, renameTableContext)+ }+ for _, alterTableContext := range databaseEdit.AlterTableList {+ err := transformAlterTableContext(ctx, alterTableContext)+ if err != nil {+ return "", err+ }+ }+ for _, dropTableContext := range databaseEdit.DropTableList {+ transformDropTableContext(ctx, dropTableContext)+ }++ var stmtList []string+ for _, node := range ctx.NodeList {+ stmt, err := restoreASTNode(node)+ if err != nil {+ return "", err+ }+ stmtList = append(stmtList, stmt)+ }+ stmtList = append(stmtList, ctx.StmtList...)+ return strings.Join(stmtList, "\n"), nil+}++func transformCreateTableContext(ctx *DeparseContext, createTableContext *api.CreateTableContext) error {+ table := ast.TableDef{+ Type: ast.TableTypeBaseTable,+ Schema: createTableContext.Schema,+ Name: createTableContext.Name,+ }+ createTableStmt := &ast.CreateTableStmt{+ Name: &table,+ ColumnList: []*ast.ColumnDef{},+ ConstraintList: []*ast.ConstraintDef{},+ }++ for _, addColumnContext := range createTableContext.AddColumnList {+ columnDef, err := transformAddColumnContext(ctx, addColumnContext)+ if err != nil {+ return err+ }+ createTableStmt.ColumnList = append(createTableStmt.ColumnList, columnDef)++ // TODO(steven): remove this after our pg parser supports comment stmt.+ if addColumnContext.Comment != "" {+ commemtStmt := fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s';", table.Name, columnDef.ColumnName, addColumnContext.Comment)+ ctx.StmtList = append(ctx.StmtList, commemtStmt)+ }+ }++ if len(createTableContext.PrimaryKeyList) > 0 {+ constraint := ast.ConstraintDef{+ Type: ast.ConstraintTypePrimary,+ KeyList: []string{},+ }+ constraint.KeyList = append(constraint.KeyList, createTableContext.PrimaryKeyList...)+ createTableStmt.ConstraintList = append(createTableStmt.ConstraintList, &constraint)+ }++ for _, addForeignKeyContext := range createTableContext.AddForeignKeyList {+ foreignKeyDef := ast.ForeignDef{+ Table: &ast.TableDef{+ Type: ast.TableTypeBaseTable,+ Schema: addForeignKeyContext.ReferencedSchema,+ Name: addForeignKeyContext.ReferencedTable,+ },+ ColumnList: addForeignKeyContext.ReferencedColumnList,+ MatchType: ast.ForeignMatchTypeSimple,+ OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},+ OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},+ }+ constraint := ast.ConstraintDef{+ Type: ast.ConstraintTypeForeign,+ KeyList: addForeignKeyContext.ColumnList,+ Foreign: &foreignKeyDef,+ }+ createTableStmt.ConstraintList = append(createTableStmt.ConstraintList, &constraint)+ }++ ctx.NodeList = append(ctx.NodeList, createTableStmt)+ return nil+}++func transformAlterTableContext(ctx *DeparseContext, alterTableContext *api.AlterTableContext) error {+ table := &ast.TableDef{+ Type: ast.TableTypeBaseTable,+ Schema: alterTableContext.Schema,+ Name: alterTableContext.Name,+ }+ alterTableStmt := &ast.AlterTableStmt{+ Table: table,+ AlterItemList: []ast.Node{},+ }++ for _, dropColumnContext := range alterTableContext.DropColumnList {+ dropColumnStmt := ast.DropColumnStmt{+ Table: table,+ ColumnName: dropColumnContext.Name,+ }+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &dropColumnStmt)+ }++ for _, addColumnContext := range alterTableContext.AddColumnList {+ columnDef, err := transformAddColumnContext(ctx, addColumnContext)+ if err != nil {+ return err+ }+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.AddColumnListStmt{+ Table: table,+ ColumnList: []*ast.ColumnDef{columnDef},+ })+ if addColumnContext.Comment != "" {+ commemtStmt := fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s';", table.Name, columnDef.ColumnName, addColumnContext.Comment)+ ctx.StmtList = append(ctx.StmtList, commemtStmt)+ }+ }++ for _, changeColumnContext := range alterTableContext.ChangeColumnList {+ if changeColumnContext.OldName != changeColumnContext.NewName {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.RenameColumnStmt{+ Table: table,+ ColumnName: changeColumnContext.OldName,+ NewName: changeColumnContext.NewName,+ })+ }+ columnType, err := transformColumnType(changeColumnContext.Type)+ if err != nil {+ return errors.Wrap(err, "failed to transform column type")+ }+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.AlterColumnTypeStmt{+ Table: table,+ ColumnName: changeColumnContext.NewName,+ Type: columnType,+ })+ if changeColumnContext.Nullable {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.DropNotNullStmt{+ Table: table,+ ColumnName: changeColumnContext.NewName,+ })+ } else {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.SetNotNullStmt{+ Table: table,+ ColumnName: changeColumnContext.NewName,+ })+ }+ if changeColumnContext.Default == nil {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.DropDefaultStmt{+ Table: table,+ ColumnName: changeColumnContext.NewName,+ })+ } else {+ expression := ast.UnconvertedExpressionDef{}+ expression.SetText(*changeColumnContext.Default)+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.SetDefaultStmt{+ Table: table,+ ColumnName: changeColumnContext.NewName,+ Expression: &expression,+ })+ }+ if changeColumnContext.Comment != "" {+ commemtStmt := fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s';", table.Name, changeColumnContext.NewName, changeColumnContext.Comment)+ ctx.StmtList = append(ctx.StmtList, commemtStmt)+ }+ }++ for _, dropPrimaryKey := range alterTableContext.DropPrimaryKeyList {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.DropConstraintStmt{+ Table: table,+ ConstraintName: dropPrimaryKey,+ IfExists: true,+ })+ }++ if alterTableContext.PrimaryKeyList != nil && len(*alterTableContext.PrimaryKeyList) != 0 {+ constraint := ast.ConstraintDef{+ Type: ast.ConstraintTypePrimary,+ KeyList: []string{},+ }+ constraint.KeyList = append(constraint.KeyList, *alterTableContext.PrimaryKeyList...)+ addConstraintSmt := ast.AddConstraintStmt{+ Table: table,+ Constraint: &constraint,+ }+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &addConstraintSmt)+ }++ for _, dropForeignKey := range alterTableContext.DropForeignKeyList {+ dropConstraintStmt := ast.DropConstraintStmt{+ Table: table,+ ConstraintName: dropForeignKey,+ IfExists: true,+ }+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &dropConstraintStmt)+ }++ for _, addForeignKeyContext := range alterTableContext.AddForeignKeyList {+ foreignKeyDef := ast.ForeignDef{+ Table: &ast.TableDef{+ Schema: addForeignKeyContext.ReferencedSchema,+ Name: addForeignKeyContext.ReferencedTable,+ },+ ColumnList: addForeignKeyContext.ReferencedColumnList,+ MatchType: ast.ForeignMatchTypeSimple,+ OnUpdate: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},+ OnDelete: &ast.ReferentialActionDef{Type: ast.ReferentialActionTypeNoAction},+ }+ constraint := ast.ConstraintDef{+ Type: ast.ConstraintTypeForeign,+ KeyList: addForeignKeyContext.ColumnList,+ Foreign: &foreignKeyDef,+ }+ addConstraintSmt := ast.AddConstraintStmt{+ Table: table,+ Constraint: &constraint,+ }+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &addConstraintSmt)+ }++ ctx.NodeList = append(ctx.NodeList, alterTableStmt)+ return nil+}++func transformRenameTableContext(ctx *DeparseContext, renameTableContext *api.RenameTableContext) {+ table := ast.TableDef{+ Type: ast.TableTypeBaseTable,+ Schema: renameTableContext.Schema,+ Name: renameTableContext.OldName,+ }+ alterTableStmt := &ast.AlterTableStmt{+ Table: &table,+ AlterItemList: []ast.Node{+ &ast.RenameTableStmt{+ Table: &table,+ NewName: renameTableContext.NewName,+ },+ },+ }+ ctx.NodeList = append(ctx.NodeList, alterTableStmt)+}++func transformDropTableContext(ctx *DeparseContext, dropTableContext *api.DropTableContext) {+ dropTableStmt := &ast.DropTableStmt{+ IfExists: true,+ TableList: []*ast.TableDef{+ {+ Type: ast.TableTypeBaseTable,+ Schema: dropTableContext.Schema,+ Name: dropTableContext.Name,+ },+ },+ }+ ctx.NodeList = append(ctx.NodeList, dropTableStmt)+}++func transformAddColumnContext(_ *DeparseContext, addColumnContext *api.AddColumnContext) (*ast.ColumnDef, error) {+ columnType, err := transformColumnType(addColumnContext.Type)+ if err != nil {+ return nil, errors.Wrap(err, "failed to transform column type")+ }++ columnDef := &ast.ColumnDef{+ ColumnName: addColumnContext.Name,+ Type: columnType,+ }++ var constraintList []*ast.ConstraintDef+ if addColumnContext.Default != nil {+ expression := ast.UnconvertedExpressionDef{}+ expression.SetText(*addColumnContext.Default)+ constraintList = append(constraintList, &ast.ConstraintDef{+ Type: ast.ConstraintTypeDefault,+ KeyList: []string{addColumnContext.Name},+ Expression: &expression,+ })+ }+ if !addColumnContext.Nullable {+ constraintList = append(constraintList, &ast.ConstraintDef{+ Type: ast.ConstraintTypeNotNull,+ KeyList: []string{addColumnContext.Name},+ })+ }+ columnDef.ConstraintList = constraintList++ return columnDef, nil+}++func transformColumnType(typeStr string) (ast.DataType, error) {+ // Mock a CreateTableStmt with type string to get the actually types.FieldType.+ stmt := fmt.Sprintf(`CREATE TABLE "public"."column_type" ("column_type" %s);`, typeStr)+ nodeList, err := parser.Parse(parser.Postgres, parser.ParseContext{}, stmt)+ if err != nil {+ return nil, err+ }+ if len(nodeList) != 1 {+ return nil, errors.Errorf("expect node list length to be 1, get %d", len(nodeList))+ }++ node, ok := nodeList[0].(*ast.CreateTableStmt)+ if !ok {+ return nil, errors.New("expect the type of the node to be CreateTableStmt")+ }+ if len(node.ColumnList) != 1 {+ return nil, errors.Errorf("expect node list length to be 1, get %d", len(nodeList))+ }++ col := node.ColumnList[0]+ return col.Type, nil+}++func restoreASTNode(node ast.Node) (string, error) {+ stmt, err := parser.Deparse(parser.Postgres, parser.DeparseContext{}, node)+ if err != nil {+ return "", err+ }+ return stmt, nil+}diff --git a/plugin/parser/edit/pg/deparse_test.go b/plugin/parser/edit/pg/deparse_test.gonew file mode 100644index 0000000000..8be48fc931--- /dev/null+++ b/plugin/parser/edit/pg/deparse_test.go@@ -0,0 +1,480 @@+package pg++import (+ "testing"++ "github.com/stretchr/testify/assert"++ "github.com/bytebase/bytebase/api"++ // Register PostgreSQL parser engine.+ _ "github.com/bytebase/bytebase/plugin/parser/engine/pg"+)++func TestDeparseCreateTable(t *testing.T) {+ var defaultValue = "0"++ tests := []struct {+ name string+ databaseEdit *api.DatabaseEdit+ want string+ }{+ {+ name: "create table t1",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ CreateTableList: []*api.CreateTableContext{+ {+ Schema: "public",+ Name: "t1",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ Comment: "ID",+ Default: &defaultValue,+ },+ },+ },+ },+ },+ want: "CREATE TABLE \"public\".\"t1\" (\n \"id\" integer DEFAULT 0 NOT NULL\n);\nCOMMENT ON COLUMN t1.id IS 'ID';",+ },+ {+ name: "create table t1",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ CreateTableList: []*api.CreateTableContext{+ {+ Schema: "public",+ Name: "t1",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ Default: &defaultValue,+ },+ {+ Name: "name",+ Type: "int",+ Default: &defaultValue,+ },+ },+ PrimaryKeyList: []string{"id", "name"},+ },+ },+ },+ want: "CREATE TABLE \"public\".\"t1\" (\n \"id\" integer DEFAULT 0 NOT NULL,\n \"name\" integer DEFAULT 0 NOT NULL,\n PRIMARY KEY (\"id\", \"name\")\n);",+ },+ }++ postgresEditor := &SchemaEditor{}+ for _, test := range tests {+ stmt, err := postgresEditor.DeparseDatabaseEdit(test.databaseEdit)+ assert.NoError(t, err)+ assert.Equal(t, test.want, stmt)+ }+}++func TestDeparseAlterTable(t *testing.T) {+ var defaultValue = "0"++ tests := []struct {+ name string+ databaseEdit *api.DatabaseEdit+ want string+ }{+ {+ name: "alter table t1 and add column id, id_card",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ AlterTableList: []*api.AlterTableContext{+ {+ Name: "t1",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ },+ {+ Name: "id_card",+ Type: "int",+ },+ },+ DropColumnList: []*api.DropColumnContext{+ {+ Name: "name",+ },+ },+ ChangeColumnList: []*api.ChangeColumnContext{+ {+ OldName: "address",+ NewName: "address",+ Type: "int",+ Nullable: false,+ Comment: "Address",+ Default: &defaultValue,+ },+ },+ },+ },+ },+ want: "ALTER TABLE \"t1\"\n DROP COLUMN \"name\",\n ADD COLUMN \"id\" integer NOT NULL,\n ADD COLUMN \"id_card\" integer NOT NULL,\n ALTER COLUMN \"address\" SET DATA TYPE integer,\n ALTER COLUMN \"address\" SET NOT NULL,\n ALTER COLUMN \"address\" SET DEFAULT 0;\nCOMMENT ON COLUMN t1.address IS 'Address';",+ },+ }++ postgresEditor := &SchemaEditor{}+ for _, test := range tests {+ stmt, err := postgresEditor.DeparseDatabaseEdit(test.databaseEdit)+ assert.NoError(t, err)+ assert.Equal(t, test.want, stmt)+ }+}++func TestDeparseRenameTable(t *testing.T) {+ tests := []struct {+ name string+ databaseEdit *api.DatabaseEdit+ want string+ }{+ {+ name: "rename table name t1 to t2",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ RenameTableList: []*api.RenameTableContext{+ {+ Schema: "public",+ OldName: "t1",+ NewName: "t2",+ },+ },+ },+ want: "ALTER TABLE \"public\".\"t1\"\n RENAME TO \"t2\";",+ },+ }++ postgresEditor := &SchemaEditor{}+ for _, test := range tests {+ stmt, err := postgresEditor.DeparseDatabaseEdit(test.databaseEdit)+ assert.NoError(t, err)+ assert.Equal(t, test.want, stmt)+ }+}++func TestDeparseAlterAndRenameTable(t *testing.T) {+ tests := []struct {+ name string+ databaseEdit *api.DatabaseEdit+ want string+ }{+ {+ name: "alter table t1 and rename to t2",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ AlterTableList: []*api.AlterTableContext{+ {+ Schema: "public",+ Name: "t2",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ },+ {+ Name: "id_card",+ Type: "int",+ },+ },+ },+ },+ RenameTableList: []*api.RenameTableContext{+ {+ Schema: "public",+ OldName: "t1",+ NewName: "t2",+ },+ },+ },+ want: "ALTER TABLE \"public\".\"t1\"\n RENAME TO \"t2\";\nALTER TABLE \"public\".\"t2\"\n ADD COLUMN \"id\" integer NOT NULL,\n ADD COLUMN \"id_card\" integer NOT NULL;",+ },+ }++ postgresEditor := &SchemaEditor{}+ for _, test := range tests {+ stmt, err := postgresEditor.DeparseDatabaseEdit(test.databaseEdit)+ assert.NoError(t, err)+ assert.Equal(t, test.want, stmt)+ }+}++func TestDeparseDropTable(t *testing.T) {+ tests := []struct {+ name string+ databaseEdit *api.DatabaseEdit+ want string+ }{+ {+ name: "drop table t1",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ DropTableList: []*api.DropTableContext{+ {+ Schema: "public",+ Name: "t1",+ },+ },+ },+ want: "DROP TABLE IF EXISTS \"public\".\"t1\";",+ },+ }++ postgresEditor := &SchemaEditor{}+ for _, test := range tests {+ stmt, err := postgresEditor.DeparseDatabaseEdit(test.databaseEdit)+ assert.NoError(t, err)+ assert.Equal(t, test.want, stmt)+ }+}++func TestDeparseCreateTableWithPrimaryKey(t *testing.T) {+ tests := []struct {+ name string+ databaseEdit *api.DatabaseEdit+ want string+ }{+ {+ name: "create table t1",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ CreateTableList: []*api.CreateTableContext{+ {+ Name: "t1",+ Type: "BASE TABLE",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ Nullable: false,+ },+ },+ PrimaryKeyList: []string{"id"},+ },+ },+ },+ want: "CREATE TABLE \"t1\" (\n \"id\" integer NOT NULL,\n PRIMARY KEY (\"id\")\n);",+ },+ {+ name: "create table t2",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ CreateTableList: []*api.CreateTableContext{+ {+ Name: "t2",+ Type: "BASE TABLE",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ Nullable: false,+ },+ {+ Name: "name",+ Type: "varchar(255)",+ Nullable: false,+ },+ },+ PrimaryKeyList: []string{"id", "name"},+ },+ },+ },+ want: "CREATE TABLE \"t2\" (\n \"id\" integer NOT NULL,\n \"name\" character varying(255) NOT NULL,\n PRIMARY KEY (\"id\", \"name\")\n);",+ },+ {+ name: "create table t3",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ CreateTableList: []*api.CreateTableContext{+ {+ Name: "t3",+ Type: "BASE TABLE",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ Nullable: false,+ },+ {+ Name: "name",+ Type: "varchar(255)",+ Nullable: false,+ },+ },+ PrimaryKeyList: []string{"id"},+ },+ },+ },+ want: "CREATE TABLE \"t3\" (\n \"id\" integer NOT NULL,\n \"name\" character varying(255) NOT NULL,\n PRIMARY KEY (\"id\")\n);",+ },+ }++ postgresEditor := &SchemaEditor{}+ for _, test := range tests {+ stmt, err := postgresEditor.DeparseDatabaseEdit(test.databaseEdit)+ assert.NoError(t, err)+ assert.Equal(t, test.want, stmt)+ }+}++func TestDeparseAlterTableWithPrimaryKey(t *testing.T) {+ tests := []struct {+ name string+ databaseEdit *api.DatabaseEdit+ want string+ }{+ {+ name: "alter table t1",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ AlterTableList: []*api.AlterTableContext{+ {+ Name: "t1",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ Nullable: false,+ },+ },+ PrimaryKeyList: &[]string{"id"},+ },+ },+ },+ want: "ALTER TABLE \"t1\"\n ADD COLUMN \"id\" integer NOT NULL,\n ADD PRIMARY KEY (\"id\");",+ },+ {+ name: "alter table t2",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ AlterTableList: []*api.AlterTableContext{+ {+ Name: "t2",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ Nullable: false,+ },+ },+ DropPrimaryKeyList: []string{"_pk_1"},+ },+ },+ },+ want: "ALTER TABLE \"t2\"\n ADD COLUMN \"id\" integer NOT NULL,\n DROP CONSTRAINT IF EXISTS \"_pk_1\";",+ },+ }++ postgresEditor := &SchemaEditor{}+ for _, test := range tests {+ stmt, err := postgresEditor.DeparseDatabaseEdit(test.databaseEdit)+ assert.NoError(t, err)+ assert.Equal(t, test.want, stmt)+ }+}++func TestDeparseCreateTableWithForeignKey(t *testing.T) {+ tests := []struct {+ name string+ databaseEdit *api.DatabaseEdit+ want string+ }{+ {+ name: "create table t1",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ CreateTableList: []*api.CreateTableContext{+ {+ Schema: "public",+ Name: "t1",+ Type: "BASE TABLE",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ Nullable: false,+ },+ {+ Name: "name",+ Type: "int",+ Nullable: false,+ },+ },+ AddForeignKeyList: []*api.AddForeignKeyContext{+ {+ ColumnList: []string{"name"},+ ReferencedSchema: "public",+ ReferencedTable: "t2",+ ReferencedColumnList: []string{"name"},+ },+ },+ },+ },+ },+ want: "CREATE TABLE \"public\".\"t1\" (\n \"id\" integer NOT NULL,\n \"name\" integer NOT NULL,\n FOREIGN KEY (\"name\") REFERENCES \"public\".\"t2\" (\"name\")\n);",+ },+ }++ postgresEditor := &SchemaEditor{}+ for _, test := range tests {+ stmt, err := postgresEditor.DeparseDatabaseEdit(test.databaseEdit)+ assert.NoError(t, err)+ assert.Equal(t, test.want, stmt)+ }+}++func TestDeparseAlterTableWithForeignKey(t *testing.T) {+ tests := []struct {+ name string+ databaseEdit *api.DatabaseEdit+ want string+ }{+ {+ name: "create table t1",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ AlterTableList: []*api.AlterTableContext{+ {+ Name: "t1",+ AddColumnList: []*api.AddColumnContext{+ {+ Name: "id",+ Type: "int",+ Nullable: false,+ },+ {+ Name: "name",+ Type: "int",+ Nullable: false,+ },+ },+ DropForeignKeyList: []string{"t1_ibkf_1", "t1_ibkf_2"},+ AddForeignKeyList: []*api.AddForeignKeyContext{+ {+ ColumnList: []string{"name"},+ ReferencedTable: "t2",+ ReferencedColumnList: []string{"name"},+ },+ },+ },+ },+ },+ want: "ALTER TABLE \"t1\"\n ADD COLUMN \"id\" integer NOT NULL,\n ADD COLUMN \"name\" integer NOT NULL,\n DROP CONSTRAINT IF EXISTS \"t1_ibkf_1\",\n DROP CONSTRAINT IF EXISTS \"t1_ibkf_2\",\n ADD FOREIGN KEY (\"name\") REFERENCES \"t2\" (\"name\");",+ },+ }++ postgresEditor := &SchemaEditor{}+ for _, test := range tests {+ stmt, err := postgresEditor.DeparseDatabaseEdit(test.databaseEdit)+ assert.NoError(t, err)+ assert.Equal(t, test.want, stmt)+ }+}diff --git a/plugin/parser/edit/pg/edit.go b/plugin/parser/edit/pg/edit.gonew file mode 100644index 0000000000..9840f80f6c--- /dev/null+++ b/plugin/parser/edit/pg/edit.go@@ -0,0 +1,19 @@+// Package pg provides the Postgres schema edit plugin.+package pg++import (+ bbparser "github.com/bytebase/bytebase/plugin/parser"++ "github.com/bytebase/bytebase/plugin/parser/edit"+)++var (+ _ edit.SchemaEditor = (*SchemaEditor)(nil)+)++func init() {+ edit.Register(bbparser.Postgres, &SchemaEditor{})+}++// SchemaEditor it the editor for Postgres dialect.+type SchemaEditor struct{}diff --git a/plugin/parser/edit/pg/validate.go b/plugin/parser/edit/pg/validate.gonew file mode 100644index 0000000000..b55c34f1ea--- /dev/null+++ b/plugin/parser/edit/pg/validate.go@@ -0,0 +1,11 @@+package pg++import (+ "github.com/bytebase/bytebase/api"+)++// ValidateDatabaseEdit validates the api message DatabaseEdit, including related column type.+func (*SchemaEditor) ValidateDatabaseEdit(_ *api.DatabaseEdit) ([]*api.ValidateResult, error) {+ // Because Postgres has a custom data type, so skip directly here.+ return []*api.ValidateResult{}, nil+}diff --git a/plugin/parser/edit/pg/validate_test.go b/plugin/parser/edit/pg/validate_test.gonew file mode 100644index 0000000000..ddad9d4ba7--- /dev/null+++ b/plugin/parser/edit/pg/validate_test.go@@ -0,0 +1,23 @@+package pg++import (+ "testing"++ "github.com/stretchr/testify/assert"++ "github.com/bytebase/bytebase/api"+)++func TestValidateDatabaseEditColumnType(t *testing.T) {+ tests := []struct {+ databaseEdit *api.DatabaseEdit+ validateResultList []*api.ValidateResult+ }{}++ postgresEditor := &SchemaEditor{}+ for _, test := range tests {+ validateResultList, err := postgresEditor.ValidateDatabaseEdit(test.databaseEdit)+ assert.NoError(t, err)+ assert.Equal(t, test.validateResultList, validateResultList)+ }+}diff --git a/server/server.go b/server/server.goindex 64a866d677..25cefa70ca 100644--- a/server/server.go+++ b/server/server.go@@ -85,12 +85,14 @@ import (_ "github.com/bytebase/bytebase/plugin/parser/differ/mysql"// Register postgres differ driver._ "github.com/bytebase/bytebase/plugin/parser/differ/pg"+ // Register mysql edit driver.+ _ "github.com/bytebase/bytebase/plugin/parser/edit/mysql"+ // Register postgres edit driver.+ _ "github.com/bytebase/bytebase/plugin/parser/edit/pg"// Register postgres parser driver._ "github.com/bytebase/bytebase/plugin/parser/engine/pg"// Register mysql transform driver._ "github.com/bytebase/bytebase/plugin/parser/transform/mysql"- // Register mysql edit driver.- _ "github.com/bytebase/bytebase/plugin/parser/edit/mysql")const (