-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsqlt.go
100 lines (78 loc) · 1.91 KB
/
sqlt.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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package sqlt
import (
"context"
"database/sql"
"github.com/jmoiron/sqlx"
)
type Rows interface {
Next() bool
NextResultSet() bool
Err() error
Scan(...interface{}) error
MapScan(map[string]interface{}) error
StructScan(interface{}) error
ColumnTypes() ([]*sql.ColumnType, error)
Columns() ([]string, error)
}
type ExtractFunc func(Rows) error
func (e ExtractFunc) Extract(rs Rows) error {
return e(rs)
}
type RowsExtractor interface {
Extract(Rows) error
}
type Dbop struct {
Maker
*sqlx.DB
}
func Default(dbname, dbsource, pattern string) *Dbop {
dbx := MustConnect(dbname, dbsource)
maker := NewSqlTemplate(pattern)
return New(dbx, maker)
}
func New(db *sqlx.DB, maker Maker) *Dbop {
return &Dbop{
DB: db,
Maker: maker,
}
}
func (c *Dbop) TQuery(ctx context.Context, id string, param interface{}, h RowsExtractor) error {
return query(ctx, c, id, param, h)
}
func (c *Dbop) TExec(ctx context.Context, id string, param interface{}) (r sql.Result, e error) {
r, e = exec(ctx, c, id, param)
return
}
func (c *Dbop) TExecRtn(ctx context.Context, id string, param interface{}, h RowsExtractor) error {
return query(ctx, c, id, param, h)
}
func (c *Dbop) TBegin(ctx context.Context, opt *sql.TxOptions) (*Txop, error) {
tx, err := c.BeginTxx(ctx, opt)
if err != nil {
return nil, err
}
return &Txop{
Tx: tx,
Maker: c.Maker,
}, nil
}
type Txop struct {
Maker
*sqlx.Tx
}
func (t *Txop) TQuery(ctx context.Context, id string, param interface{}, h RowsExtractor) error {
return query(ctx, t, id, param, h)
}
func (t *Txop) TExec(ctx context.Context, id string, param interface{}) (r sql.Result, e error) {
r, e = exec(ctx, t, id, param)
return
}
func (t *Txop) TExecRtn(ctx context.Context, id string, param interface{}, h RowsExtractor) error {
return query(ctx, t, id, param, h)
}
func (t *Txop) TCommit() error {
return t.Commit()
}
func (t *Txop) TRollback() error {
return t.Rollback()
}