Skip to content

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

chore: implement backup check (#13405)

rebeliceabb87028c03b
diff --git a/backend/plugin/advisor/pg/advisor_builtin_prior_backup_check.go b/backend/plugin/advisor/pg/advisor_builtin_prior_backup_check.go
index bc318553d3..34e414babc 100644
--- a/backend/plugin/advisor/pg/advisor_builtin_prior_backup_check.go
+++ b/backend/plugin/advisor/pg/advisor_builtin_prior_backup_check.go
@@ -8,8 +8,11 @@ import (
"github.com/pkg/errors"
+ pgquery "github.com/pganalyze/pg_query_go/v5"
+
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/parser/sql/ast"
+ pgrawparser "github.com/bytebase/bytebase/backend/plugin/parser/sql/engine/pg"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -21,6 +24,10 @@ func init() {
advisor.Register(storepb.Engine_POSTGRES, advisor.PostgreSQLBuiltinPriorBackupCheck, &BuiltinPriorBackupCheckAdvisor{})
}
+const (
+ maxMixedDMLCount = 5
+)
+
// BuiltinPriorBackupCheckAdvisor is the advisor checking for disallow mix DDL and DML.
type BuiltinPriorBackupCheckAdvisor struct {
}
@@ -42,12 +49,11 @@ func (*BuiltinPriorBackupCheckAdvisor) Check(ctx advisor.Context, _ string) ([]*
}
title := string(ctx.Rule.Type)
+ var needBackup []ast.Node
+
for _, stmt := range stmtList {
- var isDDL bool
- if _, ok := stmt.(ast.DDLNode); ok {
- isDDL = true
- }
- if isDDL {
+ switch n := stmt.(type) {
+ case ast.DDLNode:
adviceList = append(adviceList, &storepb.Advice{
Status: level,
Title: title,
@@ -57,14 +63,15 @@ func (*BuiltinPriorBackupCheckAdvisor) Check(ctx advisor.Context, _ string) ([]*
Line: int32(stmt.LastLine()),
},
})
- }
- if n, ok := stmt.(*ast.VariableSetStmt); ok {
+ case *ast.UpdateStmt, *ast.DeleteStmt:
+ needBackup = append(needBackup, stmt)
+ case *ast.VariableSetStmt:
if n.Name == "role" {
adviceList = append(adviceList, &storepb.Advice{
Status: level,
Title: title,
Content: "Backup cannot deal with SET ROLE statement",
- Code: int32(advisor.BuiltinPriorBackupCheck.Int32()),
+ Code: advisor.BuiltinPriorBackupCheck.Int32(),
StartPosition: &storepb.Position{
Line: int32(stmt.LastLine()),
},
@@ -86,9 +93,170 @@ func (*BuiltinPriorBackupCheckAdvisor) Check(ctx advisor.Context, _ string) ([]*
})
}
+ if len(needBackup) > maxMixedDMLCount && !updateForOneTableWithUnique(ctx.DBSchema, needBackup) {
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: level,
+ Title: title,
+ Content: fmt.Sprintf("Prior backup cannot deal with mixed DML more than %d statements, otherwise statements need be UPDATE for one table with PRIMARY KEY or UNIQUE KEY in WHERE clause", maxMixedDMLCount),
+ Code: advisor.BuiltinPriorBackupCheck.Int32(),
+ StartPosition: &storepb.Position{
+ Line: 0,
+ },
+ })
+ }
+
return adviceList, nil
}
+func updateForOneTableWithUnique(dbSchema *storepb.DatabaseSchemaMetadata, stmtList []ast.Node) bool {
+ var table *ast.TableDef
+ for _, stmt := range stmtList {
+ update, ok := stmt.(*ast.UpdateStmt)
+ if !ok {
+ return false
+ }
+ if table == nil {
+ table = update.Table
+ } else if !equalTable(table, update.Table) {
+ return false
+ }
+ node := update.GetOriginalNode()
+ if !hasUniqueInWhereClause(dbSchema, table, node) {
+ return false
+ }
+ }
+
+ return true
+}
+
+func hasUniqueInWhereClause(dbSchema *storepb.DatabaseSchemaMetadata, table *ast.TableDef, node *pgquery.Node_UpdateStmt) bool {
+ list := extractColumnsInEqualCondition(table, node.UpdateStmt.WhereClause)
+ columnMap := make(map[string]bool)
+ for _, column := range list {
+ columnMap[column] = true
+ }
+
+ if dbSchema == nil {
+ return false
+ }
+
+ for _, schema := range dbSchema.Schemas {
+ if schema.Name == table.Schema || (schema.Name == "public" && table.Schema == "") {
+ for _, t := range schema.Tables {
+ if t.Name == table.Name {
+ for _, index := range t.Indexes {
+ if index.Unique || index.Primary {
+ exists := true
+ for _, column := range index.Expressions {
+ if !columnMap[column] {
+ exists = false
+ break
+ }
+ }
+ if exists {
+ return true
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return false
+}
+
+func extractColumnsInEqualCondition(table *ast.TableDef, node *pgquery.Node) []string {
+ if node == nil {
+ return nil
+ }
+
+ switch n := node.Node.(type) {
+ case *pgquery.Node_BoolExpr:
+ if n.BoolExpr.Boolop != pgquery.BoolExprType_AND_EXPR {
+ return nil
+ }
+ var result []string
+ for _, arg := range n.BoolExpr.Args {
+ result = append(result, extractColumnsInEqualCondition(table, arg)...)
+ }
+ return result
+ case *pgquery.Node_AExpr:
+ if len(n.AExpr.Name) != 1 {
+ return nil
+ }
+ op, ok := n.AExpr.Name[0].Node.(*pgquery.Node_String_)
+ if !ok {
+ return nil
+ }
+ if op.String_.Sval != "=" {
+ return nil
+ }
+ if isConst(n.AExpr.Lexpr) {
+ column, err := extractColumn(table, n.AExpr.Rexpr)
+ if err == nil && column != "" {
+ return []string{column}
+ }
+ } else if isConst(n.AExpr.Rexpr) {
+ column, err := extractColumn(table, n.AExpr.Lexpr)
+ if err == nil && column != "" {
+ return []string{column}
+ }
+ }
+ }
+ return nil
+}
+
+func isConst(node *pgquery.Node) bool {
+ switch node.Node.(type) {
+ case *pgquery.Node_AConst:
+ return true
+ default:
+ return false
+ }
+}
+
+func extractColumn(table *ast.TableDef, node *pgquery.Node) (string, error) {
+ switch n := node.Node.(type) {
+ case *pgquery.Node_ColumnRef:
+ columnNameDef, err := pgrawparser.ConvertNodeListToColumnNameDef(n.ColumnRef.Fields)
+ if err != nil {
+ return "", err
+ }
+ if columnNameDef.Table != nil {
+ if columnNameDef.Table.Schema != "" && columnNameDef.Table.Schema != table.Schema {
+ return "", nil
+ }
+ if columnNameDef.Table.Name != "" && columnNameDef.Table.Name != table.Name {
+ return "", nil
+ }
+ }
+ return columnNameDef.ColumnName, nil
+ default:
+ return "", nil
+ }
+}
+
+func equalTable(a, b *ast.TableDef) bool {
+ if a == nil || b == nil {
+ return false
+ }
+
+ if a.Schema == "" && b.Schema != "" && b.Schema != "public" {
+ return false
+ }
+
+ if a.Schema != "" && a.Schema != "public" && b.Schema == "" {
+ return false
+ }
+
+ if a.Schema != b.Schema {
+ return false
+ }
+
+ return a.Name == b.Name
+}
+
func extractDatabaseName(databaseUID string) string {
segments := strings.Split(databaseUID, "/")
return segments[len(segments)-1]
diff --git a/backend/plugin/advisor/pg/test/builtin_prior_backup_check.yaml b/backend/plugin/advisor/pg/test/builtin_prior_backup_check.yaml
index 980b3f7a43..43afeb6410 100644
--- a/backend/plugin/advisor/pg/test/builtin_prior_backup_check.yaml
+++ b/backend/plugin/advisor/pg/test/builtin_prior_backup_check.yaml
@@ -1,3 +1,49 @@
+- statement: |-
+ UPDATE tech_book SET id = 1 WHERE id = 1 and name = 'test';
+ UPDATE tech_book SET id = 2 WHERE id = 2 and name = 'test';
+ UPDATE tech_book SET id = 3 WHERE id = 3 and name = 'test';
+ UPDATE tech_book SET id = 4 WHERE id = 4 and name = 'test';
+ UPDATE tech_book SET id = 4 WHERE id = 4 and name = 'test';
+ UPDATE abc SET id = 4 WHERE id = 4 and name = 'test';
+ changeType: 2
+ want:
+ - status: 3
+ code: 2001
+ title: builtin.prior-backup-check
+ content: Prior backup cannot deal with mixed DML more than 5 statements, otherwise statements need be UPDATE for one table with PRIMARY KEY or UNIQUE KEY in WHERE clause
+ detail: ""
+ startposition:
+ line: 0
+ column: 0
+ endposition: null
+- statement: |-
+ UPDATE tech_book SET id = 1 WHERE id = 1 and name = 'test';
+ UPDATE tech_book SET id = 2 WHERE id = 2 and name = 'test';
+ UPDATE tech_book SET id = 3 WHERE id = 3 and name = 'test';
+ UPDATE tech_book SET id = 4 WHERE id = 4 and name = 'test';
+ UPDATE tech_book SET id = 5 WHERE id = 5 and name = 'test';
+ UPDATE tech_book SET id = 6 WHERE id = 6 and name = 'test';
+ UPDATE tech_book SET id = 7 WHERE id = 7 and name = 'test';
+ changeType: 2
+- statement: |-
+ UPDATE tech_book SET id = 1 WHERE id = 1;
+ UPDATE tech_book SET id = 2 WHERE id = 2;
+ UPDATE tech_book SET id = 3 WHERE id = 3;
+ UPDATE tech_book SET id = 4 WHERE id = 4;
+ UPDATE tech_book SET id = 5 WHERE id = 5;
+ UPDATE tech_book SET id = 6 WHERE id = 6;
+ UPDATE tech_book SET id = 7 WHERE id = 7;
+ changeType: 2
+ want:
+ - status: 3
+ code: 2001
+ title: builtin.prior-backup-check
+ content: Prior backup cannot deal with mixed DML more than 5 statements, otherwise statements need be UPDATE for one table with PRIMARY KEY or UNIQUE KEY in WHERE clause
+ detail: ""
+ startposition:
+ line: 0
+ column: 0
+ endposition: null
- statement: DELETE FROM tech_book WHERE a > 1;
changeType: 2
- statement: UPDATE tech_book SET id = 1;
diff --git a/backend/plugin/parser/sql/ast/update_stmt.go b/backend/plugin/parser/sql/ast/update_stmt.go
index c3618434e6..4dd8027074 100644
--- a/backend/plugin/parser/sql/ast/update_stmt.go
+++ b/backend/plugin/parser/sql/ast/update_stmt.go
@@ -1,5 +1,7 @@
package ast
+import pgquery "github.com/pganalyze/pg_query_go/v5"
+
// UpdateStmt is the struct for update statement.
type UpdateStmt struct {
dml
@@ -15,4 +17,14 @@ type UpdateStmt struct {
PatternLikeList []*PatternLikeDef
// SubqueryList is the list of the subquery nodes.
SubqueryList []*SubqueryDef
+
+ originalNode *pgquery.Node_UpdateStmt
+}
+
+func (us *UpdateStmt) SetOriginalNode(node *pgquery.Node_UpdateStmt) {
+ us.originalNode = node
+}
+
+func (us *UpdateStmt) GetOriginalNode() *pgquery.Node_UpdateStmt {
+ return us.originalNode
}
diff --git a/backend/plugin/parser/sql/engine/pg/convert.go b/backend/plugin/parser/sql/engine/pg/convert.go
index 679fc25d06..14ba9e4162 100644
--- a/backend/plugin/parser/sql/engine/pg/convert.go
+++ b/backend/plugin/parser/sql/engine/pg/convert.go
@@ -503,6 +503,7 @@ func convert(node *pgquery.Node, statement base.SingleSQL) (res ast.Node, err er
}
update.SubqueryList = append(update.SubqueryList, subqueryList...)
}
+ update.SetOriginalNode(in)
return update, nil
case *pgquery.Node_DeleteStmt:
deleteStmt := &ast.DeleteStmt{