Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(sql-review): prohibit performing calculations in 'WHERE' clause (#12137)
Azusain23378edab7c9
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.goindex 15b08a7840..4db14e2cb9 100644--- a/backend/plugin/advisor/advisor.go+++ b/backend/plugin/advisor/advisor.go@@ -618,6 +618,9 @@ const (// MSSQLStatementDisallowCrossDBQueries prohibits cross database queries.MSSQLStatementDisallowCrossDBQueries Type = "bb.plugin.advisor.mssql.statement.disallow-cross-db-queries"++ // MSSQLStatementWhereDisallowFunctionsAndCalculations prohibit using functions or performing calculation in the where clause.+ MSSQLStatementWhereDisallowFunctionsAndCalculations Type = "bb.plugin.advisor.mssql.statement.disallow-functions-and-calculations")// Advice is the result of an advisor.diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.goindex 3d2e906083..0fc5216232 100644--- a/backend/plugin/advisor/code.go+++ b/backend/plugin/advisor/code.go@@ -58,6 +58,7 @@ const (StatementAddColumnWithPosition Code = 231StatementOfflineDDL Code = 232StatementDisallowCrossDBQueries Code = 233+ StatementDisallowFunctionsAndCalculations Code = 234// 301 ~ 399 naming error code// 301 table naming advisor error code.diff --git a/backend/plugin/advisor/mssql/advisor_statement_where_disallow_functions_and_calculations.go b/backend/plugin/advisor/mssql/advisor_statement_where_disallow_functions_and_calculations.gonew file mode 100644index 0000000000..d5be0ad3e3--- /dev/null+++ b/backend/plugin/advisor/mssql/advisor_statement_where_disallow_functions_and_calculations.go@@ -0,0 +1,188 @@+package mssql++import (+ "fmt"++ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/tsql-parser"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ "github.com/bytebase/bytebase/proto/generated-go/store"+)++func init() {+ advisor.Register(store.Engine_MSSQL, advisor.MSSQLStatementWhereDisallowFunctionsAndCalculations, &DisallowFuncAndCalculationsAdvisor{})+}++type DisallowFuncAndCalculationsAdvisor struct{}++type DisallowFuncAndCalculationsChecker struct {+ *parser.BaseTSqlParserListener+ level advisor.Status+ title string++ // We only check the 'WHERE' clause in a 'SELECT' statement.+ // Also, the value of 'whereCnt' represents the depth of entering the 'WHERE' clause. Same below.+ whereCnt int+ selectStatCnt int+ havingCnt int+ // Each statement can only trigger the rule once.+ hasTriggeredRule bool+ adviceList []advisor.Advice+}++var _ advisor.Advisor = (*DisallowFuncAndCalculationsAdvisor)(nil)++func (*DisallowFuncAndCalculationsAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ tree, ok := ctx.AST.(antlr.Tree)+ if !ok {+ return nil, errors.Errorf("failed to convert to AST tree")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }++ checker := &DisallowFuncAndCalculationsChecker{+ level: level,+ title: ctx.Rule.Type,+ selectStatCnt: 0,+ whereCnt: 0,+ havingCnt: 0,+ hasTriggeredRule: false,+ }++ antlr.ParseTreeWalkerDefault.Walk(checker, 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+}++func generateAdviceOnFunctionUsing(c *DisallowFuncAndCalculationsChecker, ctx antlr.BaseParserRuleContext) *advisor.Advice {+ if c.whereCnt == 0 || c.hasTriggeredRule {+ return nil+ }+ c.hasTriggeredRule = true+ return &advisor.Advice{+ Status: c.level,+ Code: advisor.StatementDisallowFunctionsAndCalculations,+ Title: c.title,+ Content: fmt.Sprintf("Calling function '%s' in 'WHERE' clause is not allowed", ctx.GetText()),+ Line: ctx.GetStart().GetLine(),+ }+}++func generateAdviceOnPerformingCalculations(c *DisallowFuncAndCalculationsChecker, ctx antlr.BaseParserRuleContext) *advisor.Advice {+ if c.whereCnt == 0 || c.hasTriggeredRule {+ return nil+ }+ c.hasTriggeredRule = true+ return &advisor.Advice{+ Status: c.level,+ Code: advisor.StatementDisallowFunctionsAndCalculations,+ Title: c.title,+ Content: "Performing calculations in 'WHERE' clause is not allowed",+ Line: ctx.GetStart().GetLine(),+ }+}++func (c *DisallowFuncAndCalculationsChecker) EnterQuery_specification(_ *parser.Query_specificationContext) {+ c.selectStatCnt+++}++func (c *DisallowFuncAndCalculationsChecker) ExitQuery_specification(_ *parser.Query_specificationContext) {+ c.selectStatCnt--+}++func (c *DisallowFuncAndCalculationsChecker) EnterHaving_clause(_ *parser.Having_clauseContext) {+ c.havingCnt+++}++func (c *DisallowFuncAndCalculationsChecker) ExitHaving_clause(_ *parser.Having_clauseContext) {+ c.havingCnt--+}++func (c *DisallowFuncAndCalculationsChecker) EnterSearch_condition(_ *parser.Search_conditionContext) {+ if c.selectStatCnt != 0 && c.havingCnt == 0 {+ c.whereCnt+++ }+}++func (c *DisallowFuncAndCalculationsChecker) ExitSearch_condition(_ *parser.Search_conditionContext) {+ c.whereCnt--+ c.hasTriggeredRule = false+}++// Calling functions.+func (c *DisallowFuncAndCalculationsChecker) EnterBUILT_IN_FUNC(ctx *parser.BUILT_IN_FUNCContext) {+ if advice := generateAdviceOnFunctionUsing(c, ctx.BaseParserRuleContext); advice != nil {+ c.adviceList = append(c.adviceList, *advice)+ }+}++func (c *DisallowFuncAndCalculationsChecker) EnterRANKING_WINDOWED_FUNC(ctx *parser.RANKING_WINDOWED_FUNCContext) {+ if advice := generateAdviceOnFunctionUsing(c, ctx.BaseParserRuleContext); advice != nil {+ c.adviceList = append(c.adviceList, *advice)+ }+}++func (c *DisallowFuncAndCalculationsChecker) EnterAGGREGATE_WINDOWED_FUNC(ctx *parser.AGGREGATE_WINDOWED_FUNCContext) {+ if advice := generateAdviceOnFunctionUsing(c, ctx.BaseParserRuleContext); advice != nil {+ c.adviceList = append(c.adviceList, *advice)+ }+}++func (c *DisallowFuncAndCalculationsChecker) EnterANALYTIC_WINDOWED_FUNC(ctx *parser.ANALYTIC_WINDOWED_FUNCContext) {+ if advice := generateAdviceOnFunctionUsing(c, ctx.BaseParserRuleContext); advice != nil {+ c.adviceList = append(c.adviceList, *advice)+ }+}++func (c *DisallowFuncAndCalculationsChecker) EnterSCALAR_FUNCTION(ctx *parser.SCALAR_FUNCTIONContext) {+ if advice := generateAdviceOnFunctionUsing(c, ctx.BaseParserRuleContext); advice != nil {+ c.adviceList = append(c.adviceList, *advice)+ }+}++func (c *DisallowFuncAndCalculationsChecker) EnterFREE_TEXT(ctx *parser.FREE_TEXTContext) {+ if advice := generateAdviceOnFunctionUsing(c, ctx.BaseParserRuleContext); advice != nil {+ c.adviceList = append(c.adviceList, *advice)+ }+}++func (c *DisallowFuncAndCalculationsChecker) EnterPARTITION_FUNC(ctx *parser.PARTITION_FUNCContext) {+ if advice := generateAdviceOnFunctionUsing(c, ctx.BaseParserRuleContext); advice != nil {+ c.adviceList = append(c.adviceList, *advice)+ }+}++func (c *DisallowFuncAndCalculationsChecker) EnterHIERARCHYID_METHOD(ctx *parser.HIERARCHYID_METHODContext) {+ if advice := generateAdviceOnFunctionUsing(c, ctx.BaseParserRuleContext); advice != nil {+ c.adviceList = append(c.adviceList, *advice)+ }+}++// Performing calculations.+func (c *DisallowFuncAndCalculationsChecker) EnterExpression(ctx *parser.ExpressionContext) {+ if ctx.GetOp() != nil {+ if advice := generateAdviceOnPerformingCalculations(c, ctx.BaseParserRuleContext); advice != nil {+ c.adviceList = append(c.adviceList, *advice)+ }+ }+}++func (c *DisallowFuncAndCalculationsChecker) EnterUnary_operator_expression(ctx *parser.Unary_operator_expressionContext) {+ if advice := generateAdviceOnPerformingCalculations(c, ctx.BaseParserRuleContext); advice != nil {+ c.adviceList = append(c.adviceList, *advice)+ }+}diff --git a/backend/plugin/advisor/mssql/mssql_rules_test.go b/backend/plugin/advisor/mssql/mssql_rules_test.goindex 378f257f12..0c1580fd59 100644--- a/backend/plugin/advisor/mssql/mssql_rules_test.go+++ b/backend/plugin/advisor/mssql/mssql_rules_test.go@@ -28,6 +28,7 @@ func TestMSSQLRules(t *testing.T) {advisor.SchemaRuleFunctionDisallowCreate,advisor.SchemaRuleProcedureDisallowCreate,advisor.SchemaRuleStatementDisallowCrossDBQueries,+ advisor.SchemaRuleStatementWhereDisallowFunctionsAndCaculations,}for _, rule := range mssqlRules {diff --git a/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml b/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yamlnew file mode 100644index 0000000000..ab90fddf83--- /dev/null+++ b/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml@@ -0,0 +1,53 @@+- statement: |-+ CREATE TABLE pokes(foo int);+ SELECT foo FROM pokes WHERE (foo + 1) * 2 > 0;+ INSERT INTO pokes VALUES(1);+ SELECT foo FROM pokes WHERE ~foo > 0;+ want:+ - status: WARN+ title: statement.where.disallow-functions-and-calculations+ code: 234+ content: Performing calculations in 'WHERE' clause is not allowed+ line: 2+ - status: WARN+ title: statement.where.disallow-functions-and-calculations+ code: 234+ content: Performing calculations in 'WHERE' clause is not allowed+ line: 4+- statement: |-+ SELECT foo FROM pokes WHERE foo | -foo > 0;+ SELECT bar FROM pokes WHERE bar > AVG(bar);+ want:+ - status: WARN+ title: statement.where.disallow-functions-and-calculations+ code: 234+ content: Performing calculations in 'WHERE' clause is not allowed+ line: 1+ - status: WARN+ title: statement.where.disallow-functions-and-calculations+ code: 234+ content: Calling function 'AVG(bar)' in 'WHERE' clause is not allowed+ line: 2+- statement: |-+ SELECT bar FROM pokes WHERE bar > 1;+ want:+ - status: SUCCESS+ title: OK+ content: ""+- statement: |-+ SELECT Department, AVG(Salary) AS AvgSalary+ FROM Employees+ GROUP BY Department+ HAVING AVG(Salary) * 3 + 1 > 50000;+ want:+ - status: SUCCESS+ title: OK+ content: ""+- statement: |-+ select * from (select * from t where t.a > 1) t1 where a > AVG(a);+ want:+ - status: WARN+ title: statement.where.disallow-functions-and-calculations+ code: 234+ content: Calling function 'AVG(a)' in 'WHERE' clause is not allowed+ line: 1diff --git a/backend/plugin/advisor/mysql/mysql_rules_test.go b/backend/plugin/advisor/mysql/mysql_rules_test.goindex 2e6dffb1b7..296c769865 100644--- a/backend/plugin/advisor/mysql/mysql_rules_test.go+++ b/backend/plugin/advisor/mysql/mysql_rules_test.go@@ -60,7 +60,7 @@ func TestMySQLRules(t *testing.T) {// advisor.SchemaRuleStatementMaximumJoinTableCount enforces maximum of tables in the joins.advisor.SchemaRuleStatementMaximumJoinTableCount,// advisor.SchemaRuleStatementWhereDisallowUsingFunction disallow using function in where clause.- advisor.SchemaRuleStatementWhereDisallowUsingFunction,+ advisor.SchemaRuleStatementWhereDisallowFunctionsAndCaculations,// advisor.SchemaRuleStatementWhereMaximumLogicalOperatorCount enforces maximum number of logical operators in the where clause.advisor.SchemaRuleStatementWhereMaximumLogicalOperatorCount,diff --git a/backend/plugin/advisor/mysql/test/statement_where_disallow_using_function.yaml b/backend/plugin/advisor/mysql/test/statement_where_disallow_functions_and_calculations.yamlsimilarity index 79%rename from backend/plugin/advisor/mysql/test/statement_where_disallow_using_function.yamlrename to backend/plugin/advisor/mysql/test/statement_where_disallow_functions_and_calculations.yamlindex 3d84812b69..0270425f2f 100644--- a/backend/plugin/advisor/mysql/test/statement_where_disallow_using_function.yaml+++ b/backend/plugin/advisor/mysql/test/statement_where_disallow_functions_and_calculations.yaml@@ -2,7 +2,7 @@want:- status: WARNcode: 1702- title: statement.where.disallow-using-function+ title: statement.where.disallow-functions-and-calculationscontent: |-Function is disallowed in where clause, but "SELECT * FROM employee WHERE id = RAND();" usesline: 1diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 3717a9930c..a58080b0c9 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -114,8 +114,8 @@ 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"+ // SchemaRuleStatementWhereDisallowFunctionsAndCaculations disallow using function in WHERE clause.+ SchemaRuleStatementWhereDisallowFunctionsAndCaculations = "statement.where.disallow-functions-and-calculations"// SchemaRuleStatementQueryMinumumPlanLevel enforce the minimum plan level.SchemaRuleStatementQueryMinumumPlanLevel = "statement.query.minimum-plan-level"// SchemaRuleStatementWhereMaximumLogicalOperatorCount enforce the maximum logical operator count in WHERE clause.@@ -1637,10 +1637,13 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Tyif engine == storepb.Engine_MYSQL {return MySQLStatementWhereNoEqualNull, nil}- case SchemaRuleStatementWhereDisallowUsingFunction:+ case SchemaRuleStatementWhereDisallowFunctionsAndCaculations:if engine == storepb.Engine_MYSQL {return MySQLStatementWhereDisallowUsingFunction, nil}+ if engine == storepb.Engine_MSSQL {+ return MSSQLStatementWhereDisallowFunctionsAndCalculations, nil+ }case SchemaRuleStatementQueryMinumumPlanLevel:if engine == storepb.Engine_MYSQL {return MySQLStatementQueryMinumumPlanLevel, nildiff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.goindex 71cc217f14..c21d496082 100644--- a/backend/plugin/advisor/utils_for_tests.go+++ b/backend/plugin/advisor/utils_for_tests.go@@ -392,7 +392,7 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType, dbType storepb.EngSchemaRuleFunctionDisallowCreate,SchemaRuleStatementCreateSpecifySchema,SchemaRuleStatementCheckSetRoleVariable,- SchemaRuleStatementWhereDisallowUsingFunction,+ SchemaRuleStatementWhereDisallowFunctionsAndCaculations,SchemaRuleStatementDisallowMixDDLDML,SchemaRuleStatementPriorBackupCheck,SchemaRuleStatementJoinStrictColumnAttrs,diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.jsonindex 7f10f2b45f..3f3ad3dcca 100644--- a/frontend/src/locales/sql-review/en-US.json+++ b/frontend/src/locales/sql-review/en-US.json@@ -447,7 +447,7 @@"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": {+ "statement-where-disallow-functions-and-calculations": {"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."},diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.jsonindex c81b69ebf8..dd2562aabc 100644--- a/frontend/src/locales/sql-review/es-ES.json+++ b/frontend/src/locales/sql-review/es-ES.json@@ -447,7 +447,7 @@"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": {+ "statement-where-disallow-functions-and-calculations": {"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."},diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.jsonindex ecad055e8b..e83fbb8cd7 100644--- a/frontend/src/locales/sql-review/ja-JP.json+++ b/frontend/src/locales/sql-review/ja-JP.json@@ -447,7 +447,7 @@"title": "WHERE句でのNULL等価比較の使用を禁止する","description": "NULL等価比較の結果は常にNULLです、これは予期しない結果を引き起こす可能性があります。推奨エラーレベル:警告"},- "statement-where-disallow-using-function": {+ "statement-where-disallow-functions-and-calculations": {"title": "WHERE 句でインデックス付きフィールドに関数や計算を適用しないでください","description": "あなたがインデックス付けされたフィールドに関数や計算を適用すると、データベースはインデックスを使用できず、代わりにテーブル全体をスキャンする必要があります。"},diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.jsonindex f702359735..207e17d7ec 100644--- a/frontend/src/locales/sql-review/zh-CN.json+++ b/frontend/src/locales/sql-review/zh-CN.json@@ -447,7 +447,7 @@"title": "禁止在WHERE子句中使用NULL等式比较","description": "NULL 等式比较的结果始终是 NULL,可能导致意外的结果。建议错误级别:警告"},- "statement-where-disallow-using-function": {+ "statement-where-disallow-functions-and-calculations": {"title": "在 WHERE 子句中避免对索引字段应用函数或执行计算","description": "如果对索引字段应用函数或执行计算,则数据库无法使用索引,而必须扫描整个表。"},diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yamlindex 85ddb70c4c..b2fdcd1a78 100644--- a/frontend/src/types/sql-review-schema.yaml+++ b/frontend/src/types/sql-review-schema.yaml@@ -275,10 +275,11 @@ ruleList:category: STATEMENTengineList:- MYSQL- - type: statement.where.disallow-using-function+ - type: statement.where.disallow-functions-and-calculationscategory: STATEMENTengineList:- MYSQL+ - MSSQL- type: statement.query.minimum-plan-levelcategory: STATEMENTengineList: