Skip to content

Commit 947af1c

Browse files
add common interface for sql.DB and sql.Tx
1 parent fda8afd commit 947af1c

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

sql/util.go

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import (
44
"context"
55
"database/sql"
66
"fmt"
7-
8-
"github.com/jmoiron/sqlx"
97
)
108

119
var ErrTxNotFound = fmt.Errorf("transaction value not found")
@@ -29,11 +27,21 @@ func TxFromContext(ctx context.Context) (*sql.Tx, error) {
2927
return tx, nil
3028
}
3129

32-
// Executor returns a *sql.Tx or *sqlx.DB to execute a DB command based on the given context.
33-
func Executor(ctx context.Context, db *sqlx.DB) sqlx.ExecerContext {
30+
// DB interface contains the common methods between sql.DB and sql.Tx objects
31+
type DB interface {
32+
Exec(query string, args ...any) (sql.Result, error)
33+
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
34+
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
35+
Query(query string, args ...any) (*sql.Rows, error)
36+
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
37+
QueryRow(query string, args ...any) *sql.Row
38+
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
39+
}
40+
41+
// Executor returns a DbOrTx (either *sql.Tx or *sql.DB) to execute a DB command based on the given context.
42+
func Executor(ctx context.Context, db *sql.DB) DB {
3443
if tx, ok := ctx.Value(txSessionKey).(*sql.Tx); ok {
3544
return tx
3645
}
37-
3846
return db
3947
}

0 commit comments

Comments
 (0)