Repository navigation
Expand file tree
/
Copy pathtx.go
More file actions
554 lines (473 loc) · 18.3 KB
/
Copy pathtx.go
File metadata and controls
554 lines (473 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
package fbx
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"github.com/firebirdsql/fbx/fbconn"
"github.com/firebirdsql/fbx/fbproto"
"github.com/firebirdsql/fbx/internal/operationerror"
)
// TxIsoLevel is the transaction isolation level ([fbx.Serializable], [fbx.RepeatableRead], [fbx.ReadCommitted])
type TxIsoLevel string
// Transaction isolation levels
const (
Serializable TxIsoLevel = "serializable"
RepeatableRead TxIsoLevel = "repeatable read"
ReadCommitted TxIsoLevel = "read committed"
)
// TxAccessMode is the transaction access mode ([fbx.ReadWrite], [fbx.ReadOnly])
type TxAccessMode string
// Transaction access modes
const (
ReadWrite TxAccessMode = "read write"
ReadOnly TxAccessMode = "read only"
)
// TxOptions configures the modes used to start a transaction.
type TxOptions struct {
IsoLevel TxIsoLevel
AccessMode TxAccessMode
// LockTimeout controls lock wait timeout for WAIT transactions.
// Zero means no explicit lock timeout is encoded.
// When other options require a TPB, GetTPB still encodes WAIT because it is
// the Firebird/RDB default lock resolution mode.
// Non-zero values must be positive whole seconds in range [1..32767].
LockTimeout time.Duration
}
var ErrTxClosed = errors.New("tx is closed")
// ErrTxCommitRollback indicates that Commit() did not commit changes and the transaction was rolled back instead
var ErrTxCommitRollback = errors.New("commit unexpectedly resulted in rollback")
// Begin starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no
// auto-rollback on context cancellation.
func (c *Conn) Begin(ctx context.Context) (Tx, error) {
return c.BeginTx(ctx, TxOptions{})
}
// BeginTx starts a transaction with txOptions determining the transaction mode. Unlike database/sql, the context only
// affects the begin command. i.e. there is no auto-rollback on context cancellation.
func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) {
tpb, err := txOptions.GetTPB()
if err != nil {
return nil, err
}
return c.beginTxTPB(ctx, tpb)
}
// BeginTxTPB starts a transaction using a raw Firebird transaction parameter block.
// The TPB is passed to the server as-is.
func (c *Conn) BeginTxTPB(ctx context.Context, tpb []byte) (Tx, error) {
txTPB := make([]byte, len(tpb))
copy(txTPB, tpb)
return c.beginTxTPB(ctx, txTPB)
}
func (c *Conn) beginTxTPB(ctx context.Context, tpb []byte) (Tx, error) {
fbTx, err := c.fbConn.StartTransactionTPB(ctx, tpb)
if err != nil {
return nil, err
}
return &dbTx{
conn: c,
tx: fbTx,
}, nil
}
// GetTPB returns a Firebird transaction parameter block for txOptions.
//
// Empty TxOptions returns nil, allowing the server to use its default
// transaction characteristics: READ WRITE, WAIT, and SNAPSHOT isolation.
// Specifying only AccessMode preserves the default isolation level. Specifying
// only IsoLevel uses READ WRITE, matching the Firebird/RDB default access mode.
func (txOptions TxOptions) GetTPB() ([]byte, error) {
lockTimeoutSeconds, err := normalizeTxLockTimeout(txOptions.LockTimeout)
if err != nil {
return nil, err
}
// If no options are specified, use server / database defaults. This matches Firebird semantics and keeps
// database/sql LevelDefault behaving as expected (i.e. do not silently force READ COMMITTED).
if txOptions.AccessMode == "" && txOptions.IsoLevel == "" && lockTimeoutSeconds == 0 {
return nil, nil
}
tpb := fbproto.NewTPBWriterV3()
if txOptions.AccessMode != "" {
switch txOptions.AccessMode {
case ReadOnly:
tpb.PutTag(fbproto.Isc_tpb_read)
case ReadWrite:
tpb.PutTag(fbproto.Isc_tpb_write)
default:
return nil, fmt.Errorf("unknown transaction access mode: %s", txOptions.AccessMode)
}
} else if txOptions.IsoLevel != "" {
// Preserve the established isolation-only behavior.
tpb.PutTag(fbproto.Isc_tpb_write)
}
if txOptions.IsoLevel != "" {
switch txOptions.IsoLevel {
case Serializable:
tpb.PutTag(fbproto.Isc_tpb_consistency)
case RepeatableRead:
tpb.PutTag(fbproto.Isc_tpb_concurrency)
case ReadCommitted:
tpb.PutTag(fbproto.Isc_tpb_read_committed)
if txOptions.AccessMode == ReadWrite {
tpb.PutTag(fbproto.Isc_tpb_no_rec_version)
} else {
tpb.PutTag(fbproto.Isc_tpb_rec_version)
}
default:
return nil, fmt.Errorf("unknown transaction iso level: %s", txOptions.IsoLevel)
}
}
if lockTimeoutSeconds > 0 {
tpb.PutTag(fbproto.Isc_tpb_wait)
tpb.PutInt32(fbproto.Isc_tpb_lock_timeout, int32(lockTimeoutSeconds))
} else if txOptions.AccessMode != "" || txOptions.IsoLevel != "" {
tpb.PutTag(fbproto.Isc_tpb_wait)
}
return tpb.Bytes(), nil
}
func normalizeTxLockTimeout(lockTimeout time.Duration) (int, error) {
if lockTimeout == 0 {
return 0, nil
}
if lockTimeout < 0 {
return 0, fmt.Errorf("lock timeout must be >= 0")
}
seconds := int(lockTimeout.Seconds())
if seconds < 1 || seconds > 32767 {
return 0, fmt.Errorf("lock timeout must be in range [1..32767] seconds")
}
return seconds, nil
}
// Tx represents a database transaction.
//
// Tx is an interface instead of a struct to enable connection pools to be implemented without relying on internal fbx
// state, to support pseudo-nested transactions with savepoints, and to allow tests to mock transactions. However,
// adding a method to an interface is technically a breaking change. If new methods are added to Conn it may be
// desirable to add them to Tx as well. Because of this the Tx interface is partially excluded from semantic version
// requirements. Methods will not be removed or changed, but new methods may be added.
type Tx interface {
// Begin starts a pseudo nested transaction.
Begin(ctx context.Context) (Tx, error)
// Commit commits the transaction if this is a real transaction or releases the savepoint if this is a pseudo nested
// transaction. Commit will return an error where errors.Is(ErrTxClosed) is true if the Tx is already closed, but is
// otherwise safe to call multiple times. If the commit fails with a rollback status (e.g. the transaction was already
// in a broken state) then an error where errors.Is(ErrTxCommitRollback) is true will be returned.
Commit(ctx context.Context) error
// Rollback rolls back the transaction if this is a real transaction or rolls back to the savepoint if this is a
// pseudo nested transaction. Rollback will return an error where errors.Is(ErrTxClosed) is true if the Tx is already
// closed, but is otherwise safe to call multiple times. Hence, a defer tx.Rollback() is safe even if tx.Commit() will
// be called first in a non-error condition. Any other failure of a real transaction will result in the connection
// being closed.
Rollback(ctx context.Context) error
// Prepare resolves SQL in this transaction and registers the statement on
// the connection. The statement remains usable after Commit or Rollback.
// Named batches (SQL prefixed with "batch ") belong to this transaction.
Prepare(ctx context.Context, name, sql string) (*fbconn.StatementDescription, error)
// PrepareBatch creates a batch object inside the transaction.
//
// Executing the batch does not commit or roll back the transaction.
PrepareBatch(ctx context.Context, sql string) (*PreparedBatch, error)
// PrepareBatchWithOptions creates a batch object inside the transaction with
// additional batch options.
//
// Executing the batch does not commit or roll back the transaction.
PrepareBatchWithOptions(ctx context.Context, sql string, opts BatchOptions) (*PreparedBatch, error)
// Flush sends queued rows for a named batch without executing it.
Flush(ctx context.Context, name string) error
// ExecBatch flushes queued rows for a named batch, executes it, and returns
// the result.
//
// ExecBatch does not commit or roll back the transaction.
ExecBatch(ctx context.Context, name string) (BatchResult, error)
// CancelBatch discards every row queued for a named batch — both the local
// buffer and any rows already flushed to the server. The prepared batch
// statement is kept and can be reused.
CancelBatch(ctx context.Context, name string) error
Exec(ctx context.Context, sql string, arguments ...any) (commandTag fbconn.QueryStatus, err error)
Query(ctx context.Context, sql string, args ...any) (Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) Row
// Conn returns the underlying *Conn that on which this transaction is executing.
Conn() *Conn
}
// dbTx represents a database transaction.
//
// All dbTx methods return ErrTxClosed if Commit or Rollback has already been
// called on the dbTx.
type dbTx struct {
conn *Conn
savepointNum int64
closed bool
tx *fbconn.FBTransaction
}
// Begin starts a pseudo nested transaction implemented with a savepoint.
func (tx *dbTx) Begin(ctx context.Context) (Tx, error) {
if tx.closed {
return nil, ErrTxClosed
}
tx.savepointNum++
_, err := tx.Exec(ctx, "savepoint sp_"+strconv.FormatInt(tx.savepointNum, 10))
if err != nil {
return nil, err
}
return &dbSimulatedNestedTx{tx: tx, savepointNum: tx.savepointNum}, nil
}
// Commit commits the transaction.
func (tx *dbTx) Commit(ctx context.Context) error {
if tx.closed {
return ErrTxClosed
}
cleanupErr := tx.conn.closePreparedBatchesForTx(ctx, tx)
err := tx.tx.Commit(ctx)
if err != nil {
tx.closed = tx.tx.Closed || tx.conn.IsClosed()
return operationerror.Join(err, cleanupErr)
}
tx.closed = true
return operationerror.WithRetry(cleanupErr, false)
}
// Rollback rolls back the transaction. Rollback will return ErrTxClosed if the
// Tx is already closed, but is otherwise safe to call multiple times. Hence, a
// defer tx.Rollback() is safe even if tx.Commit() will be called first in a
// non-error condition.
func (tx *dbTx) Rollback(ctx context.Context) error {
if tx.closed {
return ErrTxClosed
}
cleanupErr := tx.conn.closePreparedBatchesForTx(ctx, tx)
err := tx.tx.Rollback(ctx)
tx.closed = true
if err != nil {
// A rollback failure leaves the connection in an undefined state.
tx.conn.die()
return operationerror.Join(err, cleanupErr)
}
return operationerror.WithRetry(cleanupErr, false)
}
// Exec delegates to the underlying *Conn
func (tx *dbTx) Exec(ctx context.Context, sql string, arguments ...any) (commandTag fbconn.QueryStatus, err error) {
if tx.closed {
return fbconn.QueryStatus{}, ErrTxClosed
}
return tx.conn.execTx(ctx, tx, sql, arguments...)
}
// Prepare delegates to the underlying *Conn
func (tx *dbTx) Prepare(ctx context.Context, name, sql string) (*fbconn.StatementDescription, error) {
if tx.closed {
return nil, ErrTxClosed
}
return tx.conn.prepareTx(ctx, tx, name, sql)
}
// PrepareBatch creates a batch object inside the transaction.
//
// Executing the batch does not commit or roll back the transaction.
func (tx *dbTx) PrepareBatch(ctx context.Context, sql string) (*PreparedBatch, error) {
return tx.PrepareBatchWithOptions(ctx, sql, BatchOptions{})
}
// PrepareBatchWithOptions creates a batch object inside the transaction with
// additional batch options.
//
// Executing the batch does not commit or roll back the transaction.
func (tx *dbTx) PrepareBatchWithOptions(ctx context.Context, sql string, opts BatchOptions) (*PreparedBatch, error) {
if tx.closed {
return nil, ErrTxClosed
}
return tx.conn.prepareBatchTx(ctx, tx, sql, opts)
}
// Query delegates to the underlying *Conn
func (tx *dbTx) Query(ctx context.Context, sql string, args ...any) (Rows, error) {
if tx.closed {
// Because checking for errors can be deferred to the *Rows, build one with the error
err := ErrTxClosed
return &baseRows{closed: true, err: err}, err
}
return tx.conn.queryTx(ctx, tx, sql, args...)
}
// QueryRow delegates to the underlying *Conn
func (tx *dbTx) QueryRow(ctx context.Context, sql string, args ...any) Row {
rows, _ := tx.Query(ctx, sql, args...)
return (*connRow)(rows.(*baseRows))
}
func (tx *dbTx) Conn() *Conn {
return tx.conn
}
// Flush sends queued rows for a named batch without executing it.
func (tx *dbTx) Flush(ctx context.Context, name string) error {
if tx.closed {
return ErrTxClosed
}
return tx.conn.flushTx(ctx, tx, name)
}
// ExecBatch flushes queued rows for a named batch, executes it, and returns the result.
//
// ExecBatch does not commit or roll back the transaction.
func (tx *dbTx) ExecBatch(ctx context.Context, name string) (BatchResult, error) {
if tx.closed {
return BatchResult{}, ErrTxClosed
}
return tx.conn.execBatchTx(ctx, tx, name)
}
// CancelBatch discards every row queued for a named batch — both the local
// buffer and any rows already flushed to the server. The prepared batch
// statement is kept and can be reused.
func (tx *dbTx) CancelBatch(ctx context.Context, name string) error {
if tx.closed {
return ErrTxClosed
}
return tx.conn.cancelBatchTx(ctx, tx, name)
}
// dbSimulatedNestedTx represents a simulated nested transaction implemented by a savepoint.
type dbSimulatedNestedTx struct {
tx Tx
savepointNum int64
closed bool
}
// Begin starts a pseudo nested transaction implemented with a savepoint.
func (sp *dbSimulatedNestedTx) Begin(ctx context.Context) (Tx, error) {
if sp.closed {
return nil, ErrTxClosed
}
return sp.tx.Begin(ctx)
}
// Commit releases the savepoint essentially committing the pseudo nested transaction.
func (sp *dbSimulatedNestedTx) Commit(ctx context.Context) error {
if sp.closed {
return ErrTxClosed
}
_, err := sp.Exec(ctx, "release savepoint sp_"+strconv.FormatInt(sp.savepointNum, 10))
sp.closed = true
return err
}
// Rollback rolls back to the savepoint essentially rolling back the pseudo nested transaction. Rollback will return
// ErrTxClosed if the dbSavepoint is already closed, but is otherwise safe to call multiple times. Hence, a defer sp.Rollback()
// is safe even if sp.Commit() will be called first in a non-error condition.
func (sp *dbSimulatedNestedTx) Rollback(ctx context.Context) error {
if sp.closed {
return ErrTxClosed
}
_, err := sp.Exec(ctx, "rollback to savepoint sp_"+strconv.FormatInt(sp.savepointNum, 10))
sp.closed = true
return err
}
// Exec delegates to the underlying Tx
func (sp *dbSimulatedNestedTx) Exec(ctx context.Context, sql string, arguments ...any) (commandTag fbconn.QueryStatus, err error) {
if sp.closed {
return fbconn.QueryStatus{}, ErrTxClosed
}
return sp.tx.Exec(ctx, sql, arguments...)
}
// Prepare delegates to the underlying Tx
func (sp *dbSimulatedNestedTx) Prepare(ctx context.Context, name, sql string) (*fbconn.StatementDescription, error) {
if sp.closed {
return nil, ErrTxClosed
}
return sp.tx.Prepare(ctx, name, sql)
}
// PrepareBatch creates a batch object inside the transaction.
//
// Executing the batch does not commit or roll back the transaction.
func (sp *dbSimulatedNestedTx) PrepareBatch(ctx context.Context, sql string) (*PreparedBatch, error) {
return sp.PrepareBatchWithOptions(ctx, sql, BatchOptions{})
}
// PrepareBatchWithOptions creates a batch object inside the transaction with
// additional batch options.
//
// Executing the batch does not commit or roll back the transaction.
func (sp *dbSimulatedNestedTx) PrepareBatchWithOptions(ctx context.Context, sql string, opts BatchOptions) (*PreparedBatch, error) {
if sp.closed {
return nil, ErrTxClosed
}
return sp.tx.PrepareBatchWithOptions(ctx, sql, opts)
}
// Flush sends queued rows for a named batch without executing it.
func (sp *dbSimulatedNestedTx) Flush(ctx context.Context, name string) error {
if sp.closed {
return ErrTxClosed
}
return sp.tx.Flush(ctx, name)
}
// ExecBatch flushes queued rows for a named batch, executes it, and returns the result.
//
// ExecBatch does not commit or roll back the transaction.
func (sp *dbSimulatedNestedTx) ExecBatch(ctx context.Context, name string) (BatchResult, error) {
if sp.closed {
return BatchResult{}, ErrTxClosed
}
return sp.tx.ExecBatch(ctx, name)
}
// CancelBatch discards every row queued for a named batch — both the local
// buffer and any rows already flushed to the server. The prepared batch
// statement is kept and can be reused.
func (sp *dbSimulatedNestedTx) CancelBatch(ctx context.Context, name string) error {
if sp.closed {
return ErrTxClosed
}
return sp.tx.CancelBatch(ctx, name)
}
// Query delegates to the underlying Tx
func (sp *dbSimulatedNestedTx) Query(ctx context.Context, sql string, args ...any) (Rows, error) {
if sp.closed {
// Because checking for errors can be deferred to the *Rows, build one with the error
err := ErrTxClosed
return &baseRows{closed: true, err: err}, err
}
return sp.tx.Query(ctx, sql, args...)
}
// QueryRow delegates to the underlying Tx
func (sp *dbSimulatedNestedTx) QueryRow(ctx context.Context, sql string, args ...any) Row {
rows, _ := sp.Query(ctx, sql, args...)
return (*connRow)(rows.(*baseRows))
}
func (sp *dbSimulatedNestedTx) Conn() *Conn {
return sp.tx.Conn()
}
// BeginFunc calls Begin on db and then calls fn. If fn does not return an error then it calls Commit on db. If fn
// returns an error it calls Rollback on db. The context will be used when executing the transaction control statements
// (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of fn.
func BeginFunc(
ctx context.Context,
db interface {
Begin(ctx context.Context) (Tx, error)
},
fn func(Tx) error,
) (err error) {
var tx Tx
tx, err = db.Begin(ctx)
if err != nil {
return err
}
return beginFuncExec(ctx, tx, fn)
}
// BeginTxFunc calls BeginTx on db and then calls fn. If fn does not return an error then it calls Commit on db. If fn
// returns an error it calls Rollback on db. The context will be used when executing the transaction control statements
// (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of fn.
func BeginTxFunc(
ctx context.Context,
db interface {
BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error)
},
txOptions TxOptions,
fn func(Tx) error,
) (err error) {
var tx Tx
tx, err = db.BeginTx(ctx, txOptions)
if err != nil {
return err
}
return beginFuncExec(ctx, tx, fn)
}
func beginFuncExec(ctx context.Context, tx Tx, fn func(Tx) error) (err error) {
defer func() {
cleanupCtx, cancel := cleanupContext(ctx)
defer cancel()
rollbackErr := tx.Rollback(cleanupCtx)
if rollbackErr != nil && !errors.Is(rollbackErr, ErrTxClosed) {
err = operationerror.Join(err, rollbackErr)
}
// The callback may have executed SQL even if commit was not sent.
err = operationerror.WithRetry(err, false)
}()
fErr := fn(tx)
if fErr != nil {
return fErr
}
return tx.Commit(ctx)
}