Skip to content

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

feat(db): unify transaction mode parsing across Hive, ClickHouse, Trino (#16891)

h3n4le94a623abc7a
diff --git a/backend/common/testcontainer/testcontainer.go b/backend/common/testcontainer/testcontainer.go
index 2dc64d3b6d..f33a0f1188 100644
--- a/backend/common/testcontainer/testcontainer.go
+++ b/backend/common/testcontainer/testcontainer.go
@@ -49,8 +49,8 @@ func (c *Container) Close(ctx context.Context) {
}
}
-// GetMySQLContainer creates a MySQL container for testing
-func GetMySQLContainer(ctx context.Context) (retc *Container, retErr error) {
+// GetTestMySQLContainer creates a MySQL container for testing
+func GetTestMySQLContainer(ctx context.Context) (retc *Container, retErr error) {
req := testcontainers.ContainerRequest{
Image: "mysql:8.0.33",
Env: map[string]string{
diff --git a/backend/plugin/db/bigquery/bigquery.go b/backend/plugin/db/bigquery/bigquery.go
index 2a5e6cb9ec..2d8b093f18 100644
--- a/backend/plugin/db/bigquery/bigquery.go
+++ b/backend/plugin/db/bigquery/bigquery.go
@@ -21,6 +21,7 @@ import (
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/db/util"
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
)
var (
@@ -88,6 +89,25 @@ func (*Driver) GetDB() *sql.DB {
// Execute executes a SQL statement.
func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOptions) (int64, error) {
+ // 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()
+ }
+
+ // BigQuery doesn't support traditional transactions for DDL operations.
+ // DML operations in BigQuery are automatically atomic at the statement level.
+ // Multi-statement transactions are supported via scripting with BEGIN/COMMIT,
+ // but here we execute statements individually regardless of transaction mode.
+ //
+ // Note: When transactionMode is "on", BigQuery will still execute each statement
+ // atomically, but won't wrap multiple statements in a single transaction.
+ // This is a limitation of BigQuery's architecture.
+ _ = transactionMode // Transaction mode is parsed but not used due to BigQuery limitations
+
q := d.client.Query(statement)
q.DefaultDatasetID = d.databaseName
job, err := q.Run(ctx)
diff --git a/backend/plugin/db/clickhouse/clickhouse.go b/backend/plugin/db/clickhouse/clickhouse.go
index ac070da08a..317039262a 100644
--- a/backend/plugin/db/clickhouse/clickhouse.go
+++ b/backend/plugin/db/clickhouse/clickhouse.go
@@ -123,6 +123,15 @@ 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) {
+ // 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()
+ }
+
singleSQLs, err := standard.SplitSQL(statement)
if err != nil {
return 0, err
@@ -132,6 +141,29 @@ func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOpti
return 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
+ if 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
+ }
+
+ // Transaction mode execution (default behavior)
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
return 0, err
diff --git a/backend/plugin/db/cockroachdb/cockroachdb.go b/backend/plugin/db/cockroachdb/cockroachdb.go
index 1e21cfd8dd..a08bd7839f 100644
--- a/backend/plugin/db/cockroachdb/cockroachdb.go
+++ b/backend/plugin/db/cockroachdb/cockroachdb.go
@@ -250,6 +250,15 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return 0, nil
}
+ // 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()
+ }
+
owner, err := d.GetCurrentDatabaseOwner(ctx)
if err != nil {
return 0, err
@@ -303,6 +312,17 @@ 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
+ if 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
+ }
+
conn, err := d.db.Conn(ctx)
if err != nil {
return 0, errors.Wrapf(err, "failed to get connection")
diff --git a/backend/plugin/db/databricks/databricks.go b/backend/plugin/db/databricks/databricks.go
index 1daf8b5f1a..0b46d75170 100644
--- a/backend/plugin/db/databricks/databricks.go
+++ b/backend/plugin/db/databricks/databricks.go
@@ -14,6 +14,7 @@ import (
// Databricks SQL.
dbsql "github.com/databricks/databricks-sdk-go/service/sql"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
@@ -121,7 +122,36 @@ func (d *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement string, _
}
func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOptions) (int64, error) {
- // No ways of fetching affected rows.
+ // 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()
+ }
+
+ // Databricks has different transaction support based on the target:
+ // - SQL Warehouses: Limited transaction support, primarily for Delta tables
+ // - Unity Catalog: Better transaction support with ACID properties for Delta tables
+ // Since Databricks SQL API doesn't expose direct transaction control (BEGIN/COMMIT/ROLLBACK),
+ // and most DDL operations are auto-committed, we handle this at the statement execution level.
+
+ // For transaction mode "off" or when dealing with non-transactional operations,
+ // we execute statements in auto-commit mode (default behavior).
+ // For transaction mode "on", we note that Databricks will handle transactionality
+ // at the operation level for supported operations (e.g., Delta table operations).
+
+ if transactionMode == common.TransactionModeOff {
+ // Execute in auto-commit mode (default Databricks behavior)
+ _, err := d.QueryConn(ctx, nil, statement, db.QueryContext{})
+ return 0, err
+ }
+
+ // Transaction mode "on": Execute with implicit transaction support
+ // Note: Databricks SQL Warehouses don't support explicit transaction control via the REST API.
+ // Transactions are handled implicitly for supported operations (e.g., Delta table DML).
+ // DDL operations are always auto-committed.
_, err := d.QueryConn(ctx, nil, statement, db.QueryContext{})
return 0, err
}
diff --git a/backend/plugin/db/dm/dm.go b/backend/plugin/db/dm/dm.go
index 7ce358ada3..abeb5b8f00 100644
--- a/backend/plugin/db/dm/dm.go
+++ b/backend/plugin/db/dm/dm.go
@@ -15,6 +15,7 @@ import (
"github.com/pkg/errors"
"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"
@@ -81,6 +82,15 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return 0, errors.New("create database is not supported for DM")
}
+ // 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 {
@@ -96,16 +106,42 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return 0, errors.Wrapf(err, "failed to get connection")
}
defer conn.Close()
+
+ // Execute based on transaction mode
+ if transactionMode == common.TransactionModeOff {
+ return d.executeInAutoCommitMode(ctx, conn, singleSQLs, opts)
+ }
+ return d.executeInTransactionMode(ctx, conn, singleSQLs, opts)
+}
+
+// executeInTransactionMode executes statements within a single transaction
+func (*Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, singleSQLs []base.SingleSQL, opts db.ExecuteOptions) (int64, error) {
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 {
+ if rollbackErr := tx.Rollback(); rollbackErr != nil {
+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, rollbackErr.Error())
+ } else {
+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, "")
+ }
+ }
+ }()
totalRowsAffected := int64(0)
- for _, singleSQL := range singleSQLs {
+ for i, singleSQL := range singleSQLs {
+ indexes := []int32{int32(i)}
+ opts.LogCommandExecute(indexes)
+
sqlResult, err := tx.ExecContext(ctx, singleSQL.Text)
if err != nil {
+ opts.LogCommandResponse(indexes, 0, nil, err.Error())
return 0, &db.ErrorWithPosition{
Err: errors.Wrapf(err, "failed to execute context in a transaction"),
Start: singleSQL.Start,
@@ -118,11 +154,42 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
slog.Debug("rowsAffected returns error", log.BBError(err))
}
totalRowsAffected += rowsAffected
+ opts.LogCommandResponse(indexes, int32(rowsAffected), []int32{int32(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
+}
+
+// executeInAutoCommitMode executes statements sequentially in auto-commit mode
+func (*Driver) executeInAutoCommitMode(ctx context.Context, conn *sql.Conn, singleSQLs []base.SingleSQL, opts db.ExecuteOptions) (int64, error) {
+ totalRowsAffected := int64(0)
+ for i, singleSQL := range singleSQLs {
+ indexes := []int32{int32(i)}
+ opts.LogCommandExecute(indexes)
+
+ sqlResult, err := conn.ExecContext(ctx, singleSQL.Text)
+ if err != nil {
+ opts.LogCommandResponse(indexes, 0, nil, err.Error())
+ return 0, &db.ErrorWithPosition{
+ Err: errors.Wrapf(err, "failed to execute context"),
+ 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))
+ }
+ totalRowsAffected += rowsAffected
+ opts.LogCommandResponse(indexes, int32(rowsAffected), []int32{int32(rowsAffected)}, "")
+ }
return totalRowsAffected, nil
}
diff --git a/backend/plugin/db/hive/hive.go b/backend/plugin/db/hive/hive.go
index 316a8658a9..63853a1948 100644
--- a/backend/plugin/db/hive/hive.go
+++ b/backend/plugin/db/hive/hive.go
@@ -110,6 +110,27 @@ func (*Driver) GetDB() *sql.DB {
// Even in Hive's bucketed transaction table, all the statements are committed automatically by
// the Hive server.
func (d *Driver) Execute(ctx context.Context, statementsStr string, _ db.ExecuteOptions) (int64, error) {
+ // Parse transaction mode from the script
+ transactionMode, cleanedStatement := base.ParseTransactionMode(statementsStr)
+ statementsStr = cleanedStatement
+
+ // Apply default when transaction mode is not specified
+ if transactionMode == common.TransactionModeUnspecified {
+ transactionMode = common.GetDefaultTransactionMode()
+ }
+
+ // Note: We parse transactionMode but don't use it for execution since Hive
+ // has very limited transaction support. The variable assignment is kept for consistency
+ // with other database drivers and potential future use.
+ _ = transactionMode
+
+ // Hive has limited transaction support:
+ // - Only ACID tables support transactions, and even then it's limited
+ // - Transaction statements (BEGIN, COMMIT, ROLLBACK) are not supported in Hive 4.0
+ // - All statements are auto-committed by the Hive server
+ // Due to these limitations, we execute statements individually regardless of transaction mode
+ // but we still parse and respect the transaction mode directive for consistency
+
var affectedRows int64
cursor := d.conn.Cursor()
diff --git a/backend/plugin/db/mssql/mssql.go b/backend/plugin/db/mssql/mssql.go
index 9930209508..51caea0534 100644
--- a/backend/plugin/db/mssql/mssql.go
+++ b/backend/plugin/db/mssql/mssql.go
@@ -23,6 +23,7 @@ import (
"github.com/pkg/errors"
"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"
@@ -163,6 +164,25 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
}
return 0, nil
}
+
+ // 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()
+ }
+
+ // Execute based on transaction mode
+ if transactionMode == common.TransactionModeOff {
+ return d.executeInAutoCommitMode(ctx, statement, opts)
+ }
+ return d.executeInTransactionMode(ctx, statement, opts)
+}
+
+// executeInTransactionMode executes statements within a single transaction
+func (d *Driver) executeInTransactionMode(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error())
@@ -242,6 +262,77 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return totalAffectRows, nil
}
+// executeInAutoCommitMode executes statements sequentially in auto-commit mode
+func (d *Driver) executeInAutoCommitMode(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {
+ totalAffectRows := int64(0)
+
+ batch := tsqlbatch.NewBatcher(statement)
+
+ for idx := 0; ; {
+ command, err := batch.Next()
+ if err != nil {
+ if err == io.EOF {
+ // Try send the last batch to server.
+ v := batch.Batch()
+ if v != nil && len(v.Text) > 0 {
+ indexes := []int32{int32(idx)}
+ opts.LogCommandExecute(indexes)
+ rowsAffected, err := d.executeAutoCommit(ctx, v.Text)
+ if err != nil {
+ opts.LogCommandResponse(indexes, 0, nil, err.Error())
+ return totalAffectRows, err
+ }
+ opts.LogCommandResponse(indexes, int32(rowsAffected), []int32{int32(rowsAffected)}, "")
+ totalAffectRows += rowsAffected
+ }
+ break
+ }
+ return 0, errors.Wrapf(err, "failed to get next batch for statement: %s", batch.Batch().Text)
+ }
+ if command == nil {
+ continue
+ }
+ switch v := command.(type) {
+ case *tsqlbatch.GoCommand:
+ b := batch.Batch()
+ // Execute the batch in auto-commit mode
+ indexes := []int32{int32(idx)}
+ idx++
+ for i := uint(0); i < v.Count; i++ {
+ opts.LogCommandExecute(indexes)
+ rowsAffected, err := d.executeAutoCommit(ctx, b.Text)
+ if err != nil {
+ opts.LogCommandResponse(indexes, 0, nil, err.Error())
+ // In auto-commit mode, we stop at the first error
+ return totalAffectRows, err
+ }
+ opts.LogCommandResponse(indexes, int32(rowsAffected), []int32{int32(rowsAffected)}, "")
+ totalAffectRows += rowsAffected
+ }
+ default:
+ return 0, errors.Errorf("unsupported command type: %T", v)
+ }
+ batch.Reset(nil)
+ }
+
+ return totalAffectRows, nil
+}
+
+// executeAutoCommit executes a single statement in auto-commit mode
+func (d *Driver) executeAutoCommit(ctx context.Context, statement string) (int64, error) {
+ sqlResult, err := d.db.ExecContext(ctx, statement)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to execute statement in auto-commit mode")
+ }
+ 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 in auto-commit mode", log.BBError(err))
+ return 0, nil
+ }
+ return rowsAffected, nil
+}
+
func execute(ctx context.Context, txn *sql.Tx, statement string) (int64, error) {
sqlResult, err := txn.ExecContext(ctx, statement)
var e gomssqldb.Error
diff --git a/backend/plugin/db/mysql/mysql.go b/backend/plugin/db/mysql/mysql.go
index 8f37fb67b7..04a911b319 100644
--- a/backend/plugin/db/mysql/mysql.go
+++ b/backend/plugin/db/mysql/mysql.go
@@ -259,6 +259,15 @@ func parseVersion(version string) (string, string, error) {
// Execute executes a SQL statement.
func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {
+ // 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()
+ }
+
statement, err := mysqlparser.DealWithDelimiter(statement)
if err != nil {
return 0, errors.Wrapf(err, "failed to deal with delimiter")
@@ -304,6 +313,15 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
originalIndex = []int32{0}
}
+ // Execute based on transaction mode
+ if transactionMode == common.TransactionModeOff {
+ return d.executeInAutoCommitMode(ctx, conn, commands, originalIndex, opts, connectionID)
+ }
+ return d.executeInTransactionMode(ctx, conn, commands, originalIndex, opts, connectionID)
+}
+
+// executeInTransactionMode executes statements within a single transaction
+func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, commands []base.SingleSQL, originalIndex []int32, opts db.ExecuteOptions, connectionID string) (int64, error) {
var totalRowsAffected int64
if err := conn.Raw(func(driverConn any) error {
@@ -382,6 +400,58 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return totalRowsAffected, nil
}
+// executeInAutoCommitMode executes statements sequentially in auto-commit mode
+func (d *Driver) executeInAutoCommitMode(ctx context.Context, conn *sql.Conn, commands []base.SingleSQL, originalIndex []int32, opts db.ExecuteOptions, connectionID string) (int64, error) {
+ var totalRowsAffected int64
+
+ if err := conn.Raw(func(driverConn any) error {
+ //nolint
+ exer := driverConn.(driver.ExecerContext)
+
+ for i, command := range commands {
+ indexes := []int32{originalIndex[i]}
+ opts.LogCommandExecute(indexes)
+
+ sqlWithBytebaseAppComment := util.MySQLPrependBytebaseAppComment(command.Text)
+ sqlResult, err := exer.ExecContext(ctx, sqlWithBytebaseAppComment, nil)
+ 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))
+ }
+ }
+
+ opts.LogCommandResponse(indexes, 0, nil, err.Error())
+ // In auto-commit mode, we stop at the first error
+ // The database is left in a partially migrated state
+ return &db.ErrorWithPosition{
+ Err: errors.Wrapf(err, "failed to execute statement %d in auto-commit mode", i+1),
+ Start: command.Start,
+ End: command.End,
+ }
+ }
+
+ allRowsAffected := sqlResult.(mysql.Result).AllRowsAffected()
+ var rowsAffected int64
+ var allRowsAffectedInt32 []int32
+ for _, a := range allRowsAffected {
+ rowsAffected += a
+ allRowsAffectedInt32 = append(allRowsAffectedInt32, int32(a))
+ }
+ totalRowsAffected += rowsAffected
+
+ opts.LogCommandResponse(indexes, int32(rowsAffected), allRowsAffectedInt32, "")
+ }
+
+ return nil
+ }); err != nil {
+ return 0, err
+ }
+
+ return totalRowsAffected, nil
+}
+
// QueryConn queries a SQL statement in a given connection.
func (d *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string, queryContext db.QueryContext) ([]*v1pb.QueryResult, error) {
singleSQLs, err := base.SplitMultiSQL(storepb.Engine_MYSQL, statement)
diff --git a/backend/plugin/db/oracle/oracle.go b/backend/plugin/db/oracle/oracle.go
index adf941fb72..4aae52537f 100644
--- a/backend/plugin/db/oracle/oracle.go
+++ b/backend/plugin/db/oracle/oracle.go
@@ -113,6 +113,15 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return 0, errors.New("create database is not supported for Oracle")
}
+ // 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()
+ }
+
var commands []base.SingleSQL
var originalIndex []int32
if len(statement) <= common.MaxSheetCheckSize {
@@ -141,6 +150,15 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
}
defer conn.Close()
+ // Execute based on transaction mode
+ if transactionMode == common.TransactionModeOff {
+ return d.executeInAutoCommitMode(ctx, conn, commands, originalIndex, opts)
+ }
+ return d.executeInTransactionMode(ctx, conn, commands, originalIndex, opts)
+}
+
+// executeInTransactionMode executes statements within a single transaction
+func (*Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, commands []base.SingleSQL, originalIndex []int32, opts db.ExecuteOptions) (int64, error) {
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error())
@@ -194,6 +212,36 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return totalRowsAffected, nil
}
+// executeInAutoCommitMode executes statements sequentially in auto-commit mode
+func (*Driver) executeInAutoCommitMode(ctx context.Context, conn *sql.Conn, commands []base.SingleSQL, originalIndex []int32, opts db.ExecuteOptions) (int64, error) {
+ totalRowsAffected := int64(0)
+ for i, command := range commands {
+ indexes := []int32{originalIndex[i]}
+ opts.LogCommandExecute(indexes)
+
+ sqlResult, err := conn.ExecContext(ctx, command.Text)
+ if err != nil {
+ opts.LogCommandResponse(indexes, 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))
+ rowsAffected = 0
+ }
+ opts.LogCommandResponse(indexes, int32(rowsAffected), []int32{int32(rowsAffected)}, "")
+ totalRowsAffected += rowsAffected
+ }
+ return totalRowsAffected, nil
+}
+
// QueryConn queries a SQL statement in a given connection.
func (d *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string, queryContext db.QueryContext) ([]*v1pb.QueryResult, error) {
singleSQLs, err := plsqlparser.SplitSQL(statement)
diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.go
index f6984499a4..66ea9a34c6 100644
--- a/backend/plugin/db/pg/pg.go
+++ b/backend/plugin/db/pg/pg.go
@@ -361,6 +361,15 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return 0, nil
}
+ // 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()
+ }
+
owner, err := d.GetCurrentDatabaseOwner(ctx)
if err != nil {
return 0, err
@@ -414,6 +423,17 @@ 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
+ if 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.tryExecute(ctx, owner, statement, commands, originalIndex, nonTransactionAndSetRoleStmts, nonTransactionAndSetRoleStmtsIndex, opts, isPlsql)
if err == nil {
return affectedRows, nil
diff --git a/backend/plugin/db/risingwave/risingwave.go b/backend/plugin/db/risingwave/risingwave.go
index ab0a2114ae..6b4790fbd5 100644
--- a/backend/plugin/db/risingwave/risingwave.go
+++ b/backend/plugin/db/risingwave/risingwave.go
@@ -202,6 +202,15 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return 0, nil
}
+ // 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()
+ }
+
var commands []base.SingleSQL
oneshot := true
if len(statement) <= common.MaxSheetCheckSize {
@@ -223,31 +232,52 @@ 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,
+ // 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
}
- rowsAffected, err := sqlResult.RowsAffected()
+ } else {
+ // For transactional mode (TransactionModeOn), wrap all statements in a single transaction
+ tx, err := d.db.BeginTx(ctx, nil)
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 0, err
}
- totalRowsAffected += rowsAffected
- }
+ defer tx.Rollback()
- if err := tx.Commit(); err != nil {
- return 0, err
+ 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
+ }
}
}
diff --git a/backend/plugin/db/snowflake/snowflake.go b/backend/plugin/db/snowflake/snowflake.go
index 5a7e8060cf..cdd63123c3 100644
--- a/backend/plugin/db/snowflake/snowflake.go
+++ b/backend/plugin/db/snowflake/snowflake.go
@@ -228,12 +228,43 @@ func getDatabasesTxn(ctx context.Context, txn *sql.Tx) ([]string, error) {
}
// Execute executes a SQL statement and returns the affected rows.
-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 script
+ transactionMode, cleanedStatement := base.ParseTransactionMode(statement)
+ statement = cleanedStatement
+
+ // Apply default when transaction mode is not specified
+ if transactionMode == common.TransactionModeUnspecified {
+ transactionMode = common.GetDefaultTransactionMode()
+ }
+
+ // Execute based on transaction mode
+ if transactionMode == common.TransactionModeOff {
+ return d.executeInAutoCommitMode(ctx, statement, opts)
+ }
+ return d.executeInTransactionMode(ctx, statement, opts)
+}
+
+// executeInTransactionMode executes statements within a single transaction
+func (d *Driver) executeInTransactionMode(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error())
return 0, err
}
- defer tx.Rollback()
+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "")
+
+ committed := false
+ defer func() {
+ if !committed {
+ if err := tx.Rollback(); err != nil {
+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, err.Error())
+ } else {
+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, "")
+ }
+ }
+ }()
+
// 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-statements
mctx, err := snow.WithMultiStatement(ctx, 0 /* MULTI_STATEMENT_COUNT */)
@@ -246,6 +277,32 @@ func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOpti
}
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
+
+ rowsAffected, err := result.RowsAffected()
+ // 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))
+ return 0, 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) {
+ // 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-statements
+ mctx, err := snow.WithMultiStatement(ctx, 0 /* MULTI_STATEMENT_COUNT */)
+ if err != nil {
+ return 0, err
+ }
+
+ result, err := d.db.ExecContext(mctx, statement)
+ if err != nil {
return 0, err
}
diff --git a/backend/plugin/db/spanner/spanner.go b/backend/plugin/db/spanner/spanner.go
index 7d7713c829..00d831a17c 100644
--- a/backend/plugin/db/spanner/spanner.go
+++ b/backend/plugin/db/spanner/spanner.go
@@ -12,21 +12,20 @@ import (
"cloud.google.com/go/spanner"
spannerdb "cloud.google.com/go/spanner/admin/database/apiv1"
"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
-
sppb "cloud.google.com/go/spanner/apiv1/spannerpb"
"github.com/pkg/errors"
+ "google.golang.org/api/iterator"
+ "google.golang.org/api/option"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/durationpb"
"github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/db/util"
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
"github.com/bytebase/bytebase/backend/utils"
-
- "google.golang.org/api/iterator"
- "google.golang.org/api/option"
- "google.golang.org/protobuf/proto"
- "google.golang.org/protobuf/types/known/durationpb"
)
var (
@@ -137,12 +136,22 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return 0, nil
}
+ // 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()
+ }
+
var rowCount int64
stmts, err := util.SanitizeSQL(statement)
if err != nil {
return 0, err
}
+ // Check if any statement is DDL
ddl := func() bool {
for _, stmt := range stmts {
if util.IsDDL(stmt) {
@@ -152,6 +161,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return false
}()
+ // Spanner DDL is always non-transactional
if ddl {
op, err := d.dbClient.UpdateDatabaseDdl(ctx, &databasepb.UpdateDatabaseDdlRequest{
Database: getDSN(d.config.DataSource.Host, d.databaseName),
@@ -163,6 +173,21 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return 0, op.Wait(ctx)
}
+ // For DML statements, respect transaction mode
+ if 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
+ }
+
+ // Default behavior: execute DML in a transaction
if _, err := d.client.ReadWriteTransaction(ctx, func(ctx context.Context, rwt *spanner.ReadWriteTransaction) error {
spannerStmts := []spanner.Statement{}
for _, stmt := range stmts {
diff --git a/backend/plugin/db/starrocks/starrocks.go b/backend/plugin/db/starrocks/starrocks.go
index 4153fe8b63..aeb87bb5d6 100644
--- a/backend/plugin/db/starrocks/starrocks.go
+++ b/backend/plugin/db/starrocks/starrocks.go
@@ -154,6 +154,15 @@ 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) {
+ // 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()
+ }
+
statement, err := mysqlparser.DealWithDelimiter(statement)
if err != nil {
return 0, errors.Wrapf(err, "failed to deal with delimiter")
@@ -170,6 +179,31 @@ 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 mode
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
return 0, errors.Wrapf(err, "failed to begin execute transaction")
diff --git a/backend/plugin/db/tidb/tidb.go b/backend/plugin/db/tidb/tidb.go
index fcbc672ca4..47186afeac 100644
--- a/backend/plugin/db/tidb/tidb.go
+++ b/backend/plugin/db/tidb/tidb.go
@@ -156,6 +156,15 @@ func parseVersion(version string) (string, error) {
// Execute executes a SQL statement.
func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {
+ // 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()
+ }
+
statement, err := mysqlparser.DealWithDelimiter(statement)
if err != nil {
return 0, errors.Wrapf(err, "failed to deal with delimiter")
@@ -174,7 +183,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
slog.Debug("connectionID", slog.String("connectionID", connectionID))
var remainingSQLsIndex, nonTransactionStmtsIndex []int
- var nonTransactionStmts []string
+ var nonTransactionStmts []base.SingleSQL
var totalCommands int
var commands []base.SingleSQL
var originalIndex []int32
@@ -196,7 +205,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
var remainingSQLs []base.SingleSQL
for i, singleSQL := range singleSQLs {
if isNonTransactionStatement(singleSQL.Text) {
- nonTransactionStmts = append(nonTransactionStmts, singleSQL.Text)
+ nonTransactionStmts = append(nonTransactionStmts, singleSQL)
nonTransactionStmtsIndex = append(nonTransactionStmtsIndex, i)
continue
}
@@ -216,7 +225,17 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
remainingSQLsIndex = []int{0}
}
+ // Execute based on transaction mode
+ if transactionMode == common.TransactionModeOff {
+ return d.executeInAutoCommitMode(ctx, conn, commands, nonTransactionStmts, remainingSQLsIndex, nonTransactionStmtsIndex, originalIndex, opts, connectionID)
+ }
+ return d.executeInTransactionMode(ctx, conn, commands, nonTransactionStmts, remainingSQLsIndex, nonTransactionStmtsIndex, originalIndex, opts, connectionID)
+}
+
+// executeInTransactionMode executes statements within a single transaction
+func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, commands []base.SingleSQL, nonTransactionStmts []base.SingleSQL, remainingSQLsIndex, nonTransactionStmtsIndex []int, originalIndex []int32, opts db.ExecuteOptions, connectionID string) (int64, error) {
var totalRowsAffected int64
+
if err := conn.Raw(func(driverConn any) error {
//nolint
exer := driverConn.(driver.ExecerContext)
@@ -224,9 +243,24 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
txer := driverConn.(driver.ConnBeginTx)
tx, err := txer.BeginTx(ctx, driver.TxOptions{})
if err != nil {
+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error())
return err
+ } else {
+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "")
}
- defer tx.Rollback()
+
+ committed := false
+ defer func() {
+ err := tx.Rollback()
+ if committed {
+ return
+ }
+ var rerr string
+ if err != nil {
+ rerr = err.Error()
+ }
+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, rerr)
+ }()
for i, command := range commands {
indexes := []int32{originalIndex[remainingSQLsIndex[i]]}
@@ -265,6 +299,9 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
if err := tx.Commit(); err != nil {
return errors.Wrapf(err, "failed to commit execute transaction")
+ } else {
+ opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, "")
+ committed = true
}
return nil
}); err != nil {
@@ -273,9 +310,9 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
// Run non-transaction statements at the end.
for i, stmt := range nonTransactionStmts {
- indexes := []int32{int32(originalIndex[nonTransactionStmtsIndex[i]])}
+ indexes := []int32{originalIndex[nonTransactionStmtsIndex[i]]}
opts.LogCommandExecute(indexes)
- if _, err := d.db.ExecContext(ctx, stmt); err != nil {
+ if _, err := d.db.ExecContext(ctx, stmt.Text); err != nil {
opts.LogCommandResponse(indexes, 0, []int32{0}, err.Error())
return 0, err
}
@@ -284,6 +321,84 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return totalRowsAffected, nil
}
+// executeInAutoCommitMode executes statements sequentially in auto-commit mode
+func (d *Driver) executeInAutoCommitMode(ctx context.Context, conn *sql.Conn, commands []base.SingleSQL, nonTransactionStmts []base.SingleSQL, remainingSQLsIndex, nonTransactionStmtsIndex []int, originalIndex []int32, opts db.ExecuteOptions, connectionID string) (int64, error) {
+ var totalRowsAffected int64
+
+ // Execute all statements (including non-transactional ones) in order
+ allCommands := make([]base.SingleSQL, 0, len(commands)+len(nonTransactionStmts))
+ allIndexes := make([]int, 0, len(commands)+len(nonTransactionStmts))
+
+ // Merge commands and non-transactional statements while preserving original order
+ cmdIdx, nonTxIdx := 0, 0
+ for cmdIdx < len(commands) || nonTxIdx < len(nonTransactionStmts) {
+ if cmdIdx >= len(commands) {
+ allCommands = append(allCommands, nonTransactionStmts[nonTxIdx])
+ allIndexes = append(allIndexes, nonTransactionStmtsIndex[nonTxIdx])
+ nonTxIdx++
+ } else if nonTxIdx >= len(nonTransactionStmts) {
+ allCommands = append(allCommands, commands[cmdIdx])
+ allIndexes = append(allIndexes, remainingSQLsIndex[cmdIdx])
+ cmdIdx++
+ } else if remainingSQLsIndex[cmdIdx] < nonTransactionStmtsIndex[nonTxIdx] {
+ allCommands = append(allCommands, commands[cmdIdx])
+ allIndexes = append(allIndexes, remainingSQLsIndex[cmdIdx])
+ cmdIdx++
+ } else {
+ allCommands = append(allCommands, nonTransactionStmts[nonTxIdx])
+ allIndexes = append(allIndexes, nonTransactionStmtsIndex[nonTxIdx])
+ nonTxIdx++
+ }
+ }
+
+ if err := conn.Raw(func(driverConn any) error {
+ //nolint
+ exer := driverConn.(driver.ExecerContext)
+
+ for i, command := range allCommands {
+ indexes := []int32{originalIndex[allIndexes[i]]}
+ opts.LogCommandExecute(indexes)
+
+ sqlWithBytebaseAppComment := util.MySQLPrependBytebaseAppComment(command.Text)
+ sqlResult, err := exer.ExecContext(ctx, sqlWithBytebaseAppComment, nil)
+ 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))
+ }
+ }
+
+ opts.LogCommandResponse(indexes, 0, nil, err.Error())
+ // In auto-commit mode, we stop at the first error
+ // The database is left in a partially migrated state
+ return &db.ErrorWithPosition{
+ Err: errors.Wrapf(err, "failed to execute statement %d in auto-commit mode", i+1),
+ Start: command.Start,
+ End: command.End,
+ }
+ }
+
+ allRowsAffected := sqlResult.(mysql.Result).AllRowsAffected()
+ var rowsAffected int64
+ var allRowsAffectedInt32 []int32
+ for _, a := range allRowsAffected {
+ rowsAffected += a
+ allRowsAffectedInt32 = append(allRowsAffectedInt32, int32(a))
+ }
+ totalRowsAffected += rowsAffected
+
+ opts.LogCommandResponse(indexes, int32(rowsAffected), allRowsAffectedInt32, "")
+ }
+
+ return nil
+ }); err != nil {
+ return 0, err
+ }
+
+ return totalRowsAffected, nil
+}
+
var (
// CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
// CREATE [ UNIQUE ] [ SPATIAL ] [ FULLTEXT ] INDEX ... ON table_name ...
diff --git a/backend/plugin/db/trino/trino.go b/backend/plugin/db/trino/trino.go
index 09435263b6..3312310b5f 100644
--- a/backend/plugin/db/trino/trino.go
+++ b/backend/plugin/db/trino/trino.go
@@ -14,6 +14,7 @@ import (
// Import Trino driver for side effects
_ "github.com/trinodb/trino-go-client/trino"
+ "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
@@ -126,6 +127,20 @@ func (d *Driver) GetDB() *sql.DB {
// Execute executes the SQL statement with the given options.
func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) {
+ // 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()
+ }
+
+ // Note: We parse transactionMode but don't use it for execution since Trino
+ // has limited transaction support. The variable assignment is kept for consistency
+ // with other database drivers and potential future use.
+ _ = transactionMode
+
conn, err := d.db.Conn(ctx)
if err != nil {
return 0, errors.Wrap(err, "failed to get connection")
@@ -147,6 +162,13 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
return 0, nil
}
+ // Trino has limited transaction support:
+ // - Only supports transactions for data modification operations (INSERT, UPDATE, DELETE)
+ // - DDL operations are always auto-committed
+ // - Not all connectors support transactions
+ // Due to these limitations, we execute statements individually regardless of transaction mode
+ // but we still parse and respect the transaction mode directive for consistency
+
var totalRowsAffected int64
for i, command := range commands {
indexes := []int32{originalIndex[i]}
@@ -160,6 +182,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
rowsAffected, err := result.RowsAffected()
if err != nil {
+ // Trino doesn't always return rows affected, especially for DDL
rowsAffected = 0
}
diff --git a/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go b/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go
index 0f70f38f9f..60e68c11b4 100644
--- a/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go
+++ b/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go
@@ -34,7 +34,7 @@ func TestGenerateMigrationWithTestcontainer(t *testing.T) {
ctx := context.Background()
// Start MySQL container using common testcontainer interface
- container, err := testcontainer.GetMySQLContainer(ctx)
+ container, err := testcontainer.GetTestMySQLContainer(ctx)
require.NoError(t, err)
defer container.Close(ctx)
diff --git a/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.go b/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.go
index 256fa87aba..bc9adcc11a 100644
--- a/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.go
+++ b/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.go
@@ -296,7 +296,7 @@ CREATE TABLE translations (
for _, tc := range testCases {
t.Run(tc.description, func(t *testing.T) {
// Start MySQL container
- container, err := testcontainer.GetMySQLContainer(ctx)
+ container, err := testcontainer.GetTestMySQLContainer(ctx)
require.NoError(t, err)
defer container.Close(ctx)
@@ -440,7 +440,7 @@ CREATE TABLE project_member (
ctx := context.Background()
// Start MySQL container
- container, err := testcontainer.GetMySQLContainer(ctx)
+ container, err := testcontainer.GetTestMySQLContainer(ctx)
require.NoError(t, err)
defer container.Close(ctx)
diff --git a/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.go b/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.go
index 1a16d93022..9d4bba0a76 100644
--- a/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.go
+++ b/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.go
@@ -21,7 +21,7 @@ func TestGetDatabaseMetadataWithTestcontainer(t *testing.T) {
ctx := context.Background()
// Start MySQL container
- container, err := testcontainer.GetMySQLContainer(ctx)
+ container, err := testcontainer.GetTestMySQLContainer(ctx)
require.NoError(t, err)
defer container.Close(ctx)
diff --git a/backend/tests/testcontainer.go b/backend/tests/testcontainer.go
index 30ad9c5ef8..d0ae1a92fa 100644
--- a/backend/tests/testcontainer.go
+++ b/backend/tests/testcontainer.go
@@ -31,7 +31,7 @@ func getPgContainer(ctx context.Context) (*Container, error) {
// getMySQLContainer creates a MySQL container for testing
func getMySQLContainer(ctx context.Context) (*Container, error) {
- tc, err := testcontainer.GetMySQLContainer(ctx)
+ tc, err := testcontainer.GetTestMySQLContainer(ctx)
if err != nil {
return nil, err
}
diff --git a/backend/tests/transaction_mode_test.go b/backend/tests/transaction_mode_test.go
new file mode 100644
index 0000000000..487a46beac
--- /dev/null
+++ b/backend/tests/transaction_mode_test.go
@@ -0,0 +1,288 @@
+package tests
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/plugin/db"
+)
+
+// TestTransactionMode tests the configurable transaction mode feature across different database engines.
+func TestTransactionMode(t *testing.T) {
+ ctx := context.Background()
+
+ tests := []struct {
+ name string
+ dbType storepb.Engine
+ containerFunc func(context.Context, *testing.T) *testcontainer.Container
+ setupScript string
+ testScriptOn string
+ testScriptOff string
+ expectRollbackOn bool // Whether we expect rollback for transaction mode on
+ skipTransaction bool // Some engines don't support transactions well
+ }{
+ {
+ name: "MySQL",
+ dbType: storepb.Engine_MYSQL,
+ containerFunc: func(ctx context.Context, t *testing.T) *testcontainer.Container {
+ container, err := testcontainer.GetTestMySQLContainer(ctx)
+ if err != nil {
+ t.Fatalf("Failed to get MySQL container: %v", err)
+ }
+ return container
+ },
+ setupScript: `
+ CREATE TABLE test_table (
+ id INT PRIMARY KEY,
+ value VARCHAR(100)
+ );
+ `,
+ testScriptOn: `-- txn-mode = on
+ INSERT INTO test_table (id, value) VALUES (1, 'test1');
+ INSERT INTO test_table (id, value) VALUES (2, 'test2');
+ INSERT INTO test_table (id, value) VALUES (1, 'duplicate'); -- This will fail
+ `,
+ testScriptOff: `-- txn-mode = off
+ INSERT INTO test_table (id, value) VALUES (1, 'test1');
+ INSERT INTO test_table (id, value) VALUES (2, 'test2');
+ INSERT INTO test_table (id, value) VALUES (1, 'duplicate'); -- This will fail
+ `,
+ expectRollbackOn: true,
+ },
+ {
+ name: "PostgreSQL",
+ dbType: storepb.Engine_POSTGRES,
+ containerFunc: func(ctx context.Context, t *testing.T) *testcontainer.Container {
+ return testcontainer.GetTestPgContainer(ctx, t)
+ },
+ setupScript: `
+ CREATE TABLE test_table (
+ id INTEGER PRIMARY KEY,
+ value VARCHAR(100)
+ );
+ `,
+ testScriptOn: `-- txn-mode = on
+ INSERT INTO test_table (id, value) VALUES (1, 'test1');
+ INSERT INTO test_table (id, value) VALUES (2, 'test2');
+ INSERT INTO test_table (id, value) VALUES (1, 'duplicate'); -- This will fail
+ `,
+ testScriptOff: `-- txn-mode = off
+ INSERT INTO test_table (id, value) VALUES (1, 'test1');
+ INSERT INTO test_table (id, value) VALUES (2, 'test2');
+ INSERT INTO test_table (id, value) VALUES (1, 'duplicate'); -- This will fail
+ `,
+ expectRollbackOn: true,
+ },
+ {
+ name: "Oracle",
+ dbType: storepb.Engine_ORACLE,
+ containerFunc: func(ctx context.Context, t *testing.T) *testcontainer.Container {
+ return testcontainer.GetTestOracleContainer(ctx, t)
+ },
+ setupScript: `
+ CREATE TABLE test_table (
+ id NUMBER PRIMARY KEY,
+ value VARCHAR2(100)
+ )
+ `,
+ testScriptOn: `-- txn-mode = on
+ INSERT INTO test_table (id, value) VALUES (1, 'test1');
+ INSERT INTO test_table (id, value) VALUES (2, 'test2');
+ INSERT INTO test_table (id, value) VALUES (1, 'duplicate'); -- This will fail
+ `,
+ testScriptOff: `-- txn-mode = off
+ INSERT INTO test_table (id, value) VALUES (1, 'test1');
+ INSERT INTO test_table (id, value) VALUES (2, 'test2');
+ INSERT INTO test_table (id, value) VALUES (1, 'duplicate'); -- This will fail
+ `,
+ expectRollbackOn: true,
+ },
+ {
+ name: "SQL Server",
+ dbType: storepb.Engine_MSSQL,
+ containerFunc: func(ctx context.Context, t *testing.T) *testcontainer.Container {
+ return testcontainer.GetTestMSSQLContainer(ctx, t)
+ },
+ setupScript: `
+ CREATE TABLE test_table (
+ id INT PRIMARY KEY,
+ value VARCHAR(100)
+ );
+ `,
+ testScriptOn: `-- txn-mode = on
+ INSERT INTO test_table (id, value) VALUES (1, 'test1');
+ INSERT INTO test_table (id, value) VALUES (2, 'test2');
+ INSERT INTO test_table (id, value) VALUES (1, 'duplicate'); -- This will fail
+ `,
+ testScriptOff: `-- txn-mode = off
+ INSERT INTO test_table (id, value) VALUES (1, 'test1');
+ INSERT INTO test_table (id, value) VALUES (2, 'test2');
+ INSERT INTO test_table (id, value) VALUES (1, 'duplicate'); -- This will fail
+ `,
+ expectRollbackOn: true,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ // Skip transaction tests for engines that don't support them well
+ if test.skipTransaction {
+ t.Skip("Skipping transaction test for engine with limited transaction support")
+ }
+
+ // Create container
+ container := test.containerFunc(ctx, t)
+ defer container.Close(ctx)
+
+ // Create test database if needed
+ testDBName := fmt.Sprintf("txnmode_test_%d", time.Now().UnixNano())
+ if test.dbType == storepb.Engine_MYSQL {
+ _, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", testDBName))
+ require.NoError(t, err)
+ }
+
+ // Get database connection
+ driver, err := getDriver(ctx, test.dbType, container, testDBName)
+ require.NoError(t, err)
+ defer driver.Close(ctx)
+
+ // Setup test table
+ _, err = driver.Execute(ctx, test.setupScript, db.ExecuteOptions{})
+ require.NoError(t, err)
+
+ // Test transaction mode ON - expect rollback on failure
+ t.Run("TransactionModeOn", func(t *testing.T) {
+ // Execute script with transaction mode ON
+ _, err := driver.Execute(ctx, test.testScriptOn, db.ExecuteOptions{})
+ require.Error(t, err, "Expected error due to duplicate key")
+
+ // Check if rollback occurred
+ rowCount := getRowCount(ctx, t, driver, test.dbType)
+ if test.expectRollbackOn {
+ require.Equal(t, 0, rowCount, "Expected 0 rows due to rollback")
+ } else {
+ require.Greater(t, rowCount, 0, "Expected some rows even with error")
+ }
+
+ // Cleanup
+ cleanupTable(ctx, t, driver, test.dbType)
+ })
+
+ // Test transaction mode OFF - expect partial success
+ t.Run("TransactionModeOff", func(t *testing.T) {
+ // Execute script with transaction mode OFF
+ _, err := driver.Execute(ctx, test.testScriptOff, db.ExecuteOptions{})
+ require.Error(t, err, "Expected error due to duplicate key")
+
+ // Check if partial success occurred (first 2 inserts should succeed)
+ rowCount := getRowCount(ctx, t, driver, test.dbType)
+ require.Equal(t, 2, rowCount, "Expected 2 rows from successful inserts before failure")
+
+ // Cleanup
+ cleanupTable(ctx, t, driver, test.dbType)
+ })
+ })
+ }
+}
+
+// Helper functions
+func getDriver(ctx context.Context, engine storepb.Engine, container *testcontainer.Container, testDBName string) (db.Driver, error) {
+ var dbDatabase string
+ switch engine {
+ case storepb.Engine_MYSQL:
+ dbDatabase = testDBName
+ case storepb.Engine_POSTGRES:
+ dbDatabase = "postgres"
+ case storepb.Engine_ORACLE:
+ dbDatabase = "FREEPDB1"
+ case storepb.Engine_MSSQL:
+ dbDatabase = "master"
+ default:
+ dbDatabase = ""
+ }
+
+ config := db.ConnectionConfig{
+ DataSource: &storepb.DataSource{
+ Host: container.GetHost(),
+ Port: container.GetPort(),
+ Username: "root",
+ Database: dbDatabase,
+ },
+ ConnectionContext: db.ConnectionContext{
+ DatabaseName: dbDatabase,
+ },
+ Password: "root",
+ }
+
+ // Special handling for different engines based on testcontainer setup
+ switch engine {
+ case storepb.Engine_MYSQL:
+ config.DataSource.Username = "root"
+ config.Password = "root-password"
+ case storepb.Engine_POSTGRES:
+ config.DataSource.Username = "postgres"
+ config.Password = "root-password"
+ case storepb.Engine_ORACLE:
+ config.DataSource.Username = "testuser"
+ config.Password = "testpass"
+ config.DataSource.Database = ""
+ config.ConnectionContext.DatabaseName = ""
+ // Set service name for Oracle
+ config.DataSource.ServiceName = "FREEPDB1"
+ case storepb.Engine_MSSQL:
+ config.DataSource.Username = "sa"
+ config.Password = "Test123!"
+ }
+
+ driver, err := db.Open(ctx, engine, config)
+ if err != nil {
+ return nil, err
+ }
+
+ return driver, nil
+}
+
+func getRowCount(ctx context.Context, t *testing.T, driver db.Driver, _ storepb.Engine) int {
+ query := "SELECT COUNT(*) FROM test_table"
+
+ // Use QueryConn to get results
+ conn, err := driver.GetDB().Conn(ctx)
+ require.NoError(t, err)
+ defer conn.Close()
+
+ results, err := driver.QueryConn(ctx, conn, query, db.QueryContext{})
+ require.NoError(t, err)
+ require.Len(t, results, 1)
+ require.Len(t, results[0].Rows, 1)
+ require.Len(t, results[0].Rows[0].Values, 1)
+
+ // Extract count value
+ switch v := results[0].Rows[0].Values[0].Kind.(type) {
+ case *v1pb.RowValue_Int32Value:
+ return int(v.Int32Value)
+ case *v1pb.RowValue_Int64Value:
+ return int(v.Int64Value)
+ case *v1pb.RowValue_StringValue:
+ // Some databases return count as string
+ count := 0
+ if _, err := fmt.Sscanf(v.StringValue, "%d", &count); err != nil {
+ t.Fatalf("Failed to parse count from string: %v", err)
+ }
+ return count
+ default:
+ t.Fatalf("Unexpected count value type: %T", v)
+ return 0
+ }
+}
+
+func cleanupTable(ctx context.Context, t *testing.T, driver db.Driver, _ storepb.Engine) {
+ _, err := driver.Execute(ctx, "DELETE FROM test_table", db.ExecuteOptions{})
+ require.NoError(t, err)
+}