executeInTransactionMode executes statements within a single transaction
(ctx context.Context, statement string, opts db.ExecuteOptions)
| 184 | |
| 185 | // executeInTransactionMode executes statements within a single transaction |
| 186 | func (d *Driver) executeInTransactionMode(ctx context.Context, statement string, opts db.ExecuteOptions) (int64, error) { |
| 187 | tx, err := d.db.BeginTx(ctx, nil) |
| 188 | if err != nil { |
| 189 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, err.Error()) |
| 190 | return 0, err |
| 191 | } |
| 192 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_BEGIN, "") |
| 193 | |
| 194 | committed := false |
| 195 | defer func() { |
| 196 | err := tx.Rollback() |
| 197 | if committed { |
| 198 | return |
| 199 | } |
| 200 | var rerr string |
| 201 | if err != nil { |
| 202 | rerr = err.Error() |
| 203 | } |
| 204 | opts.LogTransactionControl(storepb.TaskRunLog_TransactionControl_ROLLBACK, rerr) |
| 205 | }() |
| 206 | |
| 207 | totalAffectRows := int64(0) |
| 208 | |
| 209 | batch := tsqlbatch.NewBatcher(statement) |
| 210 | |
| 211 | for idx := 0; ; { |
| 212 | command, err := batch.Next() |
| 213 | if err != nil { |
| 214 | if err == io.EOF { |
| 215 | // Try send the last batch to server. |
| 216 | v := batch.Batch() |
| 217 | if v != nil && len(v.Text) > 0 { |
| 218 | opts.LogCommandExecute(&storepb.Range{Start: int32(v.Start), End: int32(v.End)}, v.Text) |
| 219 | rowsAffected, err := execute(ctx, tx, v.Text) |
| 220 | if err != nil { |
| 221 | opts.LogCommandResponse(0, nil, err.Error()) |
| 222 | return 0, err |
| 223 | } |
| 224 | opts.LogCommandResponse(rowsAffected, []int64{rowsAffected}, "") |
| 225 | totalAffectRows += rowsAffected |
| 226 | } |
| 227 | break |
| 228 | } |
| 229 | return 0, errors.Wrapf(err, "failed to get next batch for statement: %s", batch.Batch().Text) |
| 230 | } |
| 231 | if command == nil { |
| 232 | continue |
| 233 | } |
| 234 | switch v := command.(type) { |
| 235 | case *tsqlbatch.GoCommand: |
| 236 | b := batch.Batch() |
| 237 | // Try send the batch to server. |
| 238 | idx++ |
| 239 | for i := uint(0); i < v.Count; i++ { |
| 240 | opts.LogCommandExecute(&storepb.Range{Start: int32(b.Start), End: int32(b.End)}, b.Text) |
| 241 | rowsAffected, err := execute(ctx, tx, b.Text) |
| 242 | if err != nil { |
| 243 | opts.LogCommandResponse(0, nil, err.Error()) |
no test coverage detected