From 99566b768e97e5e3fc7d2b3d1671142d1e29c353 Mon Sep 17 00:00:00 2001 From: Joost Jager Date: Thu, 23 Dec 2021 11:19:37 +0100 Subject: [PATCH] kvdb/postgres: use readonly db transaction if possible --- kvdb/postgres/readwrite_tx.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/kvdb/postgres/readwrite_tx.go b/kvdb/postgres/readwrite_tx.go index 942552580..59be148fc 100644 --- a/kvdb/postgres/readwrite_tx.go +++ b/kvdb/postgres/readwrite_tx.go @@ -4,6 +4,7 @@ package postgres import ( + "context" "database/sql" "sync" @@ -39,7 +40,16 @@ func newReadWriteTx(db *db, readOnly bool) (*readWriteTx, error) { } locker.Lock() - tx, err := db.db.Begin() + // Start the transaction. Don't use the timeout context because it would + // be applied to the transaction as a whole. If possible, mark the + // transaction as read-only to make sure that potential programming + // errors cannot cause changes to the database. + tx, err := db.db.BeginTx( + context.Background(), + &sql.TxOptions{ + ReadOnly: readOnly, + }, + ) if err != nil { locker.Unlock() return nil, err