-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.go
381 lines (303 loc) · 9.22 KB
/
storage.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package sqluct
import (
"context"
"database/sql"
"errors"
"reflect"
"github.com/Masterminds/squirrel"
"github.com/bool64/ctxd"
"github.com/jmoiron/sqlx"
)
// ToSQL defines query builder.
type ToSQL interface {
ToSql() (string, []interface{}, error)
}
// StringStatement is a plain string statement.
type StringStatement string
// Plain is a plain string statement.
type Plain = StringStatement
// ToSql implements query builder result.
func (s StringStatement) ToSql() (string, []interface{}, error) { //nolint // Method name matches ext. implementation.
return string(s), nil, nil
}
type stmt struct {
query string
args []interface{}
}
func (s stmt) ToSql() (string, []interface{}, error) { //nolint // Method name matches ext. implementation.
return s.query, s.args, nil
}
// Stmt is a statement with placeholder arguments.
func Stmt(query string, args ...interface{}) ToSQL {
return stmt{
query: query,
args: args,
}
}
// Open opens a database specified by its database driver name and a
// driver-specific data source name, usually consisting of at least a
// database name and connection information.
func Open(driverName, dataSourceName string) (*Storage, error) {
db, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
dbx := sqlx.NewDb(db, driverName)
s := Storage{
db: dbx,
Mapper: &Mapper{},
}
switch driverName {
case "postgres":
s.Mapper.Dialect = DialectPostgres
s.Format = squirrel.Dollar
s.IdentifierQuoter = QuoteANSI
case "mysql":
s.Mapper.Dialect = DialectMySQL
s.Format = squirrel.Question
s.IdentifierQuoter = QuoteBackticks
case "sqlite3", "sqlite":
s.Mapper.Dialect = DialectSQLite3
s.Format = squirrel.Question
s.IdentifierQuoter = QuoteBackticks
}
return &s, nil
}
// NewStorage creates an instance of Storage.
func NewStorage(db *sqlx.DB) *Storage {
return &Storage{
db: db,
}
}
// Storage creates and executes database statements.
type Storage struct {
db *sqlx.DB
Mapper *Mapper
// Format is a placeholder format, default squirrel.Dollar.
// Other values are squirrel.Question, squirrel.AtP and squirrel.Colon.
Format squirrel.PlaceholderFormat
// IdentifierQuoter is formatter of column and table names.
// Default QuoteNoop.
IdentifierQuoter func(tableAndColumn ...string) string
// OnError is called when error is encountered, could be useful for logging.
OnError func(ctx context.Context, err error)
// Trace wraps a call to database.
// It takes statement as arguments and returns
// instrumented context with callback to call after db call is finished.
Trace func(ctx context.Context, stmt string, args []interface{}) (newCtx context.Context, onFinish func(error))
}
// Dialect defines SQL dialect.
type Dialect string
// Supported dialects.
const (
DialectUnknown = Dialect("")
DialectMySQL = Dialect("mysql")
DialectPostgres = Dialect("postgres")
DialectSQLite3 = Dialect("sqlite3")
)
// InTx runs callback in a transaction.
//
// If transaction already exists, it will reuse that. Otherwise, it starts a new transaction and commit or rollback
// (in case of error) at the end.
func (s *Storage) InTx(ctx context.Context, fn func(context.Context) error) (err error) {
var finish func(ctx context.Context, err error) error
if tx := TxFromContext(ctx); tx == nil {
finish = s.submitTx
// Start a new transaction.
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return s.error(ctx, ctxd.WrapError(ctx, err, "failed to begin tx"))
}
ctx = TxToContext(ctx, tx)
} else {
// Do nothing because parent tx is still running and
// this is not the beginner, so it can't be the finisher.
finish = func(_ context.Context, err error) error {
return err
}
}
defer func() {
err = finish(ctx, err)
}()
return fn(ctx)
}
func (s *Storage) submitTx(ctx context.Context, err error) error {
tx := TxFromContext(ctx)
if tx == nil {
err := ctxd.NewError(ctx, "no running transaction")
return s.error(ctx, err)
}
if err != nil {
if rbErr := tx.Rollback(); rbErr != nil {
return s.error(ctx, ctxd.WrapError(ctx, rbErr, "failed to rollback",
"error", err,
))
}
return err
}
if err := tx.Commit(); err != nil {
return s.error(ctx, ctxd.WrapError(ctx, err, "failed to commit"))
}
return nil
}
// Exec executes query according to query builder.
func (s *Storage) Exec(ctx context.Context, qb ToSQL) (res sql.Result, err error) {
var execer sqlx.ExecerContext
if tx := TxFromContext(ctx); tx != nil {
execer = tx
} else {
execer = s.db
}
query, args, err := qb.ToSql()
if err != nil {
return nil, s.error(ctx, ctxd.WrapError(ctx, err, "failed to build query"))
}
if s.Trace != nil {
ct, def := s.Trace(ctx, query, args)
ctx = ct
defer func() { def(err) }()
}
res, err = execer.ExecContext(ctx, query, args...)
if err != nil {
return nil, s.error(ctx, err)
}
return res, nil
}
// Query queries database and returns raw result.
//
// Select is recommended to use instead of Query.
func (s *Storage) Query(ctx context.Context, qb ToSQL) (*sqlx.Rows, error) {
query, args, err := qb.ToSql()
if err != nil {
return nil, s.error(ctx, ctxd.WrapError(ctx, err, "failed to build query"))
}
if s.Trace != nil {
ct, def := s.Trace(ctx, query, args)
ctx = ct
defer func() { def(err) }()
}
var queryer sqlx.QueryerContext
if tx := TxFromContext(ctx); tx != nil {
queryer = tx
} else {
queryer = s.db
}
rows, err := queryer.QueryxContext(ctx, query, args...)
if err != nil {
return nil, s.error(ctx, err)
}
return rows, nil
}
// Select queries statement of query builder and scans result into destination.
//
// Destination can be a pointer to struct or slice, e.g. `*row` or `*[]row`.
func (s *Storage) Select(ctx context.Context, qb ToSQL, dest interface{}) (err error) {
query, args, err := qb.ToSql()
if err != nil {
return s.error(ctx, ctxd.WrapError(ctx, err, "failed to build query"))
}
if s.Trace != nil {
ct, def := s.Trace(ctx, query, args)
ctx = ct
defer func() { def(err) }()
}
var queryer sqlx.QueryerContext
if tx := TxFromContext(ctx); tx != nil {
queryer = tx
} else {
queryer = s.db
}
kind := reflect.Indirect(reflect.ValueOf(dest)).Kind()
if kind == reflect.Slice {
err = sqlx.SelectContext(ctx, queryer, dest, query, args...)
} else {
err = sqlx.GetContext(ctx, queryer, dest, query, args...)
}
return s.error(ctx, err)
}
// QueryBuilder returns query builder with placeholder format.
func (s *Storage) QueryBuilder() squirrel.StatementBuilderType {
format := s.Format
if format == nil {
format = squirrel.Dollar
}
return squirrel.StatementBuilder.PlaceholderFormat(format).RunWith(s.db)
}
func (s *Storage) options(options []func(*Options)) []func(*Options) {
if s.IdentifierQuoter != nil {
options = append(options, func(options *Options) {
if options.PrepareColumn == nil {
options.PrepareColumn = func(col string) string {
return s.IdentifierQuoter(col)
}
}
})
}
return options
}
// SelectStmt makes a select query builder.
func (s *Storage) SelectStmt(tableName string, columns interface{}, options ...func(*Options)) squirrel.SelectBuilder {
if s.IdentifierQuoter != nil {
tableName = s.IdentifierQuoter(tableName)
}
qb := s.QueryBuilder().Select().From(tableName)
return mapper(s.Mapper).Select(qb, columns, s.options(options)...).RunWith(s.db)
}
// InsertStmt makes an insert query builder.
func (s *Storage) InsertStmt(tableName string, val interface{}, options ...func(*Options)) squirrel.InsertBuilder {
if s.IdentifierQuoter != nil {
tableName = s.IdentifierQuoter(tableName)
}
qb := s.QueryBuilder().Insert(tableName)
return mapper(s.Mapper).Insert(qb, val, s.options(options)...).RunWith(s.db)
}
// UpdateStmt makes an update query builder.
func (s *Storage) UpdateStmt(tableName string, val interface{}, options ...func(*Options)) squirrel.UpdateBuilder {
if s.IdentifierQuoter != nil {
tableName = s.IdentifierQuoter(tableName)
}
qb := s.QueryBuilder().Update(tableName)
return mapper(s.Mapper).Update(qb, val, s.options(options)...).RunWith(s.db)
}
// DeleteStmt makes a delete query builder.
func (s *Storage) DeleteStmt(tableName string) squirrel.DeleteBuilder {
if s.IdentifierQuoter != nil {
tableName = s.IdentifierQuoter(tableName)
}
return s.QueryBuilder().Delete(tableName).RunWith(s.db)
}
// Col will try to find column name and will panic on error.
func (s *Storage) Col(structPtr, fieldPtr interface{}) string {
col := mapper(s.Mapper).Col(structPtr, fieldPtr)
if s.IdentifierQuoter != nil {
col = s.IdentifierQuoter(col)
}
return col
}
// MakeReferencer creates Referencer for query builder.
func (s *Storage) MakeReferencer() *Referencer {
return &Referencer{
Mapper: s.Mapper,
IdentifierQuoter: s.IdentifierQuoter,
}
}
// WhereEq maps struct values as conditions to squirrel.Eq.
func (s *Storage) WhereEq(conditions interface{}, options ...func(*Options)) squirrel.Eq {
return mapper(s.Mapper).WhereEq(conditions, s.options(options)...)
}
func (s *Storage) error(ctx context.Context, err error) error {
if err != nil && !errors.Is(err, sql.ErrNoRows) && s.OnError != nil {
s.OnError(ctx, err)
}
return err
}
func mapper(m *Mapper) *Mapper {
if m == nil {
return defaultMapper
}
return m
}
// DB returns database instance.
func (s *Storage) DB() *sqlx.DB {
return s.db
}