Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: unify transaction mode pattern (#16896)
h3n4lf3da85151b51
diff --git a/backend/plugin/db/clickhouse/clickhouse.go b/backend/plugin/db/clickhouse/clickhouse.goindex 317039262a..0770abcad1 100644--- a/backend/plugin/db/clickhouse/clickhouse.go+++ b/backend/plugin/db/clickhouse/clickhouse.go@@ -122,7 +122,7 @@ func (d *Driver) getVersion(ctx context.Context) (string, error) {}// Execute executes a SQL statement.-func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOptions) (int64, error) {+func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {// Parse transaction mode from the scripttransactionMode, cleanedStatement := base.ParseTransactionMode(statement)statement = cleanedStatement@@ -141,53 +141,83 @@ func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOptireturn 0, nil}- // ClickHouse has limited transaction support, so we handle both modes similarly- // For auto-commit mode (TransactionModeOff), we execute each statement independently- // For transaction mode, we use the existing transaction approach+ // Execute based on transaction modeif transactionMode == common.TransactionModeOff {- // Execute statements independently without transaction- totalRowsAffected := int64(0)- for _, singleSQL := range singleSQLs {- sqlResult, err := d.db.ExecContext(ctx, singleSQL.Text)- if err != nil {- return totalRowsAffected, err- }- 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))- } else {- totalRowsAffected += rowsAffected- }- }- return totalRowsAffected, nil+ return d.executeInAutoCommitMode(ctx, singleSQLs, opts)}+ return d.executeInTransactionMode(ctx, singleSQLs, opts)+}- // Transaction mode execution (default behavior)+func (d *Driver) executeInTransactionMode(ctx context.Context, singleSQLs []base.SingleSQL, opts db.ExecuteOptions) (int64, error) {tx, err := d.db.BeginTx(ctx, nil)if err != nil {return 0, err}- defer tx.Rollback()++ committed := false+ defer func() {+ if !committed {+ err := tx.Rollback()+ 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)+ }+ }()++ // Log transaction start+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "")totalRowsAffected := int64(0)- for _, singleSQL := range singleSQLs {+ for i, singleSQL := range singleSQLs {+ opts.LogCommandExecute([]int32{int32(i)})sqlResult, err := tx.ExecContext(ctx, singleSQL.Text)if err != nil {- return 0, err+ 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: singleSQL.Start,+ End: singleSQL.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))- } else {- totalRowsAffected += rowsAffected}+ 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}- return totalRowsAffected, err+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, "")+ committed = true+ return totalRowsAffected, nil+}++func (d *Driver) executeInAutoCommitMode(ctx context.Context, singleSQLs []base.SingleSQL, opts db.ExecuteOptions) (int64, error) {+ totalRowsAffected := int64(0)+ for i, singleSQL := range singleSQLs {+ opts.LogCommandExecute([]int32{int32(i)})+ sqlResult, err := d.db.ExecContext(ctx, singleSQL.Text)+ if err != nil {+ opts.LogCommandResponse([]int32{int32(i)}, 0, nil, err.Error())+ return totalRowsAffected, err+ }+ 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))+ } else {+ totalRowsAffected += rowsAffected+ }+ opts.LogCommandResponse([]int32{int32(i)}, int32(rowsAffected), nil, "")+ }+ return totalRowsAffected, nil}diff --git a/backend/plugin/db/cockroachdb/cockroachdb.go b/backend/plugin/db/cockroachdb/cockroachdb.goindex a08bd7839f..ea85c6a20b 100644--- a/backend/plugin/db/cockroachdb/cockroachdb.go+++ b/backend/plugin/db/cockroachdb/cockroachdb.go@@ -312,17 +312,24 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO}commands, originalIndex = tmpCommands, tmpOriginalIndex- // For auto-commit mode, treat all statements as non-transactional+ // Execute based on transaction modeif transactionMode == common.TransactionModeOff {- // Move all commands to non-transaction list for auto-commit execution- for i, command := range commands {- nonTransactionAndSetRoleStmts = append(nonTransactionAndSetRoleStmts, command.Text)- nonTransactionAndSetRoleStmtsIndex = append(nonTransactionAndSetRoleStmtsIndex, originalIndex[i])- }- commands = nil- originalIndex = nil+ return d.executeInAutoCommitMode(ctx, owner, statement, commands, originalIndex, nonTransactionAndSetRoleStmts, nonTransactionAndSetRoleStmtsIndex, opts, isPlsql)}+ return d.executeInTransactionMode(ctx, owner, statement, commands, originalIndex, nonTransactionAndSetRoleStmts, nonTransactionAndSetRoleStmtsIndex, opts, isPlsql)+}+func (d *Driver) executeInTransactionMode(+ ctx context.Context,+ owner string,+ statement string,+ commands []base.SingleSQL,+ originalIndex []int32,+ nonTransactionAndSetRoleStmts []string,+ nonTransactionAndSetRoleStmtsIndex []int32,+ opts db.ExecuteOptions,+ isPlsql bool,+) (int64, error) {conn, err := d.db.Conn(ctx)if err != nil {return 0, errors.Wrapf(err, "failed to get connection")@@ -458,6 +465,98 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOreturn totalRowsAffected, nil}+func (d *Driver) executeInAutoCommitMode(+ ctx context.Context,+ owner string,+ statement string,+ commands []base.SingleSQL,+ originalIndex []int32,+ nonTransactionAndSetRoleStmts []string,+ nonTransactionAndSetRoleStmtsIndex []int32,+ opts db.ExecuteOptions,+ isPlsql bool,+) (int64, error) {+ // For auto-commit mode, treat all statements as non-transactional+ for i, command := range commands {+ nonTransactionAndSetRoleStmts = append(nonTransactionAndSetRoleStmts, command.Text)+ nonTransactionAndSetRoleStmtsIndex = append(nonTransactionAndSetRoleStmtsIndex, originalIndex[i])+ }++ conn, err := d.db.Conn(ctx)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to get connection")+ }+ defer conn.Close()++ if opts.SetConnectionID != nil {+ var pid string+ if err := conn.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil {+ return 0, errors.Wrapf(err, "failed to get connection id")+ }+ opts.SetConnectionID(pid)++ if opts.DeleteConnectionID != nil {+ defer opts.DeleteConnectionID()+ }+ }++ if isPlsql {+ // USE SET SESSION ROLE to set the role for the current session.+ if err := crdb.Execute(func() error {+ _, err := conn.ExecContext(ctx, fmt.Sprintf("SET SESSION ROLE '%s'", owner))+ return err+ }); err != nil {+ return 0, errors.Wrapf(err, "failed to set role to database owner %q", owner)+ }+ opts.LogCommandExecute([]int32{0})+ if err := crdb.Execute(func() error {+ _, err := conn.ExecContext(ctx, statement)+ return err+ }); err != nil {+ return 0, err+ }+ opts.LogCommandResponse([]int32{0}, 0, []int32{0}, "")+ return 0, nil+ }++ // USE SET SESSION ROLE to set the role for the current session.+ if err := crdb.Execute(func() error {+ _, err := conn.ExecContext(ctx, fmt.Sprintf("SET SESSION ROLE '%s'", owner))+ return err+ }); err != nil {+ return 0, errors.Wrapf(err, "failed to set role to database owner %q", owner)+ }++ totalRowsAffected := int64(0)+ // Execute all statements individually in auto-commit mode+ for i, stmt := range nonTransactionAndSetRoleStmts {+ indexes := []int32{nonTransactionAndSetRoleStmtsIndex[i]}+ opts.LogCommandExecute(indexes)++ if err := crdb.Execute(func() error {+ sqlResult, err := conn.ExecContext(ctx, stmt)+ if err != nil {+ opts.LogCommandResponse(indexes, 0, []int32{0}, err.Error())+ return err+ }++ rowsAffected, err := sqlResult.RowsAffected()+ if err != nil {+ // CockroachDB returns error for statements that don't support RowsAffected+ rowsAffected = 0+ }++ opts.LogCommandResponse(indexes, int32(rowsAffected), []int32{int32(rowsAffected)}, "")+ totalRowsAffected += rowsAffected+ return nil+ }); err != nil {+ return totalRowsAffected, err+ }+ }++ return totalRowsAffected, nil+}+func (d *Driver) createDatabaseExecute(ctx context.Context, statement string) error {databaseName, err := getDatabaseInCreateDatabaseStatement(statement)if err != nil {diff --git a/backend/plugin/db/obo/obo.go b/backend/plugin/db/obo/obo.goindex 03aeeba5bd..73604214fc 100644--- a/backend/plugin/db/obo/obo.go+++ b/backend/plugin/db/obo/obo.go@@ -15,6 +15,7 @@ import ("golang.org/x/exp/slog""google.golang.org/protobuf/types/known/durationpb"+ "github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"@@ -83,6 +84,15 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOreturn 0, errors.New("create database is not supported for OceanBase Oracle mode")}+ // Parse transaction mode from the script+ transactionMode, cleanedStatement := base.ParseTransactionMode(statement)+ statement = cleanedStatement++ // Apply default when transaction mode is not specified+ if transactionMode == common.TransactionModeUnspecified {+ transactionMode = common.GetDefaultTransactionMode()+ }+// Use Oracle sql parser.singleSQLs, err := plsqlparser.SplitSQL(statement)if err != nil {@@ -93,21 +103,46 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOreturn 0, nil}+ // Execute based on transaction mode+ if transactionMode == common.TransactionModeOff {+ return d.executeInAutoCommitMode(ctx, singleSQLs, opts)+ }+ return d.executeInTransactionMode(ctx, singleSQLs, opts)+}++func (d *Driver) executeInTransactionMode(ctx context.Context, singleSQLs []base.SingleSQL, opts db.ExecuteOptions) (int64, error) {conn, err := d.db.Conn(ctx)if err != nil {return 0, errors.Wrapf(err, "failed to get connection")}defer conn.Close()+tx, err := conn.BeginTx(ctx, nil)if err != nil {+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error())return 0, errors.Wrapf(err, "failed to begin transaction")}- defer tx.Rollback()+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "")++ committed := false+ defer func() {+ if !committed {+ err := tx.Rollback()+ 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)+ }+ }()totalRowsAffected := int64(0)- for _, singleSQL := range singleSQLs {+ for i, singleSQL := range singleSQLs {+ opts.LogCommandExecute([]int32{int32(i)})sqlResult, err := tx.ExecContext(ctx, singleSQL.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: singleSQL.Start,@@ -119,12 +154,46 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO// 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, errors.Wrapf(err, "failed to commit transaction")}+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, "")+ committed = true+ return totalRowsAffected, nil+}++func (d *Driver) executeInAutoCommitMode(ctx context.Context, singleSQLs []base.SingleSQL, opts db.ExecuteOptions) (int64, error) {+ conn, err := d.db.Conn(ctx)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to get connection")+ }+ defer conn.Close()++ totalRowsAffected := int64(0)+ for i, singleSQL := range singleSQLs {+ opts.LogCommandExecute([]int32{int32(i)})+ sqlResult, err := conn.ExecContext(ctx, singleSQL.Text)+ if err != nil {+ opts.LogCommandResponse([]int32{int32(i)}, 0, nil, err.Error())+ return totalRowsAffected, &db.ErrorWithPosition{+ Err: errors.Wrapf(err, "failed to execute context in auto-commit mode"),+ Start: singleSQL.Start,+ End: singleSQL.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}diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.goindex 66ea9a34c6..f5ed0486f2 100644--- a/backend/plugin/db/pg/pg.go+++ b/backend/plugin/db/pg/pg.go@@ -423,18 +423,13 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOcommands, originalIndex = tmpCommands, tmpOriginalIndex}- // For auto-commit mode, treat all statements as non-transactional+ // Execute based on transaction mode+ var affectedRows int64if transactionMode == common.TransactionModeOff {- // Move all commands to non-transaction list for auto-commit execution- for i, command := range commands {- nonTransactionAndSetRoleStmts = append(nonTransactionAndSetRoleStmts, command.Text)- nonTransactionAndSetRoleStmtsIndex = append(nonTransactionAndSetRoleStmtsIndex, originalIndex[i])- }- commands = nil- originalIndex = nil+ affectedRows, err = d.executeInAutoCommitMode(ctx, owner, statement, commands, originalIndex, nonTransactionAndSetRoleStmts, nonTransactionAndSetRoleStmtsIndex, opts, isPlsql)+ } else {+ affectedRows, err = d.executeInTransactionMode(ctx, owner, statement, commands, originalIndex, nonTransactionAndSetRoleStmts, nonTransactionAndSetRoleStmtsIndex, opts, isPlsql)}-- affectedRows, err := d.tryExecute(ctx, owner, statement, commands, originalIndex, nonTransactionAndSetRoleStmts, nonTransactionAndSetRoleStmtsIndex, opts, isPlsql)if err == nil {return affectedRows, nil}@@ -453,7 +448,11 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOopts.LogRetryInfo(err, i+1)// Do retry.- affectedRows, err = d.tryExecute(ctx, owner, statement, commands, originalIndex, nonTransactionAndSetRoleStmts, nonTransactionAndSetRoleStmtsIndex, opts, isPlsql)+ if transactionMode == common.TransactionModeOff {+ affectedRows, err = d.executeInAutoCommitMode(ctx, owner, statement, commands, originalIndex, nonTransactionAndSetRoleStmts, nonTransactionAndSetRoleStmtsIndex, opts, isPlsql)+ } else {+ affectedRows, err = d.executeInTransactionMode(ctx, owner, statement, commands, originalIndex, nonTransactionAndSetRoleStmts, nonTransactionAndSetRoleStmtsIndex, opts, isPlsql)+ }if err == nil {break}@@ -477,7 +476,7 @@ func isLockTimeoutError(message string) bool {return strings.Contains(message, "canceling statement due to lock timeout")}-func (d *Driver) tryExecute(+func (d *Driver) executeInTransactionMode(ctx context.Context,owner string,statement string,@@ -539,13 +538,13 @@ func (d *Driver) tryExecute(committed := falsedefer func() {- err := tx.Rollback(ctx)+ rollbackErr := tx.Rollback(ctx)if committed {return}var rerr string- if err != nil {- rerr = err.Error()+ if rollbackErr != nil {+ rerr = rollbackErr.Error()}opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, rerr)}()@@ -623,6 +622,94 @@ func (d *Driver) tryExecute(return totalRowsAffected, nil}+func (d *Driver) executeInAutoCommitMode(+ ctx context.Context,+ owner string,+ statement string,+ commands []base.SingleSQL,+ originalIndex []int32,+ nonTransactionAndSetRoleStmts []string,+ nonTransactionAndSetRoleStmtsIndex []int32,+ opts db.ExecuteOptions,+ isPlsql bool,+) (int64, error) {+ // For auto-commit mode, treat all statements as non-transactional+ for i, command := range commands {+ nonTransactionAndSetRoleStmts = append(nonTransactionAndSetRoleStmts, command.Text)+ nonTransactionAndSetRoleStmtsIndex = append(nonTransactionAndSetRoleStmtsIndex, originalIndex[i])+ }++ conn, err := d.db.Conn(ctx)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to get connection")+ }+ defer conn.Close()++ if opts.SetConnectionID != nil {+ var pid string+ if err := conn.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil {+ return 0, errors.Wrapf(err, "failed to get connection id")+ }+ opts.SetConnectionID(pid)++ if opts.DeleteConnectionID != nil {+ defer opts.DeleteConnectionID()+ }+ }++ if isPlsql {+ if d.connectionCtx.UseDatabaseOwner {+ // USE SET SESSION ROLE to set the role for the current session.+ if _, err := conn.ExecContext(ctx, fmt.Sprintf("SET SESSION ROLE '%s'", owner)); err != nil {+ return 0, errors.Wrapf(err, "failed to set role to database owner %q", owner)+ }+ }+ opts.LogCommandExecute([]int32{0})+ if _, err := conn.ExecContext(ctx, statement); err != nil {+ opts.LogCommandResponse([]int32{0}, 0, []int32{0}, err.Error())+ return 0, err+ }+ opts.LogCommandResponse([]int32{0}, 0, []int32{0}, "")+ return 0, nil+ }++ if d.connectionCtx.UseDatabaseOwner {+ // USE SET SESSION ROLE to set the role for the current session.+ if _, err := conn.ExecContext(ctx, fmt.Sprintf("SET SESSION ROLE '%s'", owner)); err != nil {+ return 0, errors.Wrapf(err, "failed to set role to database owner %q", owner)+ }+ }++ totalRowsAffected := int64(0)+ // Execute all statements individually in auto-commit mode+ for i, stmt := range nonTransactionAndSetRoleStmts {+ indexes := []int32{nonTransactionAndSetRoleStmtsIndex[i]}+ opts.LogCommandExecute(indexes)++ sqlResult, err := conn.ExecContext(ctx, stmt)+ if err != nil {+ opts.LogCommandResponse(indexes, 0, []int32{0}, err.Error())+ if isLockTimeoutError(err.Error()) {+ return totalRowsAffected, &LockTimeoutError{+ Message: err.Error(),+ }+ }+ return totalRowsAffected, err+ }++ rowsAffected, err := sqlResult.RowsAffected()+ if err != nil {+ // PostgreSQL returns error for statements that don't support RowsAffected+ rowsAffected = 0+ }++ opts.LogCommandResponse(indexes, int32(rowsAffected), []int32{int32(rowsAffected)}, "")+ totalRowsAffected += rowsAffected+ }++ return totalRowsAffected, nil+}+func (d *Driver) createDatabaseExecute(ctx context.Context, statement string) error {databaseName, err := getDatabaseInCreateDatabaseStatement(statement)if err != nil {diff --git a/backend/plugin/db/risingwave/risingwave.go b/backend/plugin/db/risingwave/risingwave.goindex 6b4790fbd5..7292a4066c 100644--- a/backend/plugin/db/risingwave/risingwave.go+++ b/backend/plugin/db/risingwave/risingwave.go@@ -230,57 +230,89 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO},}}- totalRowsAffected := int64(0)- if len(commands) != 0 {- // For auto-commit mode (TransactionModeOff), execute each statement individually without transactions- if transactionMode == common.TransactionModeOff {- for _, command := range commands {- sqlResult, err := d.db.ExecContext(ctx, command.Text)- if err != nil {- return totalRowsAffected, &db.ErrorWithPosition{- Err: errors.Wrapf(err, "failed to execute context in auto-commit mode"),- 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- }- } else {- // For transactional mode (TransactionModeOn), wrap all statements in a single transaction- tx, err := d.db.BeginTx(ctx, nil)- if err != nil {- return 0, err- }- defer tx.Rollback()+ // Execute based on transaction mode+ if transactionMode == common.TransactionModeOff {+ return d.executeInAutoCommitMode(ctx, commands, opts)+ }+ return d.executeInTransactionMode(ctx, commands, opts)+}- 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+func (d *Driver) executeInTransactionMode(ctx context.Context, commands []base.SingleSQL, opts db.ExecuteOptions) (int64, error) {+ 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() {+ if !committed {+ err := tx.Rollback()+ 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)+ }+ }()- if err := tx.Commit(); err != nil {- return 0, err+ totalRowsAffected := int64(0)+ 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+}++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())+ return totalRowsAffected, &db.ErrorWithPosition{+ Err: errors.Wrapf(err, "failed to execute context in auto-commit mode"),+ 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}diff --git a/backend/plugin/db/snowflake/snowflake.go b/backend/plugin/db/snowflake/snowflake.goindex cdd63123c3..c705ba67ec 100644--- a/backend/plugin/db/snowflake/snowflake.go+++ b/backend/plugin/db/snowflake/snowflake.go@@ -271,8 +271,13 @@ func (d *Driver) executeInTransactionMode(ctx context.Context, statement string,if err != nil {return 0, err}++ // Log the entire multi-statement execution+ opts.LogCommandExecute([]int32{0})+result, err := tx.ExecContext(mctx, statement)if err != nil {+ opts.LogCommandResponse([]int32{0}, 0, nil, err.Error())return 0, err}@@ -287,13 +292,15 @@ func (d *Driver) executeInTransactionMode(ctx context.Context, statement string,// Since we cannot differentiate DDL and DML yet, we have to ignore the error.if err != nil {slog.Debug("rowsAffected returns error", log.BBError(err))+ opts.LogCommandResponse([]int32{0}, 0, nil, "")return 0, nil}+ opts.LogCommandResponse([]int32{0}, int32(rowsAffected), nil, "")return rowsAffected, nil}// executeInAutoCommitMode executes statements with autocommit enabled (no explicit transaction)-func (d *Driver) executeInAutoCommitMode(ctx context.Context, statement string, _ db.ExecuteOptions) (int64, error) {+func (d *Driver) executeInAutoCommitMode(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {// To submit a variable number of SQL statements in the statement field, set MULTI_STATEMENT_COUNT to 0."// https://docs.snowflake.com/en/developer-guide/sql-api/submitting-multiple-statementsmctx, err := snow.WithMultiStatement(ctx, 0 /* MULTI_STATEMENT_COUNT */)@@ -301,8 +308,12 @@ func (d *Driver) executeInAutoCommitMode(ctx context.Context, statement string,return 0, err}+ // Log the entire multi-statement execution+ opts.LogCommandExecute([]int32{0})+result, err := d.db.ExecContext(mctx, statement)if err != nil {+ opts.LogCommandResponse([]int32{0}, 0, nil, err.Error())return 0, err}@@ -310,8 +321,10 @@ func (d *Driver) executeInAutoCommitMode(ctx context.Context, statement string,// Since we cannot differentiate DDL and DML yet, we have to ignore the error.if err != nil {slog.Debug("rowsAffected returns error", log.BBError(err))+ opts.LogCommandResponse([]int32{0}, 0, nil, "")return 0, nil}+ opts.LogCommandResponse([]int32{0}, int32(rowsAffected), nil, "")return rowsAffected, nil}diff --git a/backend/plugin/db/spanner/spanner.go b/backend/plugin/db/spanner/spanner.goindex 00d831a17c..41e1855c69 100644--- a/backend/plugin/db/spanner/spanner.go+++ b/backend/plugin/db/spanner/spanner.go@@ -145,7 +145,6 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOtransactionMode = common.GetDefaultTransactionMode()}- var rowCount int64stmts, err := util.SanitizeSQL(statement)if err != nil {return 0, err@@ -163,31 +162,34 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO// Spanner DDL is always non-transactionalif ddl {- op, err := d.dbClient.UpdateDatabaseDdl(ctx, &databasepb.UpdateDatabaseDdlRequest{- Database: getDSN(d.config.DataSource.Host, d.databaseName),- Statements: stmts,- })- if err != nil {- return 0, err- }- return 0, op.Wait(ctx)+ return d.executeDDL(ctx, stmts, opts)}- // For DML statements, respect transaction mode+ // Execute based on transaction modeif transactionMode == common.TransactionModeOff {- // Execute statements individually in auto-commit mode- for _, stmt := range stmts {- spannerStmt := spanner.NewStatement(stmt)- count, err := d.client.PartitionedUpdate(ctx, spannerStmt)- if err != nil {- return rowCount, err- }- rowCount += count- }- return rowCount, nil+ return d.executeInAutoCommitMode(ctx, stmts, opts)+ }+ return d.executeInTransactionMode(ctx, stmts, opts)+}++func (d *Driver) executeDDL(ctx context.Context, stmts []string, _ db.ExecuteOptions) (int64, error) {+ op, err := d.dbClient.UpdateDatabaseDdl(ctx, &databasepb.UpdateDatabaseDdlRequest{+ Database: getDSN(d.config.DataSource.Host, d.databaseName),+ Statements: stmts,+ })+ if err != nil {+ return 0, err}+ return 0, op.Wait(ctx)+}++func (d *Driver) executeInTransactionMode(ctx context.Context, stmts []string, opts db.ExecuteOptions) (int64, error) {+ var rowCount int64++ // Log transaction start+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "")- // Default behavior: execute DML in a transaction+ committed := falseif _, err := d.client.ReadWriteTransaction(ctx, func(ctx context.Context, rwt *spanner.ReadWriteTransaction) error {spannerStmts := []spanner.Statement{}for _, stmt := range stmts {@@ -200,10 +202,30 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOfor _, count := range counts {rowCount += count}+ committed = truereturn nil}); err != nil {+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, "")return 0, err}++ if committed {+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, "")+ }+ return rowCount, nil+}++func (d *Driver) executeInAutoCommitMode(ctx context.Context, stmts []string, _ db.ExecuteOptions) (int64, error) {+ var rowCount int64+ // Execute statements individually in auto-commit mode+ for _, stmt := range stmts {+ spannerStmt := spanner.NewStatement(stmt)+ count, err := d.client.PartitionedUpdate(ctx, spannerStmt)+ if err != nil {+ return rowCount, err+ }+ rowCount += count+ }return rowCount, nil}diff --git a/backend/plugin/db/starrocks/starrocks.go b/backend/plugin/db/starrocks/starrocks.goindex aeb87bb5d6..2ef8bd2eee 100644--- a/backend/plugin/db/starrocks/starrocks.go+++ b/backend/plugin/db/starrocks/starrocks.go@@ -153,7 +153,7 @@ func parseVersion(version string) (string, string, error) {}// Execute executes a SQL statement.-func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOptions) (int64, error) {+func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {// Parse transaction mode from the scripttransactionMode, cleanedStatement := base.ParseTransactionMode(statement)statement = cleanedStatement@@ -167,6 +167,17 @@ func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOptiif err != nil {return 0, errors.Wrapf(err, "failed to deal with delimiter")}+ // Execute based on transaction mode+ // Note: StarRocks is an OLAP database with limited transaction support.+ // For DDL operations, transactions are not supported. For DML operations,+ // StarRocks supports transactions within certain limitations.+ if transactionMode == common.TransactionModeOff {+ return d.executeInAutoCommitMode(ctx, statement)+ }+ return d.executeInTransactionMode(ctx, statement, opts)+}++func (d *Driver) executeInTransactionMode(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {conn, err := d.db.Conn(ctx)if err != nil {return 0, err@@ -179,36 +190,25 @@ func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOpti}slog.Debug("connectionID", slog.String("connectionID", connectionID))- // Execute based on transaction mode- // Note: StarRocks is an OLAP database with limited transaction support.- // For DDL operations, transactions are not supported. For DML operations,- // StarRocks supports transactions within certain limitations.- if transactionMode == common.TransactionModeOff {- // Execute in auto-commit mode- sqlResult, err := conn.ExecContext(ctx, statement)- if err != nil {- if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {- slog.Info("cancel connection", slog.String("connectionID", connectionID))- if err := d.StopConnectionByID(connectionID); err != nil {- slog.Error("failed to cancel connection", slog.String("connectionID", connectionID), log.BBError(err))- }- }- return 0, err- }- 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))- }- return rowsAffected, nil- }-- // Execute in transaction modetx, err := conn.BeginTx(ctx, nil)if err != nil {+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error())return 0, errors.Wrapf(err, "failed to begin execute transaction")}- defer tx.Rollback()+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "")++ committed := false+ defer func() {+ if !committed {+ err := tx.Rollback()+ 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)+ }+ }()sqlResult, err := tx.ExecContext(ctx, statement)if err != nil {@@ -218,18 +218,54 @@ func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOptislog.Error("failed to cancel connection", slog.String("connectionID", connectionID), log.BBError(err))}}-return 0, err}+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))}+if err := tx.Commit(); err != nil {+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, err.Error())return 0, errors.Wrapf(err, "failed to commit execute transaction")}+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, "")+ committed = true+ return rowsAffected, nil+}++func (d *Driver) executeInAutoCommitMode(ctx context.Context, statement string) (int64, error) {+ conn, err := d.db.Conn(ctx)+ if err != nil {+ return 0, err+ }+ defer conn.Close()++ connectionID, err := getConnectionID(ctx, conn)+ if err != nil {+ return 0, err+ }+ slog.Debug("connectionID", slog.String("connectionID", connectionID))+ // Execute in auto-commit mode+ sqlResult, err := conn.ExecContext(ctx, statement)+ if err != nil {+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {+ slog.Info("cancel connection", slog.String("connectionID", connectionID))+ if err := d.StopConnectionByID(connectionID); err != nil {+ slog.Error("failed to cancel connection", slog.String("connectionID", connectionID), log.BBError(err))+ }+ }+ return 0, err+ }++ 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))+ }return rowsAffected, nil}diff --git a/backend/plugin/db/tidb/tidb.go b/backend/plugin/db/tidb/tidb.goindex 47186afeac..321d13d879 100644--- a/backend/plugin/db/tidb/tidb.go+++ b/backend/plugin/db/tidb/tidb.go@@ -298,6 +298,7 @@ func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, c}if err := tx.Commit(); err != nil {+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, err.Error())return errors.Wrapf(err, "failed to commit execute transaction")} else {opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, "")diff --git a/transaction_pattern_analysis.md b/transaction_pattern_analysis.mdnew file mode 100644index 0000000000..af79d1163e--- /dev/null+++ b/transaction_pattern_analysis.md@@ -0,0 +1,72 @@+# Transaction Pattern Analysis for Database Engines++## Engines Using Two-Function Pattern (executeInTransactionMode/executeInAutoCommitMode)+These engines have already been refactored to use the consistent pattern:++1. **ClickHouse** - `/backend/plugin/db/clickhouse/clickhouse.go`+2. **DM** - `/backend/plugin/db/dm/dm.go`+3. **MySQL** - `/backend/plugin/db/mysql/mysql.go`+4. **MSSQL** - `/backend/plugin/db/mssql/mssql.go`+5. **Oracle** - `/backend/plugin/db/oracle/oracle.go`+6. **Redshift** - `/backend/plugin/db/redshift/redshift.go`+7. **Snowflake** - `/backend/plugin/db/snowflake/snowflake.go`+8. **TiDB** - `/backend/plugin/db/tidb/tidb.go`++## Engines Using If-Else Pattern (Need Refactoring)+These engines still use the old if-else pattern and need to be refactored:++1. **CockroachDB** - `/backend/plugin/db/cockroachdb/cockroachdb.go`+2. **Databricks** - `/backend/plugin/db/databricks/databricks.go`+3. **PostgreSQL** - `/backend/plugin/db/pg/pg.go`+4. **RisingWave** - `/backend/plugin/db/risingwave/risingwave.go`+5. **Spanner** - `/backend/plugin/db/spanner/spanner.go`+6. **StarRocks** - `/backend/plugin/db/starrocks/starrocks.go`++## Engines Without Transaction Mode Handling+These engines don't implement transaction mode handling (might not need it):++1. **BigQuery** - No transaction mode pattern found+2. **Cassandra** - No transaction mode pattern found+3. **CosmosDB** - No transaction mode pattern found+4. **Hive** - No transaction mode pattern found (explicitly notes transactions not supported)+5. **OceanBase (OBO)** - No transaction mode pattern found+6. **SQLite** - No transaction mode pattern found+7. **Trino** - No transaction mode pattern found++## Missing LogTransactionControl Calls++### Engines with Transactions but NO LogTransactionControl:+1. **StarRocks** - Has Begin/Commit/Rollback but no transaction logging+2. **RisingWave** - Has Begin/Commit/Rollback but no transaction logging+3. **OceanBase (OBO)** - Has Begin/Commit/Rollback in obo.go but no transaction logging++### Engines with Proper LogTransactionControl:+1. **ClickHouse** - Has logging (but uses old API format)+2. **CockroachDB** - Has proper logging+3. **DM** - Has proper logging+4. **MSSQL** - Has proper logging+5. **MySQL** - Has proper logging+6. **Oracle** - Has proper logging+7. **PostgreSQL** - Has proper logging+8. **Redshift** - Has proper logging+9. **Snowflake** - Has proper logging+10. **TiDB** - Has proper logging++## Action Items++### High Priority (Refactor to Two-Function Pattern):+1. CockroachDB+2. PostgreSQL+3. RisingWave+4. StarRocks+5. Spanner+6. Databricks++### Add Missing LogTransactionControl:+1. StarRocks+2. RisingWave+3. OceanBase (OBO)++### Fix ClickHouse LogTransactionControl:+- ClickHouse uses old API format: `opts.LogTransactionControl("BEGIN")`+- Should be: `opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "")`\ No newline at end of file