Skip to content

Commit dafe244

Browse files
committed
added db.ValidateWithinTransaction and ValidateNotWithinTransaction
1 parent aeaf7f2 commit dafe244

File tree

3 files changed

+32
-4
lines changed

3 files changed

+32
-4
lines changed

db/config.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@ var (
1414
)
1515

1616
var (
17-
conn = sqldb.ConnectionWithError(context.Background(), errors.New("database connection not initialized"))
18-
connCtxKey int
19-
17+
conn = sqldb.ConnectionWithError(
18+
context.Background(),
19+
errors.New("database connection not initialized"),
20+
)
21+
connCtxKey int
2022
serializedTransactionCtxKey int
2123
)

db/transaction.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,32 @@ import (
1212
"github.com/domonda/go-sqldb"
1313
)
1414

15+
// ValidateWithinTransaction returns sqldb.ErrNotWithinTransaction
16+
// if the database connection from the context is not a transaction.
17+
func ValidateWithinTransaction(ctx context.Context) error {
18+
conn := Conn(ctx)
19+
if err := conn.Config().Err; err != nil {
20+
return err
21+
}
22+
if !conn.IsTransaction() {
23+
return sqldb.ErrNotWithinTransaction
24+
}
25+
return nil
26+
}
27+
28+
// ValidateNotWithinTransaction returns sqldb.ErrWithinTransaction
29+
// if the database connection from the context is a transaction.
30+
func ValidateNotWithinTransaction(ctx context.Context) error {
31+
conn := Conn(ctx)
32+
if err := conn.Config().Err; err != nil {
33+
return err
34+
}
35+
if conn.IsTransaction() {
36+
return sqldb.ErrWithinTransaction
37+
}
38+
return nil
39+
}
40+
1541
// DebugNoTransaction executes nonTxFunc without a database transaction.
1642
// Useful to temporarely replace Transaction to debug the same code without using a transaction.
1743
func DebugNoTransaction(ctx context.Context, nonTxFunc func(context.Context) error) error {

mockconn/connection.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ func (conn *connection) Stats() sql.DBStats {
6969
}
7070

7171
func (conn *connection) Config() *sqldb.Config {
72-
return &sqldb.Config{Driver: "mockconn"}
72+
return &sqldb.Config{Driver: "mockconn", Host: "localhost", Database: "mock"}
7373
}
7474

7575
func (conn *connection) Ping(time.Duration) error {

0 commit comments

Comments
 (0)