Skip to content

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

feat: implement backup dml for mssql v2 (#15167)

rebelice9794d5e27e80
diff --git a/backend/plugin/advisor/mssql/advisor_builtin_prior_backup_check.go b/backend/plugin/advisor/mssql/advisor_builtin_prior_backup_check.go
index f9dc5baa17..a88a3528eb 100644
--- a/backend/plugin/advisor/mssql/advisor_builtin_prior_backup_check.go
+++ b/backend/plugin/advisor/mssql/advisor_builtin_prior_backup_check.go
@@ -6,8 +6,10 @@ import (
"strings"
"github.com/antlr4-go/antlr/v4"
- tsql "github.com/bytebase/tsql-parser"
+ parser "github.com/bytebase/tsql-parser"
+ "github.com/pkg/errors"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/advisor"
tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -16,8 +18,7 @@ import (
const (
// The default schema is 'dbo' for MSSQL.
// TODO(zp): We should support default schema in the future.
- defaultSchema = "dbo"
- maxMixedDMLCount = 5
+ defaultSchema = "dbo"
)
var (
@@ -48,14 +49,27 @@ func (*StatementPriorBackupCheckAdvisor) Check(ctx advisor.Context, _ string) ([
}
title := string(ctx.Rule.Type)
- if !advisor.DatabaseExists(ctx, extractDatabaseName(ctx.PreUpdateBackupDetail.Database)) {
+ if len(ctx.Statements) > common.MaxSheetCheckSize {
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: level,
+ Title: title,
+ Content: fmt.Sprintf("The size of statements in the sheet exceeds the limit of %d", common.MaxSheetCheckSize),
+ Code: advisor.BuiltinPriorBackupCheck.Int32(),
+ StartPosition: &storepb.Position{
+ Line: 1,
+ },
+ })
+ }
+
+ databaseName := extractDatabaseName(ctx.PreUpdateBackupDetail.Database)
+ if !advisor.DatabaseExists(ctx, databaseName) {
adviceList = append(adviceList, &storepb.Advice{
Status: level,
Title: title,
Content: fmt.Sprintf("Need database %q to do prior backup but it does not exist", ctx.PreUpdateBackupDetail.Database),
Code: advisor.DatabaseNotExists.Int32(),
StartPosition: &storepb.Position{
- Line: 0,
+ Line: 1,
},
})
return adviceList, nil
@@ -76,202 +90,227 @@ func (*StatementPriorBackupCheckAdvisor) Check(ctx advisor.Context, _ string) ([
})
}
- if len(checker.updateStatements)+len(checker.deleteStatements) > maxMixedDMLCount && !updateForOneTableWithUnique(ctx.DBSchema, checker) {
- adviceList = append(adviceList, &storepb.Advice{
- Status: level,
- Title: title,
- Content: fmt.Sprintf("Prior backup is feasible only with up to %d statements that are either UPDATE or DELETE, or if all UPDATEs target the same table with a PRIMARY or UNIQUE KEY in the WHERE clause", maxMixedDMLCount),
- Code: int32(advisor.BuiltinPriorBackupCheck),
- StartPosition: &storepb.Position{
- Line: 0,
- },
- })
+ statementInfoList, err := prepareTransformation(ctx.DBSchema.Name, ctx.Statements)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to prepare transformation")
+ }
+
+ groupByTable := make(map[string][]statementInfo)
+ for _, item := range statementInfoList {
+ key := fmt.Sprintf("%s.%s.%s", item.table.Database, item.table.Schema, item.table.Table)
+ groupByTable[key] = append(groupByTable[key], item)
+ }
+
+ // Check if the statement type is the same for all statements on the same table.
+ for key, list := range groupByTable {
+ statementType := StatementTypeUnknown
+ for _, item := range list {
+ if statementType == StatementTypeUnknown {
+ statementType = item.table.StatementType
+ }
+ if statementType != item.table.StatementType {
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: level,
+ Title: title,
+ Content: fmt.Sprintf("The statement type is not the same for all statements on the same table %q", key),
+ Code: advisor.BuiltinPriorBackupCheck.Int32(),
+ StartPosition: &storepb.Position{
+ Line: 1,
+ },
+ })
+ break
+ }
+ }
}
return adviceList, nil
}
-type tableRef struct {
- database string
- schema string
- table string
+type StatementType int
+
+const (
+ StatementTypeUnknown StatementType = iota
+ StatementTypeUpdate
+ StatementTypeInsert
+ StatementTypeDelete
+)
+
+type TableReference struct {
+ Database string
+ Schema string
+ Table string
+ Alias string
+ StatementType StatementType
}
-func updateForOneTableWithUnique(dbSchema *storepb.DatabaseSchemaMetadata, checker *statementDisallowMixDMLChecker) bool {
- if len(checker.deleteStatements) > 0 {
- return false
- }
+type statementInfo struct {
+ offset int
+ statement string
+ tree antlr.ParserRuleContext
+ table *TableReference
+}
- var table *tableRef
- for _, update := range checker.updateStatements {
- extractor := &tableExtractor{
- databaseName: dbSchema.Name,
- }
- antlr.ParseTreeWalkerDefault.Walk(extractor, update)
+func prepareTransformation(databaseName, statement string) ([]statementInfo, error) {
+ parseResult, err := tsqlparser.ParseTSQL(statement)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to parse statement")
+ }
- if table == nil {
- table = extractor.table
- } else if !equalTable(table, extractor.table) {
- return false
- }
- if !hasUniqueInWhereClause(dbSchema, table, update) {
- return false
- }
+ extractor := &dmlExtractor{
+ databaseName: databaseName,
}
+ antlr.ParseTreeWalkerDefault.Walk(extractor, parseResult.Tree)
+ return extractor.dmls, nil
+}
+
+type dmlExtractor struct {
+ *parser.BaseTSqlParserListener
- return true
+ databaseName string
+ dmls []statementInfo
+ offset int
}
-func hasUniqueInWhereClause(dbSchema *storepb.DatabaseSchemaMetadata, table *tableRef, update *tsql.Update_statementContext) bool {
- if update.Search_condition() == nil {
+func IsTopLevel(ctx antlr.Tree) bool {
+ if ctx == nil {
+ return true
+ }
+ switch ctx := ctx.(type) {
+ case *parser.Dml_clauseContext,
+ *parser.Sql_clausesContext,
+ *parser.Batch_without_goContext:
+ return IsTopLevel(ctx.GetParent())
+ case *parser.Tsql_fileContext:
+ return true
+ default:
return false
}
+}
- if dbSchema == nil {
- return false
+func (e *dmlExtractor) ExitBatch(ctx *parser.Batch_without_goContext) {
+ if len(ctx.AllSql_clauses()) == 0 {
+ e.offset++
}
+}
- list := extractColumnsInEqualCondition(dbSchema.Name, table, update.Search_condition())
- columnMap := make(map[string]bool)
- for _, column := range list {
- columnMap[strings.ToLower(column)] = true
+func (e *dmlExtractor) ExitSql_clauses(ctx *parser.Sql_clausesContext) {
+ if IsTopLevel(ctx.GetParent()) {
+ e.offset++
}
+}
- for _, schema := range dbSchema.Schemas {
- if !strings.EqualFold(schema.Name, table.schema) {
- continue
+func (e *dmlExtractor) EnterUpdate_statement(ctx *parser.Update_statementContext) {
+ if IsTopLevel(ctx.GetParent()) && ctx.Ddl_object() != nil {
+ extractor := &tableExtractor{
+ databaseName: e.databaseName,
}
- for _, t := range schema.Tables {
- if !strings.EqualFold(t.Name, table.table) {
- continue
- }
- for _, index := range t.Indexes {
- if index.Unique || index.Primary {
- exists := true
- for _, column := range index.Expressions {
- if !columnMap[strings.ToLower(column)] {
- exists = false
- break
- }
- }
- if exists {
- return true
- }
- }
- }
+ antlr.ParseTreeWalkerDefault.Walk(extractor, ctx.Ddl_object())
+
+ table := extractor.table
+ if extractor.table != nil && ctx.Table_sources() != nil && table.Database == e.databaseName && table.Schema == defaultSchema {
+ table = extractPhysicalTable(ctx.Table_sources(), extractor.table)
}
+ table.StatementType = StatementTypeUpdate
+ e.dmls = append(e.dmls, statementInfo{
+ offset: e.offset,
+ statement: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),
+ tree: ctx,
+ table: table,
+ })
}
+}
+
+func (e *dmlExtractor) EnterDelete_statement(ctx *parser.Delete_statementContext) {
+ if IsTopLevel(ctx.GetParent()) {
+ extractor := &tableExtractor{
+ databaseName: e.databaseName,
+ }
+ antlr.ParseTreeWalkerDefault.Walk(extractor, ctx.Delete_statement_from())
- return false
+ table := extractor.table
+ if extractor.table != nil && ctx.From_table_sources() != nil && table.Database == e.databaseName && table.Schema == defaultSchema {
+ table = extractPhysicalTable(ctx.From_table_sources().Table_sources(), extractor.table)
+ }
+ table.StatementType = StatementTypeDelete
+ e.dmls = append(e.dmls, statementInfo{
+ offset: e.offset,
+ statement: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),
+ tree: ctx,
+ table: table,
+ })
+ }
}
-func extractColumnsInEqualCondition(database string, table *tableRef, ctx antlr.ParserRuleContext) []string {
- if ctx == nil {
- return nil
+func extractPhysicalTable(ctx antlr.Tree, table *TableReference) *TableReference {
+ if ctx == nil || table == nil {
+ return table
}
- switch n := ctx.(type) {
- case *tsql.Search_conditionContext:
- switch {
- case n.AND() != nil:
- return append(extractColumnsInEqualCondition(database, table, n.Search_condition(0)), extractColumnsInEqualCondition(database, table, n.Search_condition(1))...)
- case n.OR() != nil:
- return nil
- case len(n.AllNOT()) > 0:
- return nil
- default:
- if n.Predicate() != nil {
- return extractColumnsInEqualCondition(database, table, n.Predicate())
- }
- if len(n.AllSearch_condition()) == 1 {
- return extractColumnsInEqualCondition(database, table, n.Search_condition(0))
- }
- }
- case *tsql.PredicateContext:
- if n.Comparison_operator() == nil {
- return nil
- }
- if n.Comparison_operator().GetText() != "=" {
- return nil
- }
- if n.Subquery() != nil {
- return nil
- }
- if len(n.AllExpression()) != 2 {
- return nil
- }
- if isConstant(n.Expression(0)) {
- return extractColumnsInEqualCondition(database, table, n.Expression(1))
- }
- if isConstant(n.Expression(1)) {
- return extractColumnsInEqualCondition(database, table, n.Expression(0))
- }
- case *tsql.ExpressionContext:
- return extractColumnsInEqualCondition(database, table, n.Full_column_name())
- case *tsql.Full_column_nameContext:
- if n.Full_table_name() != nil {
- databaseName, schemaName, tableName := extractFullTableName(n.Full_table_name(), database, defaultSchema)
- if !equalTable(table, &tableRef{
- database: databaseName,
- schema: schemaName,
- table: tableName,
- }) {
- return nil
- }
- if n.Id_() == nil {
- return nil
- }
- _, columnName := tsqlparser.NormalizeTSQLIdentifier(n.Id_())
- return []string{columnName}
- }
+ extractor := &physicalTableExtractor{
+ table: table,
}
+ antlr.ParseTreeWalkerDefault.Walk(extractor, ctx)
+ if extractor.result != nil {
+ return extractor.result
+ }
+ return table
+}
- return nil
+type physicalTableExtractor struct {
+ *parser.BaseTSqlParserListener
+
+ table *TableReference
+ result *TableReference
}
-func isConstant(ctx antlr.ParserRuleContext) bool {
- if ctx == nil {
- return false
- }
- switch n := ctx.(type) {
- case *tsql.ExpressionContext:
- return isConstant(n.Primitive_expression())
- case *tsql.Primitive_expressionContext:
- return isConstant(n.Primitive_constant())
- case *tsql.Primitive_constantContext:
- return true
- case *tsql.Unary_operator_expressionContext:
- return isConstant(n.Expression())
+func (e *physicalTableExtractor) EnterTable_source_item(ctx *parser.Table_source_itemContext) {
+ if ctx.As_table_alias() != nil && ctx.Full_table_name() != nil {
+ alias := unquote(ctx.As_table_alias().Table_alias().GetText())
+ if alias == e.table.Table {
+ databaseName, schemaName, tableName := extractFullTableName(ctx.Full_table_name(), e.table.Database, e.table.Schema)
+ e.result = &TableReference{
+ Database: databaseName,
+ Schema: schemaName,
+ Table: tableName,
+ Alias: alias,
+ StatementType: e.table.StatementType,
+ }
+ }
}
- return false
}
-func equalTable(a, b *tableRef) bool {
- if a == nil || b == nil {
- return false
+func unquote(name string) string {
+ if len(name) < 2 {
+ return name
+ }
+ if name[0] == '[' && name[len(name)-1] == ']' {
+ return name[1 : len(name)-1]
}
- return a.database == b.database && a.schema == b.schema && a.table == b.table
+ if len(name) > 3 && name[0] == 'N' && name[1] == '\'' && name[len(name)-1] == '\'' {
+ return name[2 : len(name)-1]
+ }
+ return name
}
type tableExtractor struct {
- *tsql.BaseTSqlParserListener
+ *parser.BaseTSqlParserListener
databaseName string
- table *tableRef
+ table *TableReference
}
-func (e *tableExtractor) EnterFull_table_name(ctx *tsql.Full_table_nameContext) {
+func (e *tableExtractor) EnterFull_table_name(ctx *parser.Full_table_nameContext) {
databaseName, schemaName, tableName := extractFullTableName(ctx, e.databaseName, defaultSchema)
- table := tableRef{
- database: databaseName,
- schema: schemaName,
- table: tableName,
+ table := TableReference{
+ Database: databaseName,
+ Schema: schemaName,
+ Table: tableName,
}
e.table = &table
}
-func extractFullTableName(ctx tsql.IFull_table_nameContext, defaultDatabase string, defaultSchema string) (string, string, string) {
+func extractFullTableName(ctx parser.IFull_table_nameContext, defaultDatabase string, defaultSchema string) (string, string, string) {
name, err := tsqlparser.NormalizeFullTableName(ctx)
if err != nil {
slog.Debug("Failed to normalize full table name", "error", err)
@@ -289,24 +328,24 @@ func extractFullTableName(ctx tsql.IFull_table_nameContext, defaultDatabase stri
}
type statementDisallowMixDMLChecker struct {
- *tsql.BaseTSqlParserListener
+ *parser.BaseTSqlParserListener
- updateStatements []*tsql.Update_statementContext
- deleteStatements []*tsql.Delete_statementContext
+ updateStatements []*parser.Update_statementContext
+ deleteStatements []*parser.Delete_statementContext
hasDDL bool
}
-func (l *statementDisallowMixDMLChecker) EnterDdl_clause(_ *tsql.Ddl_clauseContext) {
+func (l *statementDisallowMixDMLChecker) EnterDdl_clause(_ *parser.Ddl_clauseContext) {
l.hasDDL = true
}
-func (l *statementDisallowMixDMLChecker) EnterUpdate_statement(ctx *tsql.Update_statementContext) {
+func (l *statementDisallowMixDMLChecker) EnterUpdate_statement(ctx *parser.Update_statementContext) {
if tsqlparser.IsTopLevel(ctx.GetParent()) {
l.updateStatements = append(l.updateStatements, ctx)
}
}
-func (l *statementDisallowMixDMLChecker) EnterDelete_statement(ctx *tsql.Delete_statementContext) {
+func (l *statementDisallowMixDMLChecker) EnterDelete_statement(ctx *parser.Delete_statementContext) {
if tsqlparser.IsTopLevel(ctx.GetParent()) {
l.deleteStatements = append(l.deleteStatements, ctx)
}
diff --git a/backend/plugin/parser/tsql/backup.go b/backend/plugin/parser/tsql/backup.go
index 4114de42d6..5a0e2657b3 100644
--- a/backend/plugin/parser/tsql/backup.go
+++ b/backend/plugin/parser/tsql/backup.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log/slog"
+ "sort"
"strings"
"github.com/antlr4-go/antlr/v4"
@@ -25,7 +26,6 @@ const (
// TODO(zp): We should support default schema in the future.
defaultSchema = "dbo"
maxTableNameLength = 128
- maxMixedDMLCount = 5
)
type StatementType int
@@ -62,21 +62,50 @@ func TransformDMLToSelect(_ context.Context, _ base.TransformContext, statement
}
func generateSQL(statementInfoList []statementInfo, targetDatabase string, tablePrefix string) ([]base.BackupStatement, error) {
- if len(statementInfoList) <= maxMixedDMLCount {
- return generateSQLForMixedDML(statementInfoList, targetDatabase, tablePrefix)
+ groupByTable := make(map[string][]statementInfo)
+ for _, item := range statementInfoList {
+ key := fmt.Sprintf("%s.%s.%s", item.table.Database, item.table.Schema, item.table.Table)
+ groupByTable[key] = append(groupByTable[key], item)
}
- return generateSQLForSingleTable(statementInfoList, targetDatabase, tablePrefix)
-}
-func generateSQLForSingleTable(statementInfoList []statementInfo, targetDatabase string, tablePrefix string) ([]base.BackupStatement, error) {
- table := statementInfoList[0].table
+ // Check if the statement type is the same for all statements on the same table.
+ for key, list := range groupByTable {
+ statementType := StatementTypeUnknown
+ for _, item := range list {
+ if statementType == StatementTypeUnknown {
+ statementType = item.table.StatementType
+ }
+ if statementType != item.table.StatementType {
+ return nil, errors.Errorf("prior backup cannot handle mixed DMLs on the same table %s", key)
+ }
+ }
+ }
- for _, item := range statementInfoList {
- if !equalTable(table, item.table) {
- return nil, errors.Errorf("prior backup cannot handle statements on different tables more than %d", maxMixedDMLCount)
+ var result []base.BackupStatement
+ for key, list := range groupByTable {
+ backupStatement, err := generateSQLForTable(list, targetDatabase, tablePrefix)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to generate SQL for table %s", key)
}
+ result = append(result, *backupStatement)
}
+ sort.Slice(result, func(i, j int) bool {
+ if result[i].StartPosition.Line != result[j].StartPosition.Line {
+ return result[i].StartPosition.Line < result[j].StartPosition.Line
+ }
+ if result[i].StartPosition.Column != result[j].StartPosition.Column {
+ return result[i].StartPosition.Column < result[j].StartPosition.Column
+ }
+ return result[i].SourceTableName < result[j].SourceTableName
+ })
+
+ return result, nil
+}
+
+func generateSQLForTable(statementInfoList []statementInfo, targetDatabase string, tablePrefix string) (*base.BackupStatement, error) {
+ table := statementInfoList[0].table
+
targetTable := fmt.Sprintf("%s_%s_%s", tablePrefix, table.Table, table.Database)
targetTable, _ = common.TruncateString(targetTable, maxTableNameLength)
var buf strings.Builder
@@ -85,7 +114,7 @@ func generateSQLForSingleTable(statementInfoList []statementInfo, targetDatabase
}
for i, item := range statementInfoList {
if i > 0 {
- if _, err := buf.WriteString("\n UNION ALL\n"); err != nil {
+ if _, err := buf.WriteString("\n UNION\n"); err != nil {
return nil, errors.Wrap(err, "failed to write buffer")
}
}
@@ -119,93 +148,22 @@ func generateSQLForSingleTable(statementInfoList []statementInfo, targetDatabase
if _, err := buf.WriteString(") AS backup_table;"); err != nil {
return nil, errors.Wrap(err, "failed to write buffer")
}
- return []base.BackupStatement{
- {
- Statement: buf.String(),
- SourceSchema: table.Schema,
- SourceTableName: table.Table,
- TargetTableName: targetTable,
- StartPosition: &storepb.Position{
- Line: int32(statementInfoList[0].tree.GetStart().GetLine()),
- Column: int32(statementInfoList[0].tree.GetStart().GetColumn()),
- },
- EndPosition: &storepb.Position{
- Line: int32(statementInfoList[len(statementInfoList)-1].tree.GetStop().GetLine()),
- Column: int32(statementInfoList[len(statementInfoList)-1].tree.GetStop().GetColumn()),
- },
+ return &base.BackupStatement{
+ Statement: buf.String(),
+ SourceSchema: table.Schema,
+ SourceTableName: table.Table,
+ TargetTableName: targetTable,
+ StartPosition: &storepb.Position{
+ Line: int32(statementInfoList[0].tree.GetStart().GetLine()),
+ Column: int32(statementInfoList[0].tree.GetStart().GetColumn()),
+ },
+ EndPosition: &storepb.Position{
+ Line: int32(statementInfoList[len(statementInfoList)-1].tree.GetStop().GetLine()),
+ Column: int32(statementInfoList[len(statementInfoList)-1].tree.GetStop().GetColumn()),
},
}, nil
}
-func equalTable(a, b *TableReference) bool {
- if a == nil || b == nil {
- return false
- }
-
- return strings.EqualFold(a.Database, b.Database) && strings.EqualFold(a.Schema, b.Schema) && strings.EqualFold(a.Table, b.Table)
-}
-
-func generateSQLForMixedDML(statementInfoList []statementInfo, targetDatabase string, tablePrefix string) ([]base.BackupStatement, error) {
- var result []base.BackupStatement
- offsetLength := 1
- if len(statementInfoList) > 1 {
- offsetLength = base.GetOffsetLength(statementInfoList[len(statementInfoList)-1].offset)
- }
- for _, statementInfo := range statementInfoList {
- table := statementInfo.table
- targetTable := fmt.Sprintf("%s_%0*d_%s", tablePrefix, offsetLength, statementInfo.offset, table.Table)
- targetTable, _ = common.TruncateString(targetTable, maxTableNameLength)
- topClause, fromClause, err := extractSuffixSelectStatement(statementInfo.tree)
- if err != nil {
- return nil, errors.Wrap(err, "failed to extract suffix select statement")
- }
- var buf strings.Builder
- if len(table.Alias) == 0 {
- if _, err := buf.WriteString(fmt.Sprintf(`SELECT "%s"."%s"."%s".* `, table.Database, table.Schema, table.Table)); err != nil {
- return nil, errors.Wrap(err, "failed to write buffer")
- }
- } else {
- if _, err := buf.WriteString(fmt.Sprintf(`SELECT "%s".* `, table.Alias)); err != nil {
- return nil, errors.Wrap(err, "failed to write buffer")
- }
- }
- if len(topClause) > 0 {
- if _, err := buf.WriteString(topClause); err != nil {
- return nil, errors.Wrap(err, "failed to write buffer")
- }
- if _, err := buf.WriteString(" "); err != nil {
- return nil, errors.Wrap(err, "failed to write buffer")
- }
- }
- if _, err := buf.WriteString(fmt.Sprintf(`INTO "%s"."%s"."%s" `, targetDatabase, defaultSchema, targetTable)); err != nil {
- return nil, errors.Wrap(err, "failed to write buffer")
- }
- if len(fromClause) > 0 {
- if _, err := buf.WriteString(fromClause); err != nil {
- return nil, errors.Wrap(err, "failed to write buffer")
- }
- }
- if _, err := buf.WriteString(";"); err != nil {
- return nil, errors.Wrap(err, "failed to write buffer")
- }
- result = append(result, base.BackupStatement{
- Statement: buf.String(),
- SourceSchema: table.Schema,
- SourceTableName: table.Table,
- TargetTableName: targetTable,
- StartPosition: &storepb.Position{
- Line: int32(statementInfo.tree.GetStart().GetLine()),
- Column: int32(statementInfo.tree.GetStart().GetColumn()),
- },
- EndPosition: &storepb.Position{
- Line: int32(statementInfo.tree.GetStop().GetLine()),
- Column: int32(statementInfo.tree.GetStop().GetColumn()),
- },
- })
- }
- return result, nil
-}
-
func extractSuffixSelectStatement(tree antlr.Tree) (string, string, error) {
extractor := &suffixSelectStatementExtractor{}
antlr.ParseTreeWalkerDefault.Walk(extractor, tree)
@@ -415,6 +373,7 @@ func (e *dmlExtractor) EnterUpdate_statement(ctx *parser.Update_statementContext
if extractor.table != nil && ctx.Table_sources() != nil && table.Database == e.databaseName && table.Schema == defaultSchema {
table = extractPhysicalTable(ctx.Table_sources(), extractor.table)
}
+ table.StatementType = StatementTypeUpdate
e.dmls = append(e.dmls, statementInfo{
offset: e.offset,
statement: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),
@@ -435,7 +394,7 @@ func (e *dmlExtractor) EnterDelete_statement(ctx *parser.Delete_statementContext
if extractor.table != nil && ctx.From_table_sources() != nil && table.Database == e.databaseName && table.Schema == defaultSchema {
table = extractPhysicalTable(ctx.From_table_sources().Table_sources(), extractor.table)
}
-
+ table.StatementType = StatementTypeDelete
e.dmls = append(e.dmls, statementInfo{
offset: e.offset,
statement: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),
diff --git a/backend/plugin/parser/tsql/test-data/test_backup.yaml b/backend/plugin/parser/tsql/test-data/test_backup.yaml
index 22bf7b6e15..dcc33fb07a 100644
--- a/backend/plugin/parser/tsql/test-data/test_backup.yaml
+++ b/backend/plugin/parser/tsql/test-data/test_backup.yaml
@@ -10,17 +10,17 @@
- statement: |-
SELECT * INTO "backupDB"."dbo"."rollback_test_db" FROM (
SELECT "db"."dbo"."test".* FROM test WHERE test.b1 = 1
- UNION ALL
+ UNION
SELECT "db"."dbo"."test".* FROM test WHERE test.b1 = 2
- UNION ALL
+ UNION
SELECT "db"."dbo"."test".* FROM test WHERE test.b1 = 3
- UNION ALL
+ UNION
SELECT "db"."dbo"."test".* FROM test WHERE test.b1 = 4
- UNION ALL
+ UNION
SELECT "db"."dbo"."test".* FROM test WHERE test.b1 = 5
- UNION ALL
+ UNION
SELECT "db"."dbo"."test".* FROM test WHERE test.b1 = 6
- UNION ALL
+ UNION
SELECT "db"."dbo"."test".* FROM test WHERE test.b1 = 7) AS backup_table;
sourceschema: dbo
sourcetablename: test
@@ -36,10 +36,12 @@
FROM test AS t_alias
WHERE t_alias.c1 = 1;
result:
- - statement: SELECT "t_alias".* INTO "backupDB"."dbo"."rollback_0_test" FROM test AS t_alias WHERE t_alias.c1 = 1;
+ - statement: |-
+ SELECT * INTO "backupDB"."dbo"."rollback_test_db" FROM (
+ SELECT "t_alias".* FROM test AS t_alias WHERE t_alias.c1 = 1) AS backup_table;
sourceschema: dbo
sourcetablename: test
- targettablename: rollback_0_test
+ targettablename: rollback_test_db
startposition:
line: 1
column: 0
@@ -52,10 +54,12 @@
FROM test AS t_alias
WHERE t_alias.c1 = 1;
result:
- - statement: SELECT "t_alias".* INTO "backupDB"."dbo"."rollback_0_test" FROM test AS t_alias WHERE t_alias.c1 = 1;
+ - statement: |-
+ SELECT * INTO "backupDB"."dbo"."rollback_test_db" FROM (
+ SELECT "t_alias".* FROM test AS t_alias WHERE t_alias.c1 = 1) AS backup_table;
sourceschema: dbo
sourcetablename: test
- targettablename: rollback_0_test
+ targettablename: rollback_test_db
startposition:
line: 1
column: 0
@@ -67,10 +71,12 @@
FROM test JOIN test2 ON test.c1 = test2.c1
WHERE test.c1 = 1;
result:
- - statement: SELECT "db"."dbo"."test".* INTO "backupDB"."dbo"."rollback_0_test" FROM test JOIN test2 ON test.c1 = test2.c1 WHERE test.c1 = 1;
+ - statement: |-
+ SELECT * INTO "backupDB"."dbo"."rollback_test_db" FROM (
+ SELECT "db"."dbo"."test".* FROM test JOIN test2 ON test.c1 = test2.c1 WHERE test.c1 = 1) AS backup_table;
sourceschema: dbo
sourcetablename: test
- targettablename: rollback_0_test
+ targettablename: rollback_test_db
startposition:
line: 1
column: 0
@@ -83,10 +89,12 @@
FROM test JOIN test2 ON test.c1 = test2.c1
WHERE test.c1 = 1;
result:
- - statement: SELECT "db"."dbo"."test".* INTO "backupDB"."dbo"."rollback_0_test" FROM test JOIN test2 ON test.c1 = test2.c1 WHERE test.c1 = 1;
+ - statement: |-
+ SELECT * INTO "backupDB"."dbo"."rollback_test_db" FROM (
+ SELECT "db"."dbo"."test".* FROM test JOIN test2 ON test.c1 = test2.c1 WHERE test.c1 = 1) AS backup_table;
sourceschema: dbo
sourcetablename: test
- targettablename: rollback_0_test
+ targettablename: rollback_test_db
startposition:
line: 1
column: 0
@@ -94,23 +102,27 @@
line: 4
column: 17
- input: |-
- DELETE FROM test WHERE c1 = 1;
+ DELETE FROM test1 WHERE c1 = 1;
UPDATE test SET test.c1 = 2 WHERE test.c1 = 1;
result:
- - statement: SELECT "db"."dbo"."test".* INTO "backupDB"."dbo"."rollback_0_test" FROM test WHERE c1 = 1;
+ - statement: |-
+ SELECT * INTO "backupDB"."dbo"."rollback_test1_db" FROM (
+ SELECT "db"."dbo"."test1".* FROM test1 WHERE c1 = 1) AS backup_table;
sourceschema: dbo
- sourcetablename: test
- targettablename: rollback_0_test
+ sourcetablename: test1
+ targettablename: rollback_test1_db
startposition:
line: 1
column: 0
endposition:
line: 1
- column: 29
- - statement: SELECT "db"."dbo"."test".* INTO "backupDB"."dbo"."rollback_1_test" FROM test WHERE test.c1 = 1;
+ column: 30
+ - statement: |-
+ SELECT * INTO "backupDB"."dbo"."rollback_test_db" FROM (
+ SELECT "db"."dbo"."test".* FROM test WHERE test.c1 = 1) AS backup_table;
sourceschema: dbo
sourcetablename: test
- targettablename: rollback_1_test
+ targettablename: rollback_test_db
startposition:
line: 2
column: 0
@@ -119,10 +131,12 @@
column: 45
- input: DELETE FROM test WHERE c1 = 1;
result:
- - statement: SELECT "db"."dbo"."test".* INTO "backupDB"."dbo"."rollback_0_test" FROM test WHERE c1 = 1;
+ - statement: |-
+ SELECT * INTO "backupDB"."dbo"."rollback_test_db" FROM (
+ SELECT "db"."dbo"."test".* FROM test WHERE c1 = 1) AS backup_table;
sourceschema: dbo
sourcetablename: test
- targettablename: rollback_0_test
+ targettablename: rollback_test_db
startposition:
line: 1
column: 0
@@ -131,10 +145,12 @@
column: 29
- input: UPDATE test SET c1 = 1 WHERE c1=2;
result:
- - statement: SELECT "db"."dbo"."test".* INTO "backupDB"."dbo"."rollback_0_test" FROM test WHERE c1=2;
+ - statement: |-
+ SELECT * INTO "backupDB"."dbo"."rollback_test_db" FROM (
+ SELECT "db"."dbo"."test".* FROM test WHERE c1=2) AS backup_table;
sourceschema: dbo
sourcetablename: test
- targettablename: rollback_0_test
+ targettablename: rollback_test_db
startposition:
line: 1
column: 0
@@ -142,26 +158,20 @@
line: 1
column: 33
- input: |-
- UPDATE test SET test.c1 = 2 WHERE test.c1 = 1 ;
- UPDATE test SET test.c1 = 3 WHERE test.c1 = 5 ;
+ UPDATE test SET test.c1 = 2 WHERE test.c1 = 1;
+ UPDATE test SET test.c1 = 3 WHERE test.c1 = 5;
result:
- - statement: SELECT "db"."dbo"."test".* INTO "backupDB"."dbo"."rollback_0_test" FROM test WHERE test.c1 = 1 ;
+ - statement: |-
+ SELECT * INTO "backupDB"."dbo"."rollback_test_db" FROM (
+ SELECT "db"."dbo"."test".* FROM test WHERE test.c1 = 1
+ UNION
+ SELECT "db"."dbo"."test".* FROM test WHERE test.c1 = 5) AS backup_table;
sourceschema: dbo
sourcetablename: test
- targettablename: rollback_0_test
+ targettablename: rollback_test_db
startposition:
line: 1
column: 0
endposition:
- line: 1
- column: 46
- - statement: SELECT "db"."dbo"."test".* INTO "backupDB"."dbo"."rollback_1_test" FROM test WHERE test.c1 = 5 ;
- sourceschema: dbo
- sourcetablename: test
- targettablename: rollback_1_test
- startposition:
line: 2
- column: 0
- endposition:
- line: 2
- column: 46
+ column: 45