Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: add backend skeleton of sql review rules (#11073)
boojackbb62e8da074a
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.goindex 5507cc052e..2ecf350726 100644--- a/backend/plugin/advisor/advisor.go+++ b/backend/plugin/advisor/advisor.go@@ -179,6 +179,12 @@ const (// MySQLTableNoDuplicateIndex is an advisor type for MySQL no duplicate index.MySQLTableNoDuplicateIndex Type = "bb.plugin.advisor.mysql.table.no-duplicate-index"+ // MySQLTableTextFieldsTotalLength is an advisor type for MySQL table text fields total length.+ MySQLTableTextFieldsTotalLength Type = "bb.plugin.advisor.mysql.table.text-fields-total-length"++ // MySQLTableFieldsMaximumCount is an advisor type for MySQL table fields maximum count.+ MySQLTableDisallowSetCharset Type = "bb.plugin.advisor.mysql.table.disallow-set-charset"+// MySQLDatabaseAllowDropIfEmpty is an advisor type for MySQL only allow drop empty database.MySQLDatabaseAllowDropIfEmpty Type = "bb.plugin.advisor.mysql.database.drop-empty-database"@@ -248,6 +254,33 @@ const (// MySQLStatementWhereNoEqualNull is an advisor type for checking MySQL no equal null in WHERE clause.MySQLStatementWhereNoEqualNull Type = "bb.plugin.advisor.mysql.statement.where.no-equal-null"+ // MySQLStatementWhereDisallowUsingFunction is an advisor type for checking MySQL disallow using function in WHERE clause.+ MySQLStatementWhereDisallowUsingFunction Type = "bb.plugin.advisor.mysql.statement.query.disallow-using-function"++ // MySQLStatementQueryMinumumPlanLevel is an advisor type for checking MySQL query minimum plan level.+ MySQLStatementQueryMinumumPlanLevel Type = "bb.plugin.advisor.mysql.statement.query.minimum-plan-level"++ // MySQLStatementWhereMaximumLogicalOperatorCount is an advisor type for checking MySQL statement maximum logical operator count in WHERE clause.+ MySQLStatementWhereMaximumLogicalOperatorCount Type = "bb.plugin.advisor.mysql.statement.where.maximum-logical-operator-count"++ // MySQLStatementMaximumLimitValue is an advisor type for MySQL statement maximum limit value.+ MySQLStatementMaximumLimitValue Type = "bb.plugin.advisor.mysql.statement.maximum-limit-value"++ // MySQLStatementMaximumJoinTableCount is an advisor type for MySQL statement maximum join table count.+ MySQLStatementMaximumJoinTableCount Type = "bb.plugin.advisor.mysql.statement.maximum-join-table-count"++ // MySQLStatementMaximumStatementsInTransaction is an advisor type for MySQL maximum statements in transaction.+ MySQLStatementMaximumStatementsInTransaction Type = "bb.plugin.advisor.mysql.statement.maximum-statements-in-transaction"++ // MySQLStatementJoinStrictColumnAttrs is an advisor type for MySQL statement strict column attrs(type, charset) in join.+ MySQLStatementJoinStrictColumnAttrs Type = "bb.plugin.advisor.mysql.statement.join-strict-column-attrs"++ // MySQLStatementDisallowMixDML is an advisor type for MySQL disallow mix DML on same table.+ MySQLStatementDisallowMixDML Type = "bb.plugin.advisor.mysql.statement.disallow-mix-dml"++ // MySQLStatementDisallowMixDDLDML is an advisor type for MySQL disallow mix DDL and DML.+ MySQLStatementDisallowMixDDLDML Type = "bb.plugin.advisor.mysql.statement.disallow-mix-ddl-dml"+// MySQLProcedureDisallowCreate is an advisor type for MySQL disallow create procedure.MySQLProcedureDisallowCreate Type = "bb.plugin.advisor.mysql.procedure.disallow-create"diff --git a/backend/plugin/advisor/config/sql-review.dev.yaml b/backend/plugin/advisor/config/sql-review.dev.yamlindex 53b609d3a3..bb76242d68 100644--- a/backend/plugin/advisor/config/sql-review.dev.yaml+++ b/backend/plugin/advisor/config/sql-review.dev.yaml@@ -21,6 +21,12 @@ ruleList:maxLength: 64- type: table.no-duplicate-indexlevel: WARNING+ - type: table.text-fields-total-length+ level: WARNING+ payload:+ number: 1000+ - type: table.disallow-set-charset+ level: WARNING- type: statement.select.no-select-alllevel: WARNING- type: statement.where.require@@ -69,6 +75,35 @@ ruleList:level: WARNING- type: statement.where.no-equal-nulllevel: WARNING+ - type: statement.where.disallow-using-function+ level: WARNING+ - type: statement.where.statement.query.minimum-plan-level+ level: WARNING+ payload:+ required: true+ maxLength: 64+ - type: statement.where.maximum-logical-operator-count+ level: WARNING+ payload:+ number: 10+ - type: statement.maximum-limit-value+ level: WARNING+ payload:+ number: 1000+ - type: statement.maximum-join-table-count+ level: WARNING+ payload:+ number: 10+ - type: statement.maximum-statements-in-transaction+ level: WARNING+ payload:+ number: 10+ - type: statement.join-strict-column-attrs+ level: WARNING+ - type: statement.disallow-mix-dml+ level: WARNING+ - type: statement.disallow-mix-ddl-dml+ level: WARNING- type: naming.tablelevel: WARNINGpayload:diff --git a/backend/plugin/advisor/config/sql-review.prod.yaml b/backend/plugin/advisor/config/sql-review.prod.yamlindex fee3b686a0..afcf4c82f3 100644--- a/backend/plugin/advisor/config/sql-review.prod.yaml+++ b/backend/plugin/advisor/config/sql-review.prod.yaml@@ -21,6 +21,12 @@ ruleList:maxLength: 64- type: table.no-duplicate-indexlevel: WARNING+ - type: table.text-fields-total-length+ level: WARNING+ payload:+ number: 1000+ - type: table.disallow-set-charset+ level: WARNING- type: statement.select.no-select-alllevel: ERROR- type: statement.where.require@@ -69,6 +75,35 @@ ruleList:level: WARNING- type: statement.where.no-equal-nulllevel: WARNING+ - type: statement.where.disallow-using-function+ level: WARNING+ - type: statement.where.statement.query.minimum-plan-level+ level: WARNING+ payload:+ required: true+ maxLength: 64+ - type: statement.where.maximum-logical-operator-count+ level: WARNING+ payload:+ number: 10+ - type: statement.maximum-limit-value+ level: WARNING+ payload:+ number: 1000+ - type: statement.maximum-join-table-count+ level: WARNING+ payload:+ number: 10+ - type: statement.maximum-statements-in-transaction+ level: WARNING+ payload:+ number: 10+ - type: statement.join-strict-column-attrs+ level: WARNING+ - type: statement.disallow-mix-dml+ level: WARNING+ - type: statement.disallow-mix-ddl-dml+ level: WARNING- type: naming.tablelevel: WARNINGpayload:diff --git a/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_ddl_dml.go b/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_ddl_dml.gonew file mode 100644index 0000000000..5ed5b0a80a--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_ddl_dml.go@@ -0,0 +1,69 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementDisallowmixDDLDMLAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementDisallowMixDDLDML, &StatementDisallowmixDDLDMLAdvisor{})+}++type StatementDisallowmixDDLDMLAdvisor struct {+}++func (*StatementDisallowmixDDLDMLAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ checker := &statementDisallowMixDDLDMLChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type statementDisallowMixDDLDMLChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+}++func (checker *statementDisallowMixDDLDMLChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_dml.go b/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_dml.gonew file mode 100644index 0000000000..370539d337--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_dml.go@@ -0,0 +1,69 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementDisallowMixDMLAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementDisallowMixDML, &StatementDisallowMixDMLAdvisor{})+}++type StatementDisallowMixDMLAdvisor struct {+}++func (*StatementDisallowMixDMLAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ checker := &statementDisallowMixDMLChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type statementDisallowMixDMLChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+}++func (checker *statementDisallowMixDMLChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/mysql/advisor_statement_join_strict_column_attrs.go b/backend/plugin/advisor/mysql/advisor_statement_join_strict_column_attrs.gonew file mode 100644index 0000000000..4691d5cf80--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_statement_join_strict_column_attrs.go@@ -0,0 +1,75 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementJoinStrictColumnAttrsAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementJoinStrictColumnAttrs, &StatementJoinStrictColumnAttrsAdvisor{})+}++type StatementJoinStrictColumnAttrsAdvisor struct {+}++func (*StatementJoinStrictColumnAttrsAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ payload, err := advisor.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &statementJoinStrictColumnAttrsChecker{+ level: level,+ title: string(ctx.Rule.Type),+ limitMaxValue: payload.Number,+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type statementJoinStrictColumnAttrsChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+ limitMaxValue int+}++func (checker *statementJoinStrictColumnAttrsChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/mysql/advisor_statement_maximum_join_table_count.go b/backend/plugin/advisor/mysql/advisor_statement_maximum_join_table_count.gonew file mode 100644index 0000000000..7fb78c2a93--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_statement_maximum_join_table_count.go@@ -0,0 +1,75 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementMaximumJoinTableCountAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementMaximumJoinTableCount, &StatementMaximumJoinTableCountAdvisor{})+}++type StatementMaximumJoinTableCountAdvisor struct {+}++func (*StatementMaximumJoinTableCountAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ payload, err := advisor.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &statementMaximumJoinTableCountChecker{+ level: level,+ title: string(ctx.Rule.Type),+ limitMaxValue: payload.Number,+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type statementMaximumJoinTableCountChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+ limitMaxValue int+}++func (checker *statementMaximumJoinTableCountChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/mysql/advisor_statement_maximum_limit_value.go b/backend/plugin/advisor/mysql/advisor_statement_maximum_limit_value.gonew file mode 100644index 0000000000..7f2684841c--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_statement_maximum_limit_value.go@@ -0,0 +1,75 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementMaximumLimitValueAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementMaximumLimitValue, &StatementMaximumLimitValueAdvisor{})+}++type StatementMaximumLimitValueAdvisor struct {+}++func (*StatementMaximumLimitValueAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ payload, err := advisor.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &statementMaximumLimitValueChecker{+ level: level,+ title: string(ctx.Rule.Type),+ limitMaxValue: payload.Number,+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type statementMaximumLimitValueChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+ limitMaxValue int+}++func (checker *statementMaximumLimitValueChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/mysql/advisor_statement_maximum_statements_in_transaction.go b/backend/plugin/advisor/mysql/advisor_statement_maximum_statements_in_transaction.gonew file mode 100644index 0000000000..8a00cb7d36--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_statement_maximum_statements_in_transaction.go@@ -0,0 +1,75 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementMaximumStatementsInTransactionAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementMaximumStatementsInTransaction, &StatementMaximumStatementsInTransactionAdvisor{})+}++type StatementMaximumStatementsInTransactionAdvisor struct {+}++func (*StatementMaximumStatementsInTransactionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ payload, err := advisor.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &statementMaximumStatementsInTransactionChecker{+ level: level,+ title: string(ctx.Rule.Type),+ limitMaxValue: payload.Number,+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type statementMaximumStatementsInTransactionChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+ limitMaxValue int+}++func (checker *statementMaximumStatementsInTransactionChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/mysql/advisor_statement_query_minumum_plan_level.go b/backend/plugin/advisor/mysql/advisor_statement_query_minumum_plan_level.gonew file mode 100644index 0000000000..c48e52143c--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_statement_query_minumum_plan_level.go@@ -0,0 +1,69 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementQueryMinumumPlanLevelAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementQueryMinumumPlanLevel, &StatementQueryMinumumPlanLevelAdvisor{})+}++type StatementQueryMinumumPlanLevelAdvisor struct {+}++func (*StatementQueryMinumumPlanLevelAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ checker := &statementQueryMinumumPlanLevelChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type statementQueryMinumumPlanLevelChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+}++func (checker *statementQueryMinumumPlanLevelChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/mysql/advisor_statement_where_disallow_using_function.go b/backend/plugin/advisor/mysql/advisor_statement_where_disallow_using_function.gonew file mode 100644index 0000000000..f2b2ff92b5--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_statement_where_disallow_using_function.go@@ -0,0 +1,69 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementWhereDisallowUsingFunctionAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementWhereDisallowUsingFunction, &StatementWhereDisallowUsingFunctionAdvisor{})+}++type StatementWhereDisallowUsingFunctionAdvisor struct {+}++func (*StatementWhereDisallowUsingFunctionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ checker := &statementWhereDisallowUsingFunctionChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type statementWhereDisallowUsingFunctionChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+}++func (checker *statementWhereDisallowUsingFunctionChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/mysql/advisor_statement_where_maximum_logical_operator_count.go b/backend/plugin/advisor/mysql/advisor_statement_where_maximum_logical_operator_count.gonew file mode 100644index 0000000000..30443745dd--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_statement_where_maximum_logical_operator_count.go@@ -0,0 +1,69 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementWhereMaximumLogicalOperatorCountAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementWhereMaximumLogicalOperatorCount, &StatementWhereMaximumLogicalOperatorCountAdvisor{})+}++type StatementWhereMaximumLogicalOperatorCountAdvisor struct {+}++func (*StatementWhereMaximumLogicalOperatorCountAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ checker := &statementWhereMaximumLogicalOperatorCountChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type statementWhereMaximumLogicalOperatorCountChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+}++func (checker *statementWhereMaximumLogicalOperatorCountChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/mysql/advisor_table_disallow_set_charset.go b/backend/plugin/advisor/mysql/advisor_table_disallow_set_charset.gonew file mode 100644index 0000000000..763a7c3798--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_table_disallow_set_charset.go@@ -0,0 +1,69 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*TableDisallowSetCharsetAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLTableDisallowSetCharset, &TableDisallowSetCharsetAdvisor{})+}++type TableDisallowSetCharsetAdvisor struct {+}++func (*TableDisallowSetCharsetAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ checker := &tableDisallowSetCharsetChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type tableDisallowSetCharsetChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+}++func (checker *tableDisallowSetCharsetChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/mysql/advisor_table_text_fields_total_length.go b/backend/plugin/advisor/mysql/advisor_table_text_fields_total_length.gonew file mode 100644index 0000000000..3718293689--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_table_text_fields_total_length.go@@ -0,0 +1,69 @@+package mysql++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*TableMaximumVarcharLengthAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLTableTextFieldsTotalLength, &TableMaximumVarcharLengthAdvisor{})+}++type TableMaximumVarcharLengthAdvisor struct {+}++func (*TableMaximumVarcharLengthAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ checker := &tableFieldsMaximumVarcharLengthChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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+}++// TODO(sql-review): implement me please.+type tableFieldsMaximumVarcharLengthChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+}++func (checker *tableFieldsMaximumVarcharLengthChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex bdce346516..849f9fa48a 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -107,6 +107,24 @@ const (SchemaRuleStatementDisallowUsingTemporary = "statement.disallow-using-temporary"// SchemaRuleStatementWhereNoEqualNull check the WHERE clause no equal null.SchemaRuleStatementWhereNoEqualNull = "statement.where.no-equal-null"+ // SchemaRuleStatementWhereDisallowUsingFunction disallow using function in WHERE clause.+ SchemaRuleStatementWhereDisallowUsingFunction = "statement.where.disallow-using-function"+ // SchemaRuleStatementQueryMinumumPlanLevel enforce the minimum plan level.+ SchemaRuleStatementQueryMinumumPlanLevel = "statement.query.minimum-plan-level"+ // SchemaRuleStatementWhereMaximumLogicalOperatorCount enforce the maximum logical operator count in WHERE clause.+ SchemaRuleStatementWhereMaximumLogicalOperatorCount = "statement.where.maximum-logical-operator-count"+ // SchemaRuleStatementMaximumLimitValue enforce the maximum limit value.+ SchemaRuleStatementMaximumLimitValue = "statement.maximum-limit-value"+ // SchemaRuleStatementMaximumJoinTableCount enforce the maximum join table count in the statement.+ SchemaRuleStatementMaximumJoinTableCount = "statement.maximum-join-table-count"+ // SchemaRuleStatementMaximumStatementsInTransaction enforce the maximum statements in transaction.+ SchemaRuleStatementMaximumStatementsInTransaction = "statement.maximum-statements-in-transaction"+ // SchemaRuleStatementJoinStrictColumnAttrs enforce the join strict column attributes.+ SchemaRuleStatementJoinStrictColumnAttrs = "statement.join-strict-column-attrs"+ // SchemaRuleStatementDisallowMixDML disallow mix DML on the same table.+ SchemaRuleStatementDisallowMixDML = "statement.disallow-mix-dml"+ // SchemaRuleStatementDisallowMixDDLDML disallow mix DDL and DML.+ SchemaRuleStatementDisallowMixDDLDML = "statement.disallow-mix-ddl-dml"// SchemaRuleTableRequirePK require the table to have a primary key.SchemaRuleTableRequirePK SQLReviewRuleType = "table.require-pk"@@ -122,6 +140,10 @@ const (SchemaRuleTableDisallowTrigger SQLReviewRuleType = "table.disallow-trigger"// SchemaRuleTableNoDuplicateIndex require the table no duplicate index.SchemaRuleTableNoDuplicateIndex SQLReviewRuleType = "table.no-duplicate-index"+ // SchemaRuleTableTextFieldsTotalLength enforce the total length of text fields.+ SchemaRuleTableTextFieldsTotalLength SQLReviewRuleType = "table.text-fields-total-length"+ // SchemaRuleTableDisallowSetCharset disallow set table charset.+ SchemaRuleTableDisallowSetCharset SQLReviewRuleType = "table.disallow-set-charset"// SchemaRuleRequiredColumn enforce the required columns in each table.SchemaRuleRequiredColumn SQLReviewRuleType = "column.required"@@ -1331,6 +1353,14 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Tyif engine == storepb.Engine_MYSQL {return MySQLTableNoDuplicateIndex, nil}+ case SchemaRuleTableTextFieldsTotalLength:+ if engine == storepb.Engine_MYSQL {+ return MySQLTableTextFieldsTotalLength, nil+ }+ case SchemaRuleTableDisallowSetCharset:+ if engine == storepb.Engine_MYSQL {+ return MySQLTableDisallowSetCharset, nil+ }case SchemaRuleMySQLEngine:switch engine {case storepb.Engine_MYSQL, storepb.Engine_MARIADB:@@ -1383,6 +1413,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Tyif engine == storepb.Engine_MYSQL {return MySQLStatementDisallowUsingTemporary, nil}+ case SchemaRuleStatementDisallowMixDML:+ if engine == storepb.Engine_MYSQL {+ return MySQLStatementDisallowMixDML, nil+ }case SchemaRuleCharsetAllowlist:switch engine {case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:@@ -1505,6 +1539,34 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Tyif engine == storepb.Engine_MYSQL {return MySQLStatementWhereNoEqualNull, nil}+ case SchemaRuleStatementWhereDisallowUsingFunction:+ if engine == storepb.Engine_MYSQL {+ return MySQLStatementWhereDisallowUsingFunction, nil+ }+ case SchemaRuleStatementQueryMinumumPlanLevel:+ if engine == storepb.Engine_MYSQL {+ return MySQLStatementQueryMinumumPlanLevel, nil+ }+ case SchemaRuleStatementWhereMaximumLogicalOperatorCount:+ if engine == storepb.Engine_MYSQL {+ return MySQLStatementWhereMaximumLogicalOperatorCount, nil+ }+ case SchemaRuleStatementMaximumLimitValue:+ if engine == storepb.Engine_MYSQL {+ return MySQLStatementMaximumLimitValue, nil+ }+ case SchemaRuleStatementMaximumJoinTableCount:+ if engine == storepb.Engine_MYSQL {+ return MySQLStatementMaximumJoinTableCount, nil+ }+ case SchemaRuleStatementMaximumStatementsInTransaction:+ if engine == storepb.Engine_MYSQL {+ return MySQLStatementMaximumStatementsInTransaction, nil+ }+ case SchemaRuleStatementJoinStrictColumnAttrs:+ if engine == storepb.Engine_MYSQL {+ return MySQLStatementJoinStrictColumnAttrs, nil+ }case SchemaRuleCommentLength:if engine == storepb.Engine_POSTGRES {return PostgreSQLCommentConvention, nildiff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.jsonindex 825841ef38..a2e01878a9 100644--- a/frontend/src/locales/sql-review/en-US.json+++ b/frontend/src/locales/sql-review/en-US.json@@ -65,6 +65,14 @@"title": "Disallow duplicate indexes","description": "This rule prohibits the creation of duplicate indexes on a table. Duplicate indexes consume extra storage space and can potentially reduce query performance. Suggestion error level: Warning"},+ "table-text-fields-total-length": {+ "title": "Restrict the total length of text fields in a table",+ "description": "This rule limits the amount of data a table can hold, preventing excessive storage usage."+ },+ "table-disallow-set-charset": {+ "title": "Prohibit defining character set in table properties",+ "description": "It is recommended to set the charset at the database level. Setting the charset at finer granularity can bring unnecessary complexities. Suggested error level: Error."+ },"table-comment": {"title": "Comment convention","description": "Configure whether the table requires comments and the maximum comment length.",@@ -395,6 +403,42 @@"title": "Prohibit using NULL equality comparison in WHERE clause","description": "The result of NULL equality comparison is always NULL, which may cause unexpected results. Suggestion error level: Warning"},+ "statement-where-disallow-using-function": {+ "title": "Do not apply functions or perform calculations on indexed fields in the WHERE clause",+ "description": "If you apply a function or perform a calculation on the indexed field, the database cannot use the index and has to scan the entire table instead."+ },+ "statement-where-statement-query-minimum-plan-level": {+ "title": "Restrict the maximum level of query access method",+ "description": "SQL performance optimization strives for constant (const) access, aiming for reference (ref) level as a baseline, with acceptable performance at range level."+ },+ "statement-where-maximum-logical-operator-count": {+ "title": "Restrict the number of values in the IN or OR clause of the WHERE clause",+ "description": "This prevents performance degradation due to extensive comparisons and resource limitations."+ },+ "statement-maximum-limit-value": {+ "title": "Restrict the maximum number of the LIMIT clause",+ "description": "Limiting the number of rows through LIMIT ensures the database processes manageable chunks, improving query execution speed. A capped LIMIT value prevents excessive memory usage, safeguarding overall system stability and preventing performance degradation."+ },+ "statement-maximum-join-table-count": {+ "title": "Restrict the number of tables to be joined",+ "description": "The more tables you join, the more complex the query becomes and the longer it takes to execute. In general, it is best to keep the number of joins to a minimum."+ },+ "statement-maximum-statements-in-transaction": {+ "title": "Restrict the number of statements in a transaction",+ "description": "Large transactions can significantly impact database performance. If a large number of statements are involved and one fails, rolling back the entire transaction becomes complex. Limiting statements minimizes the potential damage caused by a single failure and simplifies rollback procedures."+ },+ "statement-join-strict-column-attrs": {+ "title": "Fields to be joined must have identical data types, character sets",+ "description": "If the data types, character sets of the join columns are not identical, the database may not be able to correctly identify matching rows, leading to inaccurate or incomplete results."+ },+ "statement-disallow-mix-dml": {+ "title": "Disallow DMLs on the same table",+ "description": "Performing concurrent data modifications on a table can lead to challenges in accurately identifying the impacted rows. This consequently complicates the process of creating a precise backup of the affected data."+ },+ "statement-disallow-mix-ddl-dml": {+ "title": "Disallow mixing DDL and DML",+ "description": "For optimal performance and data integrity, avoid combining DDL and DML statements within the same script."+ },"schema-backward-compatibility": {"title": "Check application backward compatibility","description": "Some changes may affect running applications, such as modifying the name of database object, adding new constraints, etc. This rule can avoid careless changes that lead to the failure of existing application. Suggestion error level: Warning"diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.jsonindex cf8174b7c3..6bbdb83648 100644--- a/frontend/src/locales/sql-review/es-ES.json+++ b/frontend/src/locales/sql-review/es-ES.json@@ -65,6 +65,14 @@"title": "No se permiten índices duplicados","description": "Esta regla prohíbe la creación de índices duplicados en una tabla. Los índices duplicados consumen espacio de almacenamiento adicional y pueden reducir el rendimiento de las consultas. Nivel de error de sugerencia: Advertencia"},+ "table-text-fields-total-length": {+ "title": "Limitar la longitud total de los campos de texto en una tabla",+ "description": "Esta regla limita la cantidad de datos que una tabla puede almacenar, evitando un uso excesivo de almacenamiento."+ },+ "table-disallow-set-charset": {+ "title": "Prohibir la definición del juego de caracteres en las propiedades de la tabla",+ "description": "Se recomienda establecer el juego de caracteres a nivel de la base de datos. Establecer el juego de caracteres con una granularidad más fina puede generar complejidades innecesarias. Nivel de error sugerido: Error."+ },"table-comment": {"title": "Convención de comentarios de tabla","description": "Configure si la tabla requiere comentarios y la longitud máxima de comentarios.",@@ -395,6 +403,42 @@"title": "Prohibir el uso de comparación de igualdad con NULL en la cláusula WHERE","description": "El resultado de la comparación de igualdad con NULL siempre es NULL, lo que puede causar resultados inesperados. Nivel de error de sugerencia: Advertencia"},+ "statement-where-disallow-using-function": {+ "title": "No aplique funciones ni realice cálculos en campos indexados en la cláusula WHERE",+ "description": "Si aplica una función o realiza un cálculo en el campo indexado, la base de datos no puede usar el índice y tiene que escanear toda la tabla."+ },+ "statement-where-statement-query-minimum-plan-level": {+ "title": "Limitar el nivel máximo del método de acceso a la consulta",+ "description": "La optimización del rendimiento de SQL busca un acceso constante (const), con el nivel de referencia (ref) como base, y un rendimiento aceptable a nivel de rango."+ },+ "statement-where-maximum-logical-operator-count": {+ "title": "Limitar el número de valores en las cláusulas IN u OR dentro de la cláusula WHERE",+ "description": "Esto evita la degradación del rendimiento debido a comparaciones exhaustivas y limitaciones de recursos."+ },+ "statement-maximum-limit-value": {+ "title": "Limitar el número máximo de la cláusula LIMIT",+ "description": "Limitar el número de filas mediante LIMIT garantiza que la base de datos procese bloques manejables, lo que mejora la velocidad de ejecución de las consultas. Un valor LIMIT limitado evita el uso excesivo de memoria, salvaguardando la estabilidad general del sistema y evitando la degradación del rendimiento."+ },+ "statement-maximum-join-table-count": {+ "title": "Limite el número de tablas a unir",+ "description": "Cuanto más tablas unes, más compleja se vuelve la consulta y más tardará en ejecutarse. En general, es recomendable mantener el número de uniones al mínimo."+ },+ "statement-maximum-statements-in-transaction": {+ "title": "Limitar el número de sentencias en una transacción",+ "description": "Las transacciones grandes pueden impactar significativamente el rendimiento de la base de datos. Si se involucra una gran cantidad de sentencias y una falla, revertir toda la transacción se vuelve complejo. Limitar las sentencias minimiza el daño potencial causado por una sola falla y simplifica los procedimientos de recuperación."+ },+ "statement-join-strict-column-attrs": {+ "title": "Los campos a unir deben tener tipos de datos y conjuntos de caracteres idénticos",+ "description": "Si los tipos de datos y los juegos de caracteres de las columnas de unión no son idénticos, es posible que la base de datos no pueda identificar correctamente las filas coincidentes, lo que dará lugar a resultados inexactos o incompletos."+ },+ "statement-disallow-mix-dml": {+ "title": "Prohibir DML en la misma tabla",+ "description": "La realización de modificaciones concurrentes de datos en una tabla puede generar dificultades para identificar con precisión las filas afectadas. En consecuencia, esto complica el proceso de crear una copia de seguridad precisa de los datos modificados."+ },+ "statement-disallow-mix-ddl-dml": {+ "title": "No se permite mezclar DDL y DML",+ "description": "Para un rendimiento óptimo e integridad de los datos, evite combinar sentencias DDL y DML dentro del mismo script."+ },"schema-backward-compatibility": {"title": "Comprobación de la compatibilidad con versiones anteriores de la aplicación","description": "Algunos cambios pueden afectar las aplicaciones en ejecución, como modificar el nombre del objeto de la base de datos, agregar nuevas restricciones, etc. Esta regla puede evitar cambios descuidados que lleven al fallo de la aplicación existente. Nivel de error sugerido: Advertencia"diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.jsonindex 27f7ede71a..94d02e0466 100644--- a/frontend/src/locales/sql-review/ja-JP.json+++ b/frontend/src/locales/sql-review/ja-JP.json@@ -65,6 +65,14 @@"title": "重複インデックスの禁止","description": "このルールは、テーブル上の重複インデックスの作成を禁止します。重複インデックスは、余分なストレージスペースを占有し、クエリのパフォーマンスを低下させる可能性があります。推奨エラーレベル: 警告"},+ "table-text-fields-total-length": {+ "title": "テキスト入力欄の文字数を制限する",+ "description": "このルールは、テーブルが保持できるデータ量を制限し、過剰なストレージ使用を防ぎます。"+ },+ "table-disallow-set-charset": {+ "title": "テーブルプロパティでの文字セットの定義を禁止する",+ "description": "データベースの文字セットは、データベースレベルで設定することを推奨します。より細かいレベルで文字セットを設定すると、不要な複雑さが生じる可能性があります。推奨されるエラーレベル: エラー。"+ },"table-comment": {"title": "コメントの規約","description": "テーブルにコメントが必要かどうか、および最大コメント長を設定します。",@@ -395,6 +403,42 @@"title": "WHERE句でのNULL等価比較の使用を禁止する","description": "NULL等価比較の結果は常にNULLです、これは予期しない結果を引き起こす可能性があります。推奨エラーレベル:警告"},+ "statement-where-disallow-using-function": {+ "title": "WHERE 句でインデックス付きフィールドに関数や計算を適用しないでください",+ "description": "あなたがインデックス付けされたフィールドに関数や計算を適用すると、データベースはインデックスを使用できず、代わりにテーブル全体をスキャンする必要があります。"+ },+ "statement-where-statement-query-minimum-plan-level": {+ "title": "クエリ アクセス メソッドの最大レベルを制限する",+ "description": "SQL パフォーマンス最適化は、定数時間 (じょうすうじかん) アクセスを目指すもので、基準として参照 (さんしょう) レベルを置き、許容範囲として範囲 (はんい) レベルのパフォーマンスを想定します。"+ },+ "statement-where-maximum-logical-operator-count": {+ "title": "WHERE 句の IN または OR 句の値数を制限する",+ "description": "このアプローチは、広範な比較とリソースの制限によるパフォーマンスの低下を防ぎます。"+ },+ "statement-maximum-limit-value": {+ "title": "リミット節の上限値を制限する",+ "description": "LIMIT による行数の制限は、データベースが管理可能なサイズの塊で処理を行い、クエリの実行速度を向上させます。上限を設定した LIMIT は、過度なメモリ使用を防ぎ、システム全体の安定性とパフォーマンスの低下を防ぐセーフガードとして機能します。"+ },+ "statement-maximum-join-table-count": {+ "title": "結合するテーブル数を制限する",+ "description": "結合するテーブル数が増えるほど、クエリは 複雑 (fukuzatsu) になり、実行時間が 長くなります (nagaku narimasu)。 一般的に、結合数を 最小限 (saishougen) に抑えることが望ましいです。"+ },+ "statement-maximum-statements-in-transaction": {+ "title": "トランザクション内のステートメント数を制限する",+ "description": "大きなトランザクションは、データベースのパフォーマンスに著しく影響を及ぼします。 多数のステートメントが関与しており、1つでも失敗すると、トランザクション全体のロールバックが複雑になります。 ステートメントを制限することで、単一の障害による潜在的な損害を最小限に抑え、ロールバック手順を簡素化できます。"+ },+ "statement-join-strict-column-attrs": {+ "title": "ジョインするフィールドは、データ型と文字セットが一致している必要があります",+ "description": "加入カラムのデータ型、文字セットが一致しないと、データベースは一致する行を正しく識別できず、不正確または不完全な結果が生じるおそれがあります。"+ },+ "statement-disallow-mix-dml": {+ "title": "同じテーブルに対する DML 操作を禁止する",+ "description": "テーブルに対する同時データ更新を行うと、影響を受ける行を正確に特定することが困難になり、結果的に、影響を受けたデータの正確なバックアップを作成するプロセスが複雑になります。"+ },+ "statement-disallow-mix-ddl-dml": {+ "title": "DDL と DML の混在を禁止する",+ "description": "最適なパフォーマンスとデータの整合性を保つために、同じスクリプト内で DDL ステートメントと DML ステートメントを組み合わせることは避けてください。"+ },"schema-backward-compatibility": {"title": "アプリケーションの後方互換性を確認する","description": "一部の変更は実行中のアプリケーションに影響を与える可能性があります。データベースオブジェクトの名前の変更や新しい制約の追加などが該当します。このルールにより、既存のアプリケーションの障害を防ぐことができます。提案されるエラーレベル:警告"diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.jsonindex 9267264c39..74eb3d1157 100644--- a/frontend/src/locales/sql-review/vi-VN.json+++ b/frontend/src/locales/sql-review/vi-VN.json@@ -65,6 +65,14 @@"title": "Cấm chỉ mục trùng lặp","description": "Quy tắc này cấm tạo các chỉ mục trùng lặp trên bảng. Các chỉ mục trùng lặp chiếm dung lượng lưu trữ bổ sung và có thể làm giảm hiệu suất truy vấn. Mức độ lỗi gợi ý: Cảnh báo"},+ "table-text-fields-total-length": {+ "title": "Giới hạn độ dài tối đa của trường văn bản trong bảng",+ "description": "Luật này giới hạn dung lượng dữ liệu mà một bảng có thể chứa, giúp ngăn chặn việc sử dụng dung lượng lưu trữ quá mức."+ },+ "table-disallow-set-charset": {+ "title": "Cấm thiết lập bảng mã trong thuộc tính của bảng",+ "description": "Cài đặt charset ở cấp độ cơ sở dữ liệu được khuyến khích. Cài đặt charset ở mức độ chi tiết hơn có thể dẫn đến những phức tạp không cần thiết. Mức độ lỗi đề xuất: Lỗi."+ },"table-comment": {"title": "quy ước bình luận","description": "Định cấu hình xem bảng có yêu cầu nhận xét hay không và độ dài nhận xét tối đa.",@@ -395,6 +403,42 @@"title": "Cấm sử dụng so sánh bằng NULL trong mệnh đề WHERE","description": "Kết quả của việc so sánh bằng NULL luôn là NULL, có thể gây ra các kết quả không mong muốn. Cấp độ lỗi gợi ý: Cảnh báo"},+ "statement-where-disallow-using-function": {+ "title": "Ch tránh sử dụng các hàm hoặc thực hiện tính toán trên các trường được lập chỉ mục trong mệnh đề WHERE",+ "description": "Nếu bạn áp dụng một hàm hoặc thực hiện tính toán trên trường được lập chỉ mục, cơ sở dữ liệu không thể sử dụng chỉ mục và phải quét toàn bộ bảng."+ },+ "statement-where-statement-query-minimum-plan-level": {+ "title": "Hạn chế mức truy cập tối đa của phương thức truy vấn",+ "description": "Ch tối ưu hóa hiệu suất SQL hướng đến truy cập hằng số (const), đặt mục tiêu mức tham chiếu (ref) làm tiêu chuẩn, với hiệu suất chấp nhận được ở mức phạm vi (range)."+ },+ "statement-where-maximum-logical-operator-count": {+ "title": "Giới hạn số lượng giá trị trong mệnh đề IN hoặc OR của mệnh đề WHERE",+ "description": "Điều này giúp ngăn chặn hiệu suất suy giảm do các phép so sánh rộng rãi và hạn chế tài nguyên."+ },+ "statement-maximum-limit-value": {+ "title": "Giới hạn số lượng tối đa của mệnh đề LIMIT",+ "description": "Bằng cách giới hạn số dòng trả về thông qua LIMIT, đảm bảo cơ sở dữ liệu xử lý các khối dữ liệu vừa phải, cải thiện tốc độ thực thi truy vấn. Giá trị LIMIT được giới hạn giúp ngăn chặn việc sử dụng bộ nhớ quá mức, bảo vệ tính ổn định tổng thể của hệ thống và ngăn ngừa hiệu suất giảm."+ },+ "statement-maximum-join-table-count": {+ "title": "Giảm thiểu số lượng bảng cần tham gia",+ "description": "Bản càng tham gia nhiều bảng, truy vấn sẽ càng phức tạp và thời gian thực thi càng lâu. Nói chung, tốt nhất nên giảm thiểu số lượng tham gia bảng xuống mức tối thiểu."+ },+ "statement-maximum-statements-in-transaction": {+ "title": "Hạn chế số lượng câu lệnh trong một giao dịch",+ "description": "Các giao dịch lớn có thể ảnh hưởng đáng kể đến hiệu suất của cơ sở dữ liệu. Nếu một số lượng lớn các câu lệnh được tham gia và một câu lệnh bị lỗi, việc khôi phục toàn bộ giao dịch sẽ trở nên phức tạp. Giới hạn các câu lệnh giúp giảm thiểu thiệt hại tiềm ẩn do một lỗi đơn lẻ gây ra và đơn giản hóa các thủ tục khôi phục."+ },+ "statement-join-strict-column-attrs": {+ "title": "Các trường cần ghép phải có cùng kiểu dữ liệu và bộ ký tự",+ "description": "Nếu kiểu dữ liệu, bảng mã của các cột dùng để ghép (join) không giống nhau, cơ sở dữ liệu có thể không xác định chính xác các hàng khớp nhau, dẫn đến kết quả không chính xác hoặc không đầy đủ."+ },+ "statement-disallow-mix-dml": {+ "title": "Chặn các truy vấn DML trên cùng một bảng",+ "description": "Ch thực hiện các sửa đổi dữ liệu đồng thời trên một bảng có thể dẫn đến những thách thức trong việc xác định chính xác các hàng bị ảnh hưởng. Điều này do đó làm phức tạp quá trình tạo bản sao lưu chính xác của dữ liệu bị ảnh hưởng."+ },+ "statement-disallow-mix-ddl-dml": {+ "title": "Không nên trộn lẫn DDL và DML",+ "description": "Chú ý để đạt hiệu suất tối ưu và tính toàn vẹn dữ liệu, tránh kết hợp các câu lệnh DDL và DML trong cùng một tập lệnh."+ },"schema-backward-compatibility": {"title": "Kiểm tra khả năng tương thích ngược của ứng dụng","description": "Một số thay đổi có thể ảnh hưởng đến các ứng dụng đang chạy, chẳng hạn như sửa đổi tên đối tượng cơ sở dữ liệu, thêm các ràng buộc mới, v.v. Quy tắc này có thể tránh những thay đổi bất cẩn dẫn đến lỗi ứng dụng hiện có. Mức độ lỗi đề xuất: Cảnh báo"diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.jsonindex 4cffb9a4d4..70383b219a 100644--- a/frontend/src/locales/sql-review/zh-CN.json+++ b/frontend/src/locales/sql-review/zh-CN.json@@ -65,6 +65,14 @@"title": "禁止重复索引","description": "此规则禁止在表上创建重复的索引。重复索引会占用额外的存储空间并可能降低查询性能。建议错误等级:警告"},+ "table-text-fields-total-length": {+ "title": "限制表格文本字段的总长度",+ "description": "该规则限制了表格所能容纳的数据量,防止存储空间的使用过量。"+ },+ "table-disallow-set-charset": {+ "title": "禁止在表格属性中定义字符集",+ "description": "建议在数据库层面设置字符集。在更细粒度设置字符集会带来不必要的复杂性。建议错误等级:错误。"+ },"table-comment": {"title": "注释检查","description": "配置表是否需要注释和最大注释长度。",@@ -395,6 +403,42 @@"title": "禁止在WHERE子句中使用NULL等式比较","description": "NULL 等式比较的结果始终是 NULL,可能导致意外的结果。建议错误级别:警告"},+ "statement-where-disallow-using-function": {+ "title": "在 WHERE 子句中避免对索引字段应用函数或执行计算",+ "description": "如果对索引字段应用函数或执行计算,则数据库无法使用索引,而必须扫描整个表。"+ },+ "statement-where-statement-query-minimum-plan-level": {+ "title": "限制查询访问方法的最大级别",+ "description": "在 SQL 性能优化中,追求常量访问速度,以引用级别作为基线,区间级别的性能尚可接受。"+ },+ "statement-where-maximum-logical-operator-count": {+ "title": "限制 WHERE 子句中的 IN 或 OR 子句中的值的数量",+ "description": "这可以防止因频繁对比和资源限制导致性能下降。"+ },+ "statement-maximum-limit-value": {+ "title": "限制 LIMIT 子句的最大行数",+ "description": "通过 LIMIT 限制行数可以确保数据库处理可管理的大小块数据,从而提高查询执行速度。 限制 LIMIT 的值可以防止过度使用内存,从而保护系统整体稳定性和防止性能下降。"+ },+ "statement-maximum-join-table-count": {+ "title": "限制语句中连接的表数量",+ "description": "连接的表越多,查询就越复杂,执行时间也越长。 通常情况下,最好将连接数控制在最低限度。"+ },+ "statement-maximum-statements-in-transaction": {+ "title": "限制事务中的语句数量",+ "description": "巨大的事务会显著影响数据库性能。如果涉及大量语句并且其中一个语句失败,则回滚整个事务会变得复杂。限制语句数量可以最小化单个故障造成的潜在损害并简化回滚过程。"+ },+ "statement-join-strict-column-attrs": {+ "title": "要进行连接的字段必须具有相同的数据类型和字符集。",+ "description": "如果连接列的数据类型、字符集不一致,数据库可能无法正确识别匹配的行,从而导致结果不准确或不完整。"+ },+ "statement-disallow-mix-dml": {+ "title": "禁止在同一张表上进行多个 DML 操作",+ "description": "对表格进行并发数据修改可能会给准确识别受影响的行带来挑战。 因此,这会使创建受影响数据的精确备份过程变得复杂。"+ },+ "statement-disallow-mix-ddl-dml": {+ "title": "禁止混合 DDL 和 DML 操作",+ "description": "为了获得最佳性能和数据完整性,请避免在同一个脚本中混合使用 DDL 和 DML 语句。"+ },"schema-backward-compatibility": {"title": "检查应用向后兼容性","description": "某些变更可能影响现有应用功能,例如修改数据库对象名,增加新的约束等,此规范可避免不谨慎变更导致现有应用运行失败。建议错误等级:警告"diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yamlindex e2d80eb37a..192f895550 100644--- a/frontend/src/types/sql-review-schema.yaml+++ b/frontend/src/types/sql-review-schema.yaml@@ -92,6 +92,20 @@ ruleList:engineList:- MYSQLcomponentList: []+ - type: table.text-fields-total-length+ category: TABLE+ engineList:+ - MYSQL+ componentList:+ - key: number+ payload:+ type: NUMBER+ default: 1000+ - type: table.disallow-set-charset+ category: TABLE+ engineList:+ - MYSQL+ componentList: []- type: statement.select.no-select-allcategory: STATEMENTengineList:@@ -268,6 +282,71 @@ ruleList:engineList:- MYSQLcomponentList: []+ - type: statement.where.disallow-using-function+ category: STATEMENT+ engineList:+ - MYSQL+ componentList: []+ - type: statement.where.statement.query.minimum-plan-level+ category: STATEMENT+ engineList:+ - MYSQL+ componentList:+ - key: level+ payload:+ type: STRING+ default: INDEX+ - type: statement.where.maximum-logical-operator-count+ category: STATEMENT+ engineList:+ - MYSQL+ componentList:+ - key: number+ payload:+ type: NUMBER+ default: 10+ - type: statement.maximum-limit-value+ category: STATEMENT+ engineList:+ - MYSQL+ componentList:+ - key: number+ payload:+ type: NUMBER+ default: 1000+ - type: statement.maximum-join-table-count+ category: STATEMENT+ engineList:+ - MYSQL+ componentList:+ - key: number+ payload:+ type: NUMBER+ default: 2+ - type: statement.maximum-statements-in-transaction+ category: STATEMENT+ engineList:+ - MYSQL+ componentList:+ - key: number+ payload:+ type: NUMBER+ default: 10+ - type: statement.join-strict-column-attrs+ category: STATEMENT+ engineList:+ - MYSQL+ componentList: []+ - type: statement.disallow-mix-dml+ category: STATEMENT+ engineList:+ - MYSQL+ componentList: []+ - type: statement.disallow-mix-ddl-dml+ category: STATEMENT+ engineList:+ - MYSQL+ componentList: []- type: naming.tablecategory: NAMINGengineList:diff --git a/frontend/src/types/sqlReview.ts b/frontend/src/types/sqlReview.tsindex e21b03b4b1..f0c6f914b3 100644--- a/frontend/src/types/sqlReview.ts+++ b/frontend/src/types/sqlReview.ts@@ -106,6 +106,8 @@ export type RuleType =| "table.disallow-partition"| "table.disallow-trigger"| "table.no-duplicate-index"+ | "table.text-fields-total-length"+ | "table.disallow-set-charset"| "table.comment"| "naming.table"| "naming.column"@@ -155,6 +157,15 @@ export type RuleType =| "statement.disallow-using-temporary"| "statement.disallow-using-filesort"| "statement.where.no-equal-null"+ | "statement.where.disallow-using-function"+ | "statement.where.statement.query.minimum-plan-level"+ | "statement.where.maximum-logical-operator-count"+ | "statement.maximum-limit-value"+ | "statement.maximum-join-table-count"+ | "statement.maximum-statements-in-transaction"+ | "statement.join-strict-column-attrs"+ | "statement.disallow-mix-dml"+ | "statement.disallow-mix-ddl-dml"| "schema.backward-compatibility"| "database.drop-empty-database"| "system.charset.allowlist"