Skip to content

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

feat(backup): support CTE for MySQL (#13712)

rebeliceb76951cd15e4
diff --git a/backend/plugin/parser/mysql/backup.go b/backend/plugin/parser/mysql/backup.go
index 642aaba7fd..d18fee5313 100644
--- a/backend/plugin/parser/mysql/backup.go
+++ b/backend/plugin/parser/mysql/backup.go
@@ -164,12 +164,21 @@ func generateSQLForSingleTable(ctx context.Context, tCtx base.TransformContext,
if len(item.table.Alias) > 0 {
tableNameOrAlias = item.table.Alias
}
+ if _, err := buf.WriteString(" "); err != nil {
+ return nil, errors.Wrap(err, "failed to write space")
+ }
+ cteString := extractCTE(item.tree)
+ if len(cteString) > 0 {
+ if _, err := buf.WriteString(fmt.Sprintf("%s ", cteString)); err != nil {
+ return nil, errors.Wrap(err, "failed to write cte")
+ }
+ }
if len(generatedColumns) == 0 {
- if _, err := buf.WriteString(fmt.Sprintf(" SELECT `%s`.* FROM ", tableNameOrAlias)); err != nil {
+ if _, err := buf.WriteString(fmt.Sprintf("SELECT `%s`.* FROM ", tableNameOrAlias)); err != nil {
return nil, errors.Wrap(err, "failed to write select statement")
}
} else {
- if _, err := buf.WriteString(" SELECT "); err != nil {
+ if _, err := buf.WriteString("SELECT "); err != nil {
return nil, errors.Wrap(err, "failed to write select statement")
}
for i, column := range normalColumns {
@@ -217,6 +226,21 @@ func equalTable(a, b *TableReference) bool {
return a.Table == b.Table
}
+func extractCTE(ctx antlr.ParserRuleContext) string {
+ switch node := ctx.(type) {
+ case *parser.UpdateStatementContext:
+ if node.WithClause() != nil {
+ return node.GetParser().GetTokenStream().GetTextFromRuleContext(node.WithClause())
+ }
+ case *parser.DeleteStatementContext:
+ if node.WithClause() != nil {
+ return node.GetParser().GetTokenStream().GetTextFromRuleContext(node.WithClause())
+ }
+ }
+
+ return ""
+}
+
func generateSQLForMixedDML(ctx context.Context, tCtx base.TransformContext, statementInfoList []statementInfo, databaseName string, tablePrefix string) ([]base.BackupStatement, error) {
var result []base.BackupStatement
offsetLength := 1
@@ -242,10 +266,19 @@ func generateSQLForMixedDML(ctx context.Context, tCtx base.TransformContext, sta
if len(table.Alias) > 0 {
tableNameOrAlias = table.Alias
}
+ cteString := extractCTE(statementInfo.tree)
if len(generatedColumns) == 0 {
- if _, err := buf.WriteString(fmt.Sprintf("INSERT INTO `%s`.`%s` SELECT `%s`.* FROM ", databaseName, targetTable, tableNameOrAlias)); err != nil {
+ if _, err := buf.WriteString(fmt.Sprintf("INSERT INTO `%s`.`%s` ", databaseName, targetTable)); err != nil {
return nil, errors.Wrap(err, "failed to write insert into statement")
}
+ if len(cteString) > 0 {
+ if _, err := buf.WriteString(fmt.Sprintf("%s ", cteString)); err != nil {
+ return nil, errors.Wrap(err, "failed to write cte")
+ }
+ }
+ if _, err := buf.WriteString(fmt.Sprintf("SELECT `%s`.* FROM ", tableNameOrAlias)); err != nil {
+ return nil, errors.Wrap(err, "failed to write SELECT")
+ }
} else {
if _, err := buf.WriteString(fmt.Sprintf("INSERT INTO `%s`.`%s` (", databaseName, targetTable)); err != nil {
return nil, errors.Wrap(err, "failed to write insert into statement")
@@ -260,7 +293,15 @@ func generateSQLForMixedDML(ctx context.Context, tCtx base.TransformContext, sta
return nil, errors.Wrap(err, "failed to write column")
}
}
- if _, err := buf.WriteString(") SELECT "); err != nil {
+ if _, err := buf.WriteString(") "); err != nil {
+ return nil, errors.Wrap(err, "failed to write")
+ }
+ if len(cteString) > 0 {
+ if _, err := buf.WriteString(fmt.Sprintf("%s ", cteString)); err != nil {
+ return nil, errors.Wrap(err, "failed to write cte")
+ }
+ }
+ if _, err := buf.WriteString("SELECT "); err != nil {
return nil, errors.Wrap(err, "failed to write select")
}
for i, column := range normalColumns {
@@ -456,6 +497,14 @@ func (l *tableReferenceListener) EnterDeleteStatement(ctx *parser.DeleteStatemen
return
}
+ cteMap := make(map[string]bool)
+ if ctx.WithClause() != nil {
+ for _, cte := range ctx.WithClause().AllCommonTableExpression() {
+ tableName := NormalizeMySQLIdentifier(cte.Identifier())
+ cteMap[tableName] = true
+ }
+ }
+
if ctx.TableRef() != nil {
// Single table delete statement.
database, table := NormalizeMySQLTableRef(ctx.TableRef())
@@ -504,6 +553,10 @@ func (l *tableReferenceListener) EnterDeleteStatement(ctx *parser.DeleteStatemen
return
}
+ if len(database) == 0 && cteMap[table] {
+ continue
+ }
+
singleTable, ok := singleTables.singleTables[table]
if !ok {
l.err = errors.Errorf("cannot extract reference table: no matched table %q in referenced table list", table)
@@ -526,8 +579,18 @@ func (l *tableReferenceListener) EnterUpdateStatement(ctx *parser.UpdateStatemen
return
}
+ cteMap := make(map[string]bool)
+
+ if ctx.WithClause() != nil {
+ for _, cte := range ctx.WithClause().AllCommonTableExpression() {
+ tableName := NormalizeMySQLIdentifier(cte.Identifier())
+ cteMap[tableName] = true
+ }
+ }
+
listener := &updateTableListener{
tables: make(map[string]bool),
+ cteMap: cteMap,
}
antlr.ParseTreeWalkerDefault.Walk(listener, ctx.UpdateList())
@@ -603,9 +666,12 @@ type updateTableListener struct {
*parser.BaseMySQLParserListener
tables map[string]bool
+ cteMap map[string]bool
}
func (l *updateTableListener) EnterUpdateElement(ctx *parser.UpdateElementContext) {
_, table, _ := NormalizeMySQLColumnRef(ctx.ColumnRef())
- l.tables[table] = true
+ if _, exists := l.cteMap[table]; !exists {
+ l.tables[table] = true
+ }
}
diff --git a/backend/plugin/parser/mysql/test-data/test_backup.yaml b/backend/plugin/parser/mysql/test-data/test_backup.yaml
index 6fc7d37170..2bf2299a36 100644
--- a/backend/plugin/parser/mysql/test-data/test_backup.yaml
+++ b/backend/plugin/parser/mysql/test-data/test_backup.yaml
@@ -1,3 +1,95 @@
+- input: |-
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) UPDATE test, t_cte SET test.c1 = 1 WHERE test.b1 = t_cte.b1 and test.b1 = 1;
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) UPDATE test, t_cte SET test.c1 = 1 WHERE test.b1 = t_cte.b1 and test.b1 = 2;
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) UPDATE test, t_cte SET test.c1 = 1 WHERE test.b1 = t_cte.b1 and test.b1 = 3;
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) UPDATE test, t_cte SET test.c1 = 1 WHERE test.b1 = t_cte.b1 and test.b1 = 4;
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) UPDATE test, t_cte SET test.c1 = 1 WHERE test.b1 = t_cte.b1 and test.b1 = 5;
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) UPDATE test, t_cte SET test.c1 = 1 WHERE test.b1 = t_cte.b1 and test.b1 = 6;
+ result:
+ - statement: |-
+ CREATE TABLE `backupDB`.`_rollback_test` LIKE `db`.`test`;
+ INSERT INTO `backupDB`.`_rollback_test` WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) SELECT `test`.* FROM test, t_cte WHERE test.b1 = t_cte.b1 and test.b1 = 1
+ UNION ALL
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) SELECT `test`.* FROM test, t_cte WHERE test.b1 = t_cte.b1 and test.b1 = 2
+ UNION ALL
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) SELECT `test`.* FROM test, t_cte WHERE test.b1 = t_cte.b1 and test.b1 = 3
+ UNION ALL
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) SELECT `test`.* FROM test, t_cte WHERE test.b1 = t_cte.b1 and test.b1 = 4
+ UNION ALL
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) SELECT `test`.* FROM test, t_cte WHERE test.b1 = t_cte.b1 and test.b1 = 5
+ UNION ALL
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) SELECT `test`.* FROM test, t_cte WHERE test.b1 = t_cte.b1 and test.b1 = 6;
+ sourceschema: ""
+ sourcetablename: test
+ targettablename: _rollback_test
+ startposition:
+ line: 1
+ column: 0
+ endposition:
+ line: 18
+ column: 77
+- input: |-
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) DELETE FROM test USING test JOIN t_cte WHERE test.b1 = t_cte.b1;
+ result:
+ - statement: |-
+ CREATE TABLE `backupDB`.`_rollback_0_test` LIKE `db`.`test`;
+ INSERT INTO `backupDB`.`_rollback_0_test` WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) SELECT `test`.* FROM test JOIN t_cte WHERE test.b1 = t_cte.b1;
+ sourceschema: ""
+ sourcetablename: test
+ targettablename: _rollback_0_test
+ startposition:
+ line: 1
+ column: 0
+ endposition:
+ line: 3
+ column: 65
+- input: |-
+ WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) UPDATE test, t_cte SET test.c1 = 1 WHERE test.b1 = t_cte.b1;
+ result:
+ - statement: |-
+ CREATE TABLE `backupDB`.`_rollback_0_test` LIKE `db`.`test`;
+ INSERT INTO `backupDB`.`_rollback_0_test` WITH t_cte AS (
+ SELECT * FROM test WHERE test.b1 > 10
+ ) SELECT `test`.* FROM test, t_cte WHERE test.b1 = t_cte.b1;
+ sourceschema: ""
+ sourcetablename: test
+ targettablename: _rollback_0_test
+ startposition:
+ line: 1
+ column: 0
+ endposition:
+ line: 3
+ column: 61
- input: |-
UPDATE test SET test.c1 = 1 WHERE test.b1 = 1;
UPDATE test SET test.c1 = 2 WHERE test.b1 = 2;