forked from square/squalor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
1572 lines (1401 loc) · 44.7 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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package squalor
import (
"bytes"
"database/sql"
"errors"
"fmt"
"io"
"reflect"
"sort"
"sync"
"time"
"golang.org/x/net/context"
)
// ErrMixedAutoIncrIDs is returned when attempting to insert multiple
// records with a mixture of set and unset auto increment ids. This
// case is difficult to handle correctly, so for now either we update
// all the ids, or none at all.
var ErrMixedAutoIncrIDs = errors.New("sql: auto increment column must be all set or unset")
// ErrConcurrentModificationDetected is returned when attempting to update
// versioned records, and concurrent modifications by another transaction
// are detected.
var ErrConcurrentModificationDetected = errors.New("sql: concurrent modification detected")
// Executor defines the common interface for executing operations on a
// DB or on a Tx.
type Executor interface {
Delete(list ...interface{}) (int64, error)
Exec(query interface{}, args ...interface{}) (sql.Result, error)
Get(dest interface{}, keys ...interface{}) error
Insert(list ...interface{}) error
Query(query interface{}, args ...interface{}) (*Rows, error)
QueryRow(query interface{}, args ...interface{}) *Row
Replace(list ...interface{}) error
Select(dest interface{}, query interface{}, args ...interface{}) error
Update(list ...interface{}) (int64, error)
Upsert(list ...interface{}) error
}
// ExecutorContext extends the Executor interface by allowing a Context object to be supplied by
// the code issuing a query, and later accessed within a QueryLogger.
type ExecutorContext interface {
Executor
// Returns an Executor that is equivalent to this Executor, expect that the
// returned Executor's GetContext() function will return the supplied Context.
// This Executor is unchanged. The supplied Context must not be nil.
WithContext(ctx context.Context) ExecutorContext
// Returns the Context supplied when this Executor was created by WithContext,
// or Context.Background() if WithContext was never called.
GetContext() context.Context
}
var _ ExecutorContext = &DB{}
var _ ExecutorContext = &Tx{}
func writeStrings(buf *bytes.Buffer, strs ...string) {
for _, s := range strs {
if _, err := buf.WriteString(s); err != nil {
panic(err)
}
}
}
type deletePlan struct {
deleteBuilder *DeleteBuilder
keyColumns []ValExprBuilder
traversals [][]int
hooks deleteHooks
}
func makeDeletePlan(m *Model) deletePlan {
p := deletePlan{}
p.deleteBuilder = m.Delete()
p.keyColumns = make([]ValExprBuilder, len(m.PrimaryKey.Columns))
columns := make([]string, len(m.PrimaryKey.Columns))
for i, col := range m.PrimaryKey.Columns {
p.keyColumns[i] = m.Table.C(col.Name)
columns[i] = col.Name
}
p.traversals = m.fields.getTraversals(columns)
return p
}
type getPlan struct {
selectBuilder *SelectBuilder
keyColumns []ValExprBuilder
traversals [][]int
hooks getHooks
}
func makeGetPlan(m *Model) getPlan {
p := getPlan{}
p.selectBuilder = m.Select(m.AllMapped())
p.traversals = m.fields.getTraversals(m.mappedColNames)
p.keyColumns = make([]ValExprBuilder, len(m.PrimaryKey.Columns))
for i, col := range m.PrimaryKey.Columns {
p.keyColumns[i] = m.Table.C(col.Name)
}
return p
}
type insertPlan struct {
insertBuilder *InsertBuilder
replaceBuilder *ReplaceBuilder
traversals [][]int
autoIncr []int
autoIncrInt bool
hooks hooks
}
func makeInsertPlan(m *Model, replace bool) insertPlan {
p := insertPlan{}
var columns []interface{}
for _, col := range m.mappedColumns {
columns = append(columns, m.Table.C(col.Name))
if col.AutoIncr {
f, ok := m.fields[col.Name]
if !ok {
panic(fmt.Errorf("%s: unable to find field %s", m.Name, col))
}
p.autoIncr = f.Index
switch f.Type.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p.autoIncrInt = true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
p.autoIncrInt = false
default:
panic(fmt.Errorf("%s: expecting int or uint for auto-increment field %s but got %s", m.Name, col, f.Type.Kind()))
}
}
}
if replace {
p.replaceBuilder = m.Replace(columns...)
p.hooks = replaceHooks{}
} else {
p.insertBuilder = m.Insert(columns...)
p.hooks = insertHooks{}
}
p.traversals = m.fields.getTraversals(m.mappedColNames)
return p
}
func makeUpsertPlan(m *Model) insertPlan {
p := makeInsertPlan(m, false)
// We're not able to process auto-increment columns on upsert. Don't
// even try.
p.autoIncr = nil
primaryKey := map[string]bool{}
for _, col := range m.PrimaryKey.Columns {
primaryKey[col.Name] = true
}
for _, col := range m.mappedColumns {
if col.AutoIncr || primaryKey[col.Name] {
continue
}
p.insertBuilder.OnDupKeyUpdateColumn(col.Name)
}
p.hooks = upsertHooks{}
return p
}
type updatePlan struct {
updateBuilder *UpdateBuilder
setColumns []ValExprBuilder
setColumnsSetter []func(reflect.Value, int) interface{}
setTraversals [][]int
whereColumns []ValExprBuilder
whereTraversals [][]int
hooks updateHooks
}
func makeUpdatePlan(m *Model) updatePlan {
p := updatePlan{}
p.updateBuilder = m.Update()
primaryKey := map[string]bool{}
whereColNames := make([]string, len(m.PrimaryKey.Columns))
p.whereColumns = make([]ValExprBuilder, len(m.PrimaryKey.Columns))
for i, col := range m.PrimaryKey.Columns {
primaryKey[col.Name] = true
p.whereColumns[i] = m.Table.C(col.Name)
whereColNames[i] = col.Name
}
if m.optlockColumnName != nil {
name := *m.optlockColumnName
p.whereColumns = append(p.whereColumns, m.Table.C(name))
whereColNames = append(whereColNames, name)
}
p.whereTraversals = m.fields.getTraversals(whereColNames)
var setColumns []string
for _, col := range m.mappedColumns {
if col.AutoIncr || primaryKey[col.Name] {
continue
}
setColumns = append(setColumns, col.Name)
p.setColumns = append(p.setColumns, m.Table.C(col.Name))
var setter func(reflect.Value, int) interface{}
if name := col.Name; m.optlockColumnName != nil && *m.optlockColumnName == name {
setter = func(reflect.Value, int) interface{} {
return m.C(name).Plus(NumVal("1"))
}
} else {
setter = func(v reflect.Value, i int) interface{} {
return v.FieldByIndex(m.update.setTraversals[i]).Interface()
}
}
p.setColumnsSetter = append(p.setColumnsSetter, setter)
}
p.setTraversals = m.fields.getTraversals(setColumns)
return p
}
// A Model contains the precomputed data for a model binding to a
// table.
type Model struct {
// The table the model is associated with.
Table
// The DB the model is associated with.
db *DB
// The mapping from column name to model object field info.
fields fieldMap
// All DB columns that are mapped in the model.
mappedColumns []*Column
mappedColNames []string
// The name of the column used for optimistic locking, if any.
optlockColumnName *string
// The incrementor for the version field, if any.
optlockInc func(reflect.Value)
// The precomputed query plans.
delete deletePlan
get getPlan
insert insertPlan
replace insertPlan
update updatePlan
upsert insertPlan
}
func newModel(db *DB, t reflect.Type, table Table) (*Model, error) {
m := &Model{
db: db,
Table: table,
fields: getDBFields(t),
}
mappedColumns, err := m.fields.getMappedColumns(m.Columns, db.IgnoreUnmappedCols, db.IgnoreMissingCols)
if err != nil {
panic(fmt.Errorf("%s: %s", table.Name, err))
}
m.mappedColumns = mappedColumns
m.mappedColNames = getColumnNames(m.mappedColumns)
if n, f, err := m.fields.getOptlockColumnNameAndInc(); err != nil {
panic(fmt.Errorf("%s: %s", table.Name, err))
} else {
m.optlockColumnName = n
m.optlockInc = f
}
m.delete = makeDeletePlan(m)
m.get = makeGetPlan(m)
m.insert = makeInsertPlan(m, false)
m.replace = makeInsertPlan(m, true)
m.update = makeUpdatePlan(m)
m.upsert = makeUpsertPlan(m)
return m, nil
}
// All builds a val expression to select all columns mapped by the model.
func (m *Model) AllMapped() ValExprBuilder {
return m.C(m.mappedColNames...)
}
// All builds a val expression to select all columns on the model's Table.
// WARNING: This is probably not the method you want. Call AllMapped() instead.
func (m *Model) All() ValExprBuilder {
if m.db.IgnoreUnmappedCols {
fmt.Print("WARNING: Calling All() on a model will include unmapped columns if they are present.")
}
return m.Table.All()
}
func getColumnNames(columns []*Column) []string {
var colNames []string
for _, c := range columns {
colNames = append(colNames, c.Name)
}
return colNames
}
func getInsert(m *Model) insertPlan {
return m.insert
}
func getReplace(m *Model) insertPlan {
return m.replace
}
func getUpsert(m *Model) insertPlan {
return m.upsert
}
// stringSerializer is a wrapper around a string that implements Serializer.
type stringSerializer string
func (ss stringSerializer) Serialize(w Writer) error {
_, err := io.WriteString(w, string(ss))
return err
}
// DB is a wrapper around a sql.DB which also implements the
// squalor.Executor interface. DB is safe for concurrent use by
// multiple goroutines.
type DB struct {
*sql.DB
AllowStringQueries bool
// Whether to ignore missing columns referenced in models for the various DB
// function calls such as StructScan, Select, Insert, BindModel, etc.
//
// The default is false, disallowing models to be bound when missing columns
// are detected to avoid run time surprises (e.g. fields not being saved).
IgnoreMissingCols bool
// Whether to ignore unmapped columns for the various DB function calls such as StructScan,
// Select, Insert, BindModel, etc. When set to true, it can suppress column mapping validation
// errors at DB migration time when new columns are added but the previous version of the binary
// is still in use, either actively running or getting started up.
//
// The default is true that ignores the unmapped columns.
// NOTE: Unmapped columns in primary keys are still not allowed.
IgnoreUnmappedCols bool
Context context.Context
Logger QueryLogger
mu sync.RWMutex
models map[reflect.Type]*Model
mappings map[reflect.Type]fieldMap
}
// NewDB creates a new DB from an sql.DB.
func NewDB(db *sql.DB) *DB {
return &DB{
DB: db,
AllowStringQueries: true,
IgnoreUnmappedCols: true,
IgnoreMissingCols: false,
Context: context.Background(),
Logger: nil,
models: map[reflect.Type]*Model{},
mappings: map[reflect.Type]fieldMap{},
}
}
func (db *DB) logQuery(query Serializer, exec Executor, start time.Time, err error) {
if db.Logger == nil {
return
}
executionTime := time.Now().Sub(start)
db.Logger.Log(query, exec, executionTime, err)
}
// GetModel retrieves the model for the specified object. Obj must be
// a struct. An error is returned if obj has not been bound to a table
// via a call to BindModel.
func (db *DB) GetModel(obj interface{}) (*Model, error) {
return db.getModel(reflect.TypeOf(obj))
}
func (db *DB) getModel(t reflect.Type) (*Model, error) {
db.mu.RLock()
defer db.mu.RUnlock()
if model, ok := db.models[t]; ok {
return model, nil
}
return nil, fmt.Errorf("unable to find model for '%s'", t)
}
func (db *DB) getMapping(t reflect.Type) fieldMap {
db.mu.RLock()
mapping := db.mappings[t]
db.mu.RUnlock()
if mapping != nil {
return mapping
}
// Note that concurrent calls to getMapping for the same type might
// create multiple (identical) mappings, only one of which will be
// cached. This is fine as the mappings are readonly and nothing
// using them relies on their identity.
mapping = getDBFields(t)
db.mu.Lock()
db.mappings[t] = mapping
db.mu.Unlock()
return mapping
}
func (db *DB) getSerializer(query interface{}) (Serializer, error) {
if t, ok := query.(Serializer); ok {
return t, nil
}
if db.AllowStringQueries {
switch t := query.(type) {
case string:
return stringSerializer(t), nil
}
}
return nil, fmt.Errorf("unsupported query type %T", query)
}
// BindModel binds the supplied interface with the named table. You
// must bind the model for any object you wish to perform operations
// on. It is an error to bind the same model type more than once and a
// single model type can only be bound to a single table.
// note: name does not get escaped. The libary assumes the parameter
// is a literal string and is safe.
func (db *DB) BindModel(name string, obj interface{}) (*Model, error) {
t := deref(reflect.TypeOf(obj))
db.mu.Lock()
m := db.models[t]
db.mu.Unlock()
if m != nil {
return nil, fmt.Errorf("%s: model '%T' already defined", name, obj)
}
table, err := LoadTable(db.DB, name)
if err != nil {
return nil, err
}
if table.PrimaryKey == nil {
return nil, fmt.Errorf("%s: table has no primary key", name)
}
m, err = newModel(db, t, *table)
if err != nil {
return nil, err
}
db.mu.Lock()
db.models[t] = m
db.mappings[t] = m.fields
db.mu.Unlock()
return m, nil
}
// MustBindModel binds the supplied interface with the named table,
// panicking if an error occurs.
func (db *DB) MustBindModel(name string, obj interface{}) *Model {
model, err := db.BindModel(name, obj)
if err != nil {
panic(fmt.Errorf("%s: unable to bind model: %s", name, err))
}
return model
}
func (db *DB) WithContext(ctx context.Context) ExecutorContext {
if ctx == nil {
panic(fmt.Errorf("Nil Context passed to Executor.WithContext"))
}
newDB := *db
newDB.Context = ctx
return &newDB
}
func (db *DB) GetContext() context.Context {
return db.Context
}
// Delete runs a batched SQL DELETE statement, grouping the objects by
// the model type of the list elements. List elements must be pointers
// to structs.
//
// On success, returns the number of rows deleted.
//
// Returns an error if an element in the list has not been registered
// with BindModel.
//
// Due to MySQL limitations, batch deletions are more restricted than
// insertions. The most natural implementation would be something
// like:
//
// DELETE FROM <table> WHERE (<cols>...) IN ((<vals1>), (<vals2>), ...)
//
// This works except that it is spectactularly slow if there is more
// than one column in the primary key. MySQL changes this into a
// full table scan and then compares the primary key for each row
// with the "IN" set of values.
//
// Instead, we batch up deletions based on the first n-1 primary key
// columns. For a two column primary key this looks like:
//
// DELETE FROM <table> WHERE <cols1>=<val1> and <col2> IN (<val2>...)
//
// If you're deleting a batch of objects where the first primary key
// column differs for each object this degrades to non-batched
// deletion. But if your first primary key column is identical then
// batching can work perfectly.
func (db *DB) Delete(list ...interface{}) (int64, error) {
return deleteObjects(db, db, list)
}
// Exec executes a query without returning any rows. The args are for any
// placeholder parameters in the query.
func (db *DB) Exec(query interface{}, args ...interface{}) (sql.Result, error) {
serializer, err := db.getSerializer(query)
if err != nil {
return nil, err
}
querystr, err := Serialize(serializer)
if err != nil {
return nil, err
}
start := time.Now()
argsConverted := argsConvert(args)
result, err := db.DB.Exec(querystr, argsConverted...)
db.logQuery(serializer, db, start, err)
return result, err
}
// Get runs a SQL SELECT to fetch a single row. Keys must be the
// primary keys defined for the table. The order must match the order
// of the columns in the primary key.
//
// Returns an error if the object type has not been registered with
// BindModel.
func (db *DB) Get(dest interface{}, keys ...interface{}) error {
return getObject(db, db, dest, keys)
}
// Insert runs a batched SQL INSERT statement, grouping the objects by
// the model type of the list elements. List elements must be pointers
// to structs.
//
// An object bound to a table with an auto-increment column will have
// its corresponding field filled in with the generated value if a
// pointer to the object was passed in "list".
//
// Returns an error if an element in the list has not been registered
// with BindModel.
func (db *DB) Insert(list ...interface{}) error {
return insertObjects(db, db, getInsert, list)
}
// Query executes a query that returns rows, typically a SELECT. The
// args are for any placeholder parameters in the query. This is a
// small wrapper around sql.DB.Query that returns a *squalor.Rows
// instead.
func (db *DB) Query(query interface{}, args ...interface{}) (*Rows, error) {
serializer, err := db.getSerializer(query)
if err != nil {
return nil, err
}
querystr, err := Serialize(serializer)
if err != nil {
return nil, err
}
start := time.Now()
argsConverted := argsConvert(args)
rows, err := db.DB.Query(querystr, argsConverted...)
db.logQuery(serializer, db, start, err)
if err != nil {
return nil, err
}
return &Rows{Rows: rows, db: db}, nil
}
// QueryRow executes a query that is expected to return at most one
// row. QueryRow always return a non-nil value. Errors are deferred
// until Row's Scan method is called. This is a small wrapper around
// sql.DB.QueryRow that returns a *squalor.Row instead.
func (db *DB) QueryRow(query interface{}, args ...interface{}) *Row {
serializer, err := db.getSerializer(query)
if err != nil {
return &Row{rows: Rows{Rows: nil, db: nil}, err: err}
}
querystr, err := Serialize(serializer)
if err != nil {
return &Row{rows: Rows{Rows: nil, db: nil}, err: err}
}
start := time.Now()
argsConverted := argsConvert(args)
rows, err := db.DB.Query(querystr, argsConverted...)
db.logQuery(serializer, db, start, err)
return &Row{rows: Rows{Rows: rows, db: db}, err: err}
}
// Replace runs a batched SQL REPLACE statement, grouping the objects
// by the model type of the list elements. List elements must be
// pointers to structs.
//
// Note that REPLACE is effectively an INSERT followed by a DELETE and
// INSERT if the object already exists. The REPLACE may fail if the
// DELETE would violate foreign key constraints. Due to the batched
// nature of the Replace implementation it is not possible to
// accurately return the assignment of auto-increment values. Updating
// of an existing object will cause the auto-increment column to
// change.
//
// Returns an error if an element in the list has not been registered
// with BindModel.
func (db *DB) Replace(list ...interface{}) error {
return insertObjects(db, db, getReplace, list)
}
// Select runs an arbitrary SQL query, unmarshalling the matching rows
// into the fields on the struct specified by dest. Args are the
// parameters to the SQL query.
//
// It is ok for dest to refer to a struct that has not been bound to a
// table. This allows querying for values that return transient
// columnts. For example, "SELECT count(*) ..." will return a "count"
// column.
//
// dest must be a pointer to a slice. Either *[]struct{} or
// *[]*struct{} is allowed. It is mildly more efficient to use
// *[]struct{} due to the reduced use of reflection and allocation.
func (db *DB) Select(dest interface{}, q interface{}, args ...interface{}) error {
return selectObjects(db, dest, q, args)
}
// Update runs a SQL UPDATE statement for each element in list. List
// elements may be structs or pointers to structs.
//
// On success, returns the number of rows updated.
//
// Returns an error if an element in the list has not been registered
// with BindModel.
func (db *DB) Update(list ...interface{}) (int64, error) {
return updateObjects(db, db, list)
}
// Upsert runs a SQL INSERT ON DUPLICATE KEY UPDATE statement for each
// element in list. List elements must be pointers to structs.
//
// Returns an error if an element in the list has not been registered
// with BindModel.
func (db *DB) Upsert(list ...interface{}) error {
return insertObjects(db, db, getUpsert, list)
}
// Begin begins a transaction and returns a *squalor.Tx instead of a
// *sql.Tx.
func (db *DB) Begin() (*Tx, error) {
tx, err := db.DB.Begin()
if err != nil {
return nil, err
}
return &Tx{Tx: tx, DB: db}, nil
}
// Tx is a wrapper around sql.Tx which also implements the
// squalor.Executor interface.
type Tx struct {
*sql.Tx
DB *DB
preHooks []PreCommit
postHooks []PostCommit
}
// AddPreCommitHook adds a pre-commit hook to this transaction.
func (tx *Tx) AddPreCommitHook(pre PreCommit) {
tx.preHooks = append(tx.preHooks, pre)
}
// AddPostCommitHook adds a post-commit hook to this transaction.
func (tx *Tx) AddPostCommitHook(post PostCommit) {
tx.postHooks = append(tx.postHooks, post)
}
// Commit is a wrapper around sql.Tx.Commit() which also provides pre- and post-
// commit hooks.
func (tx *Tx) Commit() error {
for _, pre := range tx.preHooks {
if err := pre(tx); err != nil {
return err
}
}
err := tx.Tx.Commit()
for _, post := range tx.postHooks {
post(err)
}
return err
}
func (tx *Tx) WithContext(ctx context.Context) ExecutorContext {
if ctx == nil {
panic(fmt.Errorf("Nil Context passed to Executor.WithContext"))
}
newTx := *tx
newDB := *newTx.DB
newDB.Context = ctx
newTx.DB = &newDB
return &newTx
}
func (tx *Tx) GetContext() context.Context {
return tx.DB.GetContext()
}
// Exec executes a query that doesn't return rows. For example: an
// INSERT and UPDATE.
func (tx *Tx) Exec(query interface{}, args ...interface{}) (sql.Result, error) {
serializer, err := tx.DB.getSerializer(query)
if err != nil {
return nil, err
}
querystr, err := Serialize(serializer)
if err != nil {
return nil, err
}
start := time.Now()
argsConverted := argsConvert(args)
result, err := tx.Tx.Exec(querystr, argsConverted...)
tx.DB.logQuery(serializer, tx, start, err)
return result, err
}
// Delete runs a batched SQL DELETE statement, grouping the objects by
// the model type of the list elements. List elements must be pointers
// to structs.
//
// On success, returns the number of rows deleted.
//
// Returns an error if an element in the list has not been registered
// with BindModel.
func (tx *Tx) Delete(list ...interface{}) (int64, error) {
return deleteObjects(tx.DB, tx, list)
}
// Get runs a SQL SELECT to fetch a single row. Keys must be the
// primary keys defined for the table. The order must match the order
// of the columns in the primary key.
//
// Returns an error if the object type has not been registered with
// BindModel.
func (tx *Tx) Get(dest interface{}, keys ...interface{}) error {
return getObject(tx.DB, tx, dest, keys)
}
// Insert runs a batched SQL INSERT statement, grouping the objects by
// the model type of the list elements. List elements must be pointers
// to structs.
//
// An object bound to a table with an auto-increment column will have
// its corresponding field filled in with the generated value if a
// pointer to the object was passed in "list".
//
// Returns an error if an element in the list has not been registered
// with BindModel.
func (tx *Tx) Insert(list ...interface{}) error {
return insertObjects(tx.DB, tx, getInsert, list)
}
// Query executes a query that returns rows, typically a SELECT. The
// args are for any placeholder parameters in the query. This is a
// small wrapper around sql.Tx.Query that returns a *squalor.Rows
// instead.
func (tx *Tx) Query(query interface{}, args ...interface{}) (*Rows, error) {
serializer, err := tx.DB.getSerializer(query)
if err != nil {
return nil, err
}
querystr, err := Serialize(serializer)
if err != nil {
return nil, err
}
start := time.Now()
argsConverted := argsConvert(args)
rows, err := tx.Tx.Query(querystr, argsConverted...)
tx.DB.logQuery(serializer, tx, start, err)
if err != nil {
return nil, err
}
return &Rows{Rows: rows, db: tx.DB}, nil
}
// QueryRow executes a query that is expected to return at most one
// row. QueryRow always return a non-nil value. Errors are deferred
// until Row's Scan method is called. This is a small wrapper around
// sql.Tx.QueryRow that returns a *squalor.Row instead.
func (tx *Tx) QueryRow(query interface{}, args ...interface{}) *Row {
serializer, err := tx.DB.getSerializer(query)
if err != nil {
return &Row{rows: Rows{Rows: nil, db: nil}, err: err}
}
querystr, err := Serialize(serializer)
if err != nil {
return &Row{rows: Rows{Rows: nil, db: nil}, err: err}
}
start := time.Now()
argsConverted := argsConvert(args)
rows, err := tx.Tx.Query(querystr, argsConverted...)
tx.DB.logQuery(serializer, tx, start, err)
return &Row{rows: Rows{Rows: rows, db: tx.DB}, err: err}
}
// Replace runs a batched SQL REPLACE statement, grouping the objects
// by the model type of the list elements. List elements must be
// pointers to structs.
//
// Note that REPLACE is effectively an INSERT followed by a DELETE and
// INSERT if the object already exists. The REPLACE may fail if the
// DELETE would violate foreign key constraints. Due to the batched
// nature of the Replace implementation it is not possible to
// accurately return the assignment of auto-increment values. Updating
// of an existing object will cause the auto-increment column to
// change.
//
// Returns an error if an element in the list has not been registered
// with BindModel.
func (tx *Tx) Replace(list ...interface{}) error {
return insertObjects(tx.DB, tx, getReplace, list)
}
// Select runs an arbitrary SQL query, unmarshalling the matching rows
// into the fields on the struct specified by dest. Args are the
// parameters to the SQL query.
//
// It is ok for dest to refer to a struct that has not been bound to a
// table. This allows querying for values that return transient
// columnts. For example, "SELECT count(*) ..." will return a "count"
// column.
//
// dest must be a pointer to a slice. Either *[]struct{} or
// *[]*struct{} is allowed. It is mildly more efficient to use
// *[]struct{} due to the reduced use of reflection and allocation.
func (tx *Tx) Select(dest interface{}, q interface{}, args ...interface{}) error {
return selectObjects(tx, dest, q, args)
}
// Update runs a SQL UPDATE statement for each element in list. List
// elements may be structs or pointers to structs.
//
// On success, returns the number of rows updated.
//
// Returns an error if an element in the list has not been registered
// with BindModel.
func (tx *Tx) Update(list ...interface{}) (int64, error) {
return updateObjects(tx.DB, tx, list)
}
// Upsert runs a SQL INSERT ON DUPLICATE KEY UPDATE statement for each
// element in list. List elements must be pointers to structs.
//
// Returns an error if an element in the list has not been registered
// with BindModel.
func (tx *Tx) Upsert(list ...interface{}) error {
return insertObjects(tx.DB, tx, getUpsert, list)
}
// setTyp holds a locus to set a value into, after it has been converted to
// the specified type.
type setTyp struct {
set reflect.Value
typ reflect.Type
}
// Rows is a wrapper around sql.Rows which adds a StructScan method.
type Rows struct {
*sql.Rows
db *DB
structT reflect.Type
zero reflect.Value
value reflect.Value
dest []interface{}
convert map[int]setTyp
}
// StructScan copies the columns in the current row into the struct
// pointed at by dest.
func (r *Rows) StructScan(dest interface{}) error {
v := reflect.ValueOf(dest)
if v.Kind() != reflect.Ptr {
return fmt.Errorf("dest must be a pointer: %T", dest)
}
v = v.Elem()
t := v.Type()
if r.structT != t {
r.structT = t
if err := r.initScan(t); err != nil {
return err
}
}
if err := r.scanValue(); err != nil {
return err
}
v.Set(r.value)
return nil
}
func (r *Rows) initScan(t reflect.Type) error {
if t.Kind() != reflect.Struct {
// We're not scanning into a struct. Construct the value we'll
// scan into and set up the "dest" slice which will be used for
// scanning.
ptr := reflect.New(t)
r.value = ptr.Elem()
r.dest = []interface{}{ptr.Interface()}
} else {
m := r.db.getMapping(t)
// Fetch the column names in the result.
cols, err := r.Rows.Columns()
if err != nil {
return err
}
// Set up the "dest" slice which we'll scan into. Note that the
// "dest" slice remains the same for every row we scan. That is,
// we're scanning each row into the same object ("value").
r.dest = make([]interface{}, len(cols))
r.value = reflect.New(t).Elem()
for i, col := range cols {
field, ok := m[col]
if !ok {
if !r.db.IgnoreUnmappedCols {
return fmt.Errorf("unable to find mapping for column '%s'", col)
}
r.dest[i] = new(sql.RawBytes)
continue
}
subValue := r.value.FieldByIndex(field.Index)
if !baseTypes[subValue.Type()] && baseKinds[subValue.Kind()] {
// Type alias require special handling. We create a locus to store the
// raw value, and later convert and set this value in the field. This
// odd maneuver is required because database/sql Scan implementation
// inconsistently handles type aliases.
locus := reflect.New(kindsToBaseType[subValue.Kind()])
r.dest[i] = locus.Elem().Addr().Interface()
if r.convert == nil {
r.convert = make(map[int]setTyp)
}
r.convert[i] = setTyp{
set: subValue.Addr().Elem(),
typ: subValue.Type(),
}
} else {
r.dest[i] = subValue.Addr().Interface()
}
}
}
r.zero = reflect.Zero(t)
return nil
}
func (r *Rows) scanValue() error {
// Clear out our value object in preparation for the scan.
r.value.Set(r.zero)
if err := r.Rows.Scan(r.dest...); err != nil {
return err
}
for i, c := range r.convert {
c.set.Set(reflect.ValueOf(r.dest[i]).Elem().Convert(c.typ))
}
return nil
}
// Row is a wrapper around sql.Row which adds a StructScan method.
type Row struct {
rows Rows
err error
}