@@ -4,30 +4,31 @@ import (
44 "context"
55 "database/sql"
66 "fmt"
7-
8- "github.com/Thiht/transactor"
97)
108
11- func NewTransactor (db * sql.DB , nestedTransactionStrategy nestedTransactionsStrategy ) (transactor.Transactor , DBGetter ) {
9+ func NewTransactor (db * sql.DB , nestedTransactionStrategy nestedTransactionsStrategy ) (* Transactor , DBGetter ) {
10+ txKey := & transactorKey {}
11+
1212 sqlDBGetter := func (ctx context.Context ) sqlDB {
13- if tx := txFromContext (ctx ); tx != nil {
13+ if tx := txFromContext (ctx , txKey ); tx != nil {
1414 return tx
1515 }
1616
1717 return db
1818 }
1919
2020 dbGetter := func (ctx context.Context ) DB {
21- if tx := txFromContext (ctx ); tx != nil {
21+ if tx := txFromContext (ctx , txKey ); tx != nil {
2222 return tx
2323 }
2424
2525 return db
2626 }
2727
28- return & stdlibTransactor {
28+ return & Transactor {
2929 sqlDBGetter ,
3030 nestedTransactionStrategy ,
31+ txKey ,
3132 }, dbGetter
3233}
3334
@@ -36,12 +37,13 @@ type (
3637 nestedTransactionsStrategy func (sqlDB , * sql.Tx ) (sqlDB , sqlTx )
3738)
3839
39- type stdlibTransactor struct {
40+ type Transactor struct {
4041 sqlDBGetter
4142 nestedTransactionsStrategy
43+ txKey * transactorKey
4244}
4345
44- func (t * stdlibTransactor ) WithinTransaction (ctx context.Context , txFunc func (context.Context ) error ) error {
46+ func (t * Transactor ) WithinTransaction (ctx context.Context , txFunc func (context.Context ) error ) error {
4547 currentDB := t .sqlDBGetter (ctx )
4648
4749 tx , err := currentDB .BeginTx (ctx , nil )
@@ -53,7 +55,7 @@ func (t *stdlibTransactor) WithinTransaction(ctx context.Context, txFunc func(co
5355 defer func () {
5456 _ = currentTX .Rollback () // If rollback fails, there's nothing to do, the transaction will expire by itself
5557 }()
56- txCtx := txToContext (ctx , newDB )
58+ txCtx := txToContext (ctx , t . txKey , newDB )
5759
5860 if err := txFunc (txCtx ); err != nil {
5961 return err
@@ -66,6 +68,12 @@ func (t *stdlibTransactor) WithinTransaction(ctx context.Context, txFunc func(co
6668 return nil
6769}
6870
71+ func (t * Transactor ) IsWithinTransaction (ctx context.Context ) bool {
72+ return ctx .Value (t .txKey ) != nil
73+ }
74+
75+ // Deprecated: use [Transactor.IsWithinTransaction] instead.
76+ // This function can give the wrong result if multiple transactor instances are used.
6977func IsWithinTransaction (ctx context.Context ) bool {
70- return ctx .Value (transactorKey {}) != nil
78+ return ctx .Value (transactorMarker {}) != nil
7179}
0 commit comments