forked from go-gorp/gorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
1190 lines (1060 loc) · 34.1 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 2012 James Cooper. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gorp
import (
"bytes"
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"log"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/jmoiron/sqlx"
)
// DbMap is the root gorp mapping object. Create one of these for each
// database schema you wish to map. Each DbMap contains a list of
// mapped tables.
//
// Basic Example:
//
// dialect := gorp.MySQLDialect{"InnoDB", "UTF8"}
// dbmap := &gorp.DbMap{Db: db, Dialect: dialect}
//
// Advanced Example with Table Mapping:
//
// // Define your struct
// type Post struct {
// Id int64 `db:"id"`
// Created time.Time `db:"created"`
// Title string `db:"title"`
// Body string `db:"body"`
// }
//
// // Create DbMap
// dbmap := &gorp.DbMap{Db: db, Dialect: dialect}
//
// // Register table with auto-increment primary key
// dbmap.AddTableWithName(Post{}, "posts").SetKeys(true, "Id")
//
// // Create tables
// err := dbmap.CreateTablesIfNotExists()
//
// Error Handling Best Practices:
// 1. Always check returned errors
// 2. Use the specialized error types from errors.go for better error handling
// 3. Wrap database operations in transactions when performing multiple operations
//
// Transaction Example:
//
// func UpdatePost(dbmap *gorp.DbMap, post *Post, newTitle string) error {
// tx, err := dbmap.Begin()
// if err != nil {
// return err
// }
// defer tx.Rollback() // will be ignored if Commit() is called
//
// post.Title = newTitle
// _, err = tx.Update(post)
// if err != nil {
// return err
// }
//
// return tx.Commit()
// }
type DbMap struct {
ctx context.Context
Db *sqlx.DB
Dialect Dialect
TypeConverter TypeConverter
ExpandSliceArgs bool
tables []*TableMap
tablesDynamic map[string]*TableMap
logger GorpLogger
logPrefix string
typeCache sync.Map // Cache for type to TableMap lookups
}
// Initialize validates the DbMap configuration and initializes it for use.
// Returns an error if the configuration is invalid.
func (m *DbMap) Initialize() error {
if m.Dialect != nil {
if err := ValidateDialect(m.Dialect.Type()); err != nil {
return err
}
}
// Pre-cache all registered tables
for _, t := range m.tables {
m.typeCache.Store(t.gotype, t)
}
return nil
}
// dynamicTableAdd adds a new table mapping to the dynamic table map.
// This is used internally to support tables that share the same Go struct
// but map to different database table names.
func (m *DbMap) dynamicTableAdd(tableName string, tbl *TableMap) {
if m.tablesDynamic == nil {
m.tablesDynamic = make(map[string]*TableMap)
}
m.tablesDynamic[tableName] = tbl
}
// dynamicTableFind looks up a table by name in the dynamic table map.
// Returns the table and true if found, nil and false if not found.
func (m *DbMap) dynamicTableFind(tableName string) (*TableMap, bool) {
if m.tablesDynamic == nil {
return nil, false
}
tbl, found := m.tablesDynamic[tableName]
return tbl, found
}
// dynamicTableMap returns the map of dynamic tables.
// If the map hasn't been initialized, it creates a new one.
func (m *DbMap) dynamicTableMap() map[string]*TableMap {
if m.tablesDynamic == nil {
m.tablesDynamic = make(map[string]*TableMap)
}
return m.tablesDynamic
}
// WithContext returns a new SqlExecutor that will use the given context on all operations.
func (m *DbMap) WithContext(ctx context.Context) SqlExecutor {
copy := &DbMap{}
*copy = *m
copy.ctx = ctx
return copy
}
// CreateIndex creates a database index based on the indexes defined in the table maps.
func (m *DbMap) CreateIndex() error {
var err error
dialect := reflect.TypeOf(m.Dialect)
for _, table := range m.tables {
for _, index := range table.indexes {
err = m.createIndexImpl(dialect, table, index)
if err != nil {
break
}
}
}
for _, table := range m.dynamicTableMap() {
for _, index := range table.indexes {
err = m.createIndexImpl(dialect, table, index)
if err != nil {
break
}
}
}
return err
}
// createIndexImpl is an internal function that creates a database index based on parameters from dialect and index map.
func (m *DbMap) createIndexImpl(dialect reflect.Type,
table *TableMap,
index *IndexMap) error {
s := bytes.Buffer{}
s.WriteString("create")
if index.Unique {
s.WriteString(" unique")
}
s.WriteString(" index")
s.WriteString(fmt.Sprintf(" %s on %s", index.IndexName, table.TableName))
if dname := dialect.Name(); dname == "PostgresDialect" && index.IndexType != "" {
s.WriteString(fmt.Sprintf(" %s %s", m.Dialect.CreateIndexSuffix(), index.IndexType))
}
s.WriteString(" (")
for x, col := range index.columns {
if x > 0 {
s.WriteString(", ")
}
s.WriteString(m.Dialect.QuoteField(col))
}
s.WriteString(")")
if dname := dialect.Name(); dname == "MySQLDialect" && index.IndexType != "" {
s.WriteString(fmt.Sprintf(" %s %s", m.Dialect.CreateIndexSuffix(), index.IndexType))
}
s.WriteString(";")
_, err := m.Exec(s.String())
return err
}
// DropIndex drops an individual index.
// Returns an error when the index does not exist.
func (t *TableMap) DropIndex(name string) error {
var err error
dialect := reflect.TypeOf(t.dbmap.Dialect)
for _, idx := range t.indexes {
if idx.IndexName == name {
s := bytes.Buffer{}
s.WriteString(fmt.Sprintf("DROP INDEX %s", idx.IndexName))
if dname := dialect.Name(); dname == "MySQLDialect" {
s.WriteString(fmt.Sprintf(" %s %s", t.dbmap.Dialect.DropIndexSuffix(), t.TableName))
}
s.WriteString(";")
_, e := t.dbmap.Exec(s.String())
if e != nil {
err = e
}
break
}
}
t.ResetSql()
return err
}
// AddTable registers the given interface type with gorp. The table name
// will be given the name of the TypeOf(i). You must call this function,
// or AddTableWithName, for any struct type you wish to persist with
// the given DbMap.
//
// This operation is idempotent. If i's type is already mapped, the
// existing *TableMap is returned
func (m *DbMap) AddTable(i interface{}) *TableMap {
if err := m.Initialize(); err != nil {
panic(err)
}
return m.AddTableWithNameAndSchema(i, "", "")
}
// AddTableWithName has the same behavior as AddTable, but sets
// table.TableName to name.
func (m *DbMap) AddTableWithName(i interface{}, name string) *TableMap {
if err := m.Initialize(); err != nil {
panic(err)
}
return m.AddTableWithNameAndSchema(i, "", name)
}
// AddTableWithNameAndSchema has the same behavior as AddTable, but sets
// table.TableName to name and table.SchemaName to schema.
func (m *DbMap) AddTableWithNameAndSchema(i interface{}, schema string, name string) *TableMap {
if err := m.Initialize(); err != nil {
panic(err)
}
t := reflect.TypeOf(i)
if name == "" {
name = t.Name()
}
// check if we have a table for this type already
// if so, update the name and return the existing pointer
for i := range m.tables {
table := m.tables[i]
if table.gotype == t {
table.TableName = name
m.typeCache.Store(t, table) // Update cache
return table
}
}
tmap := &TableMap{gotype: t, TableName: name, SchemaName: schema, dbmap: m}
var primaryKey []*ColumnMap
cols, primaryKey := m.readStructColumns(t)
// Initialize column caches
tmap.initColumnCaches()
// Add columns using addColumn to maintain caches
for _, col := range cols {
tmap.addColumn(col)
}
m.tables = append(m.tables, tmap)
if len(primaryKey) > 0 {
tmap.keys = append(tmap.keys, primaryKey...)
}
m.typeCache.Store(t, tmap) // Cache new table
return tmap
}
// AddTableDynamic registers the given interface type with gorp.
// The table name will be dynamically determined at runtime by
// using the GetTableName method on DynamicTable interface
func (m *DbMap) AddTableDynamic(inp DynamicTable, schema string) *TableMap {
if err := m.Initialize(); err != nil {
panic(err)
}
t := reflect.TypeOf(inp)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
tableName := inp.TableName()
if tableName == "" {
panic("Missing table name in DynamicTable instance")
}
// Check if we have a table for this type already
// If so, add it to the dynamic tables map and return the existing pointer
for i := range m.tables {
table := m.tables[i]
if table.gotype == t {
m.dynamicTableAdd(tableName, table)
return table
}
}
tmap := &TableMap{gotype: t, TableName: tableName, SchemaName: schema, dbmap: m}
var primaryKey []*ColumnMap
cols, primaryKey := m.readStructColumns(t)
// Initialize column caches
tmap.initColumnCaches()
// Add columns using addColumn to maintain caches
for _, col := range cols {
tmap.addColumn(col)
}
m.dynamicTableAdd(tableName, tmap)
if len(primaryKey) > 0 {
tmap.keys = append(tmap.keys, primaryKey...)
}
return tmap
}
// readStructColumns is an internal function that reads the column
// information from a struct type.
func (m *DbMap) readStructColumns(t reflect.Type) (cols []*ColumnMap, primaryKey []*ColumnMap) {
primaryKey = make([]*ColumnMap, 0)
cols = make([]*ColumnMap, 0)
n := t.NumField()
for i := 0; i < n; i++ {
f := t.Field(i)
if f.Anonymous && f.Type.Kind() == reflect.Struct {
// Recursively add nested fields in embedded structs.
subcols, subpk := m.readStructColumns(f.Type)
// Don't append nested fields that have the same field
// name as an already-mapped field.
for _, subcol := range subcols {
shouldAppend := true
for _, col := range cols {
if !subcol.Transient && subcol.fieldName == col.fieldName {
shouldAppend = false
break
}
}
if shouldAppend {
cols = append(cols, subcol)
}
}
if subpk != nil {
primaryKey = append(primaryKey, subpk...)
}
} else {
// Tag = Name { ',' Option }
// Option = OptionKey [ ':' OptionValue ]
cArguments := strings.Split(f.Tag.Get("db"), ",")
columnName := cArguments[0]
var maxSize int
var defaultValue string
var isAuto bool
var isPK bool
var isNotNull bool
for _, argString := range cArguments[1:] {
argString = strings.TrimSpace(argString)
arg := strings.SplitN(argString, ":", 2)
// check mandatory/unexpected option values
switch arg[0] {
case "size", "default":
// options requiring value
if len(arg) == 1 {
panic(fmt.Sprintf("missing option value for option %v on field %v", arg[0], f.Name))
}
default:
// options where value is invalid (currently all other options)
if len(arg) == 2 {
panic(fmt.Sprintf("unexpected option value for option %v on field %v", arg[0], f.Name))
}
}
switch arg[0] {
case "size":
maxSize, _ = strconv.Atoi(arg[1])
case "default":
defaultValue = arg[1]
case "primarykey":
isPK = true
case "autoincrement":
isAuto = true
case "notnull":
isNotNull = true
default:
panic(fmt.Sprintf("Unrecognized tag option for field %v: %v", f.Name, arg))
}
}
if columnName == "" {
columnName = f.Name
}
gotype := f.Type
valueType := gotype
if valueType.Kind() == reflect.Ptr {
valueType = valueType.Elem()
}
value := reflect.New(valueType).Interface()
if m.TypeConverter != nil {
// Make a new pointer to a value of type gotype and
// pass it to the TypeConverter's FromDb method to see
// if a different type should be used for the column
// type during table creation.
scanner, useHolder := m.TypeConverter.FromDb(value)
if useHolder {
value = scanner.Holder
gotype = reflect.TypeOf(value)
}
}
if typer, ok := value.(SqlTyper); ok {
gotype = reflect.TypeOf(typer.SqlType())
} else if typer, ok := value.(legacySqlTyper); ok {
log.Printf("Deprecation Warning: update your SqlType methods to return a driver.Value")
gotype = reflect.TypeOf(typer.SqlType())
} else if valuer, ok := value.(driver.Valuer); ok {
// Only check for driver.Valuer if SqlTyper wasn't
// found.
v, err := valuer.Value()
if err == nil && v != nil {
gotype = reflect.TypeOf(v)
}
}
cm := &ColumnMap{
ColumnName: columnName,
DefaultValue: defaultValue,
Transient: columnName == "-",
fieldName: f.Name,
gotype: gotype,
isPK: isPK,
isAutoIncr: isAuto,
isNotNull: isNotNull,
MaxSize: maxSize,
}
if isPK {
primaryKey = append(primaryKey, cm)
}
// Check for nested fields of the same field name and
// override them.
shouldAppend := true
for index, col := range cols {
if !col.Transient && col.fieldName == cm.fieldName {
cols[index] = cm
shouldAppend = false
break
}
}
if shouldAppend {
cols = append(cols, cm)
}
}
}
return
}
// CreateTables iterates through TableMaps registered to this DbMap and
// executes "create table" statements against the database for each.
//
// This is particularly useful in unit tests where you want to create
// and destroy the schema automatically.
func (m *DbMap) CreateTables() error {
return m.createTables(false)
}
// CreateTablesIfNotExists is similar to CreateTables, but starts
// each statement with "create table if not exists" so that existing
// tables do not raise errors
func (m *DbMap) CreateTablesIfNotExists() error {
return m.createTables(true)
}
// createTables is an internal function that creates tables with an optional "if not exists" clause.
func (m *DbMap) createTables(ifNotExists bool) error {
var err error
for i := range m.tables {
table := m.tables[i]
sql := table.SqlForCreate(ifNotExists)
_, err = m.Exec(sql)
if err != nil {
return err
}
}
for _, tbl := range m.dynamicTableMap() {
sql := tbl.SqlForCreate(ifNotExists)
_, err = m.Exec(sql)
if err != nil {
return err
}
}
return err
}
// DropTable drops an individual table.
// Returns an error when the table does not exist.
func (m *DbMap) DropTable(table interface{}) error {
t := reflect.TypeOf(table)
tableName := ""
if dyn, ok := table.(DynamicTable); ok {
tableName = dyn.TableName()
}
return m.dropTable(t, tableName, false)
}
// DropTableIfExists drops an individual table when the table exists.
func (m *DbMap) DropTableIfExists(table interface{}) error {
t := reflect.TypeOf(table)
tableName := ""
if dyn, ok := table.(DynamicTable); ok {
tableName = dyn.TableName()
}
return m.dropTable(t, tableName, true)
}
// DropTables iterates through TableMaps registered to this DbMap and
// executes "drop table" statements against the database for each.
func (m *DbMap) DropTables() error {
return m.dropTables(false)
}
// DropTablesIfExists is the same as DropTables, but uses the "if exists" clause to
// avoid errors for tables that do not exist.
func (m *DbMap) DropTablesIfExists() error {
return m.dropTables(true)
}
// dropTables is an internal function that drops all registered tables.
// If addIfExists is true, it adds an "IF EXISTS" clause to prevent errors.
func (m *DbMap) dropTables(addIfExists bool) (err error) {
for _, table := range m.tables {
err = m.dropTableImpl(table, addIfExists)
if err != nil {
return err
}
}
for _, table := range m.dynamicTableMap() {
err = m.dropTableImpl(table, addIfExists)
if err != nil {
return err
}
}
return err
}
// dropTable is an internal function that drops a single table by its reflect.Type and name.
func (m *DbMap) dropTable(t reflect.Type, name string, addIfExists bool) error {
table := tableOrNil(m, t, name)
if table == nil {
return fmt.Errorf("table %s was not registered", table.TableName)
}
return m.dropTableImpl(table, addIfExists)
}
// dropTableImpl is an internal function that implements the table drop operation.
func (m *DbMap) dropTableImpl(table *TableMap, ifExists bool) (err error) {
tableDrop := "drop table"
if ifExists {
tableDrop = m.Dialect.IfTableExists(tableDrop, table.SchemaName, table.TableName)
}
_, err = m.Exec(fmt.Sprintf("%s %s;", tableDrop, m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName)))
return err
}
// TruncateTables iterates through TableMaps registered to this DbMap and
// executes "truncate table" statements against the database for each, or in the case of
// sqlite, a "delete from" with no "where" clause, which uses the truncate optimization
// (http://www.sqlite.org/lang_delete.html)
func (m *DbMap) TruncateTables() error {
var err error
for i := range m.tables {
table := m.tables[i]
_, e := m.Exec(fmt.Sprintf("%s %s;", m.Dialect.TruncateClause(), m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName)))
if e != nil {
err = e
}
}
for _, table := range m.dynamicTableMap() {
_, e := m.Exec(fmt.Sprintf("%s %s;", m.Dialect.TruncateClause(), m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName)))
if e != nil {
err = e
}
}
return err
}
// Insert runs a SQL INSERT statement for each element in list. List
// items must be pointers.
//
// Any interface whose TableMap has an auto-increment primary key will
// have its last insert id bound to the PK field on the struct.
//
// The hook functions PreInsert() and/or PostInsert() will be executed
// before/after the INSERT statement if the interface defines them.
//
// Panics if any interface in the list has not been registered with AddTable
func (m *DbMap) Insert(list ...interface{}) error {
return insert(m, m, list...)
}
// Update runs a SQL UPDATE statement for each element in list. List
// items must be pointers.
//
// The hook functions PreUpdate() and/or PostUpdate() will be executed
// before/after the UPDATE statement if the interface defines them.
//
// Returns the number of rows updated.
//
// Returns an error if SetKeys has not been called on the TableMap
// Panics if any interface in the list has not been registered with AddTable
func (m *DbMap) Update(list ...interface{}) (int64, error) {
return update(m, m, nil, list...)
}
// UpdateColumns runs a SQL UPDATE statement for each element in list. List
// items must be pointers.
//
// Only the columns accepted by filter are included in the UPDATE.
//
// The hook functions PreUpdate() and/or PostUpdate() will be executed
// before/after the UPDATE statement if the interface defines them.
//
// Returns the number of rows updated.
//
// Returns an error if SetKeys has not been called on the TableMap
// Panics if any interface in the list has not been registered with AddTable
func (m *DbMap) UpdateColumns(filter ColumnFilter, list ...interface{}) (int64, error) {
return update(m, m, filter, list...)
}
// Delete runs a SQL DELETE statement for each element in list. List
// items must be pointers.
//
// The hook functions PreDelete() and/or PostDelete() will be executed
// before/after the DELETE statement if the interface defines them.
//
// Returns the number of rows deleted.
//
// Returns an error if SetKeys has not been called on the TableMap
// Panics if any interface in the list has not been registered with AddTable
func (m *DbMap) Delete(list ...interface{}) (int64, error) {
return delete(m, m, list...)
}
// Get runs a SQL SELECT to fetch a single row from the table based on the
// primary key(s)
//
// i should be an empty value for the struct to load. keys should be
// the primary key value(s) for the row to load. If multiple keys
// exist on the table, the order should match the column order
// specified in SetKeys() when the table mapping was defined.
//
// The hook function PostGet() will be executed after the SELECT
// statement if the interface defines them.
//
// Returns a pointer to a struct that matches or nil if no row is found.
//
// Returns an error if SetKeys has not been called on the TableMap
// Panics if any interface in the list has not been registered with AddTable
func (m *DbMap) Get(i interface{}, keys ...interface{}) (interface{}, error) {
return get(m, m, i, keys...)
}
// Select runs an arbitrary SQL query, binding the columns in the result
// to fields on the struct specified by i. args represent the bind
// parameters for the SQL statement.
//
// Column names on the SELECT statement should be aliased to the field names
// on the struct i. Returns an error if one or more columns in the result
// do not match. It is OK if fields on i are not part of the SQL
// statement.
//
// The hook function PostGet() will be executed after the SELECT
// statement if the interface defines them.
//
// Values are returned in one of two ways:
// 1. If i is a struct or a pointer to a struct, returns a slice of pointers to
// matching rows of type i.
// 2. If i is a pointer to a slice, the results will be appended to that slice
// and nil returned.
//
// Examples:
//
// // Single struct
// var post Post
// posts, err := dbmap.Select(&post, "select * from posts where id = ?", id)
//
// // Slice of structs
// var posts []Post
// _, err := dbmap.Select(&posts, "select * from posts order by created desc")
//
// // Using field aliases
// _, err := dbmap.Select(&posts, "select p.id as Id, p.title as Title from posts p")
//
// Error Handling:
//
// if err != nil {
// if gorp.NonFatalError(err) {
// // Handle non-fatal error (e.g., no rows found)
// } else {
// // Handle fatal error
// }
// }
//
// i does NOT need to be registered with AddTable()
func (m *DbMap) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return hookedselect(m, m, i, query, args...)
}
// Exec runs an arbitrary SQL statement. args represent the bind parameters.
// This is equivalent to running: Exec() using database/sql
func (m *DbMap) Exec(query string, args ...interface{}) (sql.Result, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
if m.logger != nil {
now := time.Now()
defer m.trace(now, query, args...)
}
return maybeExpandNamedQueryAndExec(m, query, args...)
}
// SelectInt is a convenience wrapper around the gorp.SelectInt function
func (m *DbMap) SelectInt(query string, args ...interface{}) (int64, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectInt(m, query, args...)
}
// SelectNullInt is a convenience wrapper around the gorp.SelectNullInt function
func (m *DbMap) SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectNullInt(m, query, args...)
}
// SelectFloat is a convenience wrapper around the gorp.SelectFloat function
func (m *DbMap) SelectFloat(query string, args ...interface{}) (float64, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectFloat(m, query, args...)
}
// SelectNullFloat is a convenience wrapper around the gorp.SelectNullFloat function
func (m *DbMap) SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectNullFloat(m, query, args...)
}
// SelectStr is a convenience wrapper around the gorp.SelectStr function
func (m *DbMap) SelectStr(query string, args ...interface{}) (string, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectStr(m, query, args...)
}
// SelectNullStr is a convenience wrapper around the gorp.SelectNullStr function
func (m *DbMap) SelectNullStr(query string, args ...interface{}) (sql.NullString, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectNullStr(m, query, args...)
}
// SelectBool is a convenience wrapper around the gorp.SelectBool function
func (m *DbMap) SelectBool(query string, args ...interface{}) (bool, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectBool(m, query, args...)
}
// SelectNullBool is a convenience wrapper around the gorp.SelectNullBool function
func (m *DbMap) SelectNullBool(query string, args ...interface{}) (sql.NullBool, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectNullBool(m, query, args...)
}
// SelectOne is a convenience wrapper around the gorp.SelectOne function
func (m *DbMap) SelectOne(holder interface{}, query string, args ...interface{}) error {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectOne(m, m, holder, query, args...)
}
// Begin starts a gorp Transaction using the provided context
func (m *DbMap) Begin() (*Transaction, error) {
if m.ctx != nil {
tx, err := m.Db.BeginTxx(m.ctx, nil)
if err != nil {
return nil, err
}
return &Transaction{dbmap: m, ctx: m.ctx, tx: tx}, nil
}
tx, err := m.Db.Beginx()
if err != nil {
return nil, err
}
return &Transaction{dbmap: m, tx: tx}, nil
}
// Query using this DbMap with standard sql.Rows result
func (m *DbMap) Query(query string, args ...interface{}) (*sql.Rows, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
if m.ctx != nil {
return m.Db.QueryContext(m.ctx, query, args...)
}
return m.Db.Query(query, args...)
}
// QueryRow using this DbMap with standard sql.Row result
func (m *DbMap) QueryRow(query string, args ...interface{}) *sql.Row {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
if m.ctx != nil {
return m.Db.QueryRowContext(m.ctx, query, args...)
}
return m.Db.QueryRow(query, args...)
}
// Queryx using this DbMap with sqlx.Rows result
func (m *DbMap) Queryx(query string, args ...interface{}) (*sqlx.Rows, error) {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
if m.ctx != nil {
return m.Db.QueryxContext(m.ctx, query, args...)
}
return m.Db.Queryx(query, args...)
}
// QueryRowx using this DbMap with sqlx.Row result
func (m *DbMap) QueryRowx(query string, args ...interface{}) *sqlx.Row {
if m.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
if m.ctx != nil {
return m.Db.QueryRowxContext(m.ctx, query, args...)
}
return m.Db.QueryRowx(query, args...)
}
// Prepare creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the returned statement.
func (m *DbMap) Prepare(query string) (*sqlx.Stmt, error) {
if m.ctx != nil {
return m.Db.PreparexContext(m.ctx, query)
}
return m.Db.Preparex(query)
}
// Getx using this DbMap with sqlx
func (m *DbMap) Getx(dest interface{}, query string, args ...interface{}) error {
if m.ctx != nil {
return m.Db.GetContext(m.ctx, dest, query, args...)
}
return m.Db.Get(dest, query, args...)
}
// Selectx using this DbMap with sqlx
func (m *DbMap) Selectx(dest interface{}, query string, args ...interface{}) error {
if m.ctx != nil {
return m.Db.SelectContext(m.ctx, dest, query, args...)
}
return m.Db.Select(dest, query, args...)
}
// NamedExec using this DbMap
func (m *DbMap) NamedExec(query string, arg interface{}) (sql.Result, error) {
if m.ctx != nil {
return m.Db.NamedExecContext(m.ctx, query, arg)
}
return m.Db.NamedExec(query, arg)
}
// NamedQuery using this DbMap
func (m *DbMap) NamedQuery(query string, arg interface{}) (*sqlx.Rows, error) {
if m.ctx != nil {
return m.Db.NamedQueryContext(m.ctx, query, arg)
}
return m.Db.NamedQuery(query, arg)
}
// PreparexNamed creates a prepared statement for later named execution
func (m *DbMap) PreparexNamed(query string) (*sqlx.NamedStmt, error) {
if m.ctx != nil {
return m.Db.PrepareNamedContext(m.ctx, query)
}
return m.Db.PrepareNamed(query)
}
// MustExec executes the query without returning an error
func (m *DbMap) MustExec(query string, args ...interface{}) sql.Result {
if m.ctx != nil {
return m.Db.MustExecContext(m.ctx, query, args...)
}
return m.Db.MustExec(query, args...)
}
// TableFor returns the *TableMap corresponding to the given Go Type
// If no table is mapped to that type an error is returned.
// If checkPK is true and the mapped table has no registered PKs, an error is returned.
func (m *DbMap) TableFor(t reflect.Type, checkPK bool) (*TableMap, error) {
table := tableOrNil(m, t, "")
if table == nil {
return nil, &TableNotFoundError{
Table: t.Name(),
}
}
if checkPK && len(table.keys) < 1 {
e := fmt.Sprintf("gorp: no keys defined for table: %s",
table.TableName)
return nil, errors.New(e)
}
return table, nil
}
// DynamicTableFor returns the *TableMap for the dynamic table corresponding
// to the input tablename
// If no table is mapped to that tablename an error is returned.
// If checkPK is true and the mapped table has no registered PKs, an error is returned.
func (m *DbMap) DynamicTableFor(tableName string, checkPK bool) (*TableMap, error) {
table, found := m.dynamicTableFind(tableName)
if !found {
return nil, &TableNotFoundError{
Table: tableName,
}
}
if checkPK && len(table.keys) < 1 {
e := fmt.Sprintf("gorp: no keys defined for table: %s",
table.TableName)
return nil, errors.New(e)
}
return table, nil
}
// tableOrNil returns the *TableMap corresponding to the given Go Type
// If no table is mapped to that type an error is returned.
// If checkPK is true and the mapped table has no registered PKs, an error is returned.
func tableOrNil(m *DbMap, t reflect.Type, name string) *TableMap {
if name != "" {