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 table partition def for pg and skip partitions def (#8212)
rebelice9568d1fccf59
diff --git a/backend/plugin/parser/sql/ast/attach_partition_stmt.go b/backend/plugin/parser/sql/ast/attach_partition_stmt.goindex aa92ca261e..15bb16ed7b 100644--- a/backend/plugin/parser/sql/ast/attach_partition_stmt.go+++ b/backend/plugin/parser/sql/ast/attach_partition_stmt.go@@ -4,6 +4,7 @@ package asttype AttachPartitionStmt struct {node- Table *TableDef+ Table *TableDef+ Partition *TableDef// TODO(rebelice): convert more attach partition statement fields.}diff --git a/backend/plugin/parser/sql/ast/create_table_stmt.go b/backend/plugin/parser/sql/ast/create_table_stmt.goindex 4a8839cca4..4974fb3833 100644--- a/backend/plugin/parser/sql/ast/create_table_stmt.go+++ b/backend/plugin/parser/sql/ast/create_table_stmt.go@@ -8,7 +8,5 @@ type CreateTableStmt struct {Name *TableDefColumnList []*ColumnDefConstraintList []*ConstraintDef-- // TODO(rebelice): convert the partition definition.- PartitionDef Node+ PartitionDef *PartitionDef}diff --git a/backend/plugin/parser/sql/ast/node.go b/backend/plugin/parser/sql/ast/node.goindex bce3a9b45c..beb9fb66a0 100644--- a/backend/plugin/parser/sql/ast/node.go+++ b/backend/plugin/parser/sql/ast/node.go@@ -1,5 +1,9 @@package ast+import (+ pgquery "github.com/pganalyze/pg_query_go/v4"+)+var (_ Node = (*node)(nil))@@ -16,6 +20,7 @@ type Node interface {type node struct {text stringlastline int+ *pgquery.ParseResult}// Text implements the Node interface.diff --git a/backend/plugin/parser/sql/ast/parition_key_def.go b/backend/plugin/parser/sql/ast/parition_key_def.gonew file mode 100644index 0000000000..dd94c5d702--- /dev/null+++ b/backend/plugin/parser/sql/ast/parition_key_def.go@@ -0,0 +1,19 @@+package ast++// PartitionKeyType is the type of partition key.+type PartitionKeyType int++const (+ // PartitionKeyTypeColumn is the type of partition key column.+ PartitionKeyTypeColumn PartitionKeyType = iota+ // PartitionKeyTypeExpression is the type of partition key expression.+ PartitionKeyTypeExpression+)++// PartitionKeyDef is the struct for partition key definition.+type PartitionKeyDef struct {+ node++ Type PartitionKeyType+ Key string+}diff --git a/backend/plugin/parser/sql/ast/partition_def.go b/backend/plugin/parser/sql/ast/partition_def.gonew file mode 100644index 0000000000..51af12d910--- /dev/null+++ b/backend/plugin/parser/sql/ast/partition_def.go@@ -0,0 +1,9 @@+package ast++// PartitionDef is the struct for partition specification.+type PartitionDef struct {+ node++ Strategy string+ KeyList []*PartitionKeyDef+}diff --git a/backend/plugin/parser/sql/differ/pg/differ.go b/backend/plugin/parser/sql/differ/pg/differ.goindex 64cca489b7..5f5c3fd606 100644--- a/backend/plugin/parser/sql/differ/pg/differ.go+++ b/backend/plugin/parser/sql/differ/pg/differ.go@@ -3,6 +3,7 @@ package pgimport ("bytes"+ "fmt""io""sort"@@ -453,12 +454,40 @@ func (m schemaMap) addSequenceOwnedBy(id int, alterStmt *ast.AlterSequenceStmt)return nil}-func parseAndPreprocessStatment(statement string) ([]ast.Node, error) {+func parseAndPreprocessStatement(statement string) ([]ast.Node, []string, error) {nodeList, err := parser.Parse(parser.Postgres, parser.ParseContext{}, statement)if err != nil {- return nil, errors.Wrapf(err, "failed to parse statement %q", statement)+ return nil, nil, errors.Wrapf(err, "failed to parse statement %q", statement)}- return mergeDefaultIntoColumn(nodeList)+ nodes, err := mergeDefaultIntoColumn(nodeList)+ if err != nil {+ return nil, nil, errors.Wrapf(err, "failed to merge default into column for statement %q", statement)+ }++ partitions := extractPartitions(nodes)+ return nodes, partitions, nil+}++func extractPartitions(nodes []ast.Node) []string {+ var partitions []string+ for _, node := range nodes {+ switch node := node.(type) {+ case *ast.AlterTableStmt:+ for _, alterItem := range node.AlterItemList {+ switch item := alterItem.(type) {+ case *ast.AttachPartitionStmt:+ if item.Partition != nil {+ partitions = append(partitions, fmt.Sprintf("%s.%s", item.Partition.Schema, item.Partition.Name))+ }+ default:+ continue+ }+ }+ default:+ continue+ }+ }+ return partitions}// mergeDefaultIntoColumn merges some statements into one statement, for example, merge@@ -511,11 +540,11 @@ func mergeDefaultIntoColumn(nodeList []ast.Node) ([]ast.Node, error) {// SchemaDiff computes the schema differences between old and new schema.func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string, _ bool) (string, error) {- oldNodes, err := parseAndPreprocessStatment(oldStmt)+ oldNodes, oldPartitions, err := parseAndPreprocessStatement(oldStmt)if err != nil {return "", errors.Wrapf(err, "failed to parse and preprocess old statements %q", oldStmt)}- newNodes, err := parseAndPreprocessStatment(newStmt)+ newNodes, newPartitions, err := parseAndPreprocessStatement(newStmt)if err != nil {return "", errors.Wrapf(err, "failed to and preprocess new statements %q", newStmt)}@@ -526,15 +555,27 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string, _ bool) (string, error)oldSchemaMap := make(schemaMap)oldSchemaMap["public"] = newSchemaInfo(-1, &ast.CreateSchemaStmt{Name: "public"})oldSchemaMap["public"].existsInNew = true+ oldPartitionMap := make(map[string]bool)+ for _, partition := range oldPartitions {+ oldPartitionMap[partition] = true+ }for i, node := range oldNodes {switch stmt := node.(type) {case *ast.CreateSchemaStmt:oldSchemaMap[stmt.Name] = newSchemaInfo(i, stmt)case *ast.CreateTableStmt:+ if _, exists := oldPartitionMap[fmt.Sprintf("%s.%s", stmt.Name.Schema, stmt.Name.Name)]; exists {+ // ignore partition table+ continue+ }if err := oldSchemaMap.addTable(i, stmt); err != nil {return "", err}case *ast.AlterTableStmt:+ // ignore partition table+ if _, exists := oldPartitionMap[fmt.Sprintf("%s.%s", stmt.Table.Schema, stmt.Table.Name)]; exists {+ continue+ }for _, alterItem := range stmt.AlterItemList {switch item := alterItem.(type) {case *ast.AddConstraintStmt:@@ -546,11 +587,18 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string, _ bool) (string, error)default:return "", errors.Errorf("unsupported constraint type %d", item.Constraint.Type)}+ case *ast.AttachPartitionStmt:+ // ignore attach partition+ continuedefault:return "", errors.Errorf("unsupported alter table item type %T", item)}}case *ast.CreateIndexStmt:+ // ignore partition index+ if _, exists := oldPartitionMap[fmt.Sprintf("%s.%s", stmt.Index.Table.Schema, stmt.Index.Table.Name)]; exists {+ continue+ }if err := oldSchemaMap.addIndex(i, stmt); err != nil {return "", err}@@ -585,9 +633,17 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string, _ bool) (string, error)}diff := &diffNode{}+ newPartitionMap := make(map[string]bool)+ for _, partition := range newPartitions {+ newPartitionMap[partition] = true+ }for _, node := range newNodes {switch stmt := node.(type) {case *ast.CreateTableStmt:+ // ignore partition table+ if _, exists := newPartitionMap[fmt.Sprintf("%s.%s", stmt.Name.Schema, stmt.Name.Name)]; exists {+ continue+ }if _, exists := systemSchemas[stmt.Name.Schema]; exists {continue}@@ -613,6 +669,10 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string, _ bool) (string, error)}schema.existsInNew = truecase *ast.AlterTableStmt:+ // ignore partition table+ if _, exists := newPartitionMap[fmt.Sprintf("%s.%s", stmt.Table.Schema, stmt.Table.Name)]; exists {+ continue+ }if _, exists := systemSchemas[stmt.Table.Schema]; exists {continue}@@ -641,11 +701,18 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string, _ bool) (string, error)default:return "", errors.Errorf("unsupported constraint type %d", item.Constraint.Type)}+ case *ast.AttachPartitionStmt:+ // ignore attach partition+ continuedefault:return "", errors.Errorf("unsupported alter table item type %T", item)}}case *ast.CreateIndexStmt:+ // ignore partition index+ if _, exists := newPartitionMap[fmt.Sprintf("%s.%s", stmt.Index.Table.Schema, stmt.Index.Table.Name)]; exists {+ continue+ }if _, exists := systemSchemas[stmt.Index.Table.Schema]; exists {continue}diff --git a/backend/plugin/parser/sql/engine/pg/convert.go b/backend/plugin/parser/sql/engine/pg/convert.goindex eb66f3cdac..963514d909 100644--- a/backend/plugin/parser/sql/engine/pg/convert.go+++ b/backend/plugin/parser/sql/engine/pg/convert.go@@ -31,6 +31,10 @@ func convert(node *pgquery.Node, statement parser.SingleSQL) (res ast.Node, err}()switch in := node.Node.(type) {case *pgquery.Node_AlterTableStmt:+ if in.AlterTableStmt.Objtype != pgquery.ObjectType_OBJECT_TABLE {+ // We only support ALTER TABLE.+ return nil, nil+ }alterTable := &ast.AlterTableStmt{Table: convertRangeVarToTableName(in.AlterTableStmt.Relation, ast.TableTypeBaseTable),AlterItemList: []ast.Node{},@@ -154,9 +158,15 @@ func convert(node *pgquery.Node, statement parser.SingleSQL) (res ast.Node, erralterTable.AlterItemList = append(alterTable.AlterItemList, setDefault)}case pgquery.AlterTableType_AT_AttachPartition:- alterTable.AlterItemList = append(alterTable.AlterItemList, &ast.AttachPartitionStmt{+ attachPartition := &ast.AttachPartitionStmt{Table: alterTable.Table,- })+ }+ if alterCmd.Def != nil {+ if partitionCmd, ok := alterCmd.Def.Node.(*pgquery.Node_PartitionCmd); ok {+ attachPartition.Partition = convertRangeVarToTableName(partitionCmd.PartitionCmd.Name, ast.TableTypeBaseTable)+ }+ }+ alterTable.AlterItemList = append(alterTable.AlterItemList, attachPartition)}}}@@ -1171,8 +1181,30 @@ func convertCreateStmt(in *pgquery.CreateStmt) (*ast.CreateTableStmt, error) {}if in.Partspec != nil {- // TODO(rebelice): convert the partition definition.- table.PartitionDef = &ast.UnconvertedStmt{}+ table.PartitionDef = &ast.PartitionDef{+ Strategy: in.Partspec.Strategy,+ }+ for _, item := range in.Partspec.PartParams {+ partElem, ok := item.Node.(*pgquery.Node_PartitionElem)+ if !ok {+ return nil, parser.NewConvertErrorf("expected PartitionElem but found %t", item.Node)+ }+ if partElem.PartitionElem.Name != "" {+ table.PartitionDef.KeyList = append(table.PartitionDef.KeyList, &ast.PartitionKeyDef{+ Type: ast.PartitionKeyTypeColumn,+ Key: partElem.PartitionElem.Name,+ })+ } else if partElem.PartitionElem.Expr != nil {+ expr, err := pgquery.DeparseNode(pgquery.DeparseTypeExpr, partElem.PartitionElem.Expr)+ if err != nil {+ return nil, err+ }+ table.PartitionDef.KeyList = append(table.PartitionDef.KeyList, &ast.PartitionKeyDef{+ Type: ast.PartitionKeyTypeExpression,+ Key: expr,+ })+ }+ }}return table, nil}diff --git a/backend/plugin/parser/sql/engine/pg/convert_test.go b/backend/plugin/parser/sql/engine/pg/convert_test.goindex 4e71d8a3fa..e4dc7790d7 100644--- a/backend/plugin/parser/sql/engine/pg/convert_test.go+++ b/backend/plugin/parser/sql/engine/pg/convert_test.go@@ -69,7 +69,7 @@ func TestPGConvertCreateTableStmt(t *testing.T) {b int,c text COLLATE public."de_DE")- PARTITION BY RANGE (a)+ PARTITION BY RANGE (a, (a+1))`,want: []ast.Node{&ast.CreateTableStmt{@@ -96,7 +96,19 @@ func TestPGConvertCreateTableStmt(t *testing.T) {},},},- PartitionDef: &ast.UnconvertedStmt{},+ PartitionDef: &ast.PartitionDef{+ Strategy: "range",+ KeyList: []*ast.PartitionKeyDef{+ {+ Type: ast.PartitionKeyTypeColumn,+ Key: "a",+ },+ {+ Type: ast.PartitionKeyTypeExpression,+ Key: "a + 1",+ },+ },+ },},},statementList: []parser.SingleSQL{@@ -106,7 +118,7 @@ func TestPGConvertCreateTableStmt(t *testing.T) {b int,c text COLLATE public."de_DE")- PARTITION BY RANGE (a)`,+ PARTITION BY RANGE (a, (a+1))`,LastLine: 7,},},@@ -3119,6 +3131,10 @@ func TestAttachPartition(t *testing.T) {Type: ast.TableTypeBaseTable,Name: "tech_book",},+ Partition: &ast.TableDef{+ Type: ast.TableTypeBaseTable,+ Name: "p1",+ },},},},diff --git a/backend/plugin/parser/sql/engine/pg/deparse.go b/backend/plugin/parser/sql/engine/pg/deparse.goindex fa56d621e3..eeba62382d 100644--- a/backend/plugin/parser/sql/engine/pg/deparse.go+++ b/backend/plugin/parser/sql/engine/pg/deparse.go@@ -849,6 +849,54 @@ func deparseCreateTable(context parser.DeparseContext, in *ast.CreateTableStmt,return err}}+ if in.PartitionDef != nil {+ if _, err := buf.WriteString("\n"); err != nil {+ return err+ }+ if err := deparsePartitionDef(columnContext, in.PartitionDef, buf); err != nil {+ return err+ }+ }++ return nil+}++func deparsePartitionDef(_ parser.DeparseContext, in *ast.PartitionDef, buf *strings.Builder) error {+ if _, err := buf.WriteString("PARTITION BY "); err != nil {+ return err+ }+ if _, err := buf.WriteString(strings.ToUpper(in.Strategy)); err != nil {+ return err+ }+ if _, err := buf.WriteString(" ("); err != nil {+ return err+ }+ for i, key := range in.KeyList {+ if i != 0 {+ if _, err := buf.WriteString(", "); err != nil {+ return err+ }+ }+ switch key.Type {+ case ast.PartitionKeyTypeColumn:+ if err := writeSurrounding(buf, key.Key, `"`); err != nil {+ return err+ }+ case ast.PartitionKeyTypeExpression:+ if _, err := buf.WriteString("("); err != nil {+ return err+ }+ if _, err := buf.WriteString(key.Key); err != nil {+ return err+ }+ if _, err := buf.WriteString(")"); err != nil {+ return err+ }+ }+ }+ if _, err := buf.WriteString(")"); err != nil {+ return err+ }return nil}diff --git a/backend/plugin/parser/sql/engine/pg/test-data/test_create_table_data.yaml b/backend/plugin/parser/sql/engine/pg/test-data/test_create_table_data.yamlindex d15f0bb4db..42adca9bea 100644--- a/backend/plugin/parser/sql/engine/pg/test-data/test_create_table_data.yaml+++ b/backend/plugin/parser/sql/engine/pg/test-data/test_create_table_data.yaml@@ -71,7 +71,7 @@c int,PRIMARY KEY(a, b, c),CONSTRAINT uk1 UNIQUE(a, b)- )+ ) partition by range(a, b, (c+1))want: |-CREATE TABLE "t" ("a" integer,@@ -79,4 +79,5 @@"c" integer,PRIMARY KEY ("a", "b", "c"),CONSTRAINT "uk1" UNIQUE ("a", "b")- );+ )+ PARTITION BY RANGE ("a", "b", (c + 1));