executeInTransactionMode executes statements within a single transaction
(ctx context.Context, conn *sql.Conn, commands []base.Statement, opts db.ExecuteOptions, connectionID string)
| 238 | |
| 239 | // executeInTransactionMode executes statements within a single transaction |
| 240 | func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, commands []base.Statement, opts db.ExecuteOptions, connectionID string) (int64, error) { |
| 241 | var totalRowsAffected int64 |
| 242 | |
| 243 | if err := conn.Raw(func(driverConn any) error { |
| 244 | //nolint |
| 245 | exer := driverConn.(driver.ExecerContext) |
| 246 | //nolint |
| 247 | txer := driverConn.(driver.ConnBeginTx) |
| 248 | tx, err := txer.BeginTx(ctx, driver.TxOptions{}) |
| 249 | if err != nil { |
| 250 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error()) |
| 251 | return err |
| 252 | } else { |
| 253 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "") |
| 254 | } |
| 255 | |
| 256 | committed := false |
| 257 | defer func() { |
| 258 | err := tx.Rollback() |
| 259 | if committed { |
| 260 | return |
| 261 | } |
| 262 | var rerr string |
| 263 | if err != nil { |
| 264 | rerr = err.Error() |
| 265 | } |
| 266 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, rerr) |
| 267 | }() |
| 268 | |
| 269 | for _, command := range commands { |
| 270 | opts.LogCommandExecute(command.Range, command.Text) |
| 271 | |
| 272 | sqlWithBytebaseAppComment := util.MySQLPrependBytebaseAppComment(command.Text) |
| 273 | sqlResult, err := exer.ExecContext(ctx, sqlWithBytebaseAppComment, nil) |
| 274 | if err != nil { |
| 275 | if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { |
| 276 | slog.Info("cancel connection", slog.String("connectionID", connectionID)) |
| 277 | if err := d.StopConnectionByID(connectionID); err != nil { |
| 278 | slog.Error("failed to cancel connection", slog.String("connectionID", connectionID), log.BBError(err)) |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | opts.LogCommandResponse(0, nil, err.Error()) |
| 283 | |
| 284 | return err |
| 285 | } |
| 286 | |
| 287 | allRowsAffected := sqlResult.(mysql.Result).AllRowsAffected() |
| 288 | var rowsAffected int64 |
| 289 | var allRowsAffectedInt64 []int64 |
| 290 | for _, a := range allRowsAffected { |
| 291 | rowsAffected += a |
| 292 | allRowsAffectedInt64 = append(allRowsAffectedInt64, a) |
| 293 | } |
| 294 | totalRowsAffected += rowsAffected |
| 295 | |
| 296 | opts.LogCommandResponse(rowsAffected, allRowsAffectedInt64, "") |
| 297 | } |
no test coverage detected