-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo.go
82 lines (68 loc) · 1.52 KB
/
repo.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
package sqlite
import (
"github.com/jmoiron/sqlx"
repo "github.com/xopoww/wishes/internal/service/repository"
)
type handle struct {
ext sqlx.ExtContext
t Trace
}
var _ repo.Handle = (*handle)(nil)
func (h *handle) db() *sqlx.DB {
db, ok := h.ext.(*sqlx.DB)
if !ok || db == nil {
panic("sqlite: handle.db() called on wrong handle")
}
return db
}
func (h *handle) tx() *sqlx.Tx {
tx, ok := h.ext.(*sqlx.Tx)
if !ok || tx == nil {
panic("sqlite: handle.tx() called on wrong handle")
}
return tx
}
type transaction struct {
handle
}
func (t *transaction) Commit() (err error) {
onDone := traceOnTxEnd(t.t, true)
defer func() { onDone(err) }()
err = t.handle.tx().Commit()
return err
}
func (t *transaction) Rollback() (err error) {
onDone := traceOnTxEnd(t.t, false)
defer func() { onDone(err) }()
err = t.handle.tx().Rollback()
return err
}
type repository struct {
handle
}
func NewRepository(dbs string, t Trace) (repo.Repository, error) {
onDone := traceOnConnect(t, dbs)
defer onDone()
dbs += "?_foreign_keys=1"
db, err := sqlx.Connect("sqlite3", dbs)
if err != nil {
return nil, err
}
return &repository{handle: handle{ext: db, t: t}}, nil
}
func (r *repository) Begin() (repo.Transaction, error) {
onDone := traceOnTxBegin(r.t)
var (
tx *sqlx.Tx
err error
)
defer func() { onDone(err) }()
tx, err = r.handle.db().Beginx()
if err != nil {
return nil, err
}
return &transaction{handle: handle{ext: tx, t: r.t}}, nil
}
func (r *repository) Close() error {
return r.handle.db().Close()
}