From 116b8165bb112740d0ddb6194aae13de906ac8e1 Mon Sep 17 00:00:00 2001 From: Peter Sanchez Date: Wed, 15 Feb 2023 13:26:08 -0600 Subject: [PATCH] Addressing issue with RO transactions started and not committed before a write request is made --- database/db.go | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/database/db.go b/database/db.go index 64d8c1b..9844586 100644 --- a/database/db.go +++ b/database/db.go @@ -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 } -- 2.45.2