Skip to content

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

refactor(Catalog): refactor the catalog interface (#1992)

rebelice95dfe5d31b54
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index c168955060..546af7f25b 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -159,8 +159,8 @@ type Context struct {
Collation string
// Schema review rule special fields.
- Rule *SQLReviewRule
- Catalog catalog.Catalog
+ Rule *SQLReviewRule
+ Database *catalog.Database
}
// Advisor is the interface for advisor.
diff --git a/plugin/advisor/catalog/catalog.go b/plugin/advisor/catalog/catalog.go
index c6a758b89e..f50f1843be 100644
--- a/plugin/advisor/catalog/catalog.go
+++ b/plugin/advisor/catalog/catalog.go
@@ -2,37 +2,152 @@ package catalog
import (
"context"
+ "sort"
)
// Catalog is the service for catalog.
type Catalog interface {
- FindIndex(ctx context.Context, find *IndexFind) (*Index, error)
- FindTable(ctx context.Context, find *TableFind) ([]*Table, error)
+ GetDatabase(ctx context.Context) (*Database, error)
}
-// Index is the API message for an index.
-type Index struct {
- Name string
- TableName string
- Type string
- Unique bool
- Primary bool
- ColumnExpressions []string
+// Database is the database.
+type Database struct {
+ Name string
+ CharacterSet string
+ Collation string
+ DbType DBType
+ SchemaList []*Schema
}
-// IndexFind is the API message for find index
-type IndexFind struct {
- TableName string
- IndexName string
+// Schema is the database schema.
+type Schema struct {
+ Name string
+ TableList []*Table
+ ViewList []*View
+ ExtensionList []*Extension
}
-// Table is the API message for an table.
+// Table is the database table.
type Table struct {
- Name string
- DatabaseName string
+ Name string
+ // CreatedTs isn't supported for ClickHouse, SQLite.
+ CreatedTs int64
+ // UpdatedTs isn't supported for SQLite.
+ UpdatedTs int64
+ Type string
+ // Engine isn't supported for Postgres, Snowflake, SQLite.
+ Engine string
+ // Collation isn't supported for Postgres, ClickHouse, Snowflake, SQLite.
+ Collation string
+ RowCount int64
+ // DataSize isn't supported for SQLite.
+ DataSize int64
+ // IndexSize isn't supported for ClickHouse, Snowflake, SQLite.
+ IndexSize int64
+ // DataFree isn't supported for Postgres, ClickHouse, Snowflake, SQLite.
+ DataFree int64
+ // CreateOptions isn't supported for Postgres, ClickHouse, Snowflake, SQLite.
+ CreateOptions string
+ // Comment isn't supported for SQLite.
+ Comment string
+ ColumnList []*Column
+ // IndexList isn't supported for ClickHouse, Snowflake.
+ IndexList []*Index
+}
+
+// Index is the database index.
+type Index struct {
+ Name string
+ // This could refer to a column or an expression.
+ Expression string
+ Position int
+ // Type isn't supported for SQLite.
+ Type string
+ Unique bool
+ Primary bool
+ // Visible isn't supported for Postgres, SQLite.
+ Visible bool
+ // Comment isn't supported for SQLite.
+ Comment string
+}
+
+// Column the database table column.
+type Column struct {
+ Name string
+ Position int
+ Default *string
+ // Nullable isn't supported for ClickHouse.
+ Nullable bool
+ Type string
+ // CharacterSet isn't supported for Postgres, ClickHouse, SQLite.
+ CharacterSet string
+ // Collation isn't supported for ClickHouse, SQLite.
+ Collation string
+ // Comment isn't supported for SQLite.
+ Comment string
+}
+
+// View is the database view.
+type View struct {
+ Name string
+ // CreatedTs isn't supported for ClickHouse.
+ CreatedTs int64
+ UpdatedTs int64
+ Definition string
+ Comment string
+}
+
+// Extension is the database extension.
+type Extension struct {
+ Name string
+ Version string
+ Description string
+}
+
+// HasNoTable returns true if the current database has no table.
+func (d *Database) HasNoTable() bool {
+ for _, schema := range d.SchemaList {
+ for _, table := range schema.TableList {
+ if table != nil {
+ return false
+ }
+ }
+ }
+
+ return true
+}
+
+// IndexFind is for find index.
+type IndexFind struct {
+ SchemaName string
+ TableName string
+ IndexName string
}
-// TableFind is the API message for find table
-type TableFind struct {
- DatabaseName string
+// FindIndex finds the index.
+func (d *Database) FindIndex(find *IndexFind) (string, []*Index) {
+ tableName := ""
+ var indexList []*Index
+ // notMatchTable is used for PostgreSQL. In PostgreSQL, the index name is unique in a schema, not a table.
+ notMatchTable := (d.DbType == Postgres && find.SchemaName != "" && find.TableName == "")
+ for _, schema := range d.SchemaList {
+ if schema.Name != find.SchemaName {
+ continue
+ }
+ for _, table := range schema.TableList {
+ if !notMatchTable && table.Name != find.TableName {
+ continue
+ }
+ for _, index := range table.IndexList {
+ if index.Name == find.IndexName {
+ tableName = table.Name
+ indexList = append(indexList, index)
+ }
+ }
+ }
+ }
+ sort.Slice(indexList, func(i, j int) bool {
+ return indexList[i].Position < indexList[j].Position
+ })
+ return tableName, indexList
}
diff --git a/plugin/advisor/catalog/db.go b/plugin/advisor/catalog/db.go
new file mode 100644
index 0000000000..56c29139f1
--- /dev/null
+++ b/plugin/advisor/catalog/db.go
@@ -0,0 +1,13 @@
+package catalog
+
+// DBType is the type of a database.
+type DBType string
+
+const (
+ // MySQL is the database type for MYSQL.
+ MySQL DBType = "MYSQL"
+ // Postgres is the database type for POSTGRES.
+ Postgres DBType = "POSTGRES"
+ // TiDB is the database type for TiDB.
+ TiDB DBType = "TIDB"
+)
diff --git a/plugin/advisor/catalog/utils.go b/plugin/advisor/catalog/utils.go
new file mode 100644
index 0000000000..cdd757f46e
--- /dev/null
+++ b/plugin/advisor/catalog/utils.go
@@ -0,0 +1,19 @@
+package catalog
+
+import (
+ "strings"
+)
+
+// JoinColumnListForIndex joins the column name with sep.
+func JoinColumnListForIndex(indexList []*Index, sep string) string {
+ return strings.Join(GetColumnListForIndex(indexList), sep)
+}
+
+// GetColumnListForIndex returns the column name list.
+func GetColumnListForIndex(indexList []*Index) []string {
+ var columnList []string
+ for _, column := range indexList {
+ columnList = append(columnList, column.Expression)
+ }
+ return columnList
+}
diff --git a/plugin/advisor/code.go b/plugin/advisor/code.go
index 90987c4592..b52e42cd94 100644
--- a/plugin/advisor/code.go
+++ b/plugin/advisor/code.go
@@ -53,7 +53,8 @@ const (
TableDropNamingConventionMismatch Code = 603
// 701 ~ 799 database advisor error code
- DatabaseNotEmpty Code = 701
+ DatabaseNotEmpty Code = 701
+ NotCurrentDatabase Code = 702
)
// Int returns the int type of code.
diff --git a/plugin/advisor/mysql/advisor_column_no_null_test.go b/plugin/advisor/mysql/advisor_column_no_null_test.go
index 09e910444a..425b849f72 100644
--- a/plugin/advisor/mysql/advisor_column_no_null_test.go
+++ b/plugin/advisor/mysql/advisor_column_no_null_test.go
@@ -108,5 +108,5 @@ func TestColumnNoNull(t *testing.T) {
Type: advisor.SchemaRuleColumnNotNull,
Level: advisor.SchemaRuleLevelWarning,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_column_required_test.go b/plugin/advisor/mysql/advisor_column_required_test.go
index a7ee42f712..ea989bd7c9 100644
--- a/plugin/advisor/mysql/advisor_column_required_test.go
+++ b/plugin/advisor/mysql/advisor_column_required_test.go
@@ -230,5 +230,5 @@ func TestColumnRequirement(t *testing.T) {
Type: advisor.SchemaRuleRequiredColumn,
Level: advisor.SchemaRuleLevelWarning,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_database_drop_empty_db.go b/plugin/advisor/mysql/advisor_database_drop_empty_db.go
index 61d945901c..a8615b65ab 100644
--- a/plugin/advisor/mysql/advisor_database_drop_empty_db.go
+++ b/plugin/advisor/mysql/advisor_database_drop_empty_db.go
@@ -1,9 +1,7 @@
package mysql
import (
- "context"
"fmt"
- "log"
"github.com/bytebase/bytebase/plugin/advisor"
"github.com/bytebase/bytebase/plugin/advisor/catalog"
@@ -36,9 +34,9 @@ func (adv *DatabaseAllowDropIfEmptyAdvisor) Check(ctx advisor.Context, statement
}
checker := &allowDropEmptyDBChecker{
- level: level,
- title: string(ctx.Rule.Type),
- catalog: ctx.Catalog,
+ level: level,
+ title: string(ctx.Rule.Type),
+ database: ctx.Database,
}
for _, stmtNode := range root {
(stmtNode).Accept(checker)
@@ -59,25 +57,20 @@ type allowDropEmptyDBChecker struct {
adviceList []advisor.Advice
level advisor.Status
title string
- catalog catalog.Catalog
+ database *catalog.Database
}
// Enter implements the ast.Visitor interface
func (v *allowDropEmptyDBChecker) Enter(in ast.Node) (ast.Node, bool) {
if node, ok := in.(*ast.DropDatabaseStmt); ok {
- ctx := context.Background()
- tableList, err := v.catalog.FindTable(ctx, &catalog.TableFind{
- DatabaseName: node.Name,
- })
-
- if err != nil {
- log.Printf(
- "Cannot find table in database %s with error %v\n",
- node.Name,
- err,
- )
- }
- if len(tableList) > 0 {
+ if v.database.Name != node.Name {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.NotCurrentDatabase,
+ Title: v.title,
+ Content: fmt.Sprintf("Database `%s` that is trying to be deleted is not the current database `%s`", node.Name, v.database.Name),
+ })
+ } else if !v.database.HasNoTable() {
v.adviceList = append(v.adviceList, advisor.Advice{
Status: v.level,
Code: advisor.DatabaseNotEmpty,
diff --git a/plugin/advisor/mysql/advisor_database_drop_empty_db_test.go b/plugin/advisor/mysql/advisor_database_drop_empty_db_test.go
index 1372114fc8..882de6d8a1 100644
--- a/plugin/advisor/mysql/advisor_database_drop_empty_db_test.go
+++ b/plugin/advisor/mysql/advisor_database_drop_empty_db_test.go
@@ -9,13 +9,24 @@ import (
func TestMySQLDatabaseAllowDropIfEmpty(t *testing.T) {
tests := []advisor.TestCase{
{
- Statement: "DROP DATABASE IF EXISTS foo",
+ Statement: "DROP DATABASE IF EXISTS test",
Want: []advisor.Advice{
{
Status: advisor.Error,
Code: advisor.DatabaseNotEmpty,
Title: "database.drop-empty-database",
- Content: "Database `foo` is not allowed to drop if not empty",
+ Content: "Database `test` is not allowed to drop if not empty",
+ },
+ },
+ },
+ {
+ Statement: "DROP DATABASE IF EXISTS foo",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NotCurrentDatabase,
+ Title: "database.drop-empty-database",
+ Content: "Database `foo` that is trying to be deleted is not the current database `test`",
},
},
},
@@ -25,5 +36,5 @@ func TestMySQLDatabaseAllowDropIfEmpty(t *testing.T) {
Type: advisor.SchemaRuleDropEmptyDatabase,
Level: advisor.SchemaRuleLevelError,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_migration_compatibility_test.go b/plugin/advisor/mysql/advisor_migration_compatibility_test.go
index 3be15e88c5..2ddbe2f488 100644
--- a/plugin/advisor/mysql/advisor_migration_compatibility_test.go
+++ b/plugin/advisor/mysql/advisor_migration_compatibility_test.go
@@ -88,7 +88,7 @@ func TestBasic(t *testing.T) {
Type: advisor.SchemaRuleSchemaBackwardCompatibility,
Level: advisor.SchemaRuleLevelWarning,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
func TestAlterTable(t *testing.T) {
@@ -262,7 +262,7 @@ func TestAlterTable(t *testing.T) {
Type: advisor.SchemaRuleSchemaBackwardCompatibility,
Level: advisor.SchemaRuleLevelWarning,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
func TestAlterTableChangeColumnType(t *testing.T) {
@@ -328,5 +328,5 @@ func TestAlterTableChangeColumnType(t *testing.T) {
Type: advisor.SchemaRuleSchemaBackwardCompatibility,
Level: advisor.SchemaRuleLevelWarning,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_naming_column_test.go b/plugin/advisor/mysql/advisor_naming_column_test.go
index 12ad9e9f58..a593f3c898 100644
--- a/plugin/advisor/mysql/advisor_naming_column_test.go
+++ b/plugin/advisor/mysql/advisor_naming_column_test.go
@@ -172,5 +172,5 @@ func TestNamingColumnConvention(t *testing.T) {
Type: advisor.SchemaRuleColumnNaming,
Level: advisor.SchemaRuleLevelWarning,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_naming_foreign_key_convention_test.go b/plugin/advisor/mysql/advisor_naming_foreign_key_convention_test.go
index 80f1f31ac5..8fee442bab 100644
--- a/plugin/advisor/mysql/advisor_naming_foreign_key_convention_test.go
+++ b/plugin/advisor/mysql/advisor_naming_foreign_key_convention_test.go
@@ -85,5 +85,5 @@ func TestNamingFKConvention(t *testing.T) {
Type: advisor.SchemaRuleFKNaming,
Level: advisor.SchemaRuleLevelError,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_naming_index_convention.go b/plugin/advisor/mysql/advisor_naming_index_convention.go
index 8a06ac627d..81395cae70 100644
--- a/plugin/advisor/mysql/advisor_naming_index_convention.go
+++ b/plugin/advisor/mysql/advisor_naming_index_convention.go
@@ -1,9 +1,7 @@
package mysql
import (
- "context"
"fmt"
- "log"
"regexp"
"strings"
@@ -47,7 +45,7 @@ func (check *NamingIndexConventionAdvisor) Check(ctx advisor.Context, statement
format: format,
maxLength: maxLength,
templateList: templateList,
- catalog: ctx.Catalog,
+ database: ctx.Database,
}
for _, stmtNode := range root {
(stmtNode).Accept(checker)
@@ -72,7 +70,7 @@ type namingIndexConventionChecker struct {
format string
maxLength int
templateList []string
- catalog catalog.Catalog
+ database *catalog.Database
}
// Enter implements the ast.Visitor interface
@@ -149,29 +147,19 @@ func (checker *namingIndexConventionChecker) getMetaDataList(in ast.Node) []*ind
for _, spec := range node.Specs {
switch spec.Tp {
case ast.AlterTableRenameIndex:
- ctx := context.Background()
- index, err := checker.catalog.FindIndex(ctx, &catalog.IndexFind{
+ _, indexList := checker.database.FindIndex(&catalog.IndexFind{
TableName: node.Table.Name.String(),
IndexName: spec.FromKey.String(),
})
- if err != nil {
- log.Printf(
- "Cannot find index %s in table %s with error %v\n",
- node.Table.Name.String(),
- spec.FromKey.String(),
- err,
- )
+ if len(indexList) == 0 {
continue
}
- if index == nil {
- continue
- }
- if index.Unique {
+ if indexList[0].Unique {
// Unique index naming convention should in advisor_naming_unique_key_convention.go
continue
}
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ColumnExpressions, "_"),
+ advisor.ColumnListTemplateToken: catalog.JoinColumnListForIndex(indexList, "_"),
advisor.TableNameTemplateToken: node.Table.Name.String(),
}
res = append(res, &indexMetaData{
diff --git a/plugin/advisor/mysql/advisor_naming_index_convention_test.go b/plugin/advisor/mysql/advisor_naming_index_convention_test.go
index 31c8c65421..5a8ed59814 100644
--- a/plugin/advisor/mysql/advisor_naming_index_convention_test.go
+++ b/plugin/advisor/mysql/advisor_naming_index_convention_test.go
@@ -137,5 +137,5 @@ func TestNamingIndexConvention(t *testing.T) {
Type: advisor.SchemaRuleIDXNaming,
Level: advisor.SchemaRuleLevelError,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_naming_table_test.go b/plugin/advisor/mysql/advisor_naming_table_test.go
index 5f3ea521cf..609595b5ea 100644
--- a/plugin/advisor/mysql/advisor_naming_table_test.go
+++ b/plugin/advisor/mysql/advisor_naming_table_test.go
@@ -117,5 +117,5 @@ func TestMySQLNamingTableConvention(t *testing.T) {
Type: advisor.SchemaRuleTableNaming,
Level: advisor.SchemaRuleLevelError,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_naming_unique_key_convention.go b/plugin/advisor/mysql/advisor_naming_unique_key_convention.go
index 627b8e5dd2..60d27729b8 100644
--- a/plugin/advisor/mysql/advisor_naming_unique_key_convention.go
+++ b/plugin/advisor/mysql/advisor_naming_unique_key_convention.go
@@ -1,9 +1,7 @@
package mysql
import (
- "context"
"fmt"
- "log"
"strings"
"github.com/bytebase/bytebase/plugin/advisor"
@@ -46,7 +44,7 @@ func (check *NamingUKConventionAdvisor) Check(ctx advisor.Context, statement str
format: format,
maxLength: maxLength,
templateList: templateList,
- catalog: ctx.Catalog,
+ database: ctx.Database,
}
for _, stmtNode := range root {
(stmtNode).Accept(checker)
@@ -70,7 +68,7 @@ type namingUKConventionChecker struct {
format string
maxLength int
templateList []string
- catalog catalog.Catalog
+ database *catalog.Database
}
// Enter implements the ast.Visitor interface
@@ -142,29 +140,19 @@ func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexM
for _, spec := range node.Specs {
switch spec.Tp {
case ast.AlterTableRenameIndex:
- ctx := context.Background()
- index, err := checker.catalog.FindIndex(ctx, &catalog.IndexFind{
+ _, indexList := checker.database.FindIndex(&catalog.IndexFind{
TableName: node.Table.Name.String(),
IndexName: spec.FromKey.String(),
})
- if err != nil {
- log.Printf(
- "Cannot find index %s in table %s with error %v\n",
- node.Table.Name.String(),
- spec.FromKey.String(),
- err,
- )
+ if len(indexList) == 0 {
continue
}
- if index == nil {
- continue
- }
- if !index.Unique {
+ if !indexList[0].Unique {
// Index naming convention should in advisor_naming_index_convention.go
continue
}
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ColumnExpressions, "_"),
+ advisor.ColumnListTemplateToken: catalog.JoinColumnListForIndex(indexList, "_"),
advisor.TableNameTemplateToken: node.Table.Name.String(),
}
res = append(res, &indexMetaData{
diff --git a/plugin/advisor/mysql/advisor_naming_unique_key_convention_test.go b/plugin/advisor/mysql/advisor_naming_unique_key_convention_test.go
index 1edf41ab5c..f6db0ea3b3 100644
--- a/plugin/advisor/mysql/advisor_naming_unique_key_convention_test.go
+++ b/plugin/advisor/mysql/advisor_naming_unique_key_convention_test.go
@@ -159,5 +159,5 @@ func TestNamingUKConvention(t *testing.T) {
Type: advisor.SchemaRuleUKNaming,
Level: advisor.SchemaRuleLevelError,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_stmt_no_leading_wildcard_like_test.go b/plugin/advisor/mysql/advisor_stmt_no_leading_wildcard_like_test.go
index d666c39fbb..82030d5270 100644
--- a/plugin/advisor/mysql/advisor_stmt_no_leading_wildcard_like_test.go
+++ b/plugin/advisor/mysql/advisor_stmt_no_leading_wildcard_like_test.go
@@ -69,5 +69,5 @@ func TestNoLeadingWildcardLike(t *testing.T) {
Type: advisor.SchemaRuleStatementNoLeadingWildcardLike,
Level: advisor.SchemaRuleLevelError,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_stmt_no_select_all_test.go b/plugin/advisor/mysql/advisor_stmt_no_select_all_test.go
index 7390efe06b..ba04ca8dfc 100644
--- a/plugin/advisor/mysql/advisor_stmt_no_select_all_test.go
+++ b/plugin/advisor/mysql/advisor_stmt_no_select_all_test.go
@@ -47,5 +47,5 @@ func TestNoSelectAll(t *testing.T) {
Type: advisor.SchemaRuleStatementNoSelectAll,
Level: advisor.SchemaRuleLevelError,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_stmt_where_required_test.go b/plugin/advisor/mysql/advisor_stmt_where_required_test.go
index 223bd92113..24ad2e09c5 100644
--- a/plugin/advisor/mysql/advisor_stmt_where_required_test.go
+++ b/plugin/advisor/mysql/advisor_stmt_where_required_test.go
@@ -91,5 +91,5 @@ func TestWhereRequirement(t *testing.T) {
Type: advisor.SchemaRuleStatementRequireWhere,
Level: advisor.SchemaRuleLevelWarning,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_table_drop_naming_convention_test.go b/plugin/advisor/mysql/advisor_table_drop_naming_convention_test.go
index 0b4e69a12a..065bb4e16e 100644
--- a/plugin/advisor/mysql/advisor_table_drop_naming_convention_test.go
+++ b/plugin/advisor/mysql/advisor_table_drop_naming_convention_test.go
@@ -53,5 +53,5 @@ func TestMySQLTableDropNamingConvention(t *testing.T) {
Type: advisor.SchemaRuleTableDropNamingConvention,
Level: advisor.SchemaRuleLevelError,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_table_no_fk_test.go b/plugin/advisor/mysql/advisor_table_no_fk_test.go
index 94b2586785..3573640e83 100644
--- a/plugin/advisor/mysql/advisor_table_no_fk_test.go
+++ b/plugin/advisor/mysql/advisor_table_no_fk_test.go
@@ -36,5 +36,5 @@ func TestTableNoFK(t *testing.T) {
Type: advisor.SchemaRuleTableNoFK,
Level: advisor.SchemaRuleLevelError,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_table_require_pk.go b/plugin/advisor/mysql/advisor_table_require_pk.go
index a29df6ee6d..44d7364907 100644
--- a/plugin/advisor/mysql/advisor_table_require_pk.go
+++ b/plugin/advisor/mysql/advisor_table_require_pk.go
@@ -1,9 +1,7 @@
package mysql
import (
- "context"
"fmt"
- "log"
"strings"
"github.com/bytebase/bytebase/plugin/advisor"
@@ -40,10 +38,10 @@ func (adv *TableRequirePKAdvisor) Check(ctx advisor.Context, statement string) (
return nil, err
}
checker := &tableRequirePKChecker{
- level: level,
- title: string(ctx.Rule.Type),
- tables: make(tablePK),
- catalog: ctx.Catalog,
+ level: level,
+ title: string(ctx.Rule.Type),
+ tables: make(tablePK),
+ database: ctx.Database,
}
for _, stmtNode := range root {
@@ -58,7 +56,7 @@ type tableRequirePKChecker struct {
level advisor.Status
title string
tables tablePK
- catalog catalog.Catalog
+ database *catalog.Database
}
// Enter implements the ast.Visitor interface
@@ -158,23 +156,15 @@ func (v *tableRequirePKChecker) createTable(node *ast.CreateTableStmt) {
func (v *tableRequirePKChecker) dropColumn(table string, column string) {
if _, ok := v.tables[table]; !ok {
- ctx := context.Background()
- pk, err := v.catalog.FindIndex(ctx, &catalog.IndexFind{
+ v.tables[table] = make(columnSet)
+ _, pkList := v.database.FindIndex(&catalog.IndexFind{
TableName: table,
IndexName: primaryKeyName,
})
- if err != nil {
- log.Printf(
- "Cannot find primary key in table %s with error %v\n",
- table,
- err,
- )
+ if len(pkList) == 0 {
return
}
- if pk == nil {
- return
- }
- v.tables[table] = newColumnSet(pk.ColumnExpressions)
+ v.tables[table] = newColumnSet(catalog.GetColumnListForIndex(pkList))
}
delete(v.tables[table], column)
diff --git a/plugin/advisor/mysql/advisor_table_require_pk_test.go b/plugin/advisor/mysql/advisor_table_require_pk_test.go
index 10a33743f4..f4b306f1f5 100644
--- a/plugin/advisor/mysql/advisor_table_require_pk_test.go
+++ b/plugin/advisor/mysql/advisor_table_require_pk_test.go
@@ -187,7 +187,7 @@ func TestRequirePK(t *testing.T) {
},
{
// Use MockCatalogService
- Statement: `ALTER TABLE t DROP COLUMN uid, DROP COLUMN name`,
+ Statement: `ALTER TABLE tech_book DROP COLUMN uid, DROP COLUMN name`,
Want: []advisor.Advice{
{
Status: advisor.Success,
@@ -199,14 +199,14 @@ func TestRequirePK(t *testing.T) {
},
{
// Use MockCatalogService
- Statement: `ALTER TABLE t CHANGE COLUMN id uid int;
- ALTER TABLE t DROP COLUMN uid, DROP COLUMN name`,
+ Statement: `ALTER TABLE tech_book CHANGE COLUMN id uid int;
+ ALTER TABLE tech_book DROP COLUMN uid, DROP COLUMN name`,
Want: []advisor.Advice{
{
Status: advisor.Error,
Code: advisor.TableNoPK,
Title: "table.require-pk",
- Content: "Table `t` requires PRIMARY KEY",
+ Content: "Table `tech_book` requires PRIMARY KEY",
},
},
},
@@ -216,5 +216,5 @@ func TestRequirePK(t *testing.T) {
Type: advisor.SchemaRuleTableRequirePK,
Level: advisor.SchemaRuleLevelError,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/mysql/advisor_use_innodb_test.go b/plugin/advisor/mysql/advisor_use_innodb_test.go
index 48d4a7c171..0e9a058bd9 100644
--- a/plugin/advisor/mysql/advisor_use_innodb_test.go
+++ b/plugin/advisor/mysql/advisor_use_innodb_test.go
@@ -90,5 +90,5 @@ func TestUseInnoDB(t *testing.T) {
Type: advisor.SchemaRuleMySQLEngine,
Level: advisor.SchemaRuleLevelError,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockMySQLDatabase)
}
diff --git a/plugin/advisor/pg/advisor_column_no_null.go b/plugin/advisor/pg/advisor_column_no_null.go
index c6848b9ae8..39d37ada3e 100644
--- a/plugin/advisor/pg/advisor_column_no_null.go
+++ b/plugin/advisor/pg/advisor_column_no_null.go
@@ -1,9 +1,7 @@
package pg
import (
- "context"
"fmt"
- "log"
"sort"
"github.com/bytebase/bytebase/plugin/advisor"
@@ -38,7 +36,7 @@ func (adv *ColumnNoNullAdvisor) Check(ctx advisor.Context, statement string) ([]
checker := &columnNoNullChecker{
level: level,
title: string(ctx.Rule.Type),
- catalog: ctx.Catalog,
+ database: ctx.Database,
nullableColumns: make(columnMap),
}
@@ -53,7 +51,7 @@ type columnNoNullChecker struct {
adviceList []advisor.Advice
level advisor.Status
title string
- catalog catalog.Catalog
+ database *catalog.Database
nullableColumns columnMap
}
@@ -146,24 +144,16 @@ func (checker *columnNoNullChecker) removeColumnByConstraintList(table *ast.Tabl
checker.removeColumn(table, column)
}
case ast.ConstraintTypePrimaryUsingIndex:
- index, err := checker.catalog.FindIndex(context.Background(), &catalog.IndexFind{
- TableName: getTableNameWithSchema(table),
- IndexName: constraint.IndexName,
+ _, indexList := checker.database.FindIndex(&catalog.IndexFind{
+ SchemaName: normalizeSchemaName(table.Schema),
+ TableName: table.Name,
+ IndexName: constraint.IndexName,
})
- if err != nil {
- log.Printf(
- "Cannot find index %s in table %s with error %v\n",
- constraint.IndexName,
- getTableNameWithSchema(table),
- err,
- )
+ if len(indexList) == 0 {
continue
}
- if index == nil {
- continue
- }
- for _, column := range index.ColumnExpressions {
- checker.removeColumn(table, column)
+ for _, index := range indexList {
+ checker.removeColumn(table, index.Expression)
}
}
}
diff --git a/plugin/advisor/pg/advisor_column_no_null_test.go b/plugin/advisor/pg/advisor_column_no_null_test.go
index d4821b5f6d..ba3a9b593a 100644
--- a/plugin/advisor/pg/advisor_column_no_null_test.go
+++ b/plugin/advisor/pg/advisor_column_no_null_test.go
@@ -119,5 +119,5 @@ func TestColumnNoNULL(t *testing.T) {
Type: advisor.SchemaRuleColumnNotNull,
Level: advisor.SchemaRuleLevelWarning,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockPostgreSQLDatabase)
}
diff --git a/plugin/advisor/pg/advisor_naming_column_test.go b/plugin/advisor/pg/advisor_naming_column_test.go
index c2f9fc9f0e..53dbd047e0 100644
--- a/plugin/advisor/pg/advisor_naming_column_test.go
+++ b/plugin/advisor/pg/advisor_naming_column_test.go
@@ -101,5 +101,5 @@ func TestNamingColumnConvention(t *testing.T) {
Type: advisor.SchemaRuleColumnNaming,
Level: advisor.SchemaRuleLevelWarning,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockPostgreSQLDatabase)
}
diff --git a/plugin/advisor/pg/advisor_naming_foreign_key_convention_test.go b/plugin/advisor/pg/advisor_naming_foreign_key_convention_test.go
index 5b952ece26..e54f264cff 100644
--- a/plugin/advisor/pg/advisor_naming_foreign_key_convention_test.go
+++ b/plugin/advisor/pg/advisor_naming_foreign_key_convention_test.go
@@ -130,5 +130,5 @@ func TestNamingFKConvention(t *testing.T) {
Type: advisor.SchemaRuleFKNaming,
Level: advisor.SchemaRuleLevelError,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockPostgreSQLDatabase)
}
diff --git a/plugin/advisor/pg/advisor_naming_table_test.go b/plugin/advisor/pg/advisor_naming_table_test.go
index 7b7d78a956..8d68b9a465 100644
--- a/plugin/advisor/pg/advisor_naming_table_test.go
+++ b/plugin/advisor/pg/advisor_naming_table_test.go
@@ -104,6 +104,6 @@ func TestPostgreSQLNamingTableConvention(t *testing.T) {
Type: advisor.SchemaRuleTableNaming,
Level: advisor.SchemaRuleLevelError,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockPostgreSQLDatabase)
}
diff --git a/plugin/advisor/pg/advisor_naming_unique_key_convention.go b/plugin/advisor/pg/advisor_naming_unique_key_convention.go
index 6a824fe5a5..09a9830c65 100644
--- a/plugin/advisor/pg/advisor_naming_unique_key_convention.go
+++ b/plugin/advisor/pg/advisor_naming_unique_key_convention.go
@@ -1,9 +1,7 @@
package pg
import (
- "context"
"fmt"
- "log"
"strings"
"github.com/bytebase/bytebase/plugin/advisor"
@@ -46,7 +44,7 @@ func (check *NamingUKConventionAdvisor) Check(ctx advisor.Context, statement str
format: format,
maxLength: maxLength,
templateList: templateList,
- catalog: ctx.Catalog,
+ database: ctx.Database,
}
for _, stmtNode := range root {
@@ -72,7 +70,7 @@ type namingUKConventionChecker struct {
format string
maxLength int
templateList []string
- catalog catalog.Catalog
+ database *catalog.Database
}
// Visit implements ast.Visitor interface
@@ -117,26 +115,26 @@ func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexM
switch node := in.(type) {
case *ast.CreateTableStmt:
for _, constraint := range node.ConstraintList {
- if metadata := checker.getUniqueKeyMetadata(constraint, node.Name.Name); metadata != nil {
+ if metadata := checker.getUniqueKeyMetadata(node.Name.Schema, node.Name.Name, constraint); metadata != nil {
res = append(res, metadata)
}
}
for _, column := range node.ColumnList {
for _, constraint := range column.ConstraintList {
- if metadata := checker.getUniqueKeyMetadata(constraint, node.Name.Name); metadata != nil {
+ if metadata := checker.getUniqueKeyMetadata(node.Name.Schema, node.Name.Name, constraint); metadata != nil {
res = append(res, metadata)
}
}
}
case *ast.AddConstraintStmt:
constraint := node.Constraint
- if metadata := checker.getUniqueKeyMetadata(constraint, node.Table.Name); metadata != nil {
+ if metadata := checker.getUniqueKeyMetadata(node.Table.Schema, node.Table.Name, constraint); metadata != nil {
res = append(res, metadata)
}
case *ast.AddColumnListStmt:
for _, column := range node.ColumnList {
for _, constraint := range column.ConstraintList {
- if metadata := checker.getUniqueKeyMetadata(constraint, node.Table.Name); metadata != nil {
+ if metadata := checker.getUniqueKeyMetadata(node.Table.Schema, node.Table.Name, constraint); metadata != nil {
res = append(res, metadata)
}
}
@@ -158,10 +156,11 @@ func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexM
})
}
case *ast.RenameConstraintStmt:
- if index := checker.findIndex(context.Background(), node.Table.Name, node.ConstraintName); index != nil && index.Unique && !index.Primary {
+ tableName, indexList := checker.findIndex(node.Table.Schema, node.Table.Name, node.ConstraintName)
+ if len(indexList) != 0 && indexList[0].Unique && !indexList[0].Primary {
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ColumnExpressions, "_"),
- advisor.TableNameTemplateToken: node.Table.Name,
+ advisor.ColumnListTemplateToken: catalog.JoinColumnListForIndex(indexList, "_"),
+ advisor.TableNameTemplateToken: tableName,
}
res = append(res, &indexMetaData{
indexName: node.NewName,
@@ -170,15 +169,16 @@ func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexM
})
}
case *ast.RenameIndexStmt:
- // TODO(rebelice): "ALTER INDEX name RENAME TO new_name" doesn't take a table name
- if index := checker.findIndex(context.Background(), "", node.IndexName); index != nil && index.Unique && !index.Primary {
+ // "ALTER INDEX name RENAME TO new_name" doesn't take a table name
+ tableName, indexList := checker.findIndex(node.Table.Schema, "", node.IndexName)
+ if len(indexList) != 0 && indexList[0].Unique && !indexList[0].Primary {
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ColumnExpressions, "_"),
- advisor.TableNameTemplateToken: index.TableName,
+ advisor.ColumnListTemplateToken: catalog.JoinColumnListForIndex(indexList, "_"),
+ advisor.TableNameTemplateToken: tableName,
}
res = append(res, &indexMetaData{
indexName: node.NewName,
- tableName: index.TableName,
+ tableName: tableName,
metaData: metaData,
})
}
@@ -187,7 +187,7 @@ func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexM
}
// getUniqueKeyMetadata returns index metadata of a unique key constraint, nil if other constraints.
-func (checker *namingUKConventionChecker) getUniqueKeyMetadata(constraint *ast.ConstraintDef, tableName string) *indexMetaData {
+func (checker *namingUKConventionChecker) getUniqueKeyMetadata(schemaName string, tableName string, constraint *ast.ConstraintDef) *indexMetaData {
switch constraint.Type {
case ast.ConstraintTypeUnique:
metaData := map[string]string{
@@ -200,9 +200,10 @@ func (checker *namingUKConventionChecker) getUniqueKeyMetadata(constraint *ast.C
metaData: metaData,
}
case ast.ConstraintTypeUniqueUsingIndex:
- if index := checker.findIndex(context.Background(), tableName, constraint.IndexName); index != nil {
+ tableName, indexList := checker.findIndex(schemaName, tableName, constraint.IndexName)
+ if len(indexList) != 0 {
metaData := map[string]string{
- advisor.ColumnListTemplateToken: strings.Join(index.ColumnExpressions, "_"),
+ advisor.ColumnListTemplateToken: catalog.JoinColumnListForIndex(indexList, "_"),
advisor.TableNameTemplateToken: tableName,
}
return &indexMetaData{
@@ -216,19 +217,10 @@ func (checker *namingUKConventionChecker) getUniqueKeyMetadata(constraint *ast.C
}
// findIndex returns index found in catalogs, nil if not found
-func (checker *namingUKConventionChecker) findIndex(ctx context.Context, tableName string, indexName string) *catalog.Index {
- index, err := checker.catalog.FindIndex(ctx, &catalog.IndexFind{
- TableName: tableName,
- IndexName: indexName,
+func (checker *namingUKConventionChecker) findIndex(schemaName string, tableName string, indexName string) (string, []*catalog.Index) {
+ return checker.database.FindIndex(&catalog.IndexFind{
+ SchemaName: normalizeSchemaName(schemaName),
+ TableName: tableName,
+ IndexName: indexName,
})
- if err != nil {
- log.Printf(
- "Cannot find index %s in table %s with error %v\n",
- indexName,
- tableName,
- err,
- )
- return nil
- }
- return index
}
diff --git a/plugin/advisor/pg/advisor_naming_unique_key_convention_test.go b/plugin/advisor/pg/advisor_naming_unique_key_convention_test.go
index 93b89960bb..957913512b 100644
--- a/plugin/advisor/pg/advisor_naming_unique_key_convention_test.go
+++ b/plugin/advisor/pg/advisor_naming_unique_key_convention_test.go
@@ -229,5 +229,5 @@ func TestNamingUKConvention(t *testing.T) {
Type: advisor.SchemaRuleUKNaming,
Level: advisor.SchemaRuleLevelError,
Payload: string(payload),
- }, &advisor.MockCatalogService{})
+ }, advisor.MockPostgreSQLDatabase)
}
diff --git a/plugin/advisor/pg/advisor_table_require_pk_test.go b/plugin/advisor/pg/advisor_table_require_pk_test.go
index 537c712e6d..cd9408fa38 100644
--- a/plugin/advisor/pg/advisor_table_require_pk_test.go
+++ b/plugin/advisor/pg/advisor_table_require_pk_test.go
@@ -18,5 +18,5 @@ func TestRequirePK(t *testing.T) {
Type: advisor.SchemaRuleTableRequirePK,
Level: advisor.SchemaRuleLevelError,
Payload: "",
- }, &advisor.MockCatalogService{})
+ }, advisor.MockPostgreSQLDatabase)
}
diff --git a/plugin/advisor/pg/utils.go b/plugin/advisor/pg/utils.go
index 834787c588..f9ccfaed42 100644
--- a/plugin/advisor/pg/utils.go
+++ b/plugin/advisor/pg/utils.go
@@ -2,8 +2,6 @@ package pg
import (
"fmt"
-
- "github.com/bytebase/bytebase/plugin/parser/ast"
)
const (
@@ -27,10 +25,9 @@ func (c columnName) normalizeTableName() string {
type columnMap map[columnName]bool
-func getTableNameWithSchema(table *ast.TableDef) string {
- schema := table.Schema
- if schema == "" {
- schema = "public"
+func normalizeSchemaName(name string) string {
+ if name != "" {
+ return name
}
- return fmt.Sprintf("%s.%s", schema, table.Name)
+ return "public"
}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index 2bc3af7374..a29a12aa2d 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -1,6 +1,7 @@
package advisor
import (
+ "context"
"encoding/json"
"fmt"
"log"
@@ -254,27 +255,31 @@ type SQLReviewCheckContext struct {
}
// SchemaReviewCheck checks the statements with schema review policy.
-func SchemaReviewCheck(statements string, policy *SQLReviewPolicy, context SQLReviewCheckContext) ([]Advice, error) {
+func SchemaReviewCheck(statements string, policy *SQLReviewPolicy, checkContext SQLReviewCheckContext) ([]Advice, error) {
var result []Advice
+ database, err := checkContext.Catalog.GetDatabase(context.Background())
+ if err != nil {
+ return nil, fmt.Errorf("failed to get database information from catalog: %w", err)
+ }
for _, rule := range policy.RuleList {
if rule.Level == SchemaRuleLevelDisabled {
continue
}
- advisorType, err := getAdvisorTypeByRule(rule.Type, context.DbType)
+ advisorType, err := getAdvisorTypeByRule(rule.Type, checkContext.DbType)
if err != nil {
log.Printf("not supported rule: %v. error: %v\n", rule.Type, err)
continue
}
adviceList, err := Check(
- context.DbType,
+ checkContext.DbType,
advisorType,
Context{
- Charset: context.Charset,
- Collation: context.Collation,
+ Charset: checkContext.Charset,
+ Collation: checkContext.Collation,
Rule: rule,
- Catalog: context.Catalog,
+ Database: database,
},
statements,
)
diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.go
index 8290010e28..8884a459ef 100644
--- a/plugin/advisor/utils_for_tests.go
+++ b/plugin/advisor/utils_for_tests.go
@@ -1,8 +1,6 @@
package advisor
import (
- "context"
- "fmt"
"math/rand"
"testing"
"time"
@@ -12,16 +10,15 @@ import (
"github.com/stretchr/testify/require"
)
-// MockCatalogService is the mock catalog service for test.
-type MockCatalogService struct{}
-
const (
// MockOldIndexName is the mock old index for test.
MockOldIndexName = "old_index"
// MockOldUKName is the mock old unique key for test.
MockOldUKName = "old_uk"
- // MockOldPKName is the mock old foreign key for test.
- MockOldPKName = "PRIMARY"
+ // MockOldMySQLPKName is the mock old primary key for MySQL test.
+ MockOldMySQLPKName = "PRIMARY"
+ // MockOldPostgreSQLPKName is the mock old primary key for PostgreSQL test.
+ MockOldPostgreSQLPKName = "old_pk"
// MockTableName is the mock table for test.
MockTableName = "tech_book"
)
@@ -29,46 +26,108 @@ const (
var (
// MockIndexColumnList is the mock index column list for test.
MockIndexColumnList = []string{"id", "name"}
-
- _ catalog.Catalog = (*MockCatalogService)(nil)
-)
-
-// FindIndex implements the catalog interface.
-func (*MockCatalogService) FindIndex(_ context.Context, find *catalog.IndexFind) (*catalog.Index, error) {
- switch find.IndexName {
- case MockOldIndexName:
- return &catalog.Index{
- Name: MockOldIndexName,
- TableName: MockTableName,
- ColumnExpressions: MockIndexColumnList,
- }, nil
- case MockOldUKName:
- return &catalog.Index{
- Unique: true,
- Name: MockOldIndexName,
- TableName: MockTableName,
- ColumnExpressions: MockIndexColumnList,
- }, nil
- case MockOldPKName:
- return &catalog.Index{
- Unique: true,
- Name: MockOldPKName,
- TableName: MockTableName,
- ColumnExpressions: MockIndexColumnList,
- }, nil
+ // MockMySQLDatabase is the mock MySQL database for test.
+ MockMySQLDatabase = &catalog.Database{
+ Name: "test",
+ DbType: catalog.MySQL,
+ SchemaList: []*catalog.Schema{
+ {
+ TableList: []*catalog.Table{
+ {
+ Name: MockTableName,
+ ColumnList: []*catalog.Column{
+ {Name: "id"},
+ {Name: "name"},
+ },
+ IndexList: []*catalog.Index{
+ {
+ Name: MockOldMySQLPKName,
+ Expression: "id",
+ Unique: true,
+ Primary: true,
+ },
+ {
+ Name: MockOldMySQLPKName,
+ Expression: "name",
+ Unique: true,
+ Primary: true,
+ },
+ {
+ Name: MockOldUKName,
+ Expression: "id",
+ Unique: true,
+ },
+ {
+ Name: MockOldUKName,
+ Expression: "name",
+ Unique: true,
+ },
+ {
+ Name: MockOldIndexName,
+ Expression: "id",
+ },
+ {
+ Name: MockOldIndexName,
+ Expression: "name",
+ },
+ },
+ },
+ },
+ },
+ },
}
- return nil, fmt.Errorf("cannot find index for %v", find)
-}
-
-// FindTable implements the catalog interface.
-func (*MockCatalogService) FindTable(_ context.Context, find *catalog.TableFind) ([]*catalog.Table, error) {
- return []*catalog.Table{
- {
- Name: "table",
- DatabaseName: find.DatabaseName,
+ // MockPostgreSQLDatabase is the mock PostgreSQL database for test.
+ MockPostgreSQLDatabase = &catalog.Database{
+ Name: "test",
+ DbType: catalog.Postgres,
+ SchemaList: []*catalog.Schema{
+ {
+ Name: "public",
+ TableList: []*catalog.Table{
+ {
+ Name: MockTableName,
+ ColumnList: []*catalog.Column{
+ {Name: "id"},
+ {Name: "name"},
+ },
+ IndexList: []*catalog.Index{
+ {
+ Name: MockOldPostgreSQLPKName,
+ Expression: "id",
+ Unique: true,
+ Primary: true,
+ },
+ {
+ Name: MockOldPostgreSQLPKName,
+ Expression: "name",
+ Unique: true,
+ Primary: true,
+ },
+ {
+ Name: MockOldUKName,
+ Expression: "id",
+ Unique: true,
+ },
+ {
+ Name: MockOldUKName,
+ Expression: "name",
+ Unique: true,
+ },
+ {
+ Name: MockOldIndexName,
+ Expression: "id",
+ },
+ {
+ Name: MockOldIndexName,
+ Expression: "name",
+ },
+ },
+ },
+ },
+ },
},
- }, nil
-}
+ }
+)
// TestCase is the data struct for test.
type TestCase struct {
@@ -82,13 +141,13 @@ func RunSchemaReviewRuleTests(
tests []TestCase,
adv Advisor,
rule *SQLReviewRule,
- catalog catalog.Catalog,
+ database *catalog.Database,
) {
ctx := Context{
Charset: "",
Collation: "",
Rule: rule,
- Catalog: catalog,
+ Database: database,
}
for _, tc := range tests {
adviceList, err := adv.Check(ctx, tc.Statement)
diff --git a/plugin/parser/ast/rename_index_stmt.go b/plugin/parser/ast/rename_index_stmt.go
index 686a231846..7b43de3f7b 100644
--- a/plugin/parser/ast/rename_index_stmt.go
+++ b/plugin/parser/ast/rename_index_stmt.go
@@ -5,7 +5,7 @@ type RenameIndexStmt struct {
node
// For PostgreSQL, we only use TableDef.Schema.
- // If this rename index statement doesn't contain schema name, Table will be nil.
+ // If this rename index statement doesn't contain schema name, Table will be not nil and the Schema name is empty string.
Table *TableDef
IndexName string
NewName string
diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.go
index d94f7e1eaa..3c06b08cba 100644
--- a/plugin/parser/engine/pg/convert.go
+++ b/plugin/parser/engine/pg/convert.go
@@ -258,9 +258,6 @@ func convertRangeVarToTableName(in *pgquery.RangeVar) *ast.TableDef {
}
func convertRangeVarToIndexTableName(in *pgquery.RangeVar) *ast.TableDef {
- if in.Schemaname == "" {
- return nil
- }
return &ast.TableDef{
Schema: in.Schemaname,
}
diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.go
index e9dd05c133..ebd3bbe5b2 100644
--- a/plugin/parser/engine/pg/convert_test.go
+++ b/plugin/parser/engine/pg/convert_test.go
@@ -404,6 +404,7 @@ func TestPGAlterIndexStmt(t *testing.T) {
stmt: "ALTER INDEX idx_id RENAME TO \"IDX_ID\"",
want: []ast.Node{
&ast.RenameIndexStmt{
+ Table: &ast.TableDef{Schema: ""},
IndexName: "idx_id",
NewName: "IDX_ID",
},
diff --git a/server/openapi.go b/server/openapi.go
index 494e7871e3..ea3ac9f114 100644
--- a/server/openapi.go
+++ b/server/openapi.go
@@ -22,15 +22,9 @@ var (
// catalogService is the catalog service for sql check api.
type catalogService struct{}
-// FindIndex is the API message for find index in catalog.
+// GetDatabase is the API message in catalog.
// We will not connect to the user's database in the early version of sql check api
-func (c *catalogService) FindIndex(context.Context, *catalog.IndexFind) (*catalog.Index, error) {
- return nil, nil
-}
-
-// FindTable is the API message for find table in catalog.
-// We will not connect to the user's database in the early version of sql check api
-func (c *catalogService) FindTable(context.Context, *catalog.TableFind) ([]*catalog.Table, error) {
+func (c *catalogService) GetDatabase(_ context.Context) (*catalog.Database, error) {
return nil, nil
}
@@ -79,7 +73,7 @@ func (s *Server) sqlCheckController(c echo.Context) error {
return err
}
dbType = database.Instance.Engine
- catalog = store.NewCatalog(&database.ID, s.store)
+ catalog = store.NewCatalog(&database.ID, s.store, dbType)
} else {
databaseType := c.QueryParams().Get("databaseType")
if databaseType == "" {
diff --git a/server/sql.go b/server/sql.go
index 3db13f36e0..5a38102378 100644
--- a/server/sql.go
+++ b/server/sql.go
@@ -207,7 +207,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
db.Collation,
instance.EnvironmentID,
exec.Statement,
- store.NewCatalog(&db.ID, s.store),
+ store.NewCatalog(&db.ID, s.store, instance.Engine),
)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to check schema review policy").SetInternal(err)
diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/task_check_executor_statement_advisor_composite.go
index 426df36108..3e6c917c09 100644
--- a/server/task_check_executor_statement_advisor_composite.go
+++ b/server/task_check_executor_statement_advisor_composite.go
@@ -61,7 +61,7 @@ func (exec *TaskCheckStatementAdvisorCompositeExecutor) Run(ctx context.Context,
return nil, common.Errorf(common.Internal, fmt.Errorf("failed to get task by id: %w", err))
}
- catalog := store.NewCatalog(task.DatabaseID, server.store)
+ catalog := store.NewCatalog(task.DatabaseID, server.store, payload.DbType)
dbType, err := api.ConvertToAdvisorDBType(payload.DbType)
if err != nil {
diff --git a/store/catalog.go b/store/catalog.go
index e445cb7523..215ff2ca2d 100644
--- a/store/catalog.go
+++ b/store/catalog.go
@@ -2,10 +2,12 @@ package store
import (
"context"
- "sort"
+ "fmt"
+ "strings"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/plugin/advisor/catalog"
+ "github.com/bytebase/bytebase/plugin/db"
)
var (
@@ -16,78 +18,207 @@ var (
type Catalog struct {
databaseID *int
store *Store
+ engineType db.Type
}
// NewCatalog creates a new database catalog.
-func NewCatalog(databaseID *int, store *Store) *Catalog {
+func NewCatalog(databaseID *int, store *Store, dbType db.Type) *Catalog {
return &Catalog{
databaseID: databaseID,
store: store,
+ engineType: dbType,
}
}
-// FindIndex finds the index by IndexFind. Implement the catalog.Catalog interface.
-func (c *Catalog) FindIndex(ctx context.Context, find *catalog.IndexFind) (*catalog.Index, error) {
- table, err := c.store.GetTable(ctx, &api.TableFind{
- DatabaseID: c.databaseID,
- Name: &find.TableName,
+// GetDatabase implements the catalog.Catalog interface.
+func (c *Catalog) GetDatabase(ctx context.Context) (*catalog.Database, error) {
+ database, err := c.store.GetDatabase(ctx, &api.DatabaseFind{
+ ID: c.databaseID,
})
if err != nil {
return nil, err
}
- if table == nil {
+ if database == nil {
return nil, nil
}
- indexList, err := c.store.FindIndex(ctx, &api.IndexFind{
- DatabaseID: c.databaseID,
- TableID: &table.ID,
- Name: &find.IndexName,
- })
+ dbType, err := convertToCatalogDBType(c.engineType)
if err != nil {
return nil, err
}
- if len(indexList) == 0 {
- return nil, nil
+
+ databaseData := catalog.Database{
+ Name: database.Name,
+ CharacterSet: database.CharacterSet,
+ Collation: database.Collation,
+ DbType: dbType,
}
- sort.Slice(indexList, func(i, j int) bool {
- return indexList[i].Position < indexList[j].Position
- })
+ if databaseData.SchemaList, err = c.getSchemaList(ctx); err != nil {
+ return nil, err
+ }
+
+ return &databaseData, nil
+}
- var columnExpressions []string
- for _, index := range indexList {
- columnExpressions = append(columnExpressions, index.Expression)
+type schemaMap map[string]*catalog.Schema
+
+func (m schemaMap) getOrCreateSchema(name string) *catalog.Schema {
+ if schema, found := m[name]; found {
+ return schema
}
- return &catalog.Index{
- Name: indexList[0].Name,
- TableName: table.Name,
- Type: indexList[0].Type,
- Unique: indexList[0].Unique,
- Primary: indexList[0].Primary,
- ColumnExpressions: columnExpressions,
- }, nil
+ schema := &catalog.Schema{
+ Name: name,
+ }
+ m[name] = schema
+ return schema
}
-// FindTable finds the table list by TableFind. Implement the catalog.Catalog interface.
-func (c *Catalog) FindTable(ctx context.Context, find *catalog.TableFind) ([]*catalog.Table, error) {
+func (c *Catalog) getSchemaList(ctx context.Context) ([]*catalog.Schema, error) {
+ schemaSet := make(schemaMap)
+
+ // find table list
tableList, err := c.store.FindTable(ctx, &api.TableFind{
DatabaseID: c.databaseID,
})
if err != nil {
return nil, err
}
-
- var res []*catalog.Table
for _, table := range tableList {
- if find.DatabaseName == table.Database.Name {
- res = append(res, &catalog.Table{
- Name: table.Name,
- DatabaseName: table.Database.Name,
- })
+ tableData := convertTable(table)
+ schemaName := ""
+ if c.engineType == db.Postgres {
+ if schemaName, tableData.Name, err = splitPGSchema(tableData.Name); err != nil {
+ return nil, err
+ }
+ }
+ schema := schemaSet.getOrCreateSchema(schemaName)
+ schema.TableList = append(schema.TableList, tableData)
+ }
+
+ // find view list
+ viewList, err := c.store.FindView(ctx, &api.ViewFind{
+ DatabaseID: c.databaseID,
+ })
+ if err != nil {
+ return nil, err
+ }
+ for _, view := range viewList {
+ viewData := convertView(view)
+ schemaName := ""
+ if c.engineType == db.Postgres {
+ if schemaName, viewData.Name, err = splitPGSchema(viewData.Name); err != nil {
+ return nil, err
+ }
}
+ schema := schemaSet.getOrCreateSchema(schemaName)
+ schema.ViewList = append(schema.ViewList, viewData)
+ }
+
+ // find extension list
+ extensionList, err := c.store.FindDBExtension(ctx, &api.DBExtensionFind{
+ DatabaseID: c.databaseID,
+ })
+ if err != nil {
+ return nil, err
+ }
+ for _, extension := range extensionList {
+ schema := schemaSet.getOrCreateSchema(extension.Schema)
+ schema.ExtensionList = append(schema.ExtensionList, &catalog.Extension{
+ Name: extension.Name,
+ Version: extension.Version,
+ Description: extension.Description,
+ })
+ }
+
+ var schemaList []*catalog.Schema
+ for _, schema := range schemaSet {
+ schemaList = append(schemaList, schema)
+ }
+ return schemaList, nil
+}
+
+func splitPGSchema(name string) (string, string, error) {
+ list := strings.Split(name, ".")
+ if len(list) != 2 {
+ return "", "", fmt.Errorf("split failed: the expected name is schemaName.name, but get %s", name)
+ }
+ return list[0], list[1], nil
+}
+
+func convertView(view *api.View) *catalog.View {
+ return &catalog.View{
+ Name: view.Name,
+ CreatedTs: view.CreatedTs,
+ UpdatedTs: view.UpdatedTs,
+ Definition: view.Definition,
+ Comment: view.Comment,
+ }
+}
+
+func convertTable(table *api.Table) *catalog.Table {
+ return &catalog.Table{
+ Name: table.Name,
+ CreatedTs: table.CreatedTs,
+ UpdatedTs: table.UpdatedTs,
+ Type: table.Type,
+ Engine: table.Engine,
+ Collation: table.Collation,
+ RowCount: table.RowCount,
+ DataSize: table.DataSize,
+ IndexSize: table.IndexSize,
+ DataFree: table.DataFree,
+ CreateOptions: table.CreateOptions,
+ Comment: table.Comment,
+ ColumnList: convertColumnList(table.ColumnList),
+ IndexList: converIndexList(table.IndexList),
+ }
+}
+
+func converIndexList(list []*api.Index) []*catalog.Index {
+ var res []*catalog.Index
+ for _, index := range list {
+ res = append(res, &catalog.Index{
+ Name: index.Name,
+ Expression: index.Expression,
+ Position: index.Position,
+ Type: index.Type,
+ Unique: index.Unique,
+ Primary: index.Primary,
+ Visible: index.Visible,
+ Comment: index.Comment,
+ })
+ }
+ return res
+}
+
+func convertColumnList(list []*api.Column) []*catalog.Column {
+ var res []*catalog.Column
+ for _, column := range list {
+ res = append(res, &catalog.Column{
+ Name: column.Name,
+ Position: column.Position,
+ Default: column.Default,
+ Nullable: column.Nullable,
+ Type: column.Type,
+ CharacterSet: column.CharacterSet,
+ Collation: column.Collation,
+ Comment: column.Comment,
+ })
+ }
+ return res
+}
+
+func convertToCatalogDBType(dbType db.Type) (catalog.DBType, error) {
+ switch dbType {
+ case db.MySQL:
+ return catalog.MySQL, nil
+ case db.Postgres:
+ return catalog.Postgres, nil
+ case db.TiDB:
+ return catalog.TiDB, nil
}
- return res, nil
+ return "", fmt.Errorf("unsupported db type %s for catalog", dbType)
}