Skip to content

Commit d06d04a

Browse files
committed
bugfix: use tx rather than conn when transaction open
bugfix: rollback transaction when panic(for reusing it quickly)
1 parent 5b62be7 commit d06d04a

1 file changed

Lines changed: 23 additions & 2 deletions

File tree

lib/xdb.go

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,20 @@ package lib
1717
import (
1818
"context"
1919
"database/sql"
20+
"fmt"
2021
"strings"
2122
)
2223

2324
type DBContexter interface {
2425
context.Context
25-
Conn() *sql.DB
26+
Conn() CommonConn
27+
}
28+
29+
type CommonConn interface {
30+
ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
31+
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
32+
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
33+
QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
2634
}
2735

2836
type DBContext struct {
@@ -39,7 +47,11 @@ func NewDBContext(ctx context.Context, conn *sql.DB) *DBContext {
3947
}
4048
}
4149

42-
func (ctx *DBContext) Conn() *sql.DB {
50+
func (ctx *DBContext) Conn() CommonConn {
51+
// use tx first
52+
if ctx.tx != nil {
53+
return ctx.tx
54+
}
4355
return ctx.conn
4456
}
4557

@@ -101,6 +113,15 @@ func RDBTxnExecute(dc *DBContext, handler func(context.Context) error) error {
101113
}
102114
}
103115

116+
defer func() {
117+
if err1 := recover(); err1 != nil {
118+
dc.tx.Rollback()
119+
120+
err = fmt.Errorf("%v", err1)
121+
return
122+
}
123+
}()
124+
104125
err = handler(dc)
105126
return commitOrRollback(dc.tx, err)
106127
}

0 commit comments

Comments
 (0)