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(redshift): dual transaction mode execution (#16866)
h3n4l4429e8aa1399
diff --git a/backend/plugin/db/redshift/redshift.go b/backend/plugin/db/redshift/redshift.goindex 133a2656e5..fe7df3e5c7 100644--- a/backend/plugin/db/redshift/redshift.go+++ b/backend/plugin/db/redshift/redshift.go@@ -166,6 +166,17 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOreturn 0, nil}+ // Parse transaction mode from the script+ transactionMode, cleanedStatement := base.ParseTransactionMode(statement)+ statement = cleanedStatement++ // For Redshift MVP, only enable transaction mode parsing for Redshift instances+ // Default to "off" for DDL if not specified+ if transactionMode == base.TransactionModeUnspecified {+ // We'll handle defaults in the next step+ transactionMode = base.TransactionModeOn // For now, maintain backward compatibility+ }+var commands []base.SingleSQLoneshot := trueif len(statement) <= common.MaxSheetCheckSize {@@ -185,37 +196,12 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO},}}- totalRowsAffected := int64(0)- if len(commands) != 0 {- tx, err := d.db.BeginTx(ctx, nil)- if err != nil {- return 0, err- }- defer tx.Rollback()-- for _, command := range commands {- sqlResult, err := tx.ExecContext(ctx, command.Text)- if err != nil {- return 0, &db.ErrorWithPosition{- Err: errors.Wrapf(err, "failed to execute context in a transaction"),- Start: command.Start,- End: command.End,- }- }- rowsAffected, err := sqlResult.RowsAffected()- if err != nil {- // Since we cannot differentiate DDL and DML yet, we have to ignore the error.- slog.Debug("rowsAffected returns error", log.BBError(err))- }- totalRowsAffected += rowsAffected- }- if err := tx.Commit(); err != nil {- return 0, err- }+ // Execute based on transaction mode+ if transactionMode == base.TransactionModeOff {+ return d.executeInAutoCommitMode(ctx, commands, opts)}-- return totalRowsAffected, nil+ return d.executeInTransactionMode(ctx, commands, opts)}func (d *Driver) createDatabaseExecute(ctx context.Context, statement string) error {@@ -242,6 +228,93 @@ func (d *Driver) createDatabaseExecute(ctx context.Context, statement string) erreturn nil}+// executeInTransactionMode executes statements within a single transaction+func (d *Driver) executeInTransactionMode(ctx context.Context, commands []base.SingleSQL, opts db.ExecuteOptions) (int64, error) {+ totalRowsAffected := int64(0)+ if len(commands) == 0 {+ return 0, nil+ }++ tx, err := d.db.BeginTx(ctx, nil)+ if err != nil {+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error())+ return 0, err+ }+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "")++ committed := false+ defer func() {+ err := tx.Rollback()+ if committed {+ return+ }+ var rerr string+ if err != nil && !errors.Is(err, sql.ErrTxDone) {+ rerr = err.Error()+ slog.Debug("failed to rollback transaction", log.BBError(err))+ }+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, rerr)+ }()++ for i, command := range commands {+ opts.LogCommandExecute([]int32{int32(i)})+ sqlResult, err := tx.ExecContext(ctx, command.Text)+ if err != nil {+ opts.LogCommandResponse([]int32{int32(i)}, 0, nil, err.Error())+ return 0, &db.ErrorWithPosition{+ Err: errors.Wrapf(err, "failed to execute context in a transaction"),+ Start: command.Start,+ End: command.End,+ }+ }+ rowsAffected, err := sqlResult.RowsAffected()+ if err != nil {+ // Since we cannot differentiate DDL and DML yet, we have to ignore the error.+ slog.Debug("rowsAffected returns error", log.BBError(err))+ }+ opts.LogCommandResponse([]int32{int32(i)}, int32(rowsAffected), nil, "")+ totalRowsAffected += rowsAffected+ }++ if err := tx.Commit(); err != nil {+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, err.Error())+ return 0, err+ }+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, "")+ committed = true++ return totalRowsAffected, nil+}++// executeInAutoCommitMode executes statements sequentially in auto-commit mode+func (d *Driver) executeInAutoCommitMode(ctx context.Context, commands []base.SingleSQL, opts db.ExecuteOptions) (int64, error) {+ totalRowsAffected := int64(0)++ for i, command := range commands {+ opts.LogCommandExecute([]int32{int32(i)})+ sqlResult, err := d.db.ExecContext(ctx, command.Text)+ if err != nil {+ opts.LogCommandResponse([]int32{int32(i)}, 0, nil, err.Error())+ // In auto-commit mode, we stop at the first error+ // The database is left in a partially migrated state+ return totalRowsAffected, &db.ErrorWithPosition{+ Err: errors.Wrapf(err, "failed to execute statement %d in auto-commit mode", i+1),+ Start: command.Start,+ End: command.End,+ }+ }+ rowsAffected, err := sqlResult.RowsAffected()+ if err != nil {+ // Since we cannot differentiate DDL and DML yet, we have to ignore the error.+ slog.Debug("rowsAffected returns error", log.BBError(err))+ }+ opts.LogCommandResponse([]int32{int32(i)}, int32(rowsAffected), nil, "")+ totalRowsAffected += rowsAffected+ }++ return totalRowsAffected, nil+}+func getDatabaseInCreateDatabaseStatement(createDatabaseStatement string) (string, error) {raw := strings.TrimRight(createDatabaseStatement, ";")raw = strings.TrimPrefix(raw, "CREATE DATABASE")diff --git a/backend/plugin/parser/base/transaction_mode.go b/backend/plugin/parser/base/transaction_mode.gonew file mode 100644index 0000000000..d07cdc43e6--- /dev/null+++ b/backend/plugin/parser/base/transaction_mode.go@@ -0,0 +1,43 @@+package base++import (+ "regexp"+ "strings"+)++// TransactionMode represents the transaction execution mode for a migration script.+type TransactionMode string++const (+ // TransactionModeOn wraps the script in a single transaction.+ TransactionModeOn TransactionMode = "on"+ // TransactionModeOff executes the script's statements sequentially in auto-commit mode.+ TransactionModeOff TransactionMode = "off"+ // TransactionModeUnspecified means no explicit mode was specified.+ TransactionModeUnspecified TransactionMode = ""+)++// txnModeDirectiveRegex matches the transaction mode directive at the beginning of a SQL script.+// Format: -- bytebase:txn-mode = on|off+var txnModeDirectiveRegex = regexp.MustCompile(`(?i)^\s*--\s*bytebase:txn-mode\s*=\s*(on|off)\s*$`)++// ParseTransactionMode extracts the transaction mode directive from the SQL script.+// It checks the first line of the script for the -- bytebase:txn-mode = on|off directive.+// Returns the transaction mode and the SQL script without the directive.+func ParseTransactionMode(script string) (TransactionMode, string) {+ lines := strings.Split(script, "\n")+ if len(lines) == 0 {+ return TransactionModeUnspecified, script+ }++ // Check the first line for the transaction mode directive+ matches := txnModeDirectiveRegex.FindStringSubmatch(lines[0])+ if len(matches) == 2 {+ mode := strings.ToLower(matches[1])+ // Remove the directive line from the script+ remainingScript := strings.Join(lines[1:], "\n")+ return TransactionMode(mode), strings.TrimSpace(remainingScript)+ }++ return TransactionModeUnspecified, script+}diff --git a/backend/plugin/parser/base/transaction_mode_test.go b/backend/plugin/parser/base/transaction_mode_test.gonew file mode 100644index 0000000000..39d9fd047c--- /dev/null+++ b/backend/plugin/parser/base/transaction_mode_test.go@@ -0,0 +1,87 @@+package base++import (+ "testing"+)++func TestParseTransactionMode(t *testing.T) {+ tests := []struct {+ name string+ script string+ expectedMode TransactionMode+ expectedScript string+ }{+ {+ name: "transaction mode on",+ script: "-- bytebase:txn-mode = on\nCREATE TABLE foo (id INT);",+ expectedMode: TransactionModeOn,+ expectedScript: "CREATE TABLE foo (id INT);",+ },+ {+ name: "transaction mode off",+ script: "-- bytebase:txn-mode = off\nCREATE INDEX CONCURRENTLY idx ON foo(id);",+ expectedMode: TransactionModeOff,+ expectedScript: "CREATE INDEX CONCURRENTLY idx ON foo(id);",+ },+ {+ name: "transaction mode uppercase",+ script: "-- BYTEBASE:TXN-MODE = OFF\nVACUUM ANALYZE;",+ expectedMode: TransactionModeOff,+ expectedScript: "VACUUM ANALYZE;",+ },+ {+ name: "transaction mode with extra spaces",+ script: " -- bytebase:txn-mode = on \nINSERT INTO foo VALUES (1);",+ expectedMode: TransactionModeOn,+ expectedScript: "INSERT INTO foo VALUES (1);",+ },+ {+ name: "no transaction mode directive",+ script: "CREATE TABLE bar (id INT);",+ expectedMode: TransactionModeUnspecified,+ expectedScript: "CREATE TABLE bar (id INT);",+ },+ {+ name: "transaction mode not on first line",+ script: "CREATE TABLE baz (id INT);\n-- bytebase:txn-mode = on\nINSERT INTO baz VALUES (1);",+ expectedMode: TransactionModeUnspecified,+ expectedScript: "CREATE TABLE baz (id INT);\n-- bytebase:txn-mode = on\nINSERT INTO baz VALUES (1);",+ },+ {+ name: "invalid transaction mode value",+ script: "-- bytebase:txn-mode = maybe\nCREATE TABLE qux (id INT);",+ expectedMode: TransactionModeUnspecified,+ expectedScript: "-- bytebase:txn-mode = maybe\nCREATE TABLE qux (id INT);",+ },+ {+ name: "empty script",+ script: "",+ expectedMode: TransactionModeUnspecified,+ expectedScript: "",+ },+ {+ name: "only directive",+ script: "-- bytebase:txn-mode = on",+ expectedMode: TransactionModeOn,+ expectedScript: "",+ },+ {+ name: "multiline script with directive",+ script: "-- bytebase:txn-mode = off\nCREATE TABLE t1 (id INT);\n\nCREATE TABLE t2 (id INT);\n-- This is a comment\nINSERT INTO t1 VALUES (1);",+ expectedMode: TransactionModeOff,+ expectedScript: "CREATE TABLE t1 (id INT);\n\nCREATE TABLE t2 (id INT);\n-- This is a comment\nINSERT INTO t1 VALUES (1);",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ mode, script := ParseTransactionMode(tt.script)+ if mode != tt.expectedMode {+ t.Errorf("expected mode %q, got %q", tt.expectedMode, mode)+ }+ if script != tt.expectedScript {+ t.Errorf("expected script %q, got %q", tt.expectedScript, script)+ }+ })+ }+}