Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
test(sql-review): add integration tests (#3110)
rebelice9fcb09470331
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex e7010de5a2..670019bd50 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -4,6 +4,7 @@ package advisorimport ("context"+ "database/sql""fmt""sync"@@ -12,7 +13,6 @@ import ("github.com/bytebase/bytebase/plugin/advisor/catalog""github.com/bytebase/bytebase/plugin/advisor/db"- database "github.com/bytebase/bytebase/plugin/db")// Status is the advisor result status.@@ -144,9 +144,6 @@ const (// MySQLTableCommentConvention is an advisor for MySQL table comment convention.MySQLTableCommentConvention Type = "bb.plugin.advisor.mysql.table.comment"- // MySQLTableDisallowCreateTableAs is an advisor type for MySQL disallow CREATE TABLE ... AS ... statement.- MySQLTableDisallowCreateTableAs Type = "bb.plugin.advisor.mysql.table.disallow-create-table-as"-// MySQLTableDisallowPartition is an advisor type for MySQL disallow table partition.MySQLTableDisallowPartition Type = "bb.plugin.advisor.mysql.table.disallow-partition"@@ -306,7 +303,7 @@ type Context struct {// SQL review rule special fields.Rule *SQLReviewRuleCatalog *catalog.Finder- Driver database.Driver+ Driver *sql.DBContext context.Context}diff --git a/plugin/advisor/catalog/walk_through.go b/plugin/advisor/catalog/walk_through.goindex 9ebd1ba8c3..ad052d5a19 100644--- a/plugin/advisor/catalog/walk_through.go+++ b/plugin/advisor/catalog/walk_through.go@@ -186,13 +186,6 @@ func (d *DatabaseState) WalkThrough(stmts string) error {}for _, node := range nodeList {- // validate DML- if dml, ok := node.(tidbast.DMLNode); ok {- if err := d.validateDML(dml); err != nil {- return err- }- continue- }// change stateif err := d.changeState(node); err != nil {return err@@ -202,34 +195,6 @@ func (d *DatabaseState) WalkThrough(stmts string) error {return nil}-func (d *DatabaseState) validateDML(in tidbast.DMLNode) (err *WalkThroughError) {- defer func() {- if err == nil {- return- }- if err.Line == 0 {- err.Line = in.OriginTextPosition()- }- }()- if d.deleted {- return &WalkThroughError{- Type: ErrorTypeDatabaseIsDeleted,- Content: fmt.Sprintf("Database `%s` is deleted", d.name),- }- }-- switch node := in.(type) {- case *tidbast.InsertStmt:- return d.checkInsert(node)- case *tidbast.DeleteStmt:- return d.checkDelete(node)- case *tidbast.UpdateStmt:- return d.checkUpdate(node)- default:- return nil- }-}-func (d *DatabaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError) {defer func() {if err == nil {@@ -269,96 +234,6 @@ func (d *DatabaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError)}}-func (d *DatabaseState) checkUpdate(node *tidbast.UpdateStmt) *WalkThroughError {- // Only check the UPDATE single TABLE case.- tableName, ok := getTableSourceName(node.TableRefs)- if ok {- table, err := d.findTableState(tableName, false /* createIncompleteTable */)- if err != nil {- return err- }- if table == nil {- return nil- }- for _, item := range node.List {- columName := item.Column.Name.O- if _, exists := table.columnSet[columName]; !exists {- return NewColumnNotExistsError(table.name, columName)- }- }- }- return nil-}--func (d *DatabaseState) checkDelete(node *tidbast.DeleteStmt) *WalkThroughError {- // Only check the DELETE FROM single TABLE case.- if !node.IsMultiTable {- tableName, ok := getTableSourceName(node.TableRefs)- if ok {- _, err := d.findTableState(tableName, false /* createIncopleteTable */)- if err != nil {- return err- }- }- }- return nil-}--func (d *DatabaseState) checkInsert(node *tidbast.InsertStmt) *WalkThroughError {- tableName, ok := getTableSourceName(node.Table)- if ok {- table, err := d.findTableState(tableName, false /* createIncompleteTable */)- if err != nil {- return err- }- if table == nil {- return nil- }- specifiedColumnMap := make(map[string]bool)- for _, col := range node.Columns {- if _, exists := table.columnSet[col.Name.O]; !exists {- return NewColumnNotExistsError(table.name, col.Name.O)- }- if _, ok := specifiedColumnMap[col.Name.O]; ok {- return &WalkThroughError{- Type: ErrorTypeInsertSpecifiedColumnTwice,- // Content is from MySQL error content- Content: fmt.Sprintf("Column '%s' specified twice", col.Name.O),- }- }- specifiedColumnMap[col.Name.O] = true- }-- if len(node.Lists) > 0 {- for i, row := range node.Lists {- if node.Columns != nil && len(node.Columns) != len(row) {- return &WalkThroughError{- Type: ErrorTypeInsertColumnCountNotMatchValueCount,- // Content is from MySQL error content- Content: fmt.Sprintf("Column count doesn't match value count at row %d", i+1),- }- }-- for columnPos, value := range row {- if value.GetType().GetType() == mysql.TypeNull {- columnName := node.Columns[columnPos].Name.O- // after check, all columns exist- column := table.columnSet[columnName]- if column.nullable != nil && !*column.nullable {- return &WalkThroughError{- Type: ErrorTypeInsertNullIntoNotNullColumn,- // Content is from MySQL error content- Content: fmt.Sprintf("Column '%s' cannot be null", columnName),- }- }- }- }- }- }- }- return nil-}-func (d *DatabaseState) renameTable(node *tidbast.RenameTableStmt) *WalkThroughError {for _, tableToTable := range node.TableToTables {schema, exists := d.schemaSet[""]@@ -1438,15 +1313,3 @@ func getIndexType(option *tidbast.IndexOption) string {}return model.IndexTypeBtree.String()}--func getTableSourceName(table *tidbast.TableRefsClause) (*tidbast.TableName, bool) {- source, isTableSource := table.TableRefs.Left.(*tidbast.TableSource)- nilRight := table.TableRefs.Right == nil- if isTableSource && nilRight {- // isTableSource and nilRight mean it's a table.- if tableName, ok := source.Source.(*tidbast.TableName); ok {- return tableName, true- }- }- return nil, false-}diff --git a/plugin/advisor/catalog/walk_through_test.go b/plugin/advisor/catalog/walk_through_test.goindex cd346757a1..2116f876c3 100644--- a/plugin/advisor/catalog/walk_through_test.go+++ b/plugin/advisor/catalog/walk_through_test.go@@ -109,49 +109,6 @@ func TestWalkThrough(t *testing.T) {Line: 2,},},- {- origin: &Database{- Name: "test",- DbType: db.MySQL,- },- statement: `- UPDATE t SET a = 1;- `,- err: &WalkThroughError{- Type: ErrorTypeTableNotExists,- Content: "Table `t` does not exist",- Line: 2,- },- },- {- origin: &Database{- Name: "test",- DbType: db.MySQL,- },- statement: `- CREATE TABLE t(a int);- UPDATE t set b = 222;- `,- err: &WalkThroughError{- Type: ErrorTypeColumnNotExists,- Content: "Column `b` does not exist in table `t`",- Line: 3,- },- },- {- origin: &Database{- Name: "test",- DbType: db.MySQL,- },- statement: `- DELETE FROM t;- `,- err: &WalkThroughError{- Type: ErrorTypeTableNotExists,- Content: "Table `t` does not exist",- Line: 2,- },- },{origin: &Database{Name: "test",@@ -166,81 +123,6 @@ func TestWalkThrough(t *testing.T) {Line: 2,},},-- {- origin: &Database{- Name: "test",- DbType: db.MySQL,- },- statement: `- CREATE TABLE t(a int NOT NULL);- INSERT INTO t(a) values (1), (NULL);- `,- err: &WalkThroughError{- Type: ErrorTypeInsertNullIntoNotNullColumn,- Content: "Column 'a' cannot be null",- Line: 3,- },- },- {- origin: &Database{- Name: "test",- DbType: db.MySQL,- },- statement: `- CREATE TABLE t(a int);- INSERT INTO t(a) values (1), ();- `,- err: &WalkThroughError{- Type: ErrorTypeInsertColumnCountNotMatchValueCount,- Content: "Column count doesn't match value count at row 2",- Line: 3,- },- },- {- origin: &Database{- Name: "test",- DbType: db.MySQL,- },- statement: `- CREATE TABLE t(a int);- INSERT INTO t(a, a) values (1, 2);- `,- err: &WalkThroughError{- Type: ErrorTypeInsertSpecifiedColumnTwice,- Content: "Column 'a' specified twice",- Line: 3,- },- },- {- origin: &Database{- Name: "test",- DbType: db.MySQL,- },- statement: `- INSERT INTO test values (1);- `,- err: &WalkThroughError{- Type: ErrorTypeTableNotExists,- Content: "Table `test` does not exist",- Line: 2,- },- },- {- origin: &Database{- Name: "test",- DbType: db.MySQL,- },- statement: `- CREATE TABLE t(a int, b int);- INSERT INTO t(a, b, c, d) values (1, 2, 3, 4);- `,- err: &WalkThroughError{- Type: ErrorTypeColumnNotExists,- Content: "Column `c` does not exist in table `t`",- Line: 3,- },- },{origin: &Database{Name: "test",diff --git a/plugin/advisor/code.go b/plugin/advisor/code.goindex 11130ac432..bcc8158cf8 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -54,7 +54,7 @@ const (NoRequiredColumn Code = 401ColumnCannotNull Code = 402ChangeColumnType Code = 403- NotNullColumnWithNullDefault Code = 404+ NotNullColumnWithNoDefault Code = 404ColumnNotExists Code = 405UseChangeColumnStatement Code = 406ChangeColumnOrder Code = 407diff --git a/plugin/advisor/mysql/advisor_column_set_default_for_not_null.go b/plugin/advisor/mysql/advisor_column_set_default_for_not_null.goindex e865623079..e5910634f9 100644--- a/plugin/advisor/mysql/advisor_column_set_default_for_not_null.go+++ b/plugin/advisor/mysql/advisor_column_set_default_for_not_null.go@@ -121,7 +121,7 @@ func (checker *columnSetDefaultForNotNullChecker) Enter(in ast.Node) (ast.Node,for _, column := range notNullColumnWithNoDefault {checker.adviceList = append(checker.adviceList, advisor.Advice{Status: checker.level,- Code: advisor.NotNullColumnWithNullDefault,+ Code: advisor.NotNullColumnWithNoDefault,Title: checker.title,Content: fmt.Sprintf("Column `%s`.`%s` is NOT NULL but doesn't have DEFAULT", column.tableName, column.columnName),Line: column.line,diff --git a/plugin/advisor/mysql/advisor_column_set_default_for_not_null_test.go b/plugin/advisor/mysql/advisor_column_set_default_for_not_null_test.goindex 508bdc7a54..0b2a315143 100644--- a/plugin/advisor/mysql/advisor_column_set_default_for_not_null_test.go+++ b/plugin/advisor/mysql/advisor_column_set_default_for_not_null_test.go@@ -43,7 +43,7 @@ func TestColumnSetDefaultForNotNull(t *testing.T) {Want: []advisor.Advice{{Status: advisor.Warn,- Code: advisor.NotNullColumnWithNullDefault,+ Code: advisor.NotNullColumnWithNoDefault,Title: "column.set-default-for-not-null",Content: "Column `book`.`id` is NOT NULL but doesn't have DEFAULT",Line: 2,@@ -58,7 +58,7 @@ func TestColumnSetDefaultForNotNull(t *testing.T) {Want: []advisor.Advice{{Status: advisor.Warn,- Code: advisor.NotNullColumnWithNullDefault,+ Code: advisor.NotNullColumnWithNoDefault,Title: "column.set-default-for-not-null",Content: "Column `book`.`id` is NOT NULL but doesn't have DEFAULT",Line: 2,@@ -85,7 +85,7 @@ func TestColumnSetDefaultForNotNull(t *testing.T) {Want: []advisor.Advice{{Status: advisor.Warn,- Code: advisor.NotNullColumnWithNullDefault,+ Code: advisor.NotNullColumnWithNoDefault,Title: "column.set-default-for-not-null",Content: "Column `book`.`id` is NOT NULL but doesn't have DEFAULT",Line: 3,@@ -99,7 +99,7 @@ func TestColumnSetDefaultForNotNull(t *testing.T) {Want: []advisor.Advice{{Status: advisor.Warn,- Code: advisor.NotNullColumnWithNullDefault,+ Code: advisor.NotNullColumnWithNoDefault,Title: "column.set-default-for-not-null",Content: "Column `book`.`id` is NOT NULL but doesn't have DEFAULT",Line: 3,@@ -139,7 +139,7 @@ func TestColumnSetDefaultForNotNull(t *testing.T) {Want: []advisor.Advice{{Status: advisor.Warn,- Code: advisor.NotNullColumnWithNullDefault,+ Code: advisor.NotNullColumnWithNoDefault,Title: "column.set-default-for-not-null",Content: "Column `book`.`id` is NOT NULL but doesn't have DEFAULT",Line: 3,diff --git a/plugin/advisor/mysql/advisor_insert_row_limit.go b/plugin/advisor/mysql/advisor_insert_row_limit.goindex c6337ec23f..197d9dbeb8 100644--- a/plugin/advisor/mysql/advisor_insert_row_limit.go+++ b/plugin/advisor/mysql/advisor_insert_row_limit.go@@ -4,14 +4,15 @@ package mysqlimport ("context"+ "database/sql""fmt"+ "strconv""github.com/pingcap/tidb/parser/ast""github.com/pkg/errors""github.com/bytebase/bytebase/plugin/advisor""github.com/bytebase/bytebase/plugin/advisor/db"- database "github.com/bytebase/bytebase/plugin/db")var (@@ -76,7 +77,7 @@ type insertRowLimitChecker struct {text stringline intmaxRow int- driver database.Driver+ driver *sql.DBctx context.Context}@@ -93,12 +94,12 @@ func (checker *insertRowLimitChecker) Enter(in ast.Node) (ast.Node, bool) {Line: checker.line,})}- } else {- res, err := checker.driver.Query(checker.ctx, fmt.Sprintf("EXPLAIN %s", node.Text()), 0)+ } else if checker.driver != nil {+ res, err := query(checker.ctx, checker.driver, fmt.Sprintf("EXPLAIN %s", node.Text()))if err != nil {checker.adviceList = append(checker.adviceList, advisor.Advice{Status: checker.level,- Code: advisor.StatementDMLDryRunFailed,+ Code: advisor.InsertTooManyRows,Title: checker.title,Content: fmt.Sprintf("\"%s\" dry runs failed: %s", checker.text, err.Error()),Line: checker.line,@@ -168,6 +169,12 @@ func getInsertRows(res []interface{}) (int64, error) {return int64(rows), nilcase int64:return rows, nil+ case string:+ v, err := strconv.ParseInt(rows, 10, 64)+ if err != nil {+ return 0, errors.Errorf("expected int or int64 but got string(%s)", rows)+ }+ return v, nildefault:return 0, errors.Errorf("expected int or in64 but got %t", rowTwo[9])}diff --git a/plugin/advisor/mysql/advisor_insert_row_limit_test.go b/plugin/advisor/mysql/advisor_insert_row_limit_test.goindex e76eebf5fd..bc67b0d384 100644--- a/plugin/advisor/mysql/advisor_insert_row_limit_test.go+++ b/plugin/advisor/mysql/advisor_insert_row_limit_test.go@@ -40,11 +40,10 @@ func TestInsertRowLimit(t *testing.T) {Statement: `INSERT INTO tech_book SELECT * FROM tech_book`,Want: []advisor.Advice{{- Status: advisor.Warn,- Code: advisor.InsertTooManyRows,- Title: "statement.insert.row-limit",- Content: "\"INSERT INTO tech_book SELECT * FROM tech_book\" inserts 1000 rows. The count exceeds 5.",- Line: 1,+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",},},},diff --git a/plugin/advisor/mysql/advisor_statement_affected_row_limit.go b/plugin/advisor/mysql/advisor_statement_affected_row_limit.goindex 0dd787ced0..b8f75e2f46 100644--- a/plugin/advisor/mysql/advisor_statement_affected_row_limit.go+++ b/plugin/advisor/mysql/advisor_statement_affected_row_limit.go@@ -4,14 +4,16 @@ package mysqlimport ("context"+ "database/sql""fmt"+ "strconv"+ "strings""github.com/pingcap/tidb/parser/ast""github.com/pkg/errors""github.com/bytebase/bytebase/plugin/advisor""github.com/bytebase/bytebase/plugin/advisor/db"- database "github.com/bytebase/bytebase/plugin/db")var (@@ -50,10 +52,12 @@ func (*StatementAffectedRowLimitAdvisor) Check(ctx advisor.Context, statement stctx: ctx.Context,}- for _, stmt := range stmtList {- checker.text = stmt.Text()- checker.line = stmt.OriginTextPosition()- (stmt).Accept(checker)+ if checker.driver != nil {+ for _, stmt := range stmtList {+ checker.text = stmt.Text()+ checker.line = stmt.OriginTextPosition()+ (stmt).Accept(checker)+ }}if len(checker.adviceList) == 0 {@@ -74,7 +78,7 @@ type statementAffectedRowLimitChecker struct {text stringline intmaxRow int- driver database.Driver+ driver *sql.DBctx context.Context}@@ -82,11 +86,11 @@ type statementAffectedRowLimitChecker struct {func (checker *statementAffectedRowLimitChecker) Enter(in ast.Node) (ast.Node, bool) {switch node := in.(type) {case *ast.UpdateStmt, *ast.DeleteStmt:- res, err := checker.driver.Query(checker.ctx, fmt.Sprintf("EXPLAIN %s", node.Text()), 0)+ res, err := query(checker.ctx, checker.driver, fmt.Sprintf("EXPLAIN %s", node.Text()))if err != nil {checker.adviceList = append(checker.adviceList, advisor.Advice{Status: checker.level,- Code: advisor.StatementDMLDryRunFailed,+ Code: advisor.StatementAffectedRowExceedsLimit,Title: checker.title,Content: fmt.Sprintf("\"%s\" dry runs failed: %s", checker.text, err.Error()),Line: checker.line,@@ -121,6 +125,96 @@ func (*statementAffectedRowLimitChecker) Leave(in ast.Node) (ast.Node, bool) {return in, true}+func query(ctx context.Context, connection *sql.DB, statement string) ([]interface{}, error) {+ tx, err := connection.BeginTx(ctx, &sql.TxOptions{})+ if err != nil {+ return nil, err+ }+ defer tx.Rollback()++ rows, err := tx.QueryContext(ctx, statement)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ columnNames, err := rows.Columns()+ if err != nil {+ return nil, err+ }++ columnTypes, err := rows.ColumnTypes()+ if err != nil {+ return nil, err+ }++ colCount := len(columnTypes)++ var columnTypeNames []string+ for _, v := range columnTypes {+ // DatabaseTypeName returns the database system name of the column type.+ // refer: https://pkg.go.dev/database/sql#ColumnType.DatabaseTypeName+ columnTypeNames = append(columnTypeNames, strings.ToUpper(v.DatabaseTypeName()))+ }++ data := []interface{}{}+ for rows.Next() {+ scanArgs := make([]interface{}, colCount)+ for i, v := range columnTypeNames {+ // TODO(steven need help): Consult a common list of data types from database driver documentation. e.g. MySQL,PostgreSQL.+ switch v {+ case "VARCHAR", "TEXT", "UUID", "TIMESTAMP":+ scanArgs[i] = new(sql.NullString)+ case "BOOL":+ scanArgs[i] = new(sql.NullBool)+ case "INT", "INTEGER":+ scanArgs[i] = new(sql.NullInt64)+ case "FLOAT":+ scanArgs[i] = new(sql.NullFloat64)+ default:+ scanArgs[i] = new(sql.NullString)+ }+ }++ if err := rows.Scan(scanArgs...); err != nil {+ return nil, err+ }++ rowData := []interface{}{}+ for i := range columnTypes {+ if v, ok := (scanArgs[i]).(*sql.NullBool); ok && v.Valid {+ rowData = append(rowData, v.Bool)+ continue+ }+ if v, ok := (scanArgs[i]).(*sql.NullString); ok && v.Valid {+ rowData = append(rowData, v.String)+ continue+ }+ if v, ok := (scanArgs[i]).(*sql.NullInt64); ok && v.Valid {+ rowData = append(rowData, v.Int64)+ continue+ }+ if v, ok := (scanArgs[i]).(*sql.NullInt32); ok && v.Valid {+ rowData = append(rowData, v.Int32)+ continue+ }+ if v, ok := (scanArgs[i]).(*sql.NullFloat64); ok && v.Valid {+ rowData = append(rowData, v.Float64)+ continue+ }+ // If none of them match, set nil to its value.+ rowData = append(rowData, nil)+ }++ data = append(data, rowData)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }++ return []interface{}{columnNames, columnTypeNames, data}, nil+}+func getRows(res []interface{}) (int64, error) {// the res struct is []interface{}{columnName, columnTable, rowDataList}if len(res) != 3 {@@ -154,7 +248,13 @@ func getRows(res []interface{}) (int64, error) {return int64(rows), nilcase int64:return rows, nil+ case string:+ v, err := strconv.ParseInt(rows, 10, 64)+ if err != nil {+ return 0, errors.Errorf("expected int or int64 but got string(%s)", rows)+ }+ return v, nildefault:- return 0, errors.Errorf("expected int or in64 but got %t", rowOne[9])+ return 0, errors.Errorf("expected int or int64 but got %t", rowOne[9])}}diff --git a/plugin/advisor/mysql/advisor_statement_affected_row_limit_test.go b/plugin/advisor/mysql/advisor_statement_affected_row_limit_test.goindex 07bd64b05f..90b3bff835 100644--- a/plugin/advisor/mysql/advisor_statement_affected_row_limit_test.go+++ b/plugin/advisor/mysql/advisor_statement_affected_row_limit_test.go@@ -28,11 +28,10 @@ func TestStatementAffectedRowLimit(t *testing.T) {Statement: `UPDATE tech_book SET id = 1`,Want: []advisor.Advice{{- Status: advisor.Warn,- Code: advisor.StatementAffectedRowExceedsLimit,- Title: "statement.affected-row-limit",- Content: "\"UPDATE tech_book SET id = 1\" affected 1000 rows. The count exceeds 5.",- Line: 1,+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",},},},diff --git a/plugin/advisor/mysql/advisor_statement_dml_dry_run.go b/plugin/advisor/mysql/advisor_statement_dml_dry_run.goindex 52b27b283c..7fc132aecb 100644--- a/plugin/advisor/mysql/advisor_statement_dml_dry_run.go+++ b/plugin/advisor/mysql/advisor_statement_dml_dry_run.go@@ -4,13 +4,13 @@ package mysqlimport ("context"+ "database/sql""fmt""github.com/pingcap/tidb/parser/ast""github.com/bytebase/bytebase/plugin/advisor""github.com/bytebase/bytebase/plugin/advisor/db"- database "github.com/bytebase/bytebase/plugin/db")var (@@ -70,7 +70,7 @@ type statementDmlDryRunChecker struct {title stringtext stringline int- driver database.Driver+ driver *sql.DBctx context.Context}@@ -78,7 +78,7 @@ type statementDmlDryRunChecker struct {func (checker *statementDmlDryRunChecker) Enter(in ast.Node) (ast.Node, bool) {switch node := in.(type) {case *ast.InsertStmt, *ast.UpdateStmt, *ast.DeleteStmt:- if _, err := checker.driver.Query(checker.ctx, fmt.Sprintf("EXPLAIN %s", node.Text()), 1); err != nil {+ if _, err := query(checker.ctx, checker.driver, fmt.Sprintf("EXPLAIN %s", node.Text())); err != nil {checker.adviceList = append(checker.adviceList, advisor.Advice{Status: checker.level,Code: advisor.StatementDMLDryRunFailed,diff --git a/plugin/advisor/mysql/advisor_statement_dml_dry_run_test.go b/plugin/advisor/mysql/advisor_statement_dml_dry_run_test.goindex 79220fff9d..a6181d6792 100644--- a/plugin/advisor/mysql/advisor_statement_dml_dry_run_test.go+++ b/plugin/advisor/mysql/advisor_statement_dml_dry_run_test.go@@ -25,11 +25,10 @@ func TestStatementDmlDryRun(t *testing.T) {Statement: `DELETE FROM tech_book`,Want: []advisor.Advice{{- Status: advisor.Warn,- Code: advisor.StatementDMLDryRunFailed,- Title: "statement.dml-dry-run",- Content: "\"DELETE FROM tech_book\" dry runs failed: MockDriver disallows it",- Line: 1,+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",},},},diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex f5f14d9ba0..990abb5902 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -2,6 +2,7 @@ package advisorimport ("context"+ "database/sql""encoding/json""log""regexp"@@ -10,7 +11,6 @@ import ("github.com/bytebase/bytebase/plugin/advisor/catalog""github.com/bytebase/bytebase/plugin/advisor/db"- database "github.com/bytebase/bytebase/plugin/db")// How to add a SQL review rule:@@ -57,8 +57,6 @@ const (SchemaRuleStatementRequireWhere SQLReviewRuleType = "statement.where.require"// SchemaRuleStatementNoLeadingWildcardLike disallow leading '%' in LIKE, e.g. LIKE foo = '%x' is not allowed.SchemaRuleStatementNoLeadingWildcardLike SQLReviewRuleType = "statement.where.no-leading-wildcard-like"- // SchemaRuleStatementNoCreateTableAs disallow 'CREATE TABLE ... [AS] SELECT.- SchemaRuleStatementNoCreateTableAs SQLReviewRuleType = "statement.create-table.no-create-table-as"// SchemaRuleStatementDisallowCommit disallow using commit in the issue.SchemaRuleStatementDisallowCommit SQLReviewRuleType = "statement.disallow-commit"// SchemaRuleStatementDisallowLimit disallow the LIMIT clause in INSERT, DELETE and UPDATE statements.@@ -86,8 +84,6 @@ const (SchemaRuleTableDropNamingConvention SQLReviewRuleType = "table.drop-naming-convention"// SchemaRuleTableCommentConvention enforce the table comment convention.SchemaRuleTableCommentConvention SQLReviewRuleType = "table.comment"- // SchemaRuleTableNotExists check the table name conflict.- SchemaRuleTableNotExists SQLReviewRuleType = "table.not-exists"// SchemaRuleTableDisallowPartition disallow the table partition.SchemaRuleTableDisallowPartition SQLReviewRuleType = "table.disallow-partition"@@ -414,7 +410,7 @@ type SQLReviewCheckContext struct {Collation stringDbType db.TypeCatalog catalog.Catalog- Driver database.Driver+ Driver *sql.DBContext context.Context}@@ -775,7 +771,7 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errcase SchemaRuleColumnRequireDefault:switch engine {case db.MySQL, db.TiDB:- return MySQLColumnSetDefaultForNotNull, nil+ return MySQLRequireColumnDefault, nil}case SchemaRuleTableRequirePK:switch engine {@@ -830,11 +826,6 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errcase db.MySQL, db.TiDB:return MySQLIndexTotalNumberLimit, nil}- case SchemaRuleStatementNoCreateTableAs:- switch engine {- case db.MySQL, db.TiDB:- return MySQLTableDisallowCreateTableAs, nil- }case SchemaRuleStatementDisallowCommit:switch engine {case db.MySQL, db.TiDB:diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.goindex c6e9dbf588..a915bb04ab 100644--- a/plugin/advisor/utils_for_tests.go+++ b/plugin/advisor/utils_for_tests.go@@ -134,7 +134,7 @@ func RunSQLReviewRuleTests(Charset: "",Collation: "",Rule: rule,- Driver: &MockDriver{},+ Driver: nil,Context: context.Background(),}for _, tc := range tests {diff --git a/server/openapi.go b/server/openapi.goindex e2ba1d1007..0ea9bb446c 100644--- a/server/openapi.go+++ b/server/openapi.go@@ -2,6 +2,7 @@ package serverimport ("context"+ "database/sql""encoding/json""fmt""io"@@ -91,6 +92,7 @@ func (s *Server) sqlCheckController(c echo.Context) error {var databaseType stringvar catalog catalog.Catalogvar driver db.Driver+ var connection *sql.DBif request.DatabaseName != "" && request.Host != "" && request.Port != "" {database, err := s.findDatabase(ctx, request.Host, request.Port, request.DatabaseName)@@ -108,6 +110,10 @@ func (s *Server) sqlCheckController(c echo.Context) error {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get database driver").SetInternal(err)}defer driver.Close(ctx)+ connection, err = driver.GetDBConnection(ctx, database.Name)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get database connection").SetInternal(err)+ }} else {databaseType = request.DatabaseTypeif databaseType == "" {@@ -141,7 +147,7 @@ func (s *Server) sqlCheckController(c echo.Context) error {envList[0].ID,request.Statement,catalog,- driver,+ connection,)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to run sql check").SetInternal(err)diff --git a/server/sql.go b/server/sql.goindex e5bd3b255f..2033c1fa7d 100644--- a/server/sql.go+++ b/server/sql.go@@ -2,6 +2,7 @@ package serverimport ("context"+ "database/sql""encoding/json""fmt""net/http"@@ -215,6 +216,10 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get database driver").SetInternal(err)}defer driver.Close(ctx)+ connection, err := driver.GetDBConnection(ctx, exec.DatabaseName)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get database connection").SetInternal(err)+ }adviceLevel, adviceList, err = s.sqlCheck(ctx,@@ -224,7 +229,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {instance.EnvironmentID,exec.Statement,catalog,- driver,+ connection,)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to check SQL review policy").SetInternal(err)@@ -681,7 +686,7 @@ func (s *Server) sqlCheck(environmentID int,statement string,catalog catalog.Catalog,- driver db.Driver,+ driver *sql.DB,) (advisor.Status, []advisor.Advice, error) {var adviceList []advisor.Advicepolicy, err := s.store.GetNormalSQLReviewPolicy(ctx, &api.PolicyFind{EnvironmentID: &environmentID})diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/task_check_executor_statement_advisor_composite.goindex 81fcb9e04f..351f312641 100644--- a/server/task_check_executor_statement_advisor_composite.go+++ b/server/task_check_executor_statement_advisor_composite.go@@ -72,13 +72,17 @@ func (*TaskCheckStatementAdvisorCompositeExecutor) Run(ctx context.Context, servreturn nil, err}defer driver.Close(ctx)+ connection, err := driver.GetDBConnection(ctx, task.Database.Name)+ if err != nil {+ return nil, err+ }adviceList, err := advisor.SQLReviewCheck(payload.Statement, policy.RuleList, advisor.SQLReviewCheckContext{Charset: payload.Charset,Collation: payload.Collation,DbType: dbType,Catalog: catalog,- Driver: driver,+ Driver: connection,Context: ctx,})if err != nil {diff --git a/server/webhook.go b/server/webhook.goindex 4b5376f948..cd1e0e0a6b 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -360,13 +360,17 @@ func (s *Server) sqlAdviceForFile(if err != nil {return nil, err}+ connection, err := driver.GetDBConnection(ctx, database.Name)+ if err != nil {+ return nil, err+ }adviceList, err := advisor.SQLReviewCheck(fileContent, policy.RuleList, advisor.SQLReviewCheckContext{Charset: database.CharacterSet,Collation: database.Collation,DbType: dbType,Catalog: catalog,- Driver: driver,+ Driver: connection,Context: ctx,})driver.Close(ctx)diff --git a/tests/sql_review_test.go b/tests/sql_review_test.goindex fca516c085..ba8cdda7e8 100644--- a/tests/sql_review_test.go+++ b/tests/sql_review_test.go@@ -378,24 +378,29 @@ func TestSQLReviewForMySQL(t *testing.T) {databaseName = "testSQLReview"statements = []string{"CREATE TABLE user(" +- "id INT PRIMARY KEY," +- "name VARCHAR(255) NOT NULL," +- "room_id INT NOT NULL," +- "creator_id INT NOT NULL," +- "created_ts TIMESTAMP NOT NULL," +- "updater_id INT NOT NULL," +- "updated_ts TIMESTAMP NOT NULL," ++ "id INT PRIMARY KEY COMMENT 'comment'," ++ "name VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'comment'," ++ "room_id INT NOT NULL DEFAULT 0 COMMENT 'comment'," ++ "creator_id INT NOT NULL DEFAULT 0 COMMENT 'comment'," ++ "created_ts TIMESTAMP NOT NULL DEFAULT NOW() COMMENT 'comment'," ++ "updater_id INT NOT NULL DEFAULT 0 COMMENT 'comment'," ++ "updated_ts TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW() COMMENT 'comment'," +"INDEX idx_user_name(name)," +"UNIQUE KEY uk_user_id_name(id, name)" +- ") ENGINE = INNODB",+ ") ENGINE = INNODB COMMENT 'comment'","CREATE TABLE userTable(" +- "id INT," +- "name VARCHAR(255)," ++ "id INT NOT NULL," ++ "name VARCHAR(255) CHARSET ascii," +"roomId INT," ++ "time_created TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW() COMMENT 'comment'," ++ "time_updated TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW() COMMENT 'comment'," ++ "content BLOB NOT NULL COMMENT 'comment'," ++ "json_content JSON NOT NULL COMMENT 'comment'," +"INDEX idx1(name)," +"UNIQUE KEY uk1(id, name)," +- "FOREIGN KEY fk1(roomId) REFERENCES room(id)" +- ") ENGINE = CSV",+ "FOREIGN KEY fk1(roomId) REFERENCES room(id)," ++ "INDEX idx_userTable_content(content)" ++ ") ENGINE = CSV COLLATE latin1_bin",}tests = []test{{@@ -481,6 +486,13 @@ func TestSQLReviewForMySQL(t *testing.T) {Title: "table.no-foreign-key",Content: "Foreign key is not allowed in the table `userTable`",},+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.NoTableComment.Int(),+ Title: "table.comment",+ Content: "Table `userTable` requires comments",+ },{Status: api.TaskCheckStatusWarn,Namespace: api.AdvisorNamespace,@@ -493,34 +505,157 @@ func TestSQLReviewForMySQL(t *testing.T) {Namespace: api.AdvisorNamespace,Code: advisor.ColumnCannotNull.Int(),Title: "column.no-null",- Content: "`userTable`.`id` cannot have NULL value",+ Content: "`userTable`.`name` cannot have NULL value",},{Status: api.TaskCheckStatusWarn,Namespace: api.AdvisorNamespace,Code: advisor.ColumnCannotNull.Int(),Title: "column.no-null",- Content: "`userTable`.`name` cannot have NULL value",+ Content: "`userTable`.`roomId` cannot have NULL value",},{Status: api.TaskCheckStatusWarn,Namespace: api.AdvisorNamespace,- Code: advisor.ColumnCannotNull.Int(),- Title: "column.no-null",- Content: "`userTable`.`roomId` cannot have NULL value",+ Code: advisor.NotNullColumnWithNoDefault.Int(),+ Title: "column.set-default-for-not-null",+ Content: "Column `userTable`.`id` is NOT NULL but doesn't have DEFAULT",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.NoColumnComment.Int(),+ Title: "column.comment",+ Content: "Column `userTable`.`id` requires comments",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.NoColumnComment.Int(),+ Title: "column.comment",+ Content: "Column `userTable`.`name` requires comments",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.NoColumnComment.Int(),+ Title: "column.comment",+ Content: "Column `userTable`.`roomId` requires comments",+ },+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.AdvisorNamespace,+ Code: advisor.DisabledColumnType.Int(),+ Title: "column.type-disallow-list",+ Content: "Disallow column type JSON but column `userTable`.`json_content` is",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.SetColumnCharset.Int(),+ Title: "column.disallow-set-charset",+ Content: fmt.Sprintf("Disallow set column charset but \"%s\" does", statements[1]),+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.OnUpdateCurrentTimeColumnCountExceedsLimit.Int(),+ Title: "column.current-time-count-limit",+ Content: "Table `userTable` has 2 ON UPDATE CURRENT_TIMESTAMP() columns. The count greater than 1.",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.NoDefault.Int(),+ Title: "column.require-default",+ Content: "Column `userTable`.`id` doesn't have DEFAULT.",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.NoDefault.Int(),+ Title: "column.require-default",+ Content: "Column `userTable`.`name` doesn't have DEFAULT.",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.NoDefault.Int(),+ Title: "column.require-default",+ Content: "Column `userTable`.`roomId` doesn't have DEFAULT.",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.IndexTypeNoBlob.Int(),+ Title: "index.type-no-blob",+ Content: "Columns in index must not be BLOB but `userTable`.`content` is blob",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.DisabledCharset.Int(),+ Title: "system.charset.allowlist",+ Content: fmt.Sprintf("\"%s\" used disabled charset 'ascii'", statements[1]),+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.DisabledCollation.Int(),+ Title: "system.collation.allowlist",+ Content: fmt.Sprintf("\"%s\" used disabled collation 'latin1_bin'", statements[1]),+ },+ },+ },+ {+ statement: `CREATE TABLE t_auto(auto_id varchar(20) AUTO_INCREMENT PRIMARY KEY COMMENT 'COMMENT') auto_increment = 2 COMMENT 'comment'`,+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.NamingAutoIncrementColumnConventionMismatch.Int(),+ Title: "naming.column.auto-increment",+ Content: "`t_auto`.`auto_id` mismatches auto_increment column naming convention, naming format should be \"^id$\"",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.NoRequiredColumn.Int(),+ Title: "column.required",+ Content: "Table `t_auto` requires columns: created_ts, creator_id, id, updated_ts, updater_id",+ },+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.AdvisorNamespace,+ Code: advisor.AutoIncrementColumnNotInteger.Int(),+ Title: "column.auto-increment-must-integer",+ Content: "Auto-increment column `t_auto`.`auto_id` requires integer type",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.AutoIncrementColumnInitialValueNotMatch.Int(),+ Title: "column.auto-increment-initial-value",+ Content: "The initial auto-increment value in table `t_auto` is 2, which doesn't equal 20",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.AutoIncrementColumnSigned.Int(),+ Title: "column.auto-increment-must-unsigned",+ Content: "Auto-increment column `t_auto`.`auto_id` is not UNSIGNED type",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.IndexPKType.Int(),+ Title: "index.pk-type-limit",+ Content: "Columns in primary key must be INT/BIGINT but `t_auto`.`auto_id` is varchar(20)",},},},{statement: `- CREATE TABLE tech_book(- id int NOT NULL,- creator_id INT NOT NULL,- created_ts TIMESTAMP NOT NULL,- updater_id INT NOT NULL,- updated_ts TIMESTAMP NOT NULL,- CONSTRAINT pk_user_id PRIMARY KEY (id)- );DELETE FROM tech_book`,result: []api.TaskCheckResult{{@@ -530,21 +665,24 @@ func TestSQLReviewForMySQL(t *testing.T) {Title: "statement.where.require",Content: "\"DELETE FROM tech_book\" requires WHERE clause",},+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementAffectedRowExceedsLimit.Int(),+ Title: "statement.affected-row-limit",+ Content: "\"DELETE FROM tech_book\" dry runs failed: Error 1146: Table 'testSQLReview.tech_book' doesn't exist",+ },+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementDMLDryRunFailed.Int(),+ Title: "statement.dml-dry-run",+ Content: "\"DELETE FROM tech_book\" dry runs failed: Error 1146: Table 'testSQLReview.tech_book' doesn't exist",+ },},},{- statement: `- CREATE TABLE tech_book(- id int NOT NULL,- name varchar(220) NOT NULL,- creator_id INT NOT NULL,- created_ts TIMESTAMP NOT NULL,- updater_id INT NOT NULL,- updated_ts TIMESTAMP NOT NULL,- CONSTRAINT pk_user_id PRIMARY KEY (id)- );- ` +- "DELETE FROM tech_book WHERE name like `%abc`",+ statement: "DELETE FROM tech_book WHERE name like `%abc`",result: []api.TaskCheckResult{{Status: api.TaskCheckStatusError,@@ -553,26 +691,24 @@ func TestSQLReviewForMySQL(t *testing.T) {Title: "statement.where.no-leading-wildcard-like",Content: "\"DELETE FROM tech_book WHERE name like `%abc`\" uses leading wildcard LIKE",},+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementAffectedRowExceedsLimit.Int(),+ Title: "statement.affected-row-limit",+ Content: "\"DELETE FROM tech_book WHERE name like `%abc`\" dry runs failed: Error 1146: Table 'testSQLReview.tech_book' doesn't exist",+ },+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementDMLDryRunFailed.Int(),+ Title: "statement.dml-dry-run",+ Content: "\"DELETE FROM tech_book WHERE name like `%abc`\" dry runs failed: Error 1146: Table 'testSQLReview.tech_book' doesn't exist",+ },},},{statement: `- CREATE TABLE t(- id int NOT NULL,- creator_id INT NOT NULL,- created_ts TIMESTAMP NOT NULL,- updater_id INT NOT NULL,- updated_ts TIMESTAMP NOT NULL,- CONSTRAINT pk_user_id PRIMARY KEY (id)- );- CREATE TABLE t_copy(- id int NOT NULL,- creator_id INT NOT NULL,- created_ts TIMESTAMP NOT NULL,- updater_id INT NOT NULL,- updated_ts TIMESTAMP NOT NULL,- CONSTRAINT pk_user_id PRIMARY KEY (id)- );INSERT INTO t_copy SELECT * FROM t`,result: []api.TaskCheckResult{{@@ -589,19 +725,83 @@ func TestSQLReviewForMySQL(t *testing.T) {Title: "statement.where.require",Content: "\"INSERT INTO t_copy SELECT * FROM t\" requires WHERE clause",},++ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.InsertTooManyRows.Int(),+ Title: "statement.insert.row-limit",+ Content: "\"INSERT INTO t_copy SELECT * FROM t\" dry runs failed: Error 1146: Table 'testSQLReview.t_copy' doesn't exist",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.InsertNotSpecifyColumn.Int(),+ Title: "statement.insert.must-specify-column",+ Content: "The INSERT statement must specify columns but \"INSERT INTO t_copy SELECT * FROM t\" does not",+ },+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementDMLDryRunFailed.Int(),+ Title: "statement.dml-dry-run",+ Content: "\"INSERT INTO t_copy SELECT * FROM t\" dry runs failed: Error 1146: Table 'testSQLReview.t_copy' doesn't exist",+ },},},{statement: `- CREATE TABLE t(- id int NOT NULL,- creator_id INT NOT NULL,- created_ts TIMESTAMP NOT NULL,- updater_id INT NOT NULL,- updated_ts TIMESTAMP NOT NULL,- CONSTRAINT pk_user_id PRIMARY KEY (id)- );INSERT INTO t VALUES (1, 1, now(), 1, now())`,+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.InsertNotSpecifyColumn.Int(),+ Title: "statement.insert.must-specify-column",+ Content: "The INSERT statement must specify columns but \"INSERT INTO t VALUES (1, 1, now(), 1, now())\" does not",+ },+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementDMLDryRunFailed.Int(),+ Title: "statement.dml-dry-run",+ Content: "\"INSERT INTO t VALUES (1, 1, now(), 1, now())\" dry runs failed: Error 1146: Table 'testSQLReview.t' doesn't exist",+ },+ },+ },+ {+ statement: "DELETE FROM tech_book WHERE id = (SELECT max(id) FROM tech_book WHERE name = 'bytebase')",+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementAffectedRowExceedsLimit.Int(),+ Title: "statement.affected-row-limit",+ Content: "\"DELETE FROM tech_book WHERE id = (SELECT max(id) FROM tech_book WHERE name = 'bytebase')\" dry runs failed: Error 1146: Table 'testSQLReview.tech_book' doesn't exist",+ },+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementDMLDryRunFailed.Int(),+ Title: "statement.dml-dry-run",+ Content: "\"DELETE FROM tech_book WHERE id = (SELECT max(id) FROM tech_book WHERE name = 'bytebase')\" dry runs failed: Error 1146: Table 'testSQLReview.tech_book' doesn't exist",+ },+ },+ },+ {+ statement: `COMMIT;`,+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementDisallowCommit.Int(),+ Title: "statement.disallow-commit",+ Content: "Commit is not allowed, related statement: \"COMMIT;\"",+ },+ },+ },+ {+ statement: statements[0],result: []api.TaskCheckResult{{Status: api.TaskCheckStatusSuccess,@@ -611,20 +811,23 @@ func TestSQLReviewForMySQL(t *testing.T) {Content: "",},},+ run: true,},{- statement: `- CREATE TABLE tech_book(- id int NOT NULL,- name varchar(220) NOT NULL,- creator_id INT NOT NULL,- created_ts TIMESTAMP NOT NULL,- updater_id INT NOT NULL,- updated_ts TIMESTAMP NOT NULL,- CONSTRAINT pk_user_id PRIMARY KEY (id)- );- ` +- "DELETE FROM tech_book WHERE id = (SELECT max(id) FROM tech_book WHERE name = 'bytebase')",+ statement: `INSERT INTO user(id, name) values (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')`,+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusSuccess,+ Namespace: api.BBNamespace,+ Code: common.Ok.Int(),+ Title: "OK",+ Content: "",+ },+ },+ run: true,+ },+ {+ statement: `DELETE FROM user WHERE id < 10`,result: []api.TaskCheckResult{{Status: api.TaskCheckStatusSuccess,@@ -635,16 +838,114 @@ func TestSQLReviewForMySQL(t *testing.T) {},},},+ {+ statement: `INSERT INTO user(id, name) values (6, 'f'), (7, 'g'), (8, 'h'), (9, 'i'), (10, 'j')`,+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusSuccess,+ Namespace: api.BBNamespace,+ Code: common.Ok.Int(),+ Title: "OK",+ Content: "",+ },+ },+ run: true,+ },+ {+ statement: `DELETE FROM user WHERE id <= 10`,+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementAffectedRowExceedsLimit.Int(),+ Title: "statement.affected-row-limit",+ Content: "\"DELETE FROM user WHERE id <= 10\" affected 10 rows. The count exceeds 5.",+ },+ },+ },+ {+ statement: `INSERT INTO user(id, name) SELECT id, name FROM user WHERE 1=1`,+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.InsertTooManyRows.Int(),+ Title: "statement.insert.row-limit",+ Content: "\"INSERT INTO user(id, name) SELECT id, name FROM user WHERE 1=1\" inserts 10 rows. The count exceeds 5.",+ },+ },+ },+ {+ statement: "INSERT INTO user(id, name) SELECT id, name FROM user WHERE id=1 LIMIT 1",+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.InsertUseLimit.Int(),+ Title: "statement.disallow-limit",+ Content: "LIMIT clause is forbidden in INSERT, UPDATE and DELETE statement, but \"INSERT INTO user(id, name) SELECT id, name FROM user WHERE id=1 LIMIT 1\" uses",+ },+ },+ },+ {+ statement: `+ ALTER TABLE user PARTITION BY HASH(id) PARTITIONS 8;+ `,+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.CreateTablePartition.Int(),+ Title: "table.disallow-partition",+ Content: "Table partition is forbidden, but \"ALTER TABLE user PARTITION BY HASH(id) PARTITIONS 8;\" creates",+ },+ },+ },+ {+ statement: `+ ALTER TABLE user CHANGE name name varchar(320) NOT NULL DEFAULT '' COMMENT 'COMMENT' FIRST;+ ALTER TABLE user ADD COLUMN c_column int NOT NULL DEFAULT 0 COMMENT 'comment';+ `,+ result: []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementRedundantAlterTable.Int(),+ Title: "statement.merge-alter-table",+ Content: "There are 2 statements to modify table `user`",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.ChangeColumnType.Int(),+ Title: "column.disallow-change-type",+ Content: "\"ALTER TABLE user CHANGE name name varchar(320) NOT NULL DEFAULT '' COMMENT 'COMMENT' FIRST;\" changes column type",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.UseChangeColumnStatement.Int(),+ Title: "column.disallow-change",+ Content: "\"ALTER TABLE user CHANGE name name varchar(320) NOT NULL DEFAULT '' COMMENT 'COMMENT' FIRST;\" contains CHANGE COLUMN statement",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.ChangeColumnOrder.Int(),+ Title: "column.disallow-changing-order",+ Content: "\"ALTER TABLE user CHANGE name name varchar(320) NOT NULL DEFAULT '' COMMENT 'COMMENT' FIRST;\" changes column order",+ },+ {+ Status: api.TaskCheckStatusWarn,+ Namespace: api.AdvisorNamespace,+ Code: advisor.CompatibilityAlterColumn.Int(),+ Title: "schema.backward-compatibility",+ Content: "\"ALTER TABLE user CHANGE name name varchar(320) NOT NULL DEFAULT '' COMMENT 'COMMENT' FIRST;\" may cause incompatibility with the existing data and code",+ },+ },+ },{statement: `- CREATE TABLE user(- id int NOT NULL,- creator_id INT NOT NULL,- created_ts TIMESTAMP NOT NULL,- updater_id INT NOT NULL,- updated_ts TIMESTAMP NOT NULL,- CONSTRAINT pk_user_id PRIMARY KEY (id)- );DROP TABLE user;`,result: []api.TaskCheckResult{@@ -766,7 +1067,7 @@ func TestSQLReviewForMySQL(t *testing.T) {for _, t := range tests {result := createIssueAndReturnSQLReviewResult(a, ctl, database.ID, project.ID, project.Creator.ID, t.statement, t.run)- a.Equal(t.result, result)+ a.Equal(t.result, result, t.statement)}// disable the SQL review policydiff --git a/tests/tests.go b/tests/tests.goindex 40ab1d57e1..e452bccde7 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -1649,14 +1649,35 @@ func setDefaultSQLReviewRulePayload(ruleTp advisor.SQLReviewRuleType) (string, evar payload []bytevar err errorswitch ruleTp {- case advisor.SchemaRuleMySQLEngine:- case advisor.SchemaRuleStatementNoSelectAll:- case advisor.SchemaRuleStatementRequireWhere:- case advisor.SchemaRuleStatementNoLeadingWildcardLike:- case advisor.SchemaRuleTableRequirePK:- case advisor.SchemaRuleTableNoFK:- case advisor.SchemaRuleColumnNotNull:- case advisor.SchemaRuleSchemaBackwardCompatibility:+ case advisor.SchemaRuleMySQLEngine,+ advisor.SchemaRuleStatementNoSelectAll,+ advisor.SchemaRuleStatementRequireWhere,+ advisor.SchemaRuleStatementNoLeadingWildcardLike,+ advisor.SchemaRuleStatementDisallowCommit,+ advisor.SchemaRuleStatementDisallowLimit,+ advisor.SchemaRuleStatementDisallowOrderBy,+ advisor.SchemaRuleStatementMergeAlterTable,+ advisor.SchemaRuleStatementInsertMustSpecifyColumn,+ advisor.SchemaRuleStatementInsertDisallowOrderByRand,+ advisor.SchemaRuleStatementDMLDryRun,+ advisor.SchemaRuleTableRequirePK,+ advisor.SchemaRuleTableNoFK,+ advisor.SchemaRuleTableDisallowPartition,+ advisor.SchemaRuleColumnNotNull,+ advisor.SchemaRuleColumnDisallowChangeType,+ advisor.SchemaRuleColumnSetDefaultForNotNull,+ advisor.SchemaRuleColumnDisallowChange,+ advisor.SchemaRuleColumnDisallowChangingOrder,+ advisor.SchemaRuleColumnAutoIncrementMustInteger,+ advisor.SchemaRuleColumnDisallowSetCharset,+ advisor.SchemaRuleColumnAutoIncrementMustUnsigned,+ advisor.SchemaRuleCurrentTimeColumnCountLimit,+ advisor.SchemaRuleColumnRequireDefault,+ advisor.SchemaRuleSchemaBackwardCompatibility,+ advisor.SchemaRuleDropEmptyDatabase,+ advisor.SchemaRuleIndexNoDuplicateColumn,+ advisor.SchemaRuleIndexPKTypeLimit,+ advisor.SchemaRuleIndexTypeNoBlob:case advisor.SchemaRuleTableDropNamingConvention:payload, err = json.Marshal(advisor.NamingRulePayload{Format: "_delete$",@@ -1665,23 +1686,42 @@ func setDefaultSQLReviewRulePayload(ruleTp advisor.SQLReviewRuleType) (string, efallthroughcase advisor.SchemaRuleColumnNaming:payload, err = json.Marshal(advisor.NamingRulePayload{- Format: "^[a-z]+(_[a-z]+)*$",+ Format: "^[a-z]+(_[a-z]+)*$",+ MaxLength: 64,})case advisor.SchemaRuleIDXNaming:payload, err = json.Marshal(advisor.NamingRulePayload{- Format: "^idx_{{table}}_{{column_list}}$",+ Format: "^idx_{{table}}_{{column_list}}$",+ MaxLength: 64,})case advisor.SchemaRulePKNaming:payload, err = json.Marshal(advisor.NamingRulePayload{- Format: "^pk_{{table}}_{{column_list}}$",+ Format: "^pk_{{table}}_{{column_list}}$",+ MaxLength: 64,})case advisor.SchemaRuleUKNaming:payload, err = json.Marshal(advisor.NamingRulePayload{- Format: "^uk_{{table}}_{{column_list}}$",+ Format: "^uk_{{table}}_{{column_list}}$",+ MaxLength: 64,})case advisor.SchemaRuleFKNaming:payload, err = json.Marshal(advisor.NamingRulePayload{- Format: "^fk_{{referencing_table}}_{{referencing_column}}_{{referenced_table}}_{{referenced_column}}$",+ Format: "^fk_{{referencing_table}}_{{referencing_column}}_{{referenced_table}}_{{referenced_column}}$",+ MaxLength: 64,+ })+ case advisor.SchemaRuleAutoIncrementColumnNaming:+ payload, err = json.Marshal(advisor.NamingRulePayload{+ Format: "^id$",+ MaxLength: 64,+ })+ case advisor.SchemaRuleStatementInsertRowLimit, advisor.SchemaRuleStatementAffectedRowLimit:+ payload, err = json.Marshal(advisor.NumberTypeRulePayload{+ Number: 5,+ })+ case advisor.SchemaRuleTableCommentConvention, advisor.SchemaRuleColumnCommentConvention:+ payload, err = json.Marshal(advisor.CommentConventionRulePayload{+ Required: true,+ MaxLength: 10,})case advisor.SchemaRuleRequiredColumn:payload, err = json.Marshal(advisor.StringArrayTypeRulePayload{@@ -1693,6 +1733,30 @@ func setDefaultSQLReviewRulePayload(ruleTp advisor.SQLReviewRuleType) (string, e"updater_id",},})+ case advisor.SchemaRuleColumnTypeDisallowList:+ payload, err = json.Marshal(advisor.StringArrayTypeRulePayload{+ List: []string{"JSON"},+ })+ case advisor.SchemaRuleColumnMaximumCharacterLength:+ payload, err = json.Marshal(advisor.NumberTypeRulePayload{+ Number: 20,+ })+ case advisor.SchemaRuleColumnAutoIncrementInitialValue:+ payload, err = json.Marshal(advisor.NumberTypeRulePayload{+ Number: 20,+ })+ case advisor.SchemaRuleIndexKeyNumberLimit, advisor.SchemaRuleIndexTotalNumberLimit:+ payload, err = json.Marshal(advisor.NumberTypeRulePayload{+ Number: 5,+ })+ case advisor.SchemaRuleCharsetAllowlist:+ payload, err = json.Marshal(advisor.StringArrayTypeRulePayload{+ List: []string{"utf8mb4"},+ })+ case advisor.SchemaRuleCollationAllowlist:+ payload, err = json.Marshal(advisor.StringArrayTypeRulePayload{+ List: []string{"utf8mb4_0900_ai_ci"},+ })default:return "", errors.Errorf("unknown SQL review type for default payload: %s", ruleTp)}@@ -1708,10 +1772,12 @@ func prodTemplateSQLReviewPolicy() (string, error) {policy := advisor.SQLReviewPolicy{Name: "Prod",RuleList: []*advisor.SQLReviewRule{+ // Engine{Type: advisor.SchemaRuleMySQLEngine,Level: advisor.SchemaRuleLevelError,},+ // Naming{Type: advisor.SchemaRuleTableNaming,Level: advisor.SchemaRuleLevelWarning,@@ -1736,6 +1802,11 @@ func prodTemplateSQLReviewPolicy() (string, error) {Type: advisor.SchemaRuleFKNaming,Level: advisor.SchemaRuleLevelWarning,},+ {+ Type: advisor.SchemaRuleAutoIncrementColumnNaming,+ Level: advisor.SchemaRuleLevelWarning,+ },+ // Statement{Type: advisor.SchemaRuleStatementNoSelectAll,Level: advisor.SchemaRuleLevelError,@@ -1748,6 +1819,43 @@ func prodTemplateSQLReviewPolicy() (string, error) {Type: advisor.SchemaRuleStatementNoLeadingWildcardLike,Level: advisor.SchemaRuleLevelError,},+ {+ Type: advisor.SchemaRuleStatementDisallowCommit,+ Level: advisor.SchemaRuleLevelError,+ },+ {+ Type: advisor.SchemaRuleStatementDisallowLimit,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleStatementDisallowOrderBy,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleStatementMergeAlterTable,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleStatementInsertRowLimit,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleStatementInsertMustSpecifyColumn,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleStatementInsertDisallowOrderByRand,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleStatementAffectedRowLimit,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleStatementDMLDryRun,+ Level: advisor.SchemaRuleLevelError,+ },+ // TABLE{Type: advisor.SchemaRuleTableRequirePK,Level: advisor.SchemaRuleLevelError,@@ -1760,6 +1868,15 @@ func prodTemplateSQLReviewPolicy() (string, error) {Type: advisor.SchemaRuleTableDropNamingConvention,Level: advisor.SchemaRuleLevelError,},+ {+ Type: advisor.SchemaRuleTableCommentConvention,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleTableDisallowPartition,+ Level: advisor.SchemaRuleLevelWarning,+ },+ // COLUMN{Type: advisor.SchemaRuleRequiredColumn,Level: advisor.SchemaRuleLevelWarning,@@ -1768,10 +1885,98 @@ func prodTemplateSQLReviewPolicy() (string, error) {Type: advisor.SchemaRuleColumnNotNull,Level: advisor.SchemaRuleLevelWarning,},+ {+ Type: advisor.SchemaRuleColumnDisallowChangeType,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleColumnSetDefaultForNotNull,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleColumnDisallowChange,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleColumnDisallowChangingOrder,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleColumnCommentConvention,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleColumnAutoIncrementMustInteger,+ Level: advisor.SchemaRuleLevelError,+ },+ {+ Type: advisor.SchemaRuleColumnTypeDisallowList,+ Level: advisor.SchemaRuleLevelError,+ },+ {+ Type: advisor.SchemaRuleColumnDisallowSetCharset,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleColumnMaximumCharacterLength,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleColumnAutoIncrementInitialValue,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleColumnAutoIncrementMustUnsigned,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleCurrentTimeColumnCountLimit,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleColumnRequireDefault,+ Level: advisor.SchemaRuleLevelWarning,+ },+ // SCHEMA{Type: advisor.SchemaRuleSchemaBackwardCompatibility,Level: advisor.SchemaRuleLevelWarning,},+ // DATABASE+ {+ Type: advisor.SchemaRuleDropEmptyDatabase,+ Level: advisor.SchemaRuleLevelError,+ },+ // INDEX+ {+ Type: advisor.SchemaRuleIndexNoDuplicateColumn,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleIndexKeyNumberLimit,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleIndexPKTypeLimit,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleIndexTypeNoBlob,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleIndexTotalNumberLimit,+ Level: advisor.SchemaRuleLevelWarning,+ },+ // SYSTEM+ {+ Type: advisor.SchemaRuleCharsetAllowlist,+ Level: advisor.SchemaRuleLevelWarning,+ },+ {+ Type: advisor.SchemaRuleCollationAllowlist,+ Level: advisor.SchemaRuleLevelWarning,+ },},}