forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
332 lines (274 loc) · 7.17 KB
/
session.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package db
import (
"context"
"database/sql"
"fmt"
"reflect"
"time"
sq "github.com/Masterminds/squirrel"
"github.com/jmoiron/sqlx"
"github.com/stivens13/go/support/db/sqlutils"
"github.com/stivens13/go/support/errors"
"github.com/stivens13/go/support/log"
)
// Begin binds this session to a new transaction.
func (s *Session) Begin() error {
if s.tx != nil {
return errors.New("already in transaction")
}
tx, err := s.DB.Beginx()
if err != nil {
return errors.Wrap(err, "beginx failed")
}
s.logBegin()
s.tx = tx
return nil
}
// Clone clones the receiver, returning a new instance backed by the same
// context and db. The result will not be bound to any transaction that the
// source is currently within.
func (s *Session) Clone() *Session {
return &Session{
DB: s.DB,
Ctx: s.Ctx,
}
}
// Commit commits the current transaction
func (s *Session) Commit() error {
if s.tx == nil {
return errors.New("not in transaction")
}
err := s.tx.Commit()
s.logCommit()
s.tx = nil
return err
}
// Dialect returns the SQL dialect that this session is configured to use
func (s *Session) Dialect() string {
return s.DB.DriverName()
}
// DeleteRange deletes a range of rows from a sql table between `start` and
// `end` (exclusive).
func (s *Session) DeleteRange(
start, end int64,
table string,
idCol string,
) error {
del := sq.Delete(table).Where(
fmt.Sprintf("%s >= ? AND %s < ?", idCol, idCol),
start,
end,
)
_, err := s.Exec(del)
return err
}
// Get runs `query`, setting the first result found on `dest`, if
// any.
func (s *Session) Get(dest interface{}, query sq.Sqlizer) error {
sql, args, err := s.build(query)
if err != nil {
return err
}
return s.GetRaw(dest, sql, args...)
}
// GetRaw runs `query` with `args`, setting the first result found on
// `dest`, if any.
func (s *Session) GetRaw(dest interface{}, query string, args ...interface{}) error {
query, err := s.ReplacePlaceholders(query)
if err != nil {
return errors.Wrap(err, "replace placeholders failed")
}
start := time.Now()
err = s.conn().Get(dest, query, args...)
s.log("get", start, query, args)
if err == nil {
return nil
}
if s.NoRows(err) {
return err
}
return errors.Wrap(err, "get failed")
}
// GetTable translates the provided struct into a Table,
func (s *Session) GetTable(name string) *Table {
return &Table{
Name: name,
Session: s,
}
}
// Exec runs `query`
func (s *Session) Exec(query sq.Sqlizer) (sql.Result, error) {
sql, args, err := s.build(query)
if err != nil {
return nil, err
}
return s.ExecRaw(sql, args...)
}
// ExecAll runs all sql commands in `script` against `r` within a single
// transaction.
func (s *Session) ExecAll(script string) error {
err := s.Begin()
if err != nil {
return err
}
defer s.Rollback()
for _, cmd := range sqlutils.AllStatements(script) {
_, err = s.ExecRaw(cmd)
if err != nil {
return err
}
}
return s.Commit()
}
// ExecRaw runs `query` with `args`
func (s *Session) ExecRaw(query string, args ...interface{}) (sql.Result, error) {
query, err := s.ReplacePlaceholders(query)
if err != nil {
return nil, errors.Wrap(err, "replace placeholders failed")
}
start := time.Now()
result, err := s.conn().Exec(query, args...)
s.log("exec", start, query, args)
if err == nil {
return result, nil
}
if s.NoRows(err) {
return nil, err
}
return nil, errors.Wrap(err, "exec failed")
}
// NoRows returns true if the provided error resulted from a query that found
// no results.
func (s *Session) NoRows(err error) bool {
return err == sql.ErrNoRows
}
// Query runs `query`, returns a *sqlx.Rows instance
func (s *Session) Query(query sq.Sqlizer) (*sqlx.Rows, error) {
sql, args, err := s.build(query)
if err != nil {
return nil, err
}
return s.QueryRaw(sql, args...)
}
// QueryRaw runs `query` with `args`
func (s *Session) QueryRaw(query string, args ...interface{}) (*sqlx.Rows, error) {
query, err := s.ReplacePlaceholders(query)
if err != nil {
return nil, errors.Wrap(err, "replace placeholders failed")
}
start := time.Now()
result, err := s.conn().Queryx(query, args...)
s.log("query", start, query, args)
if err == nil {
return result, nil
}
if s.NoRows(err) {
return nil, err
}
return nil, errors.Wrap(err, "query failed")
}
// ReplacePlaceholders replaces the '?' parameter placeholders in the provided
// sql query with a sql dialect appropriate version. Use '??' to escape a
// placeholder.
func (s *Session) ReplacePlaceholders(query string) (string, error) {
var format sq.PlaceholderFormat = sq.Question
if s.DB.DriverName() == "postgres" {
format = sq.Dollar
}
return format.ReplacePlaceholders(query)
}
// Rollback rolls back the current transaction
func (s *Session) Rollback() error {
if s.tx == nil {
return errors.New("not in transaction")
}
err := s.tx.Rollback()
s.logRollback()
s.tx = nil
return err
}
// Select runs `query`, setting the results found on `dest`.
func (s *Session) Select(dest interface{}, query sq.Sqlizer) error {
sql, args, err := s.build(query)
if err != nil {
return err
}
return s.SelectRaw(dest, sql, args...)
}
// SelectRaw runs `query` with `args`, setting the results found on `dest`.
func (s *Session) SelectRaw(
dest interface{},
query string,
args ...interface{},
) error {
s.clearSliceIfPossible(dest)
query, err := s.ReplacePlaceholders(query)
if err != nil {
return errors.Wrap(err, "replace placeholders failed")
}
start := time.Now()
err = s.conn().Select(dest, query, args...)
s.log("select", start, query, args)
if err == nil {
return nil
}
if s.NoRows(err) {
return err
}
return errors.Wrap(err, "select failed")
}
// build converts the provided sql builder `b` into the sql and args to execute
// against the raw database connections.
func (s *Session) build(b sq.Sqlizer) (sql string, args []interface{}, err error) {
sql, args, err = b.ToSql()
if err != nil {
err = errors.Wrap(err, "to-sql failed")
}
return
}
// clearSliceIfPossible is a utility function that clears a slice if the
// provided interface wraps one. In the event that `dest` is not a pointer to a
// slice this func will fail with a warning, this allowing the forthcoming db
// select fail more concretely due to an incompatible destination.
func (s *Session) clearSliceIfPossible(dest interface{}) {
v := reflect.ValueOf(dest)
vt := v.Type()
if vt.Kind() != reflect.Ptr {
log.Warn("cannot clear slice: dest is not pointer")
return
}
if vt.Elem().Kind() != reflect.Slice {
log.Warn("cannot clear slice: dest is a pointer, but not to a slice")
return
}
reflect.Indirect(v).SetLen(0)
}
func (s *Session) conn() Conn {
if s.tx != nil {
return s.tx
}
return s.DB
}
func (s *Session) log(typ string, start time.Time, query string, args []interface{}) {
log.
Ctx(s.logCtx()).
WithField("args", args).
WithField("sql", query).
WithField("dur", time.Since(start).String()).
Debugf("sql: %s", typ)
}
func (s *Session) logBegin() {
log.Ctx(s.logCtx()).Debug("sql: begin")
}
func (s *Session) logCommit() {
log.Ctx(s.logCtx()).Debug("sql: commit")
}
func (s *Session) logRollback() {
log.Ctx(s.logCtx()).Debug("sql: rollback")
}
func (s *Session) logCtx() context.Context {
if s.Ctx != nil {
return s.Ctx
}
return context.Background()
}