executeInTransactionMode executes statements within a single transaction
(ctx context.Context, conn *sql.Conn, commands []base.Statement, opts db.ExecuteOptions, connectionID string, isolationLevel common.IsolationLevel)
| 380 | |
| 381 | // executeInTransactionMode executes statements within a single transaction |
| 382 | func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, commands []base.Statement, opts db.ExecuteOptions, connectionID string, isolationLevel common.IsolationLevel) (int64, error) { |
| 383 | var totalRowsAffected int64 |
| 384 | |
| 385 | if err := conn.Raw(func(driverConn any) error { |
| 386 | //nolint |
| 387 | exer := driverConn.(driver.ExecerContext) |
| 388 | //nolint |
| 389 | txer := driverConn.(driver.ConnBeginTx) |
| 390 | |
| 391 | // Set isolation level if specified |
| 392 | txOptions := driver.TxOptions{} |
| 393 | if isolationLevel != common.IsolationLevelDefault { |
| 394 | txOptions.Isolation = driver.IsolationLevel(base.ConvertToSQLIsolation(isolationLevel)) |
| 395 | } |
| 396 | |
| 397 | tx, err := txer.BeginTx(ctx, txOptions) |
| 398 | if err != nil { |
| 399 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error()) |
| 400 | return err |
| 401 | } else { |
| 402 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "") |
| 403 | } |
| 404 | |
| 405 | committed := false |
| 406 | defer func() { |
| 407 | err := tx.Rollback() |
| 408 | if committed { |
| 409 | return |
| 410 | } |
| 411 | var rerr string |
| 412 | if err != nil { |
| 413 | rerr = err.Error() |
| 414 | } |
| 415 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, rerr) |
| 416 | }() |
| 417 | |
| 418 | for _, command := range commands { |
| 419 | opts.LogCommandExecute(command.Range, command.Text) |
| 420 | |
| 421 | sqlWithBytebaseAppComment := util.MySQLPrependBytebaseAppComment(command.Text) |
| 422 | sqlResult, err := exer.ExecContext(ctx, sqlWithBytebaseAppComment, nil) |
| 423 | if err != nil { |
| 424 | if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { |
| 425 | slog.Info("cancel connection", slog.String("connectionID", connectionID)) |
| 426 | if err := d.StopConnectionByID(connectionID); err != nil { |
| 427 | slog.Error("failed to cancel connection", slog.String("connectionID", connectionID), log.BBError(err)) |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | opts.LogCommandResponse(0, nil, err.Error()) |
| 432 | |
| 433 | return err |
| 434 | } |
| 435 | |
| 436 | allRowsAffected := sqlResult.(mysql.Result).AllRowsAffected() |
| 437 | var rowsAffected int64 |
| 438 | var allRowsAffectedInt64 []int64 |
| 439 | for _, a := range allRowsAffected { |
no test coverage detected