-
Notifications
You must be signed in to change notification settings - Fork 17
/
transaction.go
89 lines (77 loc) · 2.33 KB
/
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
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
package crud
import (
"context"
stdsql "database/sql"
"github.com/azer/logger"
)
type Tx struct {
Context context.Context
Client *stdsql.Tx
Id string
IdKey string
}
// Execute any SQL query on the transaction client. Returns sql.Result.
func (tx *Tx) Exec(sql string, params ...interface{}) (stdsql.Result, error) {
timer := log.Timer()
result, err := tx.Client.ExecContext(tx.Context, sql, params...)
timer.End("Executed SQL query.", logger.Attrs{
tx.IdKey: tx.Id,
"sql": sql,
})
return result, err
}
// Execute any SQL query on the transaction client. Returns sql.Rows.
func (tx *Tx) Query(sql string, params ...interface{}) (*stdsql.Rows, error) {
timer := log.Timer()
result, err := tx.Client.QueryContext(tx.Context, sql, params...)
timer.End("Run SQL query.", logger.Attrs{
tx.IdKey: tx.Id,
"sql": sql,
})
return result, err
}
// Commit the transaction.
func (tx *Tx) Commit() error {
log.Info("Committing", logger.Attrs{
tx.IdKey: tx.Id,
})
return tx.Client.Commit()
}
// Rollback the transaction.
func (tx *Tx) Rollback() error {
log.Info("Rolling back", logger.Attrs{
tx.IdKey: tx.Id,
})
return tx.Client.Rollback()
}
// Insert given record to the database.
func (tx *Tx) Create(record interface{}) error {
return create(tx.Exec, record)
}
// Inserts given record and scans the inserted row back to the given row.
func (tx *Tx) CreateAndRead(record interface{}) error {
return createAndRead(tx.Exec, tx.Query, record)
}
// Run a select query on the databaase (w/ given parameters optionally) and scan the result(s) to the
// target interface specified as the first parameter.
//
// Usage Example:
//
// user := &User{}
// err := tx.Read(user, "SELECT * FROM users WHERE id = ?", 1)
//
// users := &[]*User{}
// err := tx.Read(users, "SELECT * FROM users", 1)
//
func (tx *Tx) Read(scanTo interface{}, params ...interface{}) error {
return read(tx.Query, scanTo, params)
}
// Run an update query on the transaction, finding out the primary-key field of the given row.
func (tx *Tx) Update(record interface{}) error {
return mustUpdate(tx.Exec, record)
}
// Executes a DELETE query on the transaction for given struct record. It matches
// the database row by finding out the primary key field defined in the table schema.
func (tx *Tx) Delete(record interface{}) error {
return mustDelete(tx.Exec, record)
}