-
Notifications
You must be signed in to change notification settings - Fork 6
/
db.go
54 lines (45 loc) · 1.04 KB
/
db.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
package y
import (
"database/sql"
sq "github.com/Masterminds/squirrel"
)
// Versionable mixins a version to a model
type Versionable struct {
Version sql.NullInt64 `json:"-" y:"_version"`
}
// MakeVersionable inits a new version
func MakeVersionable(n int64) Versionable {
return Versionable{
sql.NullInt64{Int64: n, Valid: true},
}
}
// Qualifier updates a select builder if you need
type Qualifier func(sq.SelectBuilder) sq.SelectBuilder
// ByEq returns the filter by squirrel.Eq
var ByEq = func(eq sq.Eq) Qualifier {
return func(b sq.SelectBuilder) sq.SelectBuilder {
return b.Where(eq)
}
}
// ByID returns the filter by ID
var ByID = func(id interface{}) Qualifier {
return ByEq(sq.Eq{"id": id})
}
// TxPipe run some db statement
type TxPipe func(sq.BaseRunner) error
// Tx executes statements in a transaction
func Tx(db *sql.DB, pipes ...TxPipe) (err error) {
tx, err := db.Begin()
if err != nil {
return
}
for _, pipe := range pipes {
err = pipe(tx)
if err != nil {
tx.Rollback()
return
}
}
tx.Commit()
return
}