Skip to content

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

feat(parser): support CREATE INDEX statements (#3335)

rebelice6e3f220a2d03
diff --git a/plugin/parser/ast/create_index_stmt.go b/plugin/parser/ast/create_index_stmt.go
index b90f1a3e5d..d205dd4170 100644
--- a/plugin/parser/ast/create_index_stmt.go
+++ b/plugin/parser/ast/create_index_stmt.go
@@ -4,5 +4,6 @@ package ast
type CreateIndexStmt struct {
ddl
- Index *IndexDef
+ Index *IndexDef
+ IfNotExists bool
}
diff --git a/plugin/parser/ast/index_def.go b/plugin/parser/ast/index_def.go
index 2d6a7b6fa3..e5e8d82808 100644
--- a/plugin/parser/ast/index_def.go
+++ b/plugin/parser/ast/index_def.go
@@ -1,5 +1,23 @@
package ast
+// IndexMethodType is the index method type.
+type IndexMethodType int
+
+const (
+ // IndexMethodTypeBTree is the index method type for B-Tree. It's the default type.
+ IndexMethodTypeBTree = iota
+ // IndexMethodTypeHash is the index method type for hash.
+ IndexMethodTypeHash
+ // IndexMethodTypeGiST is the index method type for GiST.
+ IndexMethodTypeGiST
+ // IndexMethodTypeSpGiST is the index method type for SP-GiST.
+ IndexMethodTypeSpGiST
+ // IndexMethodTypeGin is the index method type for GIN.
+ IndexMethodTypeGin
+ // IndexMethodTypeBrin is the index method type for BRIN.
+ IndexMethodTypeBrin
+)
+
// IndexDef is the struct for index definition.
type IndexDef struct {
node
@@ -8,6 +26,7 @@ type IndexDef struct {
Table *TableDef
Unique bool
KeyList []*IndexKeyDef
+ Method IndexMethodType
}
// GetKeyNameList to get the name from KeyList.
diff --git a/plugin/parser/ast/index_key_def.go b/plugin/parser/ast/index_key_def.go
index 36bb1adde3..c967e856a1 100644
--- a/plugin/parser/ast/index_key_def.go
+++ b/plugin/parser/ast/index_key_def.go
@@ -1,5 +1,31 @@
package ast
+// SortOrderType is the sort order type for the index.
+type SortOrderType int
+
+const (
+ // SortOrderTypeDefault is the sort order type for default value.
+ SortOrderTypeDefault = iota
+ // SortOrderTypeAscending is the sort order type for ASC.
+ SortOrderTypeAscending
+ // SortOrderTypeDescending is the sort order type for DESC.
+ SortOrderTypeDescending
+)
+
+// NullOrderType is the null sort order type for the index.
+type NullOrderType int
+
+const (
+ // NullOrderTypeDefault is the default null sort order type.
+ NullOrderTypeDefault = iota
+ // NullOrderTypeFirst is the null sort order type that nulls sort before non-nulls.
+ // This is the default when DESC is specified.
+ NullOrderTypeFirst
+ // NullOrderTypeLast is the null sort order type that nulls sort after non-nulls.
+ // This is the default when DESC is not specified.
+ NullOrderTypeLast
+)
+
// IndexKeyType is the type for index key.
type IndexKeyType int
@@ -11,11 +37,11 @@ const (
)
// IndexKeyDef is the struct for index key definition.
-// Only support conversion IndexKeyTypeColumn now.
-// TODO(rebelice): support conversion IndexKeyTypeExpression.
type IndexKeyDef struct {
node
- Type IndexKeyType
- Key string
+ Type IndexKeyType
+ Key string
+ SortOrder SortOrderType
+ NullOrder NullOrderType
}
diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.go
index ea98738f9c..c259c70de9 100644
--- a/plugin/parser/engine/pg/convert.go
+++ b/plugin/parser/engine/pg/convert.go
@@ -208,26 +208,46 @@ func convert(node *pgquery.Node, statement parser.SingleSQL) (res ast.Node, err
Unique: in.IndexStmt.Unique,
}
+ method, err := convertMethodType(in.IndexStmt.AccessMethod)
+ if err != nil {
+ return nil, err
+ }
+ indexDef.Method = method
+
for _, key := range in.IndexStmt.IndexParams {
index, ok := key.Node.(*pgquery.Node_IndexElem)
if !ok {
return nil, parser.NewConvertErrorf("expected IndexElem but found %t", key.Node)
}
- // We only support index on columns now.
- // TODO(rebelice): support index on expressions.
+ indexKey := &ast.IndexKeyDef{}
if index.IndexElem.Name != "" {
- indexDef.KeyList = append(indexDef.KeyList, &ast.IndexKeyDef{
- Type: ast.IndexKeyTypeColumn,
- Key: index.IndexElem.Name,
- })
+ indexKey.Type = ast.IndexKeyTypeColumn
+ indexKey.Key = index.IndexElem.Name
} else {
- indexDef.KeyList = append(indexDef.KeyList, &ast.IndexKeyDef{
- Type: ast.IndexKeyTypeExpression,
- })
+ expression, err := pgquery.DeparseNode(pgquery.DeparseTypeExpr, index.IndexElem.Expr)
+ if err != nil {
+ return nil, err
+ }
+ indexKey.Type = ast.IndexKeyTypeExpression
+ indexKey.Key = expression
+ }
+
+ order, err := convertSortOrder(index.IndexElem.Ordering)
+ if err != nil {
+ return nil, err
+ }
+ indexKey.SortOrder = order
+
+ nullOrder, err := convertNullOrder(index.IndexElem.NullsOrdering)
+ if err != nil {
+ return nil, err
}
+ indexKey.NullOrder = nullOrder
+
+ indexDef.KeyList = append(indexDef.KeyList, indexKey)
}
- return &ast.CreateIndexStmt{Index: indexDef}, nil
+ return &ast.CreateIndexStmt{Index: indexDef, IfNotExists: in.IndexStmt.IfNotExists}, nil
case *pgquery.Node_DropStmt:
switch in.DropStmt.RemoveType {
case pgquery.ObjectType_OBJECT_INDEX:
@@ -496,6 +516,51 @@ func convertRoleSpec(in *pgquery.RoleSpec) (*ast.RoleSpec, error) {
return nil, parser.NewConvertErrorf("unexpected role spec type: %q", in.Roletype.String())
}
+func convertNullOrder(order pgquery.SortByNulls) (ast.NullOrderType, error) {
+ switch order {
+ case pgquery.SortByNulls_SORTBY_NULLS_DEFAULT:
+ return ast.NullOrderTypeDefault, nil
+ case pgquery.SortByNulls_SORTBY_NULLS_FIRST:
+ return ast.NullOrderTypeFirst, nil
+ case pgquery.SortByNulls_SORTBY_NULLS_LAST:
+ return ast.NullOrderTypeLast, nil
+ default:
+ return ast.NullOrderTypeDefault, parser.NewConvertErrorf("unsupported null sort order: %d", order)
+ }
+}
+
+func convertSortOrder(order pgquery.SortByDir) (ast.SortOrderType, error) {
+ switch order {
+ case pgquery.SortByDir_SORTBY_DEFAULT:
+ return ast.SortOrderTypeDefault, nil
+ case pgquery.SortByDir_SORTBY_ASC:
+ return ast.SortOrderTypeAscending, nil
+ case pgquery.SortByDir_SORTBY_DESC:
+ return ast.SortOrderTypeDescending, nil
+ default:
+ return ast.NullOrderTypeDefault, parser.NewConvertErrorf("unsupported sort order: %d", order)
+ }
+}
+
+func convertMethodType(method string) (ast.IndexMethodType, error) {
+ switch method {
+ case "btree":
+ return ast.IndexMethodTypeBTree, nil
+ case "hash":
+ return ast.IndexMethodTypeHash, nil
+ case "gist":
+ return ast.IndexMethodTypeGiST, nil
+ case "spgist":
+ return ast.IndexMethodTypeSpGiST, nil
+ case "gin":
+ return ast.IndexMethodTypeGin, nil
+ case "brin":
+ return ast.IndexMethodTypeBrin, nil
+ default:
+ return ast.IndexMethodTypeBTree, parser.NewConvertErrorf("unsupported index method type: %s", method)
+ }
+}
+
func convertExpressionNode(node *pgquery.Node) (ast.ExpressionNode, []*ast.PatternLikeDef, []*ast.SubqueryDef, error) {
if node == nil || node.Node == nil {
return &ast.UnconvertedExpressionDef{}, nil, nil, nil
diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.go
index 70c665f126..8cdc678835 100644
--- a/plugin/parser/engine/pg/convert_test.go
+++ b/plugin/parser/engine/pg/convert_test.go
@@ -713,7 +713,40 @@ func TestPGRenameConstraintStmt(t *testing.T) {
func TestPGCreateIndexStmt(t *testing.T) {
tests := []testData{
{
- stmt: "CREATE INDEX idx_id ON tech_book (id)",
+ stmt: "CREATE INDEX IF NOT EXISTS idx_id ON tech_book ((id+1) DESC, name)",
+ want: []ast.Node{
+ &ast.CreateIndexStmt{
+ IfNotExists: true,
+ Index: &ast.IndexDef{
+ Name: "idx_id",
+ Table: &ast.TableDef{Name: "tech_book"},
+ Unique: false,
+ KeyList: []*ast.IndexKeyDef{
+ {
+ Type: ast.IndexKeyTypeExpression,
+ Key: "id + 1",
+ SortOrder: ast.SortOrderTypeDescending,
+ NullOrder: ast.NullOrderTypeDefault,
+ },
+ {
+ Type: ast.IndexKeyTypeColumn,
+ Key: "name",
+ SortOrder: ast.NullOrderTypeDefault,
+ NullOrder: ast.NullOrderTypeDefault,
+ },
+ },
+ },
+ },
+ },
+ statementList: []parser.SingleSQL{
+ {
+ Text: "CREATE INDEX IF NOT EXISTS idx_id ON tech_book ((id+1) DESC, name)",
+ LastLine: 1,
+ },
+ },
+ },
+ {
+ stmt: "CREATE INDEX idx_id ON tech_book (id ASC NULLS FIRST)",
want: []ast.Node{
&ast.CreateIndexStmt{
Index: &ast.IndexDef{
@@ -722,8 +755,10 @@ func TestPGCreateIndexStmt(t *testing.T) {
Unique: false,
KeyList: []*ast.IndexKeyDef{
{
- Type: ast.IndexKeyTypeColumn,
- Key: "id",
+ Type: ast.IndexKeyTypeColumn,
+ Key: "id",
+ SortOrder: ast.SortOrderTypeAscending,
+ NullOrder: ast.NullOrderTypeFirst,
},
},
},
@@ -731,13 +766,13 @@ func TestPGCreateIndexStmt(t *testing.T) {
},
statementList: []parser.SingleSQL{
{
- Text: "CREATE INDEX idx_id ON tech_book (id)",
+ Text: "CREATE INDEX idx_id ON tech_book (id ASC NULLS FIRST)",
LastLine: 1,
},
},
},
{
- stmt: "CREATE UNIQUE INDEX idx_id ON tech_book (id)",
+ stmt: "CREATE UNIQUE INDEX idx_id ON tech_book (id NULLS LAST)",
want: []ast.Node{
&ast.CreateIndexStmt{
Index: &ast.IndexDef{
@@ -746,8 +781,10 @@ func TestPGCreateIndexStmt(t *testing.T) {
Unique: true,
KeyList: []*ast.IndexKeyDef{
{
- Type: ast.IndexKeyTypeColumn,
- Key: "id",
+ Type: ast.IndexKeyTypeColumn,
+ Key: "id",
+ SortOrder: ast.NullOrderTypeDefault,
+ NullOrder: ast.NullOrderTypeLast,
},
},
},
@@ -755,7 +792,7 @@ func TestPGCreateIndexStmt(t *testing.T) {
},
statementList: []parser.SingleSQL{
{
- Text: "CREATE UNIQUE INDEX idx_id ON tech_book (id)",
+ Text: "CREATE UNIQUE INDEX idx_id ON tech_book (id NULLS LAST)",
LastLine: 1,
},
},
diff --git a/plugin/parser/engine/pg/deparse.go b/plugin/parser/engine/pg/deparse.go
index 2a533832d5..109f65ff9a 100644
--- a/plugin/parser/engine/pg/deparse.go
+++ b/plugin/parser/engine/pg/deparse.go
@@ -44,10 +44,142 @@ func deparse(context parser.DeparseContext, in ast.Node, buf *strings.Builder) e
return err
}
return buf.WriteByte(';')
+ case *ast.CreateIndexStmt:
+ if err := deparseCreateIndex(context, node, buf); err != nil {
+ return err
+ }
+ return buf.WriteByte(';')
}
return errors.Errorf("failed to deparse %T", in)
}
+func deparseCreateIndex(context parser.DeparseContext, in *ast.CreateIndexStmt, buf *strings.Builder) error {
+ if err := context.WriteIndent(buf, parser.DeparseIndentString); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString("CREATE "); err != nil {
+ return err
+ }
+
+ if in.Index.Unique {
+ if _, err := buf.WriteString("UNIQUE "); err != nil {
+ return err
+ }
+ }
+
+ if _, err := buf.WriteString("INDEX "); err != nil {
+ return err
+ }
+
+ if in.IfNotExists {
+ if _, err := buf.WriteString("IF NOT EXISTS "); err != nil {
+ return err
+ }
+ }
+
+ if err := writeSurrounding(buf, in.Index.Name, `"`); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString(" ON "); err != nil {
+ return err
+ }
+
+ if err := deparseTableDef(context, in.Index.Table, buf); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString(" USING "); err != nil {
+ return err
+ }
+
+ if err := deparseIndexMethod(in.Index.Method, buf); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString(" ("); err != nil {
+ return err
+ }
+
+ for i, key := range in.Index.KeyList {
+ if i != 0 {
+ if _, err := buf.WriteString(", "); err != nil {
+ return err
+ }
+ }
+ if err := deparseIndexKey(parser.DeparseContext{IndentLevel: 0}, key, buf); err != nil {
+ return err
+ }
+ }
+
+ if _, err := buf.WriteString(")"); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func deparseIndexMethod(method ast.IndexMethodType, buf *strings.Builder) (err error) {
+ switch method {
+ case ast.IndexMethodTypeBTree:
+ _, err = buf.WriteString("btree")
+ case ast.IndexMethodTypeHash:
+ _, err = buf.WriteString("hash")
+ case ast.IndexMethodTypeGiST:
+ _, err = buf.WriteString("gist")
+ case ast.IndexMethodTypeSpGiST:
+ _, err = buf.WriteString("spgist")
+ case ast.IndexMethodTypeGin:
+ _, err = buf.WriteString("gin")
+ case ast.IndexMethodTypeBrin:
+ _, err = buf.WriteString("brin")
+ }
+ return err
+}
+
+func deparseIndexKey(context parser.DeparseContext, in *ast.IndexKeyDef, buf *strings.Builder) error {
+ if err := context.WriteIndent(buf, parser.DeparseIndentString); err != nil {
+ return err
+ }
+
+ switch in.Type {
+ case ast.IndexKeyTypeColumn:
+ if _, err := buf.WriteString(in.Key); err != nil {
+ return err
+ }
+ case ast.IndexKeyTypeExpression:
+ if err := buf.WriteByte('('); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(in.Key); err != nil {
+ return err
+ }
+ if err := buf.WriteByte(')'); err != nil {
+ return err
+ }
+ }
+
+ if in.SortOrder == ast.SortOrderTypeDescending {
+ if _, err := buf.WriteString(" DESC"); err != nil {
+ return err
+ }
+ }
+
+ switch in.NullOrder {
+ case ast.NullOrderTypeFirst:
+ if _, err := buf.WriteString(" NULLS FIRST"); err != nil {
+ return err
+ }
+ case ast.NullOrderTypeLast:
+ if _, err := buf.WriteString(" NULLS LAST"); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
func deparseDropTable(context parser.DeparseContext, in *ast.DropTableStmt, 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 0d944602ec..ee3f3ee543 100644
--- a/plugin/parser/engine/pg/deparse_test.go
+++ b/plugin/parser/engine/pg/deparse_test.go
@@ -64,6 +64,8 @@ func TestDeparse(t *testing.T) {
// Schema
"test_create_schema_data.yaml",
"test_drop_schema_data.yaml",
+ // Index
+ "test_create_index_data.yaml",
}
for _, test := range testFileList {
runDeparseTest(t, test, false /* record */)
diff --git a/plugin/parser/engine/pg/test-data/test_create_index_data.yaml b/plugin/parser/engine/pg/test-data/test_create_index_data.yaml
new file mode 100644
index 0000000000..d64b0a3621
--- /dev/null
+++ b/plugin/parser/engine/pg/test-data/test_create_index_data.yaml
@@ -0,0 +1,8 @@
+- stmt: create index idx_1 on public.t using btree (a, b, c)
+ want: CREATE INDEX "idx_1" ON "public"."t" USING btree (a, b, c);
+- stmt: create unique index if not exists idx_1 on public.t(a nulls first, b desc nulls last, c asc)
+ want: CREATE UNIQUE INDEX IF NOT EXISTS "idx_1" ON "public"."t" USING btree (a NULLS FIRST, b DESC NULLS LAST, c);
+- stmt: create index if not exists idx_1 on public.t using hash (a, b, c)
+ want: CREATE INDEX IF NOT EXISTS "idx_1" ON "public"."t" USING hash (a, b, c);
+- stmt: create index if not exists idx_1 on public.t using btree((a+b) desc, c)
+ want: CREATE INDEX IF NOT EXISTS "idx_1" ON "public"."t" USING btree ((a + b) DESC, c);