Skip to content

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

feat(catalog): implement PG catalog walkthrough for CREATE TABLE and CREATE INDEX (#4241)

rebelicedf08f5736afa
diff --git a/plugin/advisor/catalog/state.go b/plugin/advisor/catalog/state.go
index a8cd2afe0d..aa5b8d523a 100644
--- a/plugin/advisor/catalog/state.go
+++ b/plugin/advisor/catalog/state.go
@@ -30,18 +30,27 @@ func newDatabaseState(d *storepb.DatabaseMetadata, context *FinderContext) *Data
func newSchemaState(s *storepb.SchemaMetadata, context *FinderContext) *SchemaState {
schema := &SchemaState{
- ctx: context.Copy(),
- name: s.Name,
- tableSet: make(tableStateMap),
- viewSet: make(viewStateMap),
+ ctx: context.Copy(),
+ name: s.Name,
+ tableSet: make(tableStateMap),
+ viewSet: make(viewStateMap),
+ identifierMap: make(identifierMap),
}
for _, table := range s.Tables {
- schema.tableSet[table.Name] = newTableState(table)
+ tableState := newTableState(table)
+ schema.tableSet[table.Name] = tableState
+
+ schema.identifierMap[table.Name] = true
+ for indexName := range tableState.indexSet {
+ schema.identifierMap[indexName] = true
+ }
}
for _, view := range s.Views {
schema.viewSet[view.Name] = newViewState(view)
+
+ schema.identifierMap[view.Name] = true
}
return schema
@@ -275,12 +284,18 @@ func (d *DatabaseState) FindTable(find *TableFind) *TableState {
return table
}
+type identifierMap map[string]bool
+
// SchemaState is the state for walk-through.
type SchemaState struct {
ctx *FinderContext
name string
tableSet tableStateMap
viewSet viewStateMap
+
+ // PostgreSQL specific fields
+ // All relation names in PostgreSQL must be distinct in schema level.
+ identifierMap identifierMap
}
type schemaStateMap map[string]*SchemaState
diff --git a/plugin/advisor/catalog/test/pg_walk_through.yaml b/plugin/advisor/catalog/test/pg_walk_through.yaml
new file mode 100644
index 0000000000..f3729fb7a5
--- /dev/null
+++ b/plugin/advisor/catalog/test/pg_walk_through.yaml
@@ -0,0 +1,189 @@
+- statement: CREATE TABLE t(a int, b int);
+ want:
+ name: postgres
+ schemas:
+ - name: public
+ tables:
+ - name: t
+ columns:
+ - name: a
+ position: 1
+ default: null
+ nullable: true
+ type: integer
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: b
+ position: 2
+ default: null
+ nullable: true
+ type: integer
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes: []
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
+ views: []
+ characterset: ""
+ collation: ""
+ extensions: []
+ err: null
+- statement: |-
+ CREATE TABLE public.t(a int, "B" int);
+ CREATE INDEX ON t(a, "B");
+ CREATE UNIQUE INDEX ON t(a, "B");
+ want:
+ name: postgres
+ schemas:
+ - name: public
+ tables:
+ - name: t
+ columns:
+ - name: a
+ position: 1
+ default: null
+ nullable: true
+ type: integer
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: B
+ position: 2
+ default: null
+ nullable: true
+ type: integer
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes:
+ - name: t_a_B_idx
+ expressions:
+ - a
+ - B
+ type: btree
+ unique: false
+ primary: false
+ visible: false
+ comment: ""
+ - name: t_a_B_idx1
+ expressions:
+ - a
+ - B
+ type: btree
+ unique: true
+ primary: false
+ visible: false
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
+ views: []
+ characterset: ""
+ collation: ""
+ extensions: []
+ err: null
+- statement: |-
+ CREATE TABLE public.t(
+ a int primary key,
+ b int NOT NULL DEFAULT 1,
+ c int UNIQUE,
+ UNIQUE (a, b, c),
+ CONSTRAINT uk_a_b UNIQUE (a, b)
+ )
+ want:
+ name: postgres
+ schemas:
+ - name: public
+ tables:
+ - name: t
+ columns:
+ - name: a
+ position: 1
+ default: null
+ nullable: false
+ type: integer
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: b
+ position: 2
+ default:
+ value: "1"
+ nullable: false
+ type: integer
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: c
+ position: 3
+ default: null
+ nullable: true
+ type: integer
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes:
+ - name: t_a_b_c_idx
+ expressions:
+ - a
+ - b
+ - c
+ type: btree
+ unique: true
+ primary: false
+ visible: false
+ comment: ""
+ - name: t_c_idx
+ expressions:
+ - c
+ type: btree
+ unique: true
+ primary: false
+ visible: false
+ comment: ""
+ - name: t_pkey
+ expressions:
+ - a
+ type: btree
+ unique: true
+ primary: true
+ visible: false
+ comment: ""
+ - name: uk_a_b
+ expressions:
+ - a
+ - b
+ type: btree
+ unique: true
+ primary: false
+ visible: false
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
+ views: []
+ characterset: ""
+ collation: ""
+ extensions: []
+ err: null
diff --git a/plugin/advisor/catalog/walk_through.go b/plugin/advisor/catalog/walk_through.go
index ac679c3ee9..844cc7bf87 100644
--- a/plugin/advisor/catalog/walk_through.go
+++ b/plugin/advisor/catalog/walk_through.go
@@ -28,13 +28,15 @@ const (
// ErrorTypeUnsupported is the error for unsupported cases.
ErrorTypeUnsupported WalkThroughErrorType = 1
+ // ErrorTypeInternal is the error for internal errors.
+ ErrorTypeInternal WalkThroughErrorType = 2
// 101 parse error type.
// ErrorTypeParseError is the error in parsing.
ErrorTypeParseError WalkThroughErrorType = 101
- // ErrorTypeRestoreError is the error in restoring.
- ErrorTypeRestoreError WalkThroughErrorType = 102
+ // ErrorTypeDeparseError is the error in deparsing.
+ ErrorTypeDeparseError WalkThroughErrorType = 102
// 201 ~ 299 database error type.
@@ -94,6 +96,16 @@ const (
ErrorTypeInsertSpecifiedColumnTwice = 602
// ErrorTypeInsertNullIntoNotNullColumn is the error that insert NULL into NOT NULL columns.
ErrorTypeInsertNullIntoNotNullColumn = 603
+
+ // 701 ~ 799 schema error type.
+
+ // ErrorTypeSchemaNotExists is the error that schema does not exist.
+ ErrorTypeSchemaNotExists = 701
+
+ // 801 ~ 899 relation error type.
+
+ // ErrorTypeRelationExists is the error that relation already exists.
+ ErrorTypeRelationExists = 801
)
// WalkThroughError is the error for walking-through.
@@ -111,6 +123,14 @@ func NewParseError(content string) *WalkThroughError {
}
}
+// NewRelationExistsError returns a new ErrorTypeRelationExists.
+func NewRelationExistsError(relationName string, schemaName string) *WalkThroughError {
+ return &WalkThroughError{
+ Type: ErrorTypeRelationExists,
+ Content: fmt.Sprintf("Relation %q already exists in schema %q", relationName, schemaName),
+ }
+}
+
// NewColumnNotExistsError returns a new ErrorTypeColumnNotExists.
func NewColumnNotExistsError(tableName string, columnName string) *WalkThroughError {
return &WalkThroughError{
@@ -164,15 +184,22 @@ func (e *WalkThroughError) Error() string {
return e.Content
}
-// WalkThrough will collect the catalog schema in the databaseState as it walks through the stmts.
-func (d *DatabaseState) WalkThrough(stmts string) error {
- if d.dbType != db.MySQL && d.dbType != db.TiDB {
+// WalkThrough will collect the catalog schema in the databaseState as it walks through the stmt.
+func (d *DatabaseState) WalkThrough(stmt string) error {
+ switch d.dbType {
+ case db.MySQL, db.TiDB:
+ return d.mysqlWalkThrough(stmt)
+ case db.Postgres:
+ return d.pgWalkThrough(stmt)
+ default:
return &WalkThroughError{
Type: ErrorTypeUnsupported,
Content: fmt.Sprintf("Walk-through doesn't support engine type: %s", d.dbType),
}
}
+}
+func (d *DatabaseState) mysqlWalkThrough(stmt string) error {
// We define the Catalog as Database -> Schema -> Table. The Schema is only for PostgreSQL.
// So we use a Schema whose name is empty for other engines, such as MySQL.
// If there is no empty-string-name schema, create it to avoid corner cases.
@@ -180,7 +207,7 @@ func (d *DatabaseState) WalkThrough(stmts string) error {
d.createSchema("")
}
- nodeList, err := d.parse(stmts)
+ nodeList, err := d.parse(stmt)
if err != nil {
return err
}
@@ -1293,7 +1320,7 @@ func restoreNode(node tidbast.Node, flag format.RestoreFlags) (string, *WalkThro
ctx := format.NewRestoreCtx(flag, &buffer)
if err := node.Restore(ctx); err != nil {
return "", &WalkThroughError{
- Type: ErrorTypeRestoreError,
+ Type: ErrorTypeDeparseError,
Content: err.Error(),
}
}
diff --git a/plugin/advisor/catalog/walk_through_for_pg.go b/plugin/advisor/catalog/walk_through_for_pg.go
new file mode 100644
index 0000000000..a62ed88afc
--- /dev/null
+++ b/plugin/advisor/catalog/walk_through_for_pg.go
@@ -0,0 +1,479 @@
+package catalog
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase/plugin/parser"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+const (
+ publicSchemaName = "public"
+)
+
+func (d *DatabaseState) pgWalkThrough(stmt string) error {
+ nodeList, err := pgParse(stmt)
+ if err != nil {
+ return err
+ }
+
+ for _, node := range nodeList {
+ if err := d.pgChangeState(node); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (d *DatabaseState) pgChangeState(in ast.Node) (err *WalkThroughError) {
+ defer func() {
+ if err == nil {
+ return
+ }
+ if err.Line == 0 {
+ err.Line = in.LastLine()
+ }
+ }()
+
+ if d.deleted {
+ return &WalkThroughError{
+ Type: ErrorTypeDatabaseIsDeleted,
+ Content: fmt.Sprintf(`Database %q is deleted`, d.name),
+ }
+ }
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ return d.pgCreateTable(node)
+ case *ast.CreateIndexStmt:
+ return d.pgCreateIndex(node)
+ default:
+ return nil
+ }
+}
+
+func (d *DatabaseState) pgCreateIndex(node *ast.CreateIndexStmt) *WalkThroughError {
+ schema, err := d.getSchema(node.Index.Table.Schema)
+ if err != nil {
+ return err
+ }
+ return schema.pgCreateIndex(node, false /* isPrimary */)
+}
+
+func (d *DatabaseState) pgCreateTable(node *ast.CreateTableStmt) *WalkThroughError {
+ if node.Name.Database != "" && d.name != node.Name.Database {
+ return &WalkThroughError{
+ Type: ErrorTypeAccessOtherDatabase,
+ Content: fmt.Sprintf("Database %q is not the current database %q", node.Name.Database, d.name),
+ }
+ }
+
+ schema, err := d.getSchema(node.Name.Schema)
+ if err != nil {
+ return err
+ }
+
+ if _, exists := schema.tableSet[node.Name.Name]; exists {
+ if node.IfNotExists {
+ return nil
+ }
+ return &WalkThroughError{
+ Type: ErrorTypeTableExists,
+ Content: fmt.Sprintf(`The table %q already exists in the schema %q`, node.Name.Name, schema.name),
+ }
+ }
+
+ table := &TableState{
+ name: node.Name.Name,
+ columnSet: make(columnStateMap),
+ indexSet: make(indexStateMap),
+ }
+ schema.tableSet[table.name] = table
+
+ for _, column := range node.ColumnList {
+ if err := schema.pgCreateColumn(table, column); err != nil {
+ err.Line = column.LastLine()
+ return err
+ }
+ }
+
+ for _, constraint := range node.ConstraintList {
+ if err := schema.pgCreateTableConstraint(table, constraint); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (s *SchemaState) pgCreateTableConstraint(t *TableState, constraint *ast.ConstraintDef) *WalkThroughError {
+ switch constraint.Type {
+ case ast.ConstraintTypePrimary:
+ return s.pgCreatePrimaryKey(t, constraint)
+ case ast.ConstraintTypePrimaryUsingIndex:
+ return s.pgCreatePrimaryKeyUsingIndex(t, constraint)
+ case ast.ConstraintTypeUnique:
+ var indexKeyList []*ast.IndexKeyDef
+ for _, key := range constraint.KeyList {
+ indexKeyList = append(indexKeyList, &ast.IndexKeyDef{
+ Type: ast.IndexKeyTypeColumn,
+ Key: key,
+ })
+ }
+ return s.pgCreateIndex(&ast.CreateIndexStmt{
+ IfNotExists: false,
+ Index: &ast.IndexDef{
+ Name: constraint.Name,
+ Table: &ast.TableDef{
+ Name: t.name,
+ Schema: s.name,
+ },
+ Unique: true,
+ Method: ast.IndexMethodTypeBTree,
+ KeyList: indexKeyList,
+ },
+ }, false /* isPrimary */)
+ case ast.ConstraintTypeUniqueUsingIndex:
+ return s.pgCreateUniqueUsingIndex(t, constraint)
+ case ast.ConstraintTypeCheck:
+ // We do not deal with CHECK constraint.
+ case ast.ConstraintTypeExclusion:
+ // We do not deal with EXCLUSION constraint.
+ case ast.ConstraintTypeForeign:
+ // We do not deal with FOREIGN constraint.
+ }
+ return nil
+}
+
+func (s *SchemaState) pgCreateColumn(t *TableState, column *ast.ColumnDef) *WalkThroughError {
+ if _, exists := t.columnSet[column.ColumnName]; exists {
+ return &WalkThroughError{
+ Type: ErrorTypeColumnExists,
+ Content: fmt.Sprintf("The column %q already exists in table %q", column.ColumnName, t.name),
+ }
+ }
+
+ pos := len(t.columnSet) + 1
+ typeString, err := parser.Deparse(parser.Postgres, parser.DeparseContext{}, column.Type)
+ if err != nil {
+ return &WalkThroughError{
+ Type: ErrorTypeDeparseError,
+ Content: err.Error(),
+ }
+ }
+
+ columnState := &ColumnState{
+ name: column.ColumnName,
+ position: &pos,
+ defaultValue: nil,
+ nullable: newTruePointer(),
+ columnType: &typeString,
+ // TODO(rebelice): support collation and comment here.
+ }
+ t.columnSet[columnState.name] = columnState
+
+ for _, constraint := range column.ConstraintList {
+ switch constraint.Type {
+ case ast.ConstraintTypePrimary:
+ if err := s.pgCreatePrimaryKey(t, constraint); err != nil {
+ return err
+ }
+ case ast.ConstraintTypePrimaryUsingIndex:
+ if err := s.pgCreatePrimaryKeyUsingIndex(t, constraint); err != nil {
+ return err
+ }
+ case ast.ConstraintTypeNotNull:
+ columnState.nullable = newFalsePointer()
+ case ast.ConstraintTypeDefault:
+ columnState.defaultValue = newStringPointer(constraint.Expression.Text())
+ case ast.ConstraintTypeUnique:
+ if err := s.pgCreateIndex(&ast.CreateIndexStmt{
+ IfNotExists: false,
+ Index: &ast.IndexDef{
+ Table: &ast.TableDef{
+ Schema: s.name,
+ Name: t.name,
+ },
+ Unique: true,
+ KeyList: []*ast.IndexKeyDef{
+ {
+ Type: ast.IndexKeyTypeColumn,
+ Key: column.ColumnName,
+ },
+ },
+ Method: ast.IndexMethodTypeBTree,
+ },
+ }, false /* isPrimary */); err != nil {
+ return err
+ }
+ case ast.ConstraintTypeUniqueUsingIndex:
+ if err := s.pgCreateUniqueUsingIndex(t, constraint); err != nil {
+ return err
+ }
+ case ast.ConstraintTypeCheck:
+ // We do not deal with CHECK constraint.
+ case ast.ConstraintTypeExclusion:
+ // We do not deal with EXCLUSION constraint.
+ case ast.ConstraintTypeForeign:
+ // We do not deal with FOREIGN constraint.
+ }
+ }
+
+ return nil
+}
+
+func (s *SchemaState) pgCreateUniqueUsingIndex(t *TableState, constraint *ast.ConstraintDef) *WalkThroughError {
+ index, exists := t.indexSet[constraint.IndexName]
+ if !exists {
+ return NewIndexNotExistsError(t.name, constraint.IndexName)
+ }
+
+ var indexKeyList []*ast.IndexKeyDef
+ for _, key := range index.expressionList {
+ indexKeyList = append(indexKeyList, &ast.IndexKeyDef{
+ Type: ast.IndexKeyTypeColumn,
+ Key: key,
+ })
+ }
+ if err := t.checkIndexKey(indexKeyList); err != nil {
+ return err
+ }
+
+ index.unique = newTruePointer()
+
+ if constraint.Name != "" && constraint.Name != index.name {
+ if _, exists := s.identifierMap[constraint.Name]; exists {
+ return NewRelationExistsError(constraint.Name, s.name)
+ }
+ delete(s.identifierMap, index.name)
+ delete(t.indexSet, index.name)
+ s.identifierMap[constraint.Name] = true
+ index.name = constraint.Name
+ t.indexSet[index.name] = index
+ }
+ return nil
+}
+
+func (s *SchemaState) pgCreatePrimaryKeyUsingIndex(t *TableState, constraint *ast.ConstraintDef) *WalkThroughError {
+ index, exists := t.indexSet[constraint.IndexName]
+ if !exists {
+ return NewIndexNotExistsError(t.name, constraint.IndexName)
+ }
+
+ pkName := constraint.Name
+ if pkName == "" {
+ pkName = constraint.IndexName
+ }
+
+ createPK := &ast.ConstraintDef{
+ Type: ast.ConstraintTypePrimary,
+ Name: pkName,
+ KeyList: index.expressionList,
+ }
+ delete(s.identifierMap, index.name)
+ delete(t.indexSet, index.name)
+ return s.pgCreatePrimaryKey(t, createPK)
+}
+
+func (s *SchemaState) pgCreatePrimaryKey(t *TableState, createPrimaryKey *ast.ConstraintDef) *WalkThroughError {
+ for _, columnName := range createPrimaryKey.KeyList {
+ column, exists := t.columnSet[columnName]
+ if !exists {
+ return NewColumnNotExistsError(t.name, columnName)
+ }
+ column.nullable = newFalsePointer()
+ }
+
+ pkName := createPrimaryKey.Name
+ if pkName == "" {
+ pkName = s.pgGeneratePrimaryKeyName(t.name)
+ }
+
+ return s.pgCreateIndex(&ast.CreateIndexStmt{
+ IfNotExists: false,
+ Index: &ast.IndexDef{
+ Name: pkName,
+ Table: &ast.TableDef{
+ Name: t.name,
+ Schema: s.name,
+ },
+ Unique: true,
+ Method: ast.IndexMethodTypeBTree,
+ KeyList: pgColumnNameListToKeyList(createPrimaryKey.KeyList),
+ },
+ }, true /* isPrimary */)
+}
+
+func pgColumnNameListToKeyList(columnList []string) []*ast.IndexKeyDef {
+ var result []*ast.IndexKeyDef
+ for _, columnName := range columnList {
+ result = append(result, &ast.IndexKeyDef{
+ Type: ast.IndexKeyTypeColumn,
+ Key: columnName,
+ })
+ }
+ return result
+}
+
+func (s *SchemaState) pgGeneratePrimaryKeyName(tableName string) string {
+ pkName := fmt.Sprintf("%s_pkey", tableName)
+ if _, exists := s.identifierMap[pkName]; !exists {
+ return pkName
+ }
+ suffix := 1
+ for {
+ if _, exists := s.identifierMap[fmt.Sprintf("%s%d", pkName, suffix)]; !exists {
+ return fmt.Sprintf("%s%d", pkName, suffix)
+ }
+ suffix++
+ }
+}
+
+func (s *SchemaState) pgCreateIndex(createIndex *ast.CreateIndexStmt, isPrimary bool) *WalkThroughError {
+ indexName := createIndex.Index.Name
+ if len(createIndex.Index.KeyList) == 0 {
+ return &WalkThroughError{
+ Type: ErrorTypeIndexEmptyKeys,
+ Content: fmt.Sprintf("Index %q in table %q has empty key", indexName, createIndex.Index.Table.Name),
+ }
+ }
+
+ table, exists := s.tableSet[createIndex.Index.Table.Name]
+ if !exists {
+ return NewTableNotExistsError(createIndex.Index.Table.Name)
+ }
+
+ if indexName != "" {
+ if _, exists := s.identifierMap[indexName]; exists {
+ if createIndex.IfNotExists {
+ return nil
+ }
+ return NewRelationExistsError(indexName, s.name)
+ }
+ } else {
+ var err error
+ indexName, err = s.pgGenerateIndexName(createIndex)
+ if err != nil {
+ return &WalkThroughError{
+ Type: ErrorTypeInternal,
+ Content: fmt.Sprintf("Failed to generate PostgreSQL index name: %s", err.Error()),
+ }
+ }
+ }
+
+ if err := table.checkIndexKey(createIndex.Index.KeyList); err != nil {
+ return err
+ }
+
+ index := &IndexState{
+ name: indexName,
+ expressionList: pgKeyListToStringList(createIndex.Index.KeyList),
+ indexType: newStringPointer(getIndexMethod(createIndex.Index.Method)),
+ unique: newBoolPointer(createIndex.Index.Unique),
+ primary: newBoolPointer(isPrimary),
+ }
+
+ table.indexSet[index.name] = index
+ s.identifierMap[index.name] = true
+ return nil
+}
+
+func (t *TableState) checkIndexKey(keyList []*ast.IndexKeyDef) *WalkThroughError {
+ for _, key := range keyList {
+ if key.Type == ast.IndexKeyTypeColumn {
+ if _, exists := t.columnSet[key.Key]; !exists {
+ return NewColumnNotExistsError(t.name, key.Key)
+ }
+ }
+ }
+ return nil
+}
+
+func getIndexMethod(method ast.IndexMethodType) string {
+ switch method {
+ case ast.IndexMethodTypeBTree:
+ return "btree"
+ case ast.IndexMethodTypeHash:
+ return "hash"
+ case ast.IndexMethodTypeGiST:
+ return "gist"
+ case ast.IndexMethodTypeSpGiST:
+ return "spgist"
+ case ast.IndexMethodTypeGin:
+ return "gin"
+ case ast.IndexMethodTypeBrin:
+ return "brin"
+ }
+ return ""
+}
+
+func pgKeyListToStringList(keyList []*ast.IndexKeyDef) []string {
+ var result []string
+ for _, key := range keyList {
+ result = append(result, key.Key)
+ }
+ return result
+}
+
+func (s *SchemaState) pgGenerateIndexName(createIndex *ast.CreateIndexStmt) (string, error) {
+ buf := &strings.Builder{}
+ if _, err := buf.WriteString(createIndex.Index.Table.Name); err != nil {
+ return "", err
+ }
+ exprText := "expr"
+ expressionID := 0
+ for _, key := range createIndex.Index.KeyList {
+ if err := buf.WriteByte('_'); err != nil {
+ return "", err
+ }
+ switch key.Type {
+ case ast.IndexKeyTypeColumn:
+ if _, err := buf.WriteString(key.Key); err != nil {
+ return "", err
+ }
+ case ast.IndexKeyTypeExpression:
+ if _, err := buf.WriteString(exprText); err != nil {
+ return "", err
+ }
+ if expressionID != 0 {
+ if _, err := buf.WriteString(fmt.Sprintf("%d", expressionID)); err != nil {
+ return "", err
+ }
+ }
+ expressionID++
+ }
+ }
+ if _, err := buf.WriteString("_idx"); err != nil {
+ return "", err
+ }
+ indexName := buf.String()
+ if _, exists := s.identifierMap[indexName]; !exists {
+ return indexName, nil
+ }
+ suffix := 1
+ for {
+ if _, exists := s.identifierMap[fmt.Sprintf("%s%d", indexName, suffix)]; !exists {
+ return fmt.Sprintf("%s%d", indexName, suffix), nil
+ }
+ suffix++
+ }
+}
+
+func (d *DatabaseState) getSchema(schemaName string) (*SchemaState, *WalkThroughError) {
+ if schemaName == "" {
+ schemaName = publicSchemaName
+ }
+ schema, exists := d.schemaSet[schemaName]
+ if !exists {
+ return nil, &WalkThroughError{
+ Type: ErrorTypeSchemaNotExists,
+ Content: fmt.Sprintf("The schema %q doesn't exist", schemaName),
+ }
+ }
+ return schema, nil
+}
+
+func pgParse(stmt string) ([]ast.Node, error) {
+ return parser.Parse(parser.Postgres, parser.ParseContext{}, stmt)
+}
diff --git a/plugin/advisor/catalog/walk_through_test.go b/plugin/advisor/catalog/walk_through_test.go
index dcbae5c0e3..0e5d517009 100644
--- a/plugin/advisor/catalog/walk_through_test.go
+++ b/plugin/advisor/catalog/walk_through_test.go
@@ -16,6 +16,9 @@ import (
// Register pingcap parser driver.
_ "github.com/pingcap/tidb/types/parser_driver"
+
+ // Register postgresql parser driver.
+ _ "github.com/bytebase/bytebase/plugin/parser/engine/pg"
)
type testData struct {
@@ -34,7 +37,7 @@ func TestMySQLWalkThrough(t *testing.T) {
}
for _, test := range tests {
- runWalkThroughTest(t, test, originDatabase, false /* record */)
+ runWalkThroughTest(t, test, db.MySQL, originDatabase, false /* record */)
}
}
@@ -44,11 +47,30 @@ func TestMySQLWalkThroughForIncomplete(t *testing.T) {
}
for _, test := range tests {
- runWalkThroughTest(t, test, nil, false /* record */)
+ runWalkThroughTest(t, test, db.MySQL, nil, false /* record */)
+ }
+}
+
+func TestPostgreSQLWalkThrough(t *testing.T) {
+ originDatabase := &storepb.DatabaseMetadata{
+ Name: "postgres",
+ Schemas: []*storepb.SchemaMetadata{
+ {
+ Name: "public",
+ },
+ },
+ }
+
+ tests := []string{
+ "pg_walk_through",
+ }
+
+ for _, test := range tests {
+ runWalkThroughTest(t, test, db.Postgres, originDatabase, false /* record */)
}
}
-func runWalkThroughTest(t *testing.T, file string, originDatabase *storepb.DatabaseMetadata, record bool) {
+func runWalkThroughTest(t *testing.T, file string, engineType db.Type, originDatabase *storepb.DatabaseMetadata, record bool) {
tests := []testData{}
filepath := filepath.Join("test", file+".yaml")
yamlFile, err := os.Open(filepath)
@@ -63,9 +85,9 @@ func runWalkThroughTest(t *testing.T, file string, originDatabase *storepb.Datab
for i, test := range tests {
var state *DatabaseState
if originDatabase != nil {
- state = newDatabaseState(originDatabase, &FinderContext{CheckIntegrity: true, EngineType: db.MySQL})
+ state = newDatabaseState(originDatabase, &FinderContext{CheckIntegrity: true, EngineType: engineType})
} else {
- finder := NewEmptyFinder(&FinderContext{CheckIntegrity: false, EngineType: db.MySQL})
+ finder := NewEmptyFinder(&FinderContext{CheckIntegrity: false, EngineType: engineType})
state = finder.Origin
}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index 4ba6fb7344..1576746184 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -497,7 +497,7 @@ func convertWalkThroughErrorToAdvice(err error) ([]Advice, error) {
Title: SyntaxErrorTitle,
Content: walkThroughError.Content,
})
- case catalog.ErrorTypeRestoreError:
+ case catalog.ErrorTypeDeparseError:
res = append(res, Advice{
Status: Error,
Code: Internal,