executeInTransactionMode executes statements within a single transaction
(ctx context.Context, commands []base.Statement, opts db.ExecuteOptions)
| 229 | |
| 230 | // executeInTransactionMode executes statements within a single transaction |
| 231 | func (d *Driver) executeInTransactionMode(ctx context.Context, commands []base.Statement, opts db.ExecuteOptions) (int64, error) { |
| 232 | totalRowsAffected := int64(0) |
| 233 | if len(commands) == 0 { |
| 234 | return 0, nil |
| 235 | } |
| 236 | |
| 237 | tx, err := d.db.BeginTx(ctx, nil) |
| 238 | if err != nil { |
| 239 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error()) |
| 240 | return 0, err |
| 241 | } |
| 242 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "") |
| 243 | |
| 244 | committed := false |
| 245 | defer func() { |
| 246 | err := tx.Rollback() |
| 247 | if committed { |
| 248 | return |
| 249 | } |
| 250 | var rerr string |
| 251 | if err != nil && !errors.Is(err, sql.ErrTxDone) { |
| 252 | rerr = err.Error() |
| 253 | slog.Debug("failed to rollback transaction", log.BBError(err)) |
| 254 | } |
| 255 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, rerr) |
| 256 | }() |
| 257 | |
| 258 | for i, command := range commands { |
| 259 | opts.LogCommandExecute(command.Range, command.Text) |
| 260 | // Log the query statement in char code to see if there are some control characters that cause issues. |
| 261 | var charCode []rune |
| 262 | for _, r := range command.Text { |
| 263 | charCode = append(charCode, r) |
| 264 | } |
| 265 | slog.Debug("executing command", slog.Any("command", charCode), slog.Int("index", i)) |
| 266 | sqlResult, err := tx.ExecContext(ctx, command.Text) |
| 267 | if err != nil { |
| 268 | opts.LogCommandResponse(0, nil, err.Error()) |
| 269 | return 0, err |
| 270 | } |
| 271 | rowsAffected, err := sqlResult.RowsAffected() |
| 272 | if err != nil { |
| 273 | // Since we cannot differentiate DDL and DML yet, we have to ignore the error. |
| 274 | slog.Debug("rowsAffected returns error", log.BBError(err)) |
| 275 | } |
| 276 | opts.LogCommandResponse(rowsAffected, nil, "") |
| 277 | totalRowsAffected += rowsAffected |
| 278 | } |
| 279 | |
| 280 | if err := tx.Commit(); err != nil { |
| 281 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, err.Error()) |
| 282 | return 0, err |
| 283 | } |
| 284 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, "") |
| 285 | committed = true |
| 286 | |
| 287 | return totalRowsAffected, nil |
| 288 | } |
no test coverage detected