From 9b9013a560a098fe0597fb337bbbb2b4f225fd44 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Fri, 16 Nov 2018 19:35:47 +0000 Subject: [PATCH] postgres: use stdlib to set serializable tx level also use a context for the rollback, which is a bit cleaner since it only results in one 'defer', rather than N from the loop --- storage/sql/sql.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/storage/sql/sql.go b/storage/sql/sql.go index ddcfae9e..2ddccab7 100644 --- a/storage/sql/sql.go +++ b/storage/sql/sql.go @@ -2,6 +2,7 @@ package sql import ( + "context" "database/sql" "regexp" "time" @@ -51,18 +52,19 @@ var ( // NOTE(ericchiang): For some reason using `SET SESSION CHARACTERISTICS AS TRANSACTION` at a // session level didn't work for some edge cases. Might be something worth exploring. executeTx: func(db *sql.DB, fn func(sqlTx *sql.Tx) error) error { + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() + + opts := &sql.TxOptions{ + Isolation: sql.LevelSerializable, + } + for { - tx, err := db.Begin() + tx, err := db.BeginTx(ctx, opts) if err != nil { return err } - defer tx.Rollback() - - if _, err := tx.Exec(`SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;`); err != nil { - return err - } - if err := fn(tx); err != nil { return err }