This repository was archived by the owner on Jul 18, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.go
More file actions
78 lines (66 loc) · 1.65 KB
/
sql.go
File metadata and controls
78 lines (66 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package txnsql
import (
"context"
"database/sql"
"github.com/9ssi7/txn"
)
type SqlDbTx interface {
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
Prepare(query string) (*sql.Stmt, error)
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
Exec(query string, args ...any) (sql.Result, error)
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
Query(query string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
QueryRow(query string, args ...any) *sql.Row
}
// SqlAdapter is the interface for interacting with SQL databases within a transaction.
// It extends the txn.Adapter interface to provide additional SQL-specific functionality.
type SqlAdapter interface {
txn.Adapter
// Returns current transaction if it exists.
GetCurrent() SqlDbTx
}
// New creates a new SqlAdapter instance using the provided *sql.DB.
func New(db *sql.DB) SqlAdapter {
return &sqlAdapter{db: db}
}
type sqlAdapter struct {
db *sql.DB
tx *sql.Tx
}
func (a *sqlAdapter) Begin(ctx context.Context) error {
tx, err := a.db.BeginTx(ctx, nil)
if err != nil {
return err
}
a.tx = tx
return nil
}
func (a *sqlAdapter) Commit(_ context.Context) error {
if a.tx == nil {
return nil
}
err := a.tx.Commit()
a.tx = nil
return err
}
func (a *sqlAdapter) Rollback(_ context.Context) error {
if a.tx == nil {
return nil
}
err := a.tx.Rollback()
a.tx = nil
return err
}
func (a *sqlAdapter) End(_ context.Context) {
if a.tx != nil {
a.tx = nil
}
}
func (a *sqlAdapter) GetCurrent() SqlDbTx {
if a.tx == nil {
return a.db
}
return a.tx
}