Skip to content

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

chore(sql review): support drop database rule (#1914)

ecmadao968de998f7f7
diff --git a/frontend/src/components/Issue/TaskCheckRunPanel.vue b/frontend/src/components/Issue/TaskCheckRunPanel.vue
index 93e639a501..f9bf929be7 100644
--- a/frontend/src/components/Issue/TaskCheckRunPanel.vue
+++ b/frontend/src/components/Issue/TaskCheckRunPanel.vue
@@ -157,6 +157,7 @@ export default defineComponent({
case SQLReviewPolicyErrorCode.NO_PK_IN_TABLE:
case SQLReviewPolicyErrorCode.FK_IN_TABLE:
case SQLReviewPolicyErrorCode.TABLE_DROP_NAMING_CONVENTION:
+ case SQLReviewPolicyErrorCode.DATABASE_NOT_EMPTY:
// CompatibilityErrorCode
case CompatibilityErrorCode.COMPATIBILITY_DROP_DATABASE:
case CompatibilityErrorCode.COMPATIBILITY_RENAME_TABLE:
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index fff0d022d8..ead4422762 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -9,7 +9,8 @@
"statement": "Statement",
"table": "Table",
"column": "Column",
- "schema": "Schema"
+ "schema": "Schema",
+ "database": "Database"
},
"template": {
"mysql-prod": "Template for Prod Environment",
@@ -139,6 +140,10 @@
"schema-backward-compatibility": {
"title": "Backward compatibility",
"description": "MySQL and TiDB support checking whether the schema change is backward compatible."
+ },
+ "database-drop-empty-database": {
+ "title": "Drop database restriction",
+ "description": "Can only drop the database if there's no table in it."
}
},
"level": {
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index 495ca4536b..08aa7d3aa9 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -9,7 +9,8 @@
"statement": "语句",
"table": "表",
"column": "列",
- "schema": "Schema"
+ "schema": "Schema",
+ "database": "数据库"
},
"template": {
"mysql-prod": "针对生产环境的审核策略模板",
@@ -139,6 +140,10 @@
"schema-backward-compatibility": {
"title": "向后兼容",
"description": "MySQL 和 TiDB 支持检测 schema 变更是否向后兼容"
+ },
+ "database-drop-empty-database": {
+ "title": "数据库删除限制",
+ "description": "只有当数据库内没有表时,才可以被删除。"
}
},
"level": {
diff --git a/frontend/src/types/error.ts b/frontend/src/types/error.ts
index 1f080e9556..823837ae52 100644
--- a/frontend/src/types/error.ts
+++ b/frontend/src/types/error.ts
@@ -37,6 +37,7 @@ export enum SQLReviewPolicyErrorCode {
NO_PK_IN_TABLE = 601,
FK_IN_TABLE = 602,
TABLE_DROP_NAMING_CONVENTION = 603,
+ DATABASE_NOT_EMPTY = 701,
}
export enum CompatibilityErrorCode {
diff --git a/frontend/src/types/sqlReview.ts b/frontend/src/types/sqlReview.ts
index f1730c312b..96459105db 100644
--- a/frontend/src/types/sqlReview.ts
+++ b/frontend/src/types/sqlReview.ts
@@ -15,7 +15,8 @@ export type CategoryType =
| "STATEMENT"
| "TABLE"
| "COLUMN"
- | "SCHEMA";
+ | "SCHEMA"
+ | "DATABASE";
// The rule level
export enum RuleLevel {
@@ -86,7 +87,8 @@ export type RuleType =
| "statement.select.no-select-all"
| "statement.where.require"
| "statement.where.no-leading-wildcard-like"
- | "schema.backward-compatibility";
+ | "schema.backward-compatibility"
+ | "database.drop-empty-database";
// The naming format rule payload.
// Used by the backend.
diff --git a/frontend/src/types/sqlReviewConfig.yaml b/frontend/src/types/sqlReviewConfig.yaml
index 650e3481a0..eac9b60be1 100644
--- a/frontend/src/types/sqlReviewConfig.yaml
+++ b/frontend/src/types/sqlReviewConfig.yaml
@@ -6,6 +6,7 @@ categoryList:
- TABLE
- SCHEMA
- COLUMN
+ - DATABASE
templateList:
- id: mysql.prod
ruleList:
@@ -148,6 +149,11 @@ templateList:
engine: MYSQL
level: WARNING
componentList: []
+ - type: database.drop-empty-database
+ category: DATABASE
+ engine: COMMON
+ level: ERROR
+ componentList: []
- id: mysql.dev
ruleList:
- type: engine.mysql.use-innodb
@@ -289,3 +295,8 @@ templateList:
engine: MYSQL
level: WARNING
componentList: []
+ - type: database.drop-empty-database
+ category: DATABASE
+ engine: COMMON
+ level: ERROR
+ componentList: []
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 80ca82f67d..625fb26af6 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -93,6 +93,9 @@ const (
// MySQLTableDropNamingConvention is an advisor type for MySQL table drop with naming convention.
MySQLTableDropNamingConvention Type = "bb.plugin.advisor.mysql.table.drop-naming-convention"
+ // MySQLDatabaseAllowDropIfEmpty is an advisor type for MySQL only allow drop empty database.
+ MySQLDatabaseAllowDropIfEmpty Type = "bb.plugin.advisor.mysql.database.drop-empty-database"
+
// PostgreSQL Advisor
// PostgreSQLSyntax is an advisor type for PostgreSQL syntax.
diff --git a/plugin/advisor/catalog/catalog.go b/plugin/advisor/catalog/catalog.go
index a79523d5db..c6a758b89e 100644
--- a/plugin/advisor/catalog/catalog.go
+++ b/plugin/advisor/catalog/catalog.go
@@ -7,6 +7,7 @@ import (
// 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)
}
// Index is the API message for an index.
@@ -24,3 +25,14 @@ type IndexFind struct {
TableName string
IndexName string
}
+
+// Table is the API message for an table.
+type Table struct {
+ Name string
+ DatabaseName string
+}
+
+// TableFind is the API message for find table
+type TableFind struct {
+ DatabaseName string
+}
diff --git a/plugin/advisor/code.go b/plugin/advisor/code.go
index 12218ad0ea..90987c4592 100644
--- a/plugin/advisor/code.go
+++ b/plugin/advisor/code.go
@@ -51,6 +51,9 @@ const (
TableNoPK Code = 601
TableHasFK Code = 602
TableDropNamingConventionMismatch Code = 603
+
+ // 701 ~ 799 database advisor error code
+ DatabaseNotEmpty Code = 701
)
// Int returns the int type of code.
diff --git a/plugin/advisor/mysql/advisor_database_drop_empty_db.go b/plugin/advisor/mysql/advisor_database_drop_empty_db.go
new file mode 100644
index 0000000000..69cf8f0fed
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_database_drop_empty_db.go
@@ -0,0 +1,95 @@
+package mysql
+
+import (
+ "context"
+ "fmt"
+ "log"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/catalog"
+ "github.com/pingcap/tidb/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*DatabaseAllowDropIfEmptyAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(advisor.MySQL, advisor.MySQLDatabaseAllowDropIfEmpty, &DatabaseAllowDropIfEmptyAdvisor{})
+ advisor.Register(advisor.TiDB, advisor.MySQLDatabaseAllowDropIfEmpty, &DatabaseAllowDropIfEmptyAdvisor{})
+}
+
+// DatabaseAllowDropIfEmptyAdvisor is the advisor checking the MySQLDatabaseAllowDropIfEmpty rule.
+type DatabaseAllowDropIfEmptyAdvisor struct {
+}
+
+// Check checks for drop table naming convention.
+func (adv *DatabaseAllowDropIfEmptyAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ root, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &allowDropEmptyDBChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ catalog: ctx.Catalog,
+ }
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type allowDropEmptyDBChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ catalog catalog.Catalog
+}
+
+// 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 tableList != nil && len(tableList) > 0 {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.DatabaseNotEmpty,
+ Title: v.title,
+ Content: fmt.Sprintf("Database `%s` is not allowed to drop if not empty", node.Name),
+ })
+ }
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface
+func (v *allowDropEmptyDBChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/plugin/advisor/mysql/advisor_database_drop_empty_db_test.go b/plugin/advisor/mysql/advisor_database_drop_empty_db_test.go
new file mode 100644
index 0000000000..1372114fc8
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_database_drop_empty_db_test.go
@@ -0,0 +1,29 @@
+package mysql
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+)
+
+func TestMySQLDatabaseAllowDropIfEmpty(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: "DROP DATABASE IF EXISTS foo",
+ 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",
+ },
+ },
+ },
+ }
+
+ advisor.RunSchemaReviewRuleTests(t, tests, &DatabaseAllowDropIfEmptyAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleDropEmptyDatabase,
+ Level: advisor.SchemaRuleLevelError,
+ Payload: "",
+ }, &advisor.MockCatalogService{})
+}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index 24e062ef11..d821d78216 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -66,6 +66,9 @@ const (
// SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.
SchemaRuleSchemaBackwardCompatibility SQLReviewRuleType = "schema.backward-compatibility"
+ // SchemaRuleDropEmptyDatabase enforce the MySQL and TiDB support check if the database is empty before users drop it.
+ SchemaRuleDropEmptyDatabase SQLReviewRuleType = "database.drop-empty-database"
+
// TableNameTemplateToken is the token for table name
TableNameTemplateToken = "{{table}}"
// ColumnListTemplateToken is the token for column name list
@@ -380,6 +383,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine DBType) (Type, erro
if engine == MySQL {
return MySQLUseInnoDB, nil
}
+ case SchemaRuleDropEmptyDatabase:
+ switch engine {
+ case MySQL, TiDB:
+ return MySQLDatabaseAllowDropIfEmpty, nil
+ }
}
return Fake, fmt.Errorf("unknown schema review rule type %v for %v", ruleType, engine)
}
diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.go
index 61d4e3d988..c5e0393beb 100644
--- a/plugin/advisor/utils_for_tests.go
+++ b/plugin/advisor/utils_for_tests.go
@@ -53,6 +53,16 @@ func (c *MockCatalogService) FindIndex(ctx context.Context, find *catalog.IndexF
return nil, fmt.Errorf("cannot find index for %v", find)
}
+// FindTable implements the catalog interface.
+func (c *MockCatalogService) FindTable(ctx context.Context, find *catalog.TableFind) ([]*catalog.Table, error) {
+ return []*catalog.Table{
+ {
+ Name: "table",
+ DatabaseName: find.DatabaseName,
+ },
+ }, nil
+}
+
// TestCase is the data struct for test.
type TestCase struct {
Statement string
diff --git a/server/openapi.go b/server/openapi.go
index 996a692e9e..5b58972474 100644
--- a/server/openapi.go
+++ b/server/openapi.go
@@ -28,6 +28,12 @@ func (c *catalogService) FindIndex(ctx context.Context, find *catalog.IndexFind)
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(ctx context.Context, find *catalog.TableFind) ([]*catalog.Table, error) {
+ return nil, nil
+}
+
func (s *Server) registerOpenAPIRoutes(g *echo.Group) {
g.GET("/sql/advise", s.sqlCheckController)
}
diff --git a/store/catalog.go b/store/catalog.go
index 6259c41574..e445cb7523 100644
--- a/store/catalog.go
+++ b/store/catalog.go
@@ -69,3 +69,25 @@ func (c *Catalog) FindIndex(ctx context.Context, find *catalog.IndexFind) (*cata
ColumnExpressions: columnExpressions,
}, nil
}
+
+// 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) {
+ 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,
+ })
+ }
+ }
+
+ return res, nil
+}