Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(differ): support to sync index (#3366)

rebelice2afc9130f12c
diff --git a/plugin/parser/ast/create_index_stmt.go b/plugin/parser/ast/create_index_stmt.go
index d205dd4170..1c67079e82 100644
--- a/plugin/parser/ast/create_index_stmt.go
+++ b/plugin/parser/ast/create_index_stmt.go
@@ -1,6 +1,12 @@
package ast
// CreateIndexStmt is the struct for create index statement.
+// TODO(rebelice): fully support CREATE INDEX statements.
+// Currently, only support:
+// ```
+// CREATE [ UNIQUE ] INDEX [ [ IF NOT EXISTS ] name ] ON table_name [ USING method ]
+// ( { column_name | ( expression ) } [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] )
+// ```.
type CreateIndexStmt struct {
ddl
diff --git a/plugin/parser/ast/drop_index_stmt.go b/plugin/parser/ast/drop_index_stmt.go
index 94edff40d8..1e4d492bcc 100644
--- a/plugin/parser/ast/drop_index_stmt.go
+++ b/plugin/parser/ast/drop_index_stmt.go
@@ -7,4 +7,6 @@ type DropIndexStmt struct {
// Here use IndexDef because the drop index statement needs the schema name for PostgreSQL.
// If the drop index statement doesn't contain schema name, the Table of this index is nil.
IndexList []*IndexDef
+ IfExists bool
+ Behavior DropBehavior
}
diff --git a/plugin/parser/differ/pg/differ.go b/plugin/parser/differ/pg/differ.go
index 3630871172..b53924e116 100644
--- a/plugin/parser/differ/pg/differ.go
+++ b/plugin/parser/differ/pg/differ.go
@@ -29,18 +29,22 @@ type diffNode struct {
newSchemaList []*ast.CreateSchemaStmt
newTableList []*ast.CreateTableStmt
modifyTableList []ast.Node
+ newIndexList []*ast.CreateIndexStmt
+ modifyIndexList []ast.Node
dropNodeList []ast.Node
}
-type constraintMap map[string]*constraintInfo
-type tableMap map[string]*tableInfo
type schemaMap map[string]*schemaInfo
+type tableMap map[string]*tableInfo
+type constraintMap map[string]*constraintInfo
+type indexMap map[string]*indexInfo
type schemaInfo struct {
id int
existsInNew bool
createSchema *ast.CreateSchemaStmt
tableMap tableMap
+ indexMap indexMap
}
func newSchemaInfo(id int, createSchema *ast.CreateSchemaStmt) *schemaInfo {
@@ -49,6 +53,7 @@ func newSchemaInfo(id int, createSchema *ast.CreateSchemaStmt) *schemaInfo {
existsInNew: false,
createSchema: createSchema,
tableMap: make(tableMap),
+ indexMap: make(indexMap),
}
}
@@ -82,6 +87,20 @@ func newConstraintInfo(id int, addConstraint *ast.AddConstraintStmt) *constraint
}
}
+type indexInfo struct {
+ id int
+ existsInNew bool
+ createIndex *ast.CreateIndexStmt
+}
+
+func newIndexInfo(id int, createIndex *ast.CreateIndexStmt) *indexInfo {
+ return &indexInfo{
+ id: id,
+ existsInNew: false,
+ createIndex: createIndex,
+ }
+}
+
func (m schemaMap) addTable(id int, table *ast.CreateTableStmt) error {
schema, exists := m[table.Name.Schema]
if !exists {
@@ -128,6 +147,23 @@ func (m schemaMap) getConstraint(schemaName string, tableName string, constraint
return table.constraintMap[constraintName]
}
+func (m schemaMap) addIndex(id int, index *ast.CreateIndexStmt) error {
+ schema, exists := m[index.Index.Table.Schema]
+ if !exists {
+ return errors.Errorf("failed to add table: schema %s not found", index.Index.Table.Schema)
+ }
+ schema.indexMap[index.Index.Name] = newIndexInfo(id, index)
+ return nil
+}
+
+func (m schemaMap) getIndex(schemaName string, indexName string) *indexInfo {
+ schema, exists := m[schemaName]
+ if !exists {
+ return nil
+ }
+ return schema.indexMap[indexName]
+}
+
// SchemaDiff computes the schema differences between old and new schema.
func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {
oldNodes, err := parser.Parse(parser.Postgres, parser.ParseContext{}, oldStmt)
@@ -141,6 +177,7 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {
oldSchemaMap := make(schemaMap)
oldSchemaMap["public"] = newSchemaInfo(-1, &ast.CreateSchemaStmt{Name: "public"})
+ oldSchemaMap["public"].existsInNew = true
for i, node := range oldNodes {
switch stmt := node.(type) {
case *ast.CreateSchemaStmt:
@@ -165,6 +202,10 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {
return "", errors.Errorf("unsupported alter table item type %T", item)
}
}
+ case *ast.CreateIndexStmt:
+ if err := oldSchemaMap.addIndex(i, stmt); err != nil {
+ return "", err
+ }
}
}
@@ -230,6 +271,18 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {
if len(alterTableStmt.AlterItemList) > 0 {
diff.modifyTableList = append(diff.modifyTableList, alterTableStmt)
}
+ case *ast.CreateIndexStmt:
+ oldIndex := oldSchemaMap.getIndex(stmt.Index.Table.Schema, stmt.Index.Name)
+ // Add the new index.
+ if oldIndex == nil {
+ diff.newIndexList = append(diff.newIndexList, stmt)
+ continue
+ }
+ oldIndex.existsInNew = true
+ // Modify the index.
+ if err := diff.modifyIndex(oldIndex.createIndex, stmt); err != nil {
+ return "", err
+ }
default:
return "", errors.Errorf("unsupported statement %+v", stmt)
}
@@ -255,11 +308,16 @@ func (diff *diffNode) dropObject(oldSchemaMap schemaMap) error {
}
// Drop the remaining old constraints.
- dropConstraintStms := dropConstraint(oldSchemaMap)
- for _, dropConstraintStmt := range dropConstraintStms {
+ dropConstraintStmtList := dropConstraint(oldSchemaMap)
+ for _, dropConstraintStmt := range dropConstraintStmtList {
diff.dropNodeList = append(diff.dropNodeList, dropConstraintStmt)
}
+ // Drop the remaining old index.
+ if dropIndexStmt := dropIndex(oldSchemaMap); dropIndexStmt != nil {
+ diff.dropNodeList = append(diff.dropNodeList, dropIndexStmt)
+ }
+
return nil
}
@@ -448,6 +506,24 @@ func (*diffNode) modifyColumn(alterTableStmt *ast.AlterTableStmt, oldColumn *ast
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() {
+ diff.modifyIndexList = append(diff.modifyIndexList, &ast.DropIndexStmt{
+ IfExists: true,
+ Behavior: ast.DropBehaviorCascade,
+ IndexList: []*ast.IndexDef{
+ {
+ Table: &ast.TableDef{Schema: oldIndex.Index.Table.Schema},
+ Name: oldIndex.Index.Name,
+ },
+ },
+ })
+ diff.modifyIndexList = append(diff.modifyIndexList, newIndex)
+ }
+ return nil
+}
+
func getDefault(column *ast.ColumnDef) (string, bool) {
for _, constraint := range column.ConstraintList {
if constraint.Type == ast.ConstraintTypeDefault {
@@ -507,6 +583,26 @@ func (diff *diffNode) deparse() (string, error) {
}
}
+ for _, newIndex := range diff.newIndexList {
+ sql, err := parser.Deparse(parser.Postgres, parser.DeparseContext{}, newIndex)
+ if err != nil {
+ return "", err
+ }
+ if err := writeStringWithNewLine(&buf, sql); err != nil {
+ return "", err
+ }
+ }
+
+ for _, modifyIndex := range diff.modifyIndexList {
+ sql, err := parser.Deparse(parser.Postgres, parser.DeparseContext{}, modifyIndex)
+ if err != nil {
+ return "", err
+ }
+ if err := writeStringWithNewLine(&buf, sql); err != nil {
+ return "", err
+ }
+ }
+
// Deparse the drop node in reverse order.
for i := len(diff.dropNodeList) - 1; i >= 0; i-- {
sql, err := parser.Deparse(parser.Postgres, parser.DeparseContext{}, diff.dropNodeList[i])
@@ -611,6 +707,42 @@ func dropSchema(m schemaMap) *ast.DropSchemaStmt {
}
}
+func dropIndex(m schemaMap) *ast.DropIndexStmt {
+ var indexList []*indexInfo
+ for _, schema := range m {
+ if !schema.existsInNew {
+ // dropped by DROP SCHEMA ... CASCADE statements
+ continue
+ }
+ for _, index := range schema.indexMap {
+ if index.existsInNew {
+ // no need to drop
+ continue
+ }
+ indexList = append(indexList, index)
+ }
+ }
+ if len(indexList) == 0 {
+ return nil
+ }
+ sort.Slice(indexList, func(i, j int) bool {
+ return indexList[i].id < indexList[j].id
+ })
+
+ var indexDefList []*ast.IndexDef
+ for _, index := range indexList {
+ indexDefList = append(indexDefList, &ast.IndexDef{
+ Table: &ast.TableDef{Schema: index.createIndex.Index.Table.Schema},
+ Name: index.createIndex.Index.Name,
+ })
+ }
+ return &ast.DropIndexStmt{
+ IfExists: true,
+ IndexList: indexDefList,
+ Behavior: ast.DropBehaviorCascade,
+ }
+}
+
func writeStringWithNewLine(out io.Writer, str string) error {
if _, err := out.Write([]byte(str)); 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.yaml
index e452df7208..cbc52c2b4a 100644
--- a/plugin/parser/differ/pg/test-data/test_differ_data.yaml
+++ b/plugin/parser/differ/pg/test-data/test_differ_data.yaml
@@ -105,3 +105,14 @@
constraint check_a check(a > 1)
)
diff: ""
+- oldSchema: |
+ CREATE INDEX idx1 ON public.t1 USING btree (a, b, (c+1));
+ CREATE INDEX idx2 ON public.t1 USING hash (a);
+ newSchema: |
+ CREATE INDEX idx2 ON public.t1 USING btree (a);
+ CREATE INDEX idx3 ON public.t1 USING btree (a, b);
+ diff: |
+ CREATE INDEX "idx3" ON "public"."t1" USING btree (a, b);
+ DROP INDEX IF EXISTS "public"."idx2" CASCADE;
+ CREATE INDEX "idx2" ON "public"."t1" USING btree (a);
+ DROP INDEX IF EXISTS "public"."idx1" CASCADE;
diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.go
index a6b390c705..b94eef3418 100644
--- a/plugin/parser/engine/pg/convert.go
+++ b/plugin/parser/engine/pg/convert.go
@@ -252,7 +252,10 @@ func convert(node *pgquery.Node, statement parser.SingleSQL) (res ast.Node, err
case *pgquery.Node_DropStmt:
switch in.DropStmt.RemoveType {
case pgquery.ObjectType_OBJECT_INDEX:
- dropIndex := &ast.DropIndexStmt{}
+ dropIndex := &ast.DropIndexStmt{
+ IfExists: in.DropStmt.MissingOk,
+ Behavior: convertDropBehavior(in.DropStmt.Behavior),
+ }
for _, object := range in.DropStmt.Objects {
list, ok := object.Node.(*pgquery.Node_List)
if !ok {
diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.go
index 5380c4b5a6..c83d40ded7 100644
--- a/plugin/parser/engine/pg/convert_test.go
+++ b/plugin/parser/engine/pg/convert_test.go
@@ -808,6 +808,8 @@ func TestPGDropIndexStmt(t *testing.T) {
stmt: "DROP INDEX xschema.idx_id, idx_x",
want: []ast.Node{
&ast.DropIndexStmt{
+ IfExists: false,
+ Behavior: ast.DropBehaviorRestrict,
IndexList: []*ast.IndexDef{
{
Table: &ast.TableDef{Schema: "xschema"},
@@ -824,6 +826,50 @@ func TestPGDropIndexStmt(t *testing.T) {
},
},
},
+ {
+ stmt: "DROP INDEX xschema.idx_id, idx_x restrict",
+ want: []ast.Node{
+ &ast.DropIndexStmt{
+ IfExists: false,
+ Behavior: ast.DropBehaviorRestrict,
+ IndexList: []*ast.IndexDef{
+ {
+ Table: &ast.TableDef{Schema: "xschema"},
+ Name: "idx_id",
+ },
+ {Name: "idx_x"},
+ },
+ },
+ },
+ statementList: []parser.SingleSQL{
+ {
+ Text: "DROP INDEX xschema.idx_id, idx_x restrict",
+ LastLine: 1,
+ },
+ },
+ },
+ {
+ stmt: "DROP INDEX IF EXISTS xschema.idx_id, idx_x cascade",
+ want: []ast.Node{
+ &ast.DropIndexStmt{
+ IfExists: true,
+ Behavior: ast.DropBehaviorCascade,
+ IndexList: []*ast.IndexDef{
+ {
+ Table: &ast.TableDef{Schema: "xschema"},
+ Name: "idx_id",
+ },
+ {Name: "idx_x"},
+ },
+ },
+ },
+ statementList: []parser.SingleSQL{
+ {
+ Text: "DROP INDEX IF EXISTS xschema.idx_id, idx_x cascade",
+ LastLine: 1,
+ },
+ },
+ },
}
runTests(t, tests)
diff --git a/plugin/parser/engine/pg/deparse.go b/plugin/parser/engine/pg/deparse.go
index 22e44ac661..1722ea5370 100644
--- a/plugin/parser/engine/pg/deparse.go
+++ b/plugin/parser/engine/pg/deparse.go
@@ -51,10 +51,59 @@ func deparse(context parser.DeparseContext, in ast.Node, buf *strings.Builder) e
return err
}
return buf.WriteByte(';')
+ case *ast.DropIndexStmt:
+ if err := deparseDropIndex(context, node, buf); err != nil {
+ return err
+ }
+ return buf.WriteByte(';')
}
return errors.Errorf("failed to deparse %T", in)
}
+func deparseDropIndex(context parser.DeparseContext, in *ast.DropIndexStmt, buf *strings.Builder) error {
+ if err := context.WriteIndent(buf, parser.DeparseIndentString); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString("DROP INDEX "); err != nil {
+ return err
+ }
+
+ if in.IfExists {
+ if _, err := buf.WriteString("IF EXISTS "); err != nil {
+ return err
+ }
+ }
+
+ for i, index := range in.IndexList {
+ if i != 0 {
+ if _, err := buf.WriteString(", "); err != nil {
+ return err
+ }
+ }
+
+ if index.Table != nil && index.Table.Schema != "" {
+ if err := writeSurrounding(buf, index.Table.Schema, `"`); err != nil {
+ return err
+ }
+ if err := buf.WriteByte('.'); err != nil {
+ return err
+ }
+ }
+
+ if err := writeSurrounding(buf, index.Name, `"`); err != nil {
+ return err
+ }
+ }
+
+ if in.Behavior == ast.DropBehaviorCascade {
+ if _, err := buf.WriteString(" CASCADE"); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
func deparseCreateIndex(context parser.DeparseContext, in *ast.CreateIndexStmt, buf *strings.Builder) error {
if err := context.WriteIndent(buf, parser.DeparseIndentString); err != nil {
return err
diff --git a/plugin/parser/engine/pg/deparse_test.go b/plugin/parser/engine/pg/deparse_test.go
index ee3f3ee543..3af76c4cfd 100644
--- a/plugin/parser/engine/pg/deparse_test.go
+++ b/plugin/parser/engine/pg/deparse_test.go
@@ -66,6 +66,7 @@ func TestDeparse(t *testing.T) {
"test_drop_schema_data.yaml",
// Index
"test_create_index_data.yaml",
+ "test_drop_index_data.yaml",
}
for _, test := range testFileList {
runDeparseTest(t, test, false /* record */)
diff --git a/plugin/parser/engine/pg/test-data/test_drop_index_data.yaml b/plugin/parser/engine/pg/test-data/test_drop_index_data.yaml
new file mode 100644
index 0000000000..704468c788
--- /dev/null
+++ b/plugin/parser/engine/pg/test-data/test_drop_index_data.yaml
@@ -0,0 +1,6 @@
+- stmt: drop index if exists idx1, idx2, idx3 cascade
+ want: DROP INDEX IF EXISTS "idx1", "idx2", "idx3" CASCADE;
+- stmt: drop index idx1 restrict
+ want: DROP INDEX "idx1";
+- stmt: drop index public.idx1 cascade
+ want: DROP INDEX "public"."idx1" CASCADE;