-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
48 lines (39 loc) · 967 Bytes
/
transaction.go
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
package lorm
import (
"context"
"database/sql"
)
var (
_ Session = &Tx{}
_ Session = &DB{}
)
// Session 抽象的数据库操作接口
// 包含 事务 与 非事务
type Session interface {
queryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
execContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
// Tx 继承 Session 操作数据库
type Tx struct {
tx *sql.Tx
db *DB
}
func (t *Tx) queryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
return t.tx.QueryContext(ctx, query, args...)
}
func (t *Tx) execContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
return t.tx.ExecContext(ctx, query, args...)
}
func (t *Tx) Commit() error {
return t.tx.Commit()
}
func (t *Tx) Rollback() error {
return t.tx.Rollback()
}
func (t *Tx) RollbackIfNotCommit() error {
err := t.tx.Rollback()
if err == sql.ErrTxDone {
return nil
}
return err
}