executeInTransactionMode executes statements within a single transaction
(ctx context.Context, conn *sql.Conn, commands []base.Statement, opts db.ExecuteOptions)
| 152 | |
| 153 | // executeInTransactionMode executes statements within a single transaction |
| 154 | func (*Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, commands []base.Statement, opts db.ExecuteOptions) (int64, error) { |
| 155 | tx, err := conn.BeginTx(ctx, nil) |
| 156 | if err != nil { |
| 157 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error()) |
| 158 | return 0, errors.Wrapf(err, "failed to begin transaction") |
| 159 | } |
| 160 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "") |
| 161 | |
| 162 | committed := false |
| 163 | defer func() { |
| 164 | err := tx.Rollback() |
| 165 | if committed { |
| 166 | return |
| 167 | } |
| 168 | var rerr string |
| 169 | if err != nil { |
| 170 | rerr = err.Error() |
| 171 | } |
| 172 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, rerr) |
| 173 | }() |
| 174 | |
| 175 | totalRowsAffected := int64(0) |
| 176 | for _, command := range commands { |
| 177 | opts.LogCommandExecute(command.Range, command.Text) |
| 178 | |
| 179 | sqlResult, err := tx.ExecContext(ctx, command.Text) |
| 180 | if err != nil { |
| 181 | opts.LogCommandResponse(0, nil, err.Error()) |
| 182 | return 0, err |
| 183 | } |
| 184 | rowsAffected, err := sqlResult.RowsAffected() |
| 185 | if err != nil { |
| 186 | // Since we cannot differentiate DDL and DML yet, we have to ignore the error. |
| 187 | slog.Debug("rowsAffected returns error", log.BBError(err)) |
| 188 | rowsAffected = 0 |
| 189 | } |
| 190 | opts.LogCommandResponse(rowsAffected, []int64{rowsAffected}, "") |
| 191 | totalRowsAffected += rowsAffected |
| 192 | } |
| 193 | |
| 194 | if err := tx.Commit(); err != nil { |
| 195 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, err.Error()) |
| 196 | return 0, errors.Wrapf(err, "failed to commit transaction") |
| 197 | } |
| 198 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_COMMIT, "") |
| 199 | committed = true |
| 200 | return totalRowsAffected, nil |
| 201 | } |
| 202 | |
| 203 | // executeInAutoCommitMode executes statements sequentially in auto-commit mode |
| 204 | func (*Driver) executeInAutoCommitMode(ctx context.Context, conn *sql.Conn, commands []base.Statement, opts db.ExecuteOptions) (int64, error) { |
no test coverage detected