@@ 22,6 22,14 @@ type DB struct {
db *sql.DB
tx *sql.Tx
commit bool
+ rotx bool
+}
+
+func roTransaction(opts *sql.TxOptions) bool {
+ if opts == nil {
+ return false
+ }
+ return opts.ReadOnly
}
// BeginTx begins a db transaction
@@ 30,11 38,27 @@ func (d *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
return nil, errors.New("You must first set the *sql.DB value")
}
if d.tx != nil {
- return d.tx, nil
+ if d.rotx && !roTransaction(opts) {
+ // Current read only transaction. Commit it and create a new transaction.
+ // Should be harmless as no data has been written as of yet.
+ cval := d.commit
+ if d.commit == false {
+ d.commit = true
+ }
+ if err := d.CommitTx(); err != nil {
+ return nil, err
+ }
+ if d.commit != cval {
+ d.commit = cval
+ }
+ } else {
+ return d.tx, nil
+ }
}
var err error
d.tx, err = d.db.BeginTx(ctx, opts)
+ d.rotx = roTransaction(opts)
return d.tx, err
}