Debian Codegraph @

gorp.go

raw
1 // Copyright 2012 James Cooper. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 // Package gorp provides a simple way to marshal Go structs to and from
6 // SQL databases. It uses the database/sql package, and should work with any
7 // compliant database/sql driver.
8 //
9 // Source code and project home:
10 // https://github.com/coopernurse/gorp
11 //
12 package gorp
13
14 import (
15 "bytes"
16 "database/sql"
17 "database/sql/driver"
18 "errors"
19 "fmt"
20 "log"
21 "os"
22 "reflect"
23 "regexp"
24 "strings"
25 "sync"
26 "time"
27 )
28
29 // Oracle String (empty string is null)
30 type OracleString struct {
31 sql.NullString
32 }
33
34 // Scan implements the Scanner interface.
35 func (os *OracleString) Scan(value interface{}) error {
36 if value == nil {
37 os.String, os.Valid = "", false
38 return nil
39 }
40 os.Valid = true
41 return os.NullString.Scan(value)
42 }
43
44 // Value implements the driver Valuer interface.
45 func (os OracleString) Value() (driver.Value, error) {
46 if !os.Valid || os.String == "" {
47 return nil, nil
48 }
49 return os.String, nil
50 }
51
52 // A nullable Time value
53 type NullTime struct {
54 Time time.Time
55 Valid bool // Valid is true if Time is not NULL
56 }
57
58 // Scan implements the Scanner interface.
59 func (nt *NullTime) Scan(value interface{}) error {
60 nt.Time, nt.Valid = value.(time.Time)
61 return nil
62 }
63
64 // Value implements the driver Valuer interface.
65 func (nt NullTime) Value() (driver.Value, error) {
66 if !nt.Valid {
67 return nil, nil
68 }
69 return nt.Time, nil
70 }
71
72 var zeroVal reflect.Value
73 var versFieldConst = "[gorp_ver_field]"
74
75 // OptimisticLockError is returned by Update() or Delete() if the
76 // struct being modified has a Version field and the value is not equal to
77 // the current value in the database
78 type OptimisticLockError struct {
79 // Table name where the lock error occurred
80 TableName string
81
82 // Primary key values of the row being updated/deleted
83 Keys []interface{}
84
85 // true if a row was found with those keys, indicating the
86 // LocalVersion is stale. false if no value was found with those
87 // keys, suggesting the row has been deleted since loaded, or
88 // was never inserted to begin with
89 RowExists bool
90
91 // Version value on the struct passed to Update/Delete. This value is
92 // out of sync with the database.
93 LocalVersion int64
94 }
95
96 // Error returns a description of the cause of the lock error
97 func (e OptimisticLockError) Error() string {
98 if e.RowExists {
99 return fmt.Sprintf("gorp: OptimisticLockError table=%s keys=%v out of date version=%d", e.TableName, e.Keys, e.LocalVersion)
100 }
101
102 return fmt.Sprintf("gorp: OptimisticLockError no row found for table=%s keys=%v", e.TableName, e.Keys)
103 }
104
105 // The TypeConverter interface provides a way to map a value of one
106 // type to another type when persisting to, or loading from, a database.
107 //
108 // Example use cases: Implement type converter to convert bool types to "y"/"n" strings,
109 // or serialize a struct member as a JSON blob.
110 type TypeConverter interface {
111 // ToDb converts val to another type. Called before INSERT/UPDATE operations
112 ToDb(val interface{}) (interface{}, error)
113
114 // FromDb returns a CustomScanner appropriate for this type. This will be used
115 // to hold values returned from SELECT queries.
116 //
117 // In particular the CustomScanner returned should implement a Binder
118 // function appropriate for the Go type you wish to convert the db value to
119 //
120 // If bool==false, then no custom scanner will be used for this field.
121 FromDb(target interface{}) (CustomScanner, bool)
122 }
123
124 // CustomScanner binds a database column value to a Go type
125 type CustomScanner struct {
126 // After a row is scanned, Holder will contain the value from the database column.
127 // Initialize the CustomScanner with the concrete Go type you wish the database
128 // driver to scan the raw column into.
129 Holder interface{}
130 // Target typically holds a pointer to the target struct field to bind the Holder
131 // value to.
132 Target interface{}
133 // Binder is a custom function that converts the holder value to the target type
134 // and sets target accordingly. This function should return error if a problem
135 // occurs converting the holder to the target.
136 Binder func(holder interface{}, target interface{}) error
137 }
138
139 // Bind is called automatically by gorp after Scan()
140 func (me CustomScanner) Bind() error {
141 return me.Binder(me.Holder, me.Target)
142 }
143
144 // DbMap is the root gorp mapping object. Create one of these for each
145 // database schema you wish to map. Each DbMap contains a list of
146 // mapped tables.
147 //
148 // Example:
149 //
150 // dialect := gorp.MySQLDialect{"InnoDB", "UTF8"}
151 // dbmap := &gorp.DbMap{Db: db, Dialect: dialect}
152 //
153 type DbMap struct {
154 // Db handle to use with this map
155 Db *sql.DB
156
157 // Dialect implementation to use with this map
158 Dialect Dialect
159
160 TypeConverter TypeConverter
161
162 tables []*TableMap
163 logger GorpLogger
164 logPrefix string
165 }
166
167 // TableMap represents a mapping between a Go struct and a database table
168 // Use dbmap.AddTable() or dbmap.AddTableWithName() to create these
169 type TableMap struct {
170 // Name of database table.
171 TableName string
172 SchemaName string
173 gotype reflect.Type
174 Columns []*ColumnMap
175 keys []*ColumnMap
176 uniqueTogether [][]string
177 version *ColumnMap
178 insertPlan bindPlan
179 updatePlan bindPlan
180 deletePlan bindPlan
181 getPlan bindPlan
182 dbmap *DbMap
183 }
184
185 // ResetSql removes cached insert/update/select/delete SQL strings
186 // associated with this TableMap. Call this if you've modified
187 // any column names or the table name itself.
188 func (t *TableMap) ResetSql() {
189 t.insertPlan = bindPlan{}
190 t.updatePlan = bindPlan{}
191 t.deletePlan = bindPlan{}
192 t.getPlan = bindPlan{}
193 }
194
195 // SetKeys lets you specify the fields on a struct that map to primary
196 // key columns on the table. If isAutoIncr is set, result.LastInsertId()
197 // will be used after INSERT to bind the generated id to the Go struct.
198 //
199 // Automatically calls ResetSql() to ensure SQL statements are regenerated.
200 //
201 // Panics if isAutoIncr is true, and fieldNames length != 1
202 //
203 func (t *TableMap) SetKeys(isAutoIncr bool, fieldNames ...string) *TableMap {
204 if isAutoIncr && len(fieldNames) != 1 {
205 panic(fmt.Sprintf(
206 "gorp: SetKeys: fieldNames length must be 1 if key is auto-increment. (Saw %v fieldNames)",
207 len(fieldNames)))
208 }
209 t.keys = make([]*ColumnMap, 0)
210 for _, name := range fieldNames {
211 colmap := t.ColMap(name)
212 colmap.isPK = true
213 colmap.isAutoIncr = isAutoIncr
214 t.keys = append(t.keys, colmap)
215 }
216 t.ResetSql()
217
218 return t
219 }
220
221 // SetUniqueTogether lets you specify uniqueness constraints across multiple
222 // columns on the table. Each call adds an additional constraint for the
223 // specified columns.
224 //
225 // Automatically calls ResetSql() to ensure SQL statements are regenerated.
226 //
227 // Panics if fieldNames length < 2.
228 //
229 func (t *TableMap) SetUniqueTogether(fieldNames ...string) *TableMap {
230 if len(fieldNames) < 2 {
231 panic(fmt.Sprintf(
232 "gorp: SetUniqueTogether: must provide at least two fieldNames to set uniqueness constraint."))
233 }
234
235 columns := make([]string, 0)
236 for _, name := range fieldNames {
237 columns = append(columns, name)
238 }
239 t.uniqueTogether = append(t.uniqueTogether, columns)
240 t.ResetSql()
241
242 return t
243 }
244
245 // ColMap returns the ColumnMap pointer matching the given struct field
246 // name. It panics if the struct does not contain a field matching this
247 // name.
248 func (t *TableMap) ColMap(field string) *ColumnMap {
249 col := colMapOrNil(t, field)
250 if col == nil {
251 e := fmt.Sprintf("No ColumnMap in table %s type %s with field %s",
252 t.TableName, t.gotype.Name(), field)
253
254 panic(e)
255 }
256 return col
257 }
258
259 func colMapOrNil(t *TableMap, field string) *ColumnMap {
260 for _, col := range t.Columns {
261 if col.fieldName == field || col.ColumnName == field {
262 return col
263 }
264 }
265 return nil
266 }
267
268 // SetVersionCol sets the column to use as the Version field. By default
269 // the "Version" field is used. Returns the column found, or panics
270 // if the struct does not contain a field matching this name.
271 //
272 // Automatically calls ResetSql() to ensure SQL statements are regenerated.
273 func (t *TableMap) SetVersionCol(field string) *ColumnMap {
274 c := t.ColMap(field)
275 t.version = c
276 t.ResetSql()
277 return c
278 }
279
280 type bindPlan struct {
281 query string
282 argFields []string
283 keyFields []string
284 versField string
285 autoIncrIdx int
286 autoIncrFieldName string
287 once sync.Once
288 }
289
290 func (plan *bindPlan) createBindInstance(elem reflect.Value, conv TypeConverter) (bindInstance, error) {
291 bi := bindInstance{query: plan.query, autoIncrIdx: plan.autoIncrIdx, autoIncrFieldName: plan.autoIncrFieldName, versField: plan.versField}
292 if plan.versField != "" {
293 bi.existingVersion = elem.FieldByName(plan.versField).Int()
294 }
295
296 var err error
297
298 for i := 0; i < len(plan.argFields); i++ {
299 k := plan.argFields[i]
300 if k == versFieldConst {
301 newVer := bi.existingVersion + 1
302 bi.args = append(bi.args, newVer)
303 if bi.existingVersion == 0 {
304 elem.FieldByName(plan.versField).SetInt(int64(newVer))
305 }
306 } else {
307 val := elem.FieldByName(k).Interface()
308 if conv != nil {
309 val, err = conv.ToDb(val)
310 if err != nil {
311 return bindInstance{}, err
312 }
313 }
314 bi.args = append(bi.args, val)
315 }
316 }
317
318 for i := 0; i < len(plan.keyFields); i++ {
319 k := plan.keyFields[i]
320 val := elem.FieldByName(k).Interface()
321 if conv != nil {
322 val, err = conv.ToDb(val)
323 if err != nil {
324 return bindInstance{}, err
325 }
326 }
327 bi.keys = append(bi.keys, val)
328 }
329
330 return bi, nil
331 }
332
333 type bindInstance struct {
334 query string
335 args []interface{}
336 keys []interface{}
337 existingVersion int64
338 versField string
339 autoIncrIdx int
340 autoIncrFieldName string
341 }
342
343 func (t *TableMap) bindInsert(elem reflect.Value) (bindInstance, error) {
344 plan := &t.insertPlan
345 plan.once.Do(func() {
346 plan.autoIncrIdx = -1
347
348 s := bytes.Buffer{}
349 s2 := bytes.Buffer{}
350 s.WriteString(fmt.Sprintf("insert into %s (", t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName)))
351
352 x := 0
353 first := true
354 for y := range t.Columns {
355 col := t.Columns[y]
356 if !(col.isAutoIncr && t.dbmap.Dialect.AutoIncrBindValue() == "") {
357 if !col.Transient {
358 if !first {
359 s.WriteString(",")
360 s2.WriteString(",")
361 }
362 s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))
363
364 if col.isAutoIncr {
365 s2.WriteString(t.dbmap.Dialect.AutoIncrBindValue())
366 plan.autoIncrIdx = y
367 plan.autoIncrFieldName = col.fieldName
368 } else {
369 s2.WriteString(t.dbmap.Dialect.BindVar(x))
370 if col == t.version {
371 plan.versField = col.fieldName
372 plan.argFields = append(plan.argFields, versFieldConst)
373 } else {
374 plan.argFields = append(plan.argFields, col.fieldName)
375 }
376
377 x++
378 }
379 first = false
380 }
381 } else {
382 plan.autoIncrIdx = y
383 plan.autoIncrFieldName = col.fieldName
384 }
385 }
386 s.WriteString(") values (")
387 s.WriteString(s2.String())
388 s.WriteString(")")
389 if plan.autoIncrIdx > -1 {
390 s.WriteString(t.dbmap.Dialect.AutoIncrInsertSuffix(t.Columns[plan.autoIncrIdx]))
391 }
392 s.WriteString(t.dbmap.Dialect.QuerySuffix())
393
394 plan.query = s.String()
395 })
396
397 return plan.createBindInstance(elem, t.dbmap.TypeConverter)
398 }
399
400 func (t *TableMap) bindUpdate(elem reflect.Value) (bindInstance, error) {
401 plan := &t.updatePlan
402 plan.once.Do(func() {
403
404 s := bytes.Buffer{}
405 s.WriteString(fmt.Sprintf("update %s set ", t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName)))
406 x := 0
407
408 for y := range t.Columns {
409 col := t.Columns[y]
410 if !col.isAutoIncr && !col.Transient {
411 if x > 0 {
412 s.WriteString(", ")
413 }
414 s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))
415 s.WriteString("=")
416 s.WriteString(t.dbmap.Dialect.BindVar(x))
417
418 if col == t.version {
419 plan.versField = col.fieldName
420 plan.argFields = append(plan.argFields, versFieldConst)
421 } else {
422 plan.argFields = append(plan.argFields, col.fieldName)
423 }
424 x++
425 }
426 }
427
428 s.WriteString(" where ")
429 for y := range t.keys {
430 col := t.keys[y]
431 if y > 0 {
432 s.WriteString(" and ")
433 }
434 s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))
435 s.WriteString("=")
436 s.WriteString(t.dbmap.Dialect.BindVar(x))
437
438 plan.argFields = append(plan.argFields, col.fieldName)
439 plan.keyFields = append(plan.keyFields, col.fieldName)
440 x++
441 }
442 if plan.versField != "" {
443 s.WriteString(" and ")
444 s.WriteString(t.dbmap.Dialect.QuoteField(t.version.ColumnName))
445 s.WriteString("=")
446 s.WriteString(t.dbmap.Dialect.BindVar(x))
447 plan.argFields = append(plan.argFields, plan.versField)
448 }
449 s.WriteString(t.dbmap.Dialect.QuerySuffix())
450
451 plan.query = s.String()
452 })
453
454 return plan.createBindInstance(elem, t.dbmap.TypeConverter)
455 }
456
457 func (t *TableMap) bindDelete(elem reflect.Value) (bindInstance, error) {
458 plan := &t.deletePlan
459 plan.once.Do(func() {
460
461 s := bytes.Buffer{}
462 s.WriteString(fmt.Sprintf("delete from %s", t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName)))
463
464 for y := range t.Columns {
465 col := t.Columns[y]
466 if !col.Transient {
467 if col == t.version {
468 plan.versField = col.fieldName
469 }
470 }
471 }
472
473 s.WriteString(" where ")
474 for x := range t.keys {
475 k := t.keys[x]
476 if x > 0 {
477 s.WriteString(" and ")
478 }
479 s.WriteString(t.dbmap.Dialect.QuoteField(k.ColumnName))
480 s.WriteString("=")
481 s.WriteString(t.dbmap.Dialect.BindVar(x))
482
483 plan.keyFields = append(plan.keyFields, k.fieldName)
484 plan.argFields = append(plan.argFields, k.fieldName)
485 }
486 if plan.versField != "" {
487 s.WriteString(" and ")
488 s.WriteString(t.dbmap.Dialect.QuoteField(t.version.ColumnName))
489 s.WriteString("=")
490 s.WriteString(t.dbmap.Dialect.BindVar(len(plan.argFields)))
491
492 plan.argFields = append(plan.argFields, plan.versField)
493 }
494 s.WriteString(t.dbmap.Dialect.QuerySuffix())
495
496 plan.query = s.String()
497 })
498
499 return plan.createBindInstance(elem, t.dbmap.TypeConverter)
500 }
501
502 func (t *TableMap) bindGet() *bindPlan {
503 plan := &t.getPlan
504 plan.once.Do(func() {
505
506 s := bytes.Buffer{}
507 s.WriteString("select ")
508
509 x := 0
510 for _, col := range t.Columns {
511 if !col.Transient {
512 if x > 0 {
513 s.WriteString(",")
514 }
515 s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))
516 plan.argFields = append(plan.argFields, col.fieldName)
517 x++
518 }
519 }
520 s.WriteString(" from ")
521 s.WriteString(t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName))
522 s.WriteString(" where ")
523 for x := range t.keys {
524 col := t.keys[x]
525 if x > 0 {
526 s.WriteString(" and ")
527 }
528 s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))
529 s.WriteString("=")
530 s.WriteString(t.dbmap.Dialect.BindVar(x))
531
532 plan.keyFields = append(plan.keyFields, col.fieldName)
533 }
534 s.WriteString(t.dbmap.Dialect.QuerySuffix())
535
536 plan.query = s.String()
537 })
538
539 return plan
540 }
541
542 // ColumnMap represents a mapping between a Go struct field and a single
543 // column in a table.
544 // Unique and MaxSize only inform the
545 // CreateTables() function and are not used by Insert/Update/Delete/Get.
546 type ColumnMap struct {
547 // Column name in db table
548 ColumnName string
549
550 // If true, this column is skipped in generated SQL statements
551 Transient bool
552
553 // If true, " unique" is added to create table statements.
554 // Not used elsewhere
555 Unique bool
556
557 // Passed to Dialect.ToSqlType() to assist in informing the
558 // correct column type to map to in CreateTables()
559 // Not used elsewhere
560 MaxSize int
561
562 fieldName string
563 gotype reflect.Type
564 isPK bool
565 isAutoIncr bool
566 isNotNull bool
567 }
568
569 // Rename allows you to specify the column name in the table
570 //
571 // Example: table.ColMap("Updated").Rename("date_updated")
572 //
573 func (c *ColumnMap) Rename(colname string) *ColumnMap {
574 c.ColumnName = colname
575 return c
576 }
577
578 // SetTransient allows you to mark the column as transient. If true
579 // this column will be skipped when SQL statements are generated
580 func (c *ColumnMap) SetTransient(b bool) *ColumnMap {
581 c.Transient = b
582 return c
583 }
584
585 // SetUnique adds "unique" to the create table statements for this
586 // column, if b is true.
587 func (c *ColumnMap) SetUnique(b bool) *ColumnMap {
588 c.Unique = b
589 return c
590 }
591
592 // SetNotNull adds "not null" to the create table statements for this
593 // column, if nn is true.
594 func (c *ColumnMap) SetNotNull(nn bool) *ColumnMap {
595 c.isNotNull = nn
596 return c
597 }
598
599 // SetMaxSize specifies the max length of values of this column. This is
600 // passed to the dialect.ToSqlType() function, which can use the value
601 // to alter the generated type for "create table" statements
602 func (c *ColumnMap) SetMaxSize(size int) *ColumnMap {
603 c.MaxSize = size
604 return c
605 }
606
607 // Transaction represents a database transaction.
608 // Insert/Update/Delete/Get/Exec operations will be run in the context
609 // of that transaction. Transactions should be terminated with
610 // a call to Commit() or Rollback()
611 type Transaction struct {
612 dbmap *DbMap
613 tx *sql.Tx
614 closed bool
615 }
616
617 // SqlExecutor exposes gorp operations that can be run from Pre/Post
618 // hooks. This hides whether the current operation that triggered the
619 // hook is in a transaction.
620 //
621 // See the DbMap function docs for each of the functions below for more
622 // information.
623 type SqlExecutor interface {
624 Get(i interface{}, keys ...interface{}) (interface{}, error)
625 Insert(list ...interface{}) error
626 Update(list ...interface{}) (int64, error)
627 Delete(list ...interface{}) (int64, error)
628 Exec(query string, args ...interface{}) (sql.Result, error)
629 Select(i interface{}, query string,
630 args ...interface{}) ([]interface{}, error)
631 SelectInt(query string, args ...interface{}) (int64, error)
632 SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error)
633 SelectFloat(query string, args ...interface{}) (float64, error)
634 SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error)
635 SelectStr(query string, args ...interface{}) (string, error)
636 SelectNullStr(query string, args ...interface{}) (sql.NullString, error)
637 SelectOne(holder interface{}, query string, args ...interface{}) error
638 query(query string, args ...interface{}) (*sql.Rows, error)
639 queryRow(query string, args ...interface{}) *sql.Row
640 }
641
642 // Compile-time check that DbMap and Transaction implement the SqlExecutor
643 // interface.
644 var _, _ SqlExecutor = &DbMap{}, &Transaction{}
645
646 type GorpLogger interface {
647 Printf(format string, v ...interface{})
648 }
649
650 // TraceOn turns on SQL statement logging for this DbMap. After this is
651 // called, all SQL statements will be sent to the logger. If prefix is
652 // a non-empty string, it will be written to the front of all logged
653 // strings, which can aid in filtering log lines.
654 //
655 // Use TraceOn if you want to spy on the SQL statements that gorp
656 // generates.
657 //
658 // Note that the base log.Logger type satisfies GorpLogger, but adapters can
659 // easily be written for other logging packages (e.g., the golang-sanctioned
660 // glog framework).
661 func (m *DbMap) TraceOn(prefix string, logger GorpLogger) {
662 m.logger = logger
663 if prefix == "" {
664 m.logPrefix = prefix
665 } else {
666 m.logPrefix = fmt.Sprintf("%s ", prefix)
667 }
668 }
669
670 // TraceOff turns off tracing. It is idempotent.
671 func (m *DbMap) TraceOff() {
672 m.logger = nil
673 m.logPrefix = ""
674 }
675
676 // AddTable registers the given interface type with gorp. The table name
677 // will be given the name of the TypeOf(i). You must call this function,
678 // or AddTableWithName, for any struct type you wish to persist with
679 // the given DbMap.
680 //
681 // This operation is idempotent. If i's type is already mapped, the
682 // existing *TableMap is returned
683 func (m *DbMap) AddTable(i interface{}) *TableMap {
684 return m.AddTableWithName(i, "")
685 }
686
687 // AddTableWithName has the same behavior as AddTable, but sets
688 // table.TableName to name.
689 func (m *DbMap) AddTableWithName(i interface{}, name string) *TableMap {
690 return m.AddTableWithNameAndSchema(i, "", name)
691 }
692
693 // AddTableWithNameAndSchema has the same behavior as AddTable, but sets
694 // table.TableName to name.
695 func (m *DbMap) AddTableWithNameAndSchema(i interface{}, schema string, name string) *TableMap {
696 t := reflect.TypeOf(i)
697 if name == "" {
698 name = t.Name()
699 }
700
701 // check if we have a table for this type already
702 // if so, update the name and return the existing pointer
703 for i := range m.tables {
704 table := m.tables[i]
705 if table.gotype == t {
706 table.TableName = name
707 return table
708 }
709 }
710
711 tmap := &TableMap{gotype: t, TableName: name, SchemaName: schema, dbmap: m}
712 tmap.Columns, tmap.version = m.readStructColumns(t)
713 m.tables = append(m.tables, tmap)
714
715 return tmap
716 }
717
718 func (m *DbMap) readStructColumns(t reflect.Type) (cols []*ColumnMap, version *ColumnMap) {
719 n := t.NumField()
720 for i := 0; i < n; i++ {
721 f := t.Field(i)
722 if f.Anonymous && f.Type.Kind() == reflect.Struct {
723 // Recursively add nested fields in embedded structs.
724 subcols, subversion := m.readStructColumns(f.Type)
725 // Don't append nested fields that have the same field
726 // name as an already-mapped field.
727 for _, subcol := range subcols {
728 shouldAppend := true
729 for _, col := range cols {
730 if !subcol.Transient && subcol.fieldName == col.fieldName {
731 shouldAppend = false
732 break
733 }
734 }
735 if shouldAppend {
736 cols = append(cols, subcol)
737 }
738 }
739 if subversion != nil {
740 version = subversion
741 }
742 } else {
743 columnName := f.Tag.Get("db")
744 if columnName == "" {
745 columnName = f.Name
746 }
747 gotype := f.Type
748 if m.TypeConverter != nil {
749 // Make a new pointer to a value of type gotype and
750 // pass it to the TypeConverter's FromDb method to see
751 // if a different type should be used for the column
752 // type during table creation.
753 value := reflect.New(gotype).Interface()
754 scanner, useHolder := m.TypeConverter.FromDb(value)
755 if useHolder {
756 gotype = reflect.TypeOf(scanner.Holder)
757 }
758 }
759 cm := &ColumnMap{
760 ColumnName: columnName,
761 Transient: columnName == "-",
762 fieldName: f.Name,
763 gotype: gotype,
764 }
765 // Check for nested fields of the same field name and
766 // override them.
767 shouldAppend := true
768 for index, col := range cols {
769 if !col.Transient && col.fieldName == cm.fieldName {
770 cols[index] = cm
771 shouldAppend = false
772 break
773 }
774 }
775 if shouldAppend {
776 cols = append(cols, cm)
777 }
778 if cm.fieldName == "Version" {
779 log.New(os.Stderr, "", log.LstdFlags).Println("Warning: Automatic mapping of Version struct members to version columns (see optimistic locking) will be deprecated in next version (V2) See: https://github.com/go-gorp/gorp/pull/214")
780 version = cm
781 }
782 }
783 }
784 return
785 }
786
787 // CreateTables iterates through TableMaps registered to this DbMap and
788 // executes "create table" statements against the database for each.
789 //
790 // This is particularly useful in unit tests where you want to create
791 // and destroy the schema automatically.
792 func (m *DbMap) CreateTables() error {
793 return m.createTables(false)
794 }
795
796 // CreateTablesIfNotExists is similar to CreateTables, but starts
797 // each statement with "create table if not exists" so that existing
798 // tables do not raise errors
799 func (m *DbMap) CreateTablesIfNotExists() error {
800 return m.createTables(true)
801 }
802
803 func (m *DbMap) createTables(ifNotExists bool) error {
804 var err error
805 for i := range m.tables {
806 table := m.tables[i]
807
808 s := bytes.Buffer{}
809
810 if strings.TrimSpace(table.SchemaName) != "" {
811 schemaCreate := "create schema"
812 if ifNotExists {
813 s.WriteString(m.Dialect.IfSchemaNotExists(schemaCreate, table.SchemaName))
814 } else {
815 s.WriteString(schemaCreate)
816 }
817 s.WriteString(fmt.Sprintf(" %s;", table.SchemaName))
818 }
819
820 tableCreate := "create table"
821 if ifNotExists {
822 s.WriteString(m.Dialect.IfTableNotExists(tableCreate, table.SchemaName, table.TableName))
823 } else {
824 s.WriteString(tableCreate)
825 }
826 s.WriteString(fmt.Sprintf(" %s (", m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName)))
827
828 x := 0
829 for _, col := range table.Columns {
830 if !col.Transient {
831 if x > 0 {
832 s.WriteString(", ")
833 }
834 stype := m.Dialect.ToSqlType(col.gotype, col.MaxSize, col.isAutoIncr)
835 s.WriteString(fmt.Sprintf("%s %s", m.Dialect.QuoteField(col.ColumnName), stype))
836
837 if col.isPK || col.isNotNull {
838 s.WriteString(" not null")
839 }
840 if col.isPK && len(table.keys) == 1 {
841 s.WriteString(" primary key")
842 }
843 if col.Unique {
844 s.WriteString(" unique")
845 }
846 if col.isAutoIncr {
847 s.WriteString(fmt.Sprintf(" %s", m.Dialect.AutoIncrStr()))
848 }
849
850 x++
851 }
852 }
853 if len(table.keys) > 1 {
854 s.WriteString(", primary key (")
855 for x := range table.keys {
856 if x > 0 {
857 s.WriteString(", ")
858 }
859 s.WriteString(m.Dialect.QuoteField(table.keys[x].ColumnName))
860 }
861 s.WriteString(")")
862 }
863 if len(table.uniqueTogether) > 0 {
864 for _, columns := range table.uniqueTogether {
865 s.WriteString(", unique (")
866 for i, column := range columns {
867 if i > 0 {
868 s.WriteString(", ")
869 }
870 s.WriteString(m.Dialect.QuoteField(column))
871 }
872 s.WriteString(")")
873 }
874 }
875 s.WriteString(") ")
876 s.WriteString(m.Dialect.CreateTableSuffix())
877 s.WriteString(m.Dialect.QuerySuffix())
878 _, err = m.Exec(s.String())
879 if err != nil {
880 break
881 }
882 }
883 return err
884 }
885
886 // DropTable drops an individual table. Will throw an error
887 // if the table does not exist.
888 func (m *DbMap) DropTable(table interface{}) error {
889 t := reflect.TypeOf(table)
890 return m.dropTable(t, false)
891 }
892
893 // DropTable drops an individual table. Will NOT throw an error
894 // if the table does not exist.
895 func (m *DbMap) DropTableIfExists(table interface{}) error {
896 t := reflect.TypeOf(table)
897 return m.dropTable(t, true)
898 }
899
900 // DropTables iterates through TableMaps registered to this DbMap and
901 // executes "drop table" statements against the database for each.
902 func (m *DbMap) DropTables() error {
903 return m.dropTables(false)
904 }
905
906 // DropTablesIfExists is the same as DropTables, but uses the "if exists" clause to
907 // avoid errors for tables that do not exist.
908 func (m *DbMap) DropTablesIfExists() error {
909 return m.dropTables(true)
910 }
911
912 // Goes through all the registered tables, dropping them one by one.
913 // If an error is encountered, then it is returned and the rest of
914 // the tables are not dropped.
915 func (m *DbMap) dropTables(addIfExists bool) (err error) {
916 for _, table := range m.tables {
917 err = m.dropTableImpl(table, addIfExists)
918 if err != nil {
919 return
920 }
921 }
922 return err
923 }
924
925 // Implementation of dropping a single table.
926 func (m *DbMap) dropTable(t reflect.Type, addIfExists bool) error {
927 table := tableOrNil(m, t)
928 if table == nil {
929 return errors.New(fmt.Sprintf("table %s was not registered!", table.TableName))
930 }
931
932 return m.dropTableImpl(table, addIfExists)
933 }
934
935 func (m *DbMap) dropTableImpl(table *TableMap, ifExists bool) (err error) {
936 tableDrop := "drop table"
937 if ifExists {
938 tableDrop = m.Dialect.IfTableExists(tableDrop, table.SchemaName, table.TableName)
939 }
940 _, err = m.Exec(fmt.Sprintf("%s %s;", tableDrop, m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName)))
941 return err
942 }
943
944 // TruncateTables iterates through TableMaps registered to this DbMap and
945 // executes "truncate table" statements against the database for each, or in the case of
946 // sqlite, a "delete from" with no "where" clause, which uses the truncate optimization
947 // (http://www.sqlite.org/lang_delete.html)
948 func (m *DbMap) TruncateTables() error {
949 var err error
950 for i := range m.tables {
951 table := m.tables[i]
952 _, e := m.Exec(fmt.Sprintf("%s %s;", m.Dialect.TruncateClause(), m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName)))
953 if e != nil {
954 err = e
955 }
956 }
957 return err
958 }
959
960 // Insert runs a SQL INSERT statement for each element in list. List
961 // items must be pointers.
962 //
963 // Any interface whose TableMap has an auto-increment primary key will
964 // have its last insert id bound to the PK field on the struct.
965 //
966 // The hook functions PreInsert() and/or PostInsert() will be executed
967 // before/after the INSERT statement if the interface defines them.
968 //
969 // Panics if any interface in the list has not been registered with AddTable
970 func (m *DbMap) Insert(list ...interface{}) error {
971 return insert(m, m, list...)
972 }
973
974 // Update runs a SQL UPDATE statement for each element in list. List
975 // items must be pointers.
976 //
977 // The hook functions PreUpdate() and/or PostUpdate() will be executed
978 // before/after the UPDATE statement if the interface defines them.
979 //
980 // Returns the number of rows updated.
981 //
982 // Returns an error if SetKeys has not been called on the TableMap
983 // Panics if any interface in the list has not been registered with AddTable
984 func (m *DbMap) Update(list ...interface{}) (int64, error) {
985 return update(m, m, list...)
986 }
987
988 // Delete runs a SQL DELETE statement for each element in list. List
989 // items must be pointers.
990 //
991 // The hook functions PreDelete() and/or PostDelete() will be executed
992 // before/after the DELETE statement if the interface defines them.
993 //
994 // Returns the number of rows deleted.
995 //
996 // Returns an error if SetKeys has not been called on the TableMap
997 // Panics if any interface in the list has not been registered with AddTable
998 func (m *DbMap) Delete(list ...interface{}) (int64, error) {
999 return delete(m, m, list...)
1000 }
1001
1002 // Get runs a SQL SELECT to fetch a single row from the table based on the
1003 // primary key(s)
1004 //
1005 // i should be an empty value for the struct to load. keys should be
1006 // the primary key value(s) for the row to load. If multiple keys
1007 // exist on the table, the order should match the column order
1008 // specified in SetKeys() when the table mapping was defined.
1009 //
1010 // The hook function PostGet() will be executed after the SELECT
1011 // statement if the interface defines them.
1012 //
1013 // Returns a pointer to a struct that matches or nil if no row is found.
1014 //
1015 // Returns an error if SetKeys has not been called on the TableMap
1016 // Panics if any interface in the list has not been registered with AddTable
1017 func (m *DbMap) Get(i interface{}, keys ...interface{}) (interface{}, error) {
1018 return get(m, m, i, keys...)
1019 }
1020
1021 // Select runs an arbitrary SQL query, binding the columns in the result
1022 // to fields on the struct specified by i. args represent the bind
1023 // parameters for the SQL statement.
1024 //
1025 // Column names on the SELECT statement should be aliased to the field names
1026 // on the struct i. Returns an error if one or more columns in the result
1027 // do not match. It is OK if fields on i are not part of the SQL
1028 // statement.
1029 //
1030 // The hook function PostGet() will be executed after the SELECT
1031 // statement if the interface defines them.
1032 //
1033 // Values are returned in one of two ways:
1034 // 1. If i is a struct or a pointer to a struct, returns a slice of pointers to
1035 // matching rows of type i.
1036 // 2. If i is a pointer to a slice, the results will be appended to that slice
1037 // and nil returned.
1038 //
1039 // i does NOT need to be registered with AddTable()
1040 func (m *DbMap) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error) {
1041 return hookedselect(m, m, i, query, args...)
1042 }
1043
1044 // Exec runs an arbitrary SQL statement. args represent the bind parameters.
1045 // This is equivalent to running: Exec() using database/sql
1046 func (m *DbMap) Exec(query string, args ...interface{}) (sql.Result, error) {
1047 m.trace(query, args...)
1048 return m.Db.Exec(query, args...)
1049 }
1050
1051 // SelectInt is a convenience wrapper around the gorp.SelectInt function
1052 func (m *DbMap) SelectInt(query string, args ...interface{}) (int64, error) {
1053 return SelectInt(m, query, args...)
1054 }
1055
1056 // SelectNullInt is a convenience wrapper around the gorp.SelectNullInt function
1057 func (m *DbMap) SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error) {
1058 return SelectNullInt(m, query, args...)
1059 }
1060
1061 // SelectFloat is a convenience wrapper around the gorp.SelectFlot function
1062 func (m *DbMap) SelectFloat(query string, args ...interface{}) (float64, error) {
1063 return SelectFloat(m, query, args...)
1064 }
1065
1066 // SelectNullFloat is a convenience wrapper around the gorp.SelectNullFloat function
1067 func (m *DbMap) SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error) {
1068 return SelectNullFloat(m, query, args...)
1069 }
1070
1071 // SelectStr is a convenience wrapper around the gorp.SelectStr function
1072 func (m *DbMap) SelectStr(query string, args ...interface{}) (string, error) {
1073 return SelectStr(m, query, args...)
1074 }
1075
1076 // SelectNullStr is a convenience wrapper around the gorp.SelectNullStr function
1077 func (m *DbMap) SelectNullStr(query string, args ...interface{}) (sql.NullString, error) {
1078 return SelectNullStr(m, query, args...)
1079 }
1080
1081 // SelectOne is a convenience wrapper around the gorp.SelectOne function
1082 func (m *DbMap) SelectOne(holder interface{}, query string, args ...interface{}) error {
1083 return SelectOne(m, m, holder, query, args...)
1084 }
1085
1086 // Begin starts a gorp Transaction
1087 func (m *DbMap) Begin() (*Transaction, error) {
1088 m.trace("begin;")
1089 tx, err := m.Db.Begin()
1090 if err != nil {
1091 return nil, err
1092 }
1093 return &Transaction{m, tx, false}, nil
1094 }
1095
1096 // TableFor returns the *TableMap corresponding to the given Go Type
1097 // If no table is mapped to that type an error is returned.
1098 // If checkPK is true and the mapped table has no registered PKs, an error is returned.
1099 func (m *DbMap) TableFor(t reflect.Type, checkPK bool) (*TableMap, error) {
1100 table := tableOrNil(m, t)
1101 if table == nil {
1102 return nil, errors.New(fmt.Sprintf("No table found for type: %v", t.Name()))
1103 }
1104
1105 if checkPK && len(table.keys) < 1 {
1106 e := fmt.Sprintf("gorp: No keys defined for table: %s",
1107 table.TableName)
1108 return nil, errors.New(e)
1109 }
1110
1111 return table, nil
1112 }
1113
1114 // Prepare creates a prepared statement for later queries or executions.
1115 // Multiple queries or executions may be run concurrently from the returned statement.
1116 // This is equivalent to running: Prepare() using database/sql
1117 func (m *DbMap) Prepare(query string) (*sql.Stmt, error) {
1118 m.trace(query, nil)
1119 return m.Db.Prepare(query)
1120 }
1121
1122 func tableOrNil(m *DbMap, t reflect.Type) *TableMap {
1123 for i := range m.tables {
1124 table := m.tables[i]
1125 if table.gotype == t {
1126 return table
1127 }
1128 }
1129 return nil
1130 }
1131
1132 func (m *DbMap) tableForPointer(ptr interface{}, checkPK bool) (*TableMap, reflect.Value, error) {
1133 ptrv := reflect.ValueOf(ptr)
1134 if ptrv.Kind() != reflect.Ptr {
1135 e := fmt.Sprintf("gorp: passed non-pointer: %v (kind=%v)", ptr,
1136 ptrv.Kind())
1137 return nil, reflect.Value{}, errors.New(e)
1138 }
1139 elem := ptrv.Elem()
1140 etype := reflect.TypeOf(elem.Interface())
1141 t, err := m.TableFor(etype, checkPK)
1142 if err != nil {
1143 return nil, reflect.Value{}, err
1144 }
1145
1146 return t, elem, nil
1147 }
1148
1149 func (m *DbMap) queryRow(query string, args ...interface{}) *sql.Row {
1150 m.trace(query, args...)
1151 return m.Db.QueryRow(query, args...)
1152 }
1153
1154 func (m *DbMap) query(query string, args ...interface{}) (*sql.Rows, error) {
1155 m.trace(query, args...)
1156 return m.Db.Query(query, args...)
1157 }
1158
1159 func (m *DbMap) trace(query string, args ...interface{}) {
1160 if m.logger != nil {
1161 var margs = argsString(args...)
1162 m.logger.Printf("%s%s [%s]", m.logPrefix, query, margs)
1163 }
1164 }
1165
1166 func argsString(args ...interface{}) string {
1167 var margs string
1168 for i, a := range args {
1169 var v interface{} = a
1170 if x, ok := v.(driver.Valuer); ok {
1171 y, err := x.Value()
1172 if err == nil {
1173 v = y
1174 }
1175 }
1176 switch v.(type) {
1177 case string:
1178 v = fmt.Sprintf("%q", v)
1179 default:
1180 v = fmt.Sprintf("%v", v)
1181 }
1182 margs += fmt.Sprintf("%d:%s", i+1, v)
1183 if i+1 < len(args) {
1184 margs += " "
1185 }
1186 }
1187 return margs
1188 }
1189
1190 ///////////////
1191
1192 // Insert has the same behavior as DbMap.Insert(), but runs in a transaction.
1193 func (t *Transaction) Insert(list ...interface{}) error {
1194 return insert(t.dbmap, t, list...)
1195 }
1196
1197 // Update had the same behavior as DbMap.Update(), but runs in a transaction.
1198 func (t *Transaction) Update(list ...interface{}) (int64, error) {
1199 return update(t.dbmap, t, list...)
1200 }
1201
1202 // Delete has the same behavior as DbMap.Delete(), but runs in a transaction.
1203 func (t *Transaction) Delete(list ...interface{}) (int64, error) {
1204 return delete(t.dbmap, t, list...)
1205 }
1206
1207 // Get has the same behavior as DbMap.Get(), but runs in a transaction.
1208 func (t *Transaction) Get(i interface{}, keys ...interface{}) (interface{}, error) {
1209 return get(t.dbmap, t, i, keys...)
1210 }
1211
1212 // Select has the same behavior as DbMap.Select(), but runs in a transaction.
1213 func (t *Transaction) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error) {
1214 return hookedselect(t.dbmap, t, i, query, args...)
1215 }
1216
1217 // Exec has the same behavior as DbMap.Exec(), but runs in a transaction.
1218 func (t *Transaction) Exec(query string, args ...interface{}) (sql.Result, error) {
1219 t.dbmap.trace(query, args...)
1220 return t.tx.Exec(query, args...)
1221 }
1222
1223 // SelectInt is a convenience wrapper around the gorp.SelectInt function.
1224 func (t *Transaction) SelectInt(query string, args ...interface{}) (int64, error) {
1225 return SelectInt(t, query, args...)
1226 }
1227
1228 // SelectNullInt is a convenience wrapper around the gorp.SelectNullInt function.
1229 func (t *Transaction) SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error) {
1230 return SelectNullInt(t, query, args...)
1231 }
1232
1233 // SelectFloat is a convenience wrapper around the gorp.SelectFloat function.
1234 func (t *Transaction) SelectFloat(query string, args ...interface{}) (float64, error) {
1235 return SelectFloat(t, query, args...)
1236 }
1237
1238 // SelectNullFloat is a convenience wrapper around the gorp.SelectNullFloat function.
1239 func (t *Transaction) SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error) {
1240 return SelectNullFloat(t, query, args...)
1241 }
1242
1243 // SelectStr is a convenience wrapper around the gorp.SelectStr function.
1244 func (t *Transaction) SelectStr(query string, args ...interface{}) (string, error) {
1245 return SelectStr(t, query, args...)
1246 }
1247
1248 // SelectNullStr is a convenience wrapper around the gorp.SelectNullStr function.
1249 func (t *Transaction) SelectNullStr(query string, args ...interface{}) (sql.NullString, error) {
1250 return SelectNullStr(t, query, args...)
1251 }
1252
1253 // SelectOne is a convenience wrapper around the gorp.SelectOne function.
1254 func (t *Transaction) SelectOne(holder interface{}, query string, args ...interface{}) error {
1255 return SelectOne(t.dbmap, t, holder, query, args...)
1256 }
1257
1258 // Commit commits the underlying database transaction.
1259 func (t *Transaction) Commit() error {
1260 if !t.closed {
1261 t.closed = true
1262 t.dbmap.trace("commit;")
1263 return t.tx.Commit()
1264 }
1265
1266 return sql.ErrTxDone
1267 }
1268
1269 // Rollback rolls back the underlying database transaction.
1270 func (t *Transaction) Rollback() error {
1271 if !t.closed {
1272 t.closed = true
1273 t.dbmap.trace("rollback;")
1274 return t.tx.Rollback()
1275 }
1276
1277 return sql.ErrTxDone
1278 }
1279
1280 // Savepoint creates a savepoint with the given name. The name is interpolated
1281 // directly into the SQL SAVEPOINT statement, so you must sanitize it if it is
1282 // derived from user input.
1283 func (t *Transaction) Savepoint(name string) error {
1284 query := "savepoint " + t.dbmap.Dialect.QuoteField(name)
1285 t.dbmap.trace(query, nil)
1286 _, err := t.tx.Exec(query)
1287 return err
1288 }
1289
1290 // RollbackToSavepoint rolls back to the savepoint with the given name. The
1291 // name is interpolated directly into the SQL SAVEPOINT statement, so you must
1292 // sanitize it if it is derived from user input.
1293 func (t *Transaction) RollbackToSavepoint(savepoint string) error {
1294 query := "rollback to savepoint " + t.dbmap.Dialect.QuoteField(savepoint)
1295 t.dbmap.trace(query, nil)
1296 _, err := t.tx.Exec(query)
1297 return err
1298 }
1299
1300 // ReleaseSavepint releases the savepoint with the given name. The name is
1301 // interpolated directly into the SQL SAVEPOINT statement, so you must sanitize
1302 // it if it is derived from user input.
1303 func (t *Transaction) ReleaseSavepoint(savepoint string) error {
1304 query := "release savepoint " + t.dbmap.Dialect.QuoteField(savepoint)
1305 t.dbmap.trace(query, nil)
1306 _, err := t.tx.Exec(query)
1307 return err
1308 }
1309
1310 // Prepare has the same behavior as DbMap.Prepare(), but runs in a transaction.
1311 func (t *Transaction) Prepare(query string) (*sql.Stmt, error) {
1312 t.dbmap.trace(query, nil)
1313 return t.tx.Prepare(query)
1314 }
1315
1316 func (t *Transaction) queryRow(query string, args ...interface{}) *sql.Row {
1317 t.dbmap.trace(query, args...)
1318 return t.tx.QueryRow(query, args...)
1319 }
1320
1321 func (t *Transaction) query(query string, args ...interface{}) (*sql.Rows, error) {
1322 t.dbmap.trace(query, args...)
1323 return t.tx.Query(query, args...)
1324 }
1325
1326 ///////////////
1327
1328 // SelectInt executes the given query, which should be a SELECT statement for a single
1329 // integer column, and returns the value of the first row returned. If no rows are
1330 // found, zero is returned.
1331 func SelectInt(e SqlExecutor, query string, args ...interface{}) (int64, error) {
1332 var h int64
1333 err := selectVal(e, &h, query, args...)
1334 if err != nil && err != sql.ErrNoRows {
1335 return 0, err
1336 }
1337 return h, nil
1338 }
1339
1340 // SelectNullInt executes the given query, which should be a SELECT statement for a single
1341 // integer column, and returns the value of the first row returned. If no rows are
1342 // found, the empty sql.NullInt64 value is returned.
1343 func SelectNullInt(e SqlExecutor, query string, args ...interface{}) (sql.NullInt64, error) {
1344 var h sql.NullInt64
1345 err := selectVal(e, &h, query, args...)
1346 if err != nil && err != sql.ErrNoRows {
1347 return h, err
1348 }
1349 return h, nil
1350 }
1351
1352 // SelectFloat executes the given query, which should be a SELECT statement for a single
1353 // float column, and returns the value of the first row returned. If no rows are
1354 // found, zero is returned.
1355 func SelectFloat(e SqlExecutor, query string, args ...interface{}) (float64, error) {
1356 var h float64
1357 err := selectVal(e, &h, query, args...)
1358 if err != nil && err != sql.ErrNoRows {
1359 return 0, err
1360 }
1361 return h, nil
1362 }
1363
1364 // SelectNullFloat executes the given query, which should be a SELECT statement for a single
1365 // float column, and returns the value of the first row returned. If no rows are
1366 // found, the empty sql.NullInt64 value is returned.
1367 func SelectNullFloat(e SqlExecutor, query string, args ...interface{}) (sql.NullFloat64, error) {
1368 var h sql.NullFloat64
1369 err := selectVal(e, &h, query, args...)
1370 if err != nil && err != sql.ErrNoRows {
1371 return h, err
1372 }
1373 return h, nil
1374 }
1375
1376 // SelectStr executes the given query, which should be a SELECT statement for a single
1377 // char/varchar column, and returns the value of the first row returned. If no rows are
1378 // found, an empty string is returned.
1379 func SelectStr(e SqlExecutor, query string, args ...interface{}) (string, error) {
1380 var h string
1381 err := selectVal(e, &h, query, args...)
1382 if err != nil && err != sql.ErrNoRows {
1383 return "", err
1384 }
1385 return h, nil
1386 }
1387
1388 // SelectNullStr executes the given query, which should be a SELECT
1389 // statement for a single char/varchar column, and returns the value
1390 // of the first row returned. If no rows are found, the empty
1391 // sql.NullString is returned.
1392 func SelectNullStr(e SqlExecutor, query string, args ...interface{}) (sql.NullString, error) {
1393 var h sql.NullString
1394 err := selectVal(e, &h, query, args...)
1395 if err != nil && err != sql.ErrNoRows {
1396 return h, err
1397 }
1398 return h, nil
1399 }
1400
1401 // SelectOne executes the given query (which should be a SELECT statement)
1402 // and binds the result to holder, which must be a pointer.
1403 //
1404 // If no row is found, an error (sql.ErrNoRows specifically) will be returned
1405 //
1406 // If more than one row is found, an error will be returned.
1407 //
1408 func SelectOne(m *DbMap, e SqlExecutor, holder interface{}, query string, args ...interface{}) error {
1409 t := reflect.TypeOf(holder)
1410 if t.Kind() == reflect.Ptr {
1411 t = t.Elem()
1412 } else {
1413 return fmt.Errorf("gorp: SelectOne holder must be a pointer, but got: %t", holder)
1414 }
1415
1416 // Handle pointer to pointer
1417 isptr := false
1418 if t.Kind() == reflect.Ptr {
1419 isptr = true
1420 t = t.Elem()
1421 }
1422
1423 if t.Kind() == reflect.Struct {
1424 var nonFatalErr error
1425
1426 list, err := hookedselect(m, e, holder, query, args...)
1427 if err != nil {
1428 if !NonFatalError(err) {
1429 return err
1430 }
1431 nonFatalErr = err
1432 }
1433
1434 dest := reflect.ValueOf(holder)
1435 if isptr {
1436 dest = dest.Elem()
1437 }
1438
1439 if list != nil && len(list) > 0 {
1440 // check for multiple rows
1441 if len(list) > 1 {
1442 return fmt.Errorf("gorp: multiple rows returned for: %s - %v", query, args)
1443 }
1444
1445 // Initialize if nil
1446 if dest.IsNil() {
1447 dest.Set(reflect.New(t))
1448 }
1449
1450 // only one row found
1451 src := reflect.ValueOf(list[0])
1452 dest.Elem().Set(src.Elem())
1453 } else {
1454 // No rows found, return a proper error.
1455 return sql.ErrNoRows
1456 }
1457
1458 return nonFatalErr
1459 }
1460
1461 return selectVal(e, holder, query, args...)
1462 }
1463
1464 func selectVal(e SqlExecutor, holder interface{}, query string, args ...interface{}) error {
1465 if len(args) == 1 {
1466 switch m := e.(type) {
1467 case *DbMap:
1468 query, args = maybeExpandNamedQuery(m, query, args)
1469 case *Transaction:
1470 query, args = maybeExpandNamedQuery(m.dbmap, query, args)
1471 }
1472 }
1473 rows, err := e.query(query, args...)
1474 if err != nil {
1475 return err
1476 }
1477 defer rows.Close()
1478
1479 if !rows.Next() {
1480 return sql.ErrNoRows
1481 }
1482
1483 return rows.Scan(holder)
1484 }
1485
1486 ///////////////
1487
1488 func hookedselect(m *DbMap, exec SqlExecutor, i interface{}, query string,
1489 args ...interface{}) ([]interface{}, error) {
1490
1491 var nonFatalErr error
1492
1493 list, err := rawselect(m, exec, i, query, args...)
1494 if err != nil {
1495 if !NonFatalError(err) {
1496 return nil, err
1497 }
1498 nonFatalErr = err
1499 }
1500
1501 // Determine where the results are: written to i, or returned in list
1502 if t, _ := toSliceType(i); t == nil {
1503 for _, v := range list {
1504 if v, ok := v.(HasPostGet); ok {
1505 err := v.PostGet(exec)
1506 if err != nil {
1507 return nil, err
1508 }
1509 }
1510 }
1511 } else {
1512 resultsValue := reflect.Indirect(reflect.ValueOf(i))
1513 for i := 0; i < resultsValue.Len(); i++ {
1514 if v, ok := resultsValue.Index(i).Interface().(HasPostGet); ok {
1515 err := v.PostGet(exec)
1516 if err != nil {
1517 return nil, err
1518 }
1519 }
1520 }
1521 }
1522 return list, nonFatalErr
1523 }
1524
1525 func rawselect(m *DbMap, exec SqlExecutor, i interface{}, query string,
1526 args ...interface{}) ([]interface{}, error) {
1527 var (
1528 appendToSlice = false // Write results to i directly?
1529 intoStruct = true // Selecting into a struct?
1530 pointerElements = true // Are the slice elements pointers (vs values)?
1531 )
1532
1533 var nonFatalErr error
1534
1535 // get type for i, verifying it's a supported destination
1536 t, err := toType(i)
1537 if err != nil {
1538 var err2 error
1539 if t, err2 = toSliceType(i); t == nil {
1540 if err2 != nil {
1541 return nil, err2
1542 }
1543 return nil, err
1544 }
1545 pointerElements = t.Kind() == reflect.Ptr
1546 if pointerElements {
1547 t = t.Elem()
1548 }
1549 appendToSlice = true
1550 intoStruct = t.Kind() == reflect.Struct
1551 }
1552
1553 // If the caller supplied a single struct/map argument, assume a "named
1554 // parameter" query. Extract the named arguments from the struct/map, create
1555 // the flat arg slice, and rewrite the query to use the dialect's placeholder.
1556 if len(args) == 1 {
1557 query, args = maybeExpandNamedQuery(m, query, args)
1558 }
1559
1560 // Run the query
1561 rows, err := exec.query(query, args...)
1562 if err != nil {
1563 return nil, err
1564 }
1565 defer rows.Close()
1566
1567 // Fetch the column names as returned from db
1568 cols, err := rows.Columns()
1569 if err != nil {
1570 return nil, err
1571 }
1572
1573 if !intoStruct && len(cols) > 1 {
1574 return nil, fmt.Errorf("gorp: select into non-struct slice requires 1 column, got %d", len(cols))
1575 }
1576
1577 var colToFieldIndex [][]int
1578 if intoStruct {
1579 if colToFieldIndex, err = columnToFieldIndex(m, t, cols); err != nil {
1580 if !NonFatalError(err) {
1581 return nil, err
1582 }
1583 nonFatalErr = err
1584 }
1585 }
1586
1587 conv := m.TypeConverter
1588
1589 // Add results to one of these two slices.
1590 var (
1591 list = make([]interface{}, 0)
1592 sliceValue = reflect.Indirect(reflect.ValueOf(i))
1593 )
1594
1595 for {
1596 if !rows.Next() {
1597 // if error occured return rawselect
1598 if rows.Err() != nil {
1599 return nil, rows.Err()
1600 }
1601 // time to exit from outer "for" loop
1602 break
1603 }
1604 v := reflect.New(t)
1605 dest := make([]interface{}, len(cols))
1606
1607 custScan := make([]CustomScanner, 0)
1608
1609 for x := range cols {
1610 f := v.Elem()
1611 if intoStruct {
1612 index := colToFieldIndex[x]
1613 if index == nil {
1614 // this field is not present in the struct, so create a dummy
1615 // value for rows.Scan to scan into
1616 var dummy sql.RawBytes
1617 dest[x] = &dummy
1618 continue
1619 }
1620 f = f.FieldByIndex(index)
1621 }
1622 target := f.Addr().Interface()
1623 if conv != nil {
1624 scanner, ok := conv.FromDb(target)
1625 if ok {
1626 target = scanner.Holder
1627 custScan = append(custScan, scanner)
1628 }
1629 }
1630 dest[x] = target
1631 }
1632
1633 err = rows.Scan(dest...)
1634 if err != nil {
1635 return nil, err
1636 }
1637
1638 for _, c := range custScan {
1639 err = c.Bind()
1640 if err != nil {
1641 return nil, err
1642 }
1643 }
1644
1645 if appendToSlice {
1646 if !pointerElements {
1647 v = v.Elem()
1648 }
1649 sliceValue.Set(reflect.Append(sliceValue, v))
1650 } else {
1651 list = append(list, v.Interface())
1652 }
1653 }
1654
1655 if appendToSlice && sliceValue.IsNil() {
1656 sliceValue.Set(reflect.MakeSlice(sliceValue.Type(), 0, 0))
1657 }
1658
1659 return list, nonFatalErr
1660 }
1661
1662 // maybeExpandNamedQuery checks the given arg to see if it's eligible to be used
1663 // as input to a named query. If so, it rewrites the query to use
1664 // dialect-dependent bindvars and instantiates the corresponding slice of
1665 // parameters by extracting data from the map / struct.
1666 // If not, returns the input values unchanged.
1667 func maybeExpandNamedQuery(m *DbMap, query string, args []interface{}) (string, []interface{}) {
1668 arg := reflect.ValueOf(args[0])
1669 for arg.Kind() == reflect.Ptr {
1670 arg = arg.Elem()
1671 }
1672 switch {
1673 case arg.Kind() == reflect.Map && arg.Type().Key().Kind() == reflect.String:
1674 return expandNamedQuery(m, query, func(key string) reflect.Value {
1675 return arg.MapIndex(reflect.ValueOf(key))
1676 })
1677 // #84 - ignore time.Time structs here - there may be a cleaner way to do this
1678 case arg.Kind() == reflect.Struct && !(arg.Type().PkgPath() == "time" && arg.Type().Name() == "Time"):
1679 return expandNamedQuery(m, query, arg.FieldByName)
1680 }
1681 return query, args
1682 }
1683
1684 var keyRegexp = regexp.MustCompile(`:[[:word:]]+`)
1685
1686 // expandNamedQuery accepts a query with placeholders of the form ":key", and a
1687 // single arg of Kind Struct or Map[string]. It returns the query with the
1688 // dialect's placeholders, and a slice of args ready for positional insertion
1689 // into the query.
1690 func expandNamedQuery(m *DbMap, query string, keyGetter func(key string) reflect.Value) (string, []interface{}) {
1691 var (
1692 n int
1693 args []interface{}
1694 )
1695 return keyRegexp.ReplaceAllStringFunc(query, func(key string) string {
1696 val := keyGetter(key[1:])
1697 if !val.IsValid() {
1698 return key
1699 }
1700 args = append(args, val.Interface())
1701 newVar := m.Dialect.BindVar(n)
1702 n++
1703 return newVar
1704 }), args
1705 }
1706
1707 func columnToFieldIndex(m *DbMap, t reflect.Type, cols []string) ([][]int, error) {
1708 colToFieldIndex := make([][]int, len(cols))
1709
1710 // check if type t is a mapped table - if so we'll
1711 // check the table for column aliasing below
1712 tableMapped := false
1713 table := tableOrNil(m, t)
1714 if table != nil {
1715 tableMapped = true
1716 }
1717
1718 // Loop over column names and find field in i to bind to
1719 // based on column name. all returned columns must match
1720 // a field in the i struct
1721 missingColNames := []string{}
1722 for x := range cols {
1723 colName := strings.ToLower(cols[x])
1724 field, found := t.FieldByNameFunc(func(fieldName string) bool {
1725 field, _ := t.FieldByName(fieldName)
1726 fieldName = field.Tag.Get("db")
1727
1728 if fieldName == "-" {
1729 return false
1730 } else if fieldName == "" {
1731 fieldName = field.Name
1732 }
1733 if tableMapped {
1734 colMap := colMapOrNil(table, fieldName)
1735 if colMap != nil {
1736 fieldName = colMap.ColumnName
1737 }
1738 }
1739 return colName == strings.ToLower(fieldName)
1740 })
1741 if found {
1742 colToFieldIndex[x] = field.Index
1743 }
1744 if colToFieldIndex[x] == nil {
1745 missingColNames = append(missingColNames, colName)
1746 }
1747 }
1748 if len(missingColNames) > 0 {
1749 return colToFieldIndex, &NoFieldInTypeError{
1750 TypeName: t.Name(),
1751 MissingColNames: missingColNames,
1752 }
1753 }
1754 return colToFieldIndex, nil
1755 }
1756
1757 func fieldByName(val reflect.Value, fieldName string) *reflect.Value {
1758 // try to find field by exact match
1759 f := val.FieldByName(fieldName)
1760
1761 if f != zeroVal {
1762 return &f
1763 }
1764
1765 // try to find by case insensitive match - only the Postgres driver
1766 // seems to require this - in the case where columns are aliased in the sql
1767 fieldNameL := strings.ToLower(fieldName)
1768 fieldCount := val.NumField()
1769 t := val.Type()
1770 for i := 0; i < fieldCount; i++ {
1771 sf := t.Field(i)
1772 if strings.ToLower(sf.Name) == fieldNameL {
1773 f := val.Field(i)
1774 return &f
1775 }
1776 }
1777
1778 return nil
1779 }
1780
1781 // toSliceType returns the element type of the given object, if the object is a
1782 // "*[]*Element" or "*[]Element". If not, returns nil.
1783 // err is returned if the user was trying to pass a pointer-to-slice but failed.
1784 func toSliceType(i interface{}) (reflect.Type, error) {
1785 t := reflect.TypeOf(i)
1786 if t.Kind() != reflect.Ptr {
1787 // If it's a slice, return a more helpful error message
1788 if t.Kind() == reflect.Slice {
1789 return nil, fmt.Errorf("gorp: Cannot SELECT into a non-pointer slice: %v", t)
1790 }
1791 return nil, nil
1792 }
1793 if t = t.Elem(); t.Kind() != reflect.Slice {
1794 return nil, nil
1795 }
1796 return t.Elem(), nil
1797 }
1798
1799 func toType(i interface{}) (reflect.Type, error) {
1800 t := reflect.TypeOf(i)
1801
1802 // If a Pointer to a type, follow
1803 for t.Kind() == reflect.Ptr {
1804 t = t.Elem()
1805 }
1806
1807 if t.Kind() != reflect.Struct {
1808 return nil, fmt.Errorf("gorp: Cannot SELECT into this type: %v", reflect.TypeOf(i))
1809 }
1810 return t, nil
1811 }
1812
1813 func get(m *DbMap, exec SqlExecutor, i interface{},
1814 keys ...interface{}) (interface{}, error) {
1815
1816 t, err := toType(i)
1817 if err != nil {
1818 return nil, err
1819 }
1820
1821 table, err := m.TableFor(t, true)
1822 if err != nil {
1823 return nil, err
1824 }
1825
1826 plan := table.bindGet()
1827
1828 v := reflect.New(t)
1829 dest := make([]interface{}, len(plan.argFields))
1830
1831 conv := m.TypeConverter
1832 custScan := make([]CustomScanner, 0)
1833
1834 for x, fieldName := range plan.argFields {
1835 f := v.Elem().FieldByName(fieldName)
1836 target := f.Addr().Interface()
1837 if conv != nil {
1838 scanner, ok := conv.FromDb(target)
1839 if ok {
1840 target = scanner.Holder
1841 custScan = append(custScan, scanner)
1842 }
1843 }
1844 dest[x] = target
1845 }
1846
1847 row := exec.queryRow(plan.query, keys...)
1848 err = row.Scan(dest...)
1849 if err != nil {
1850 if err == sql.ErrNoRows {
1851 err = nil
1852 }
1853 return nil, err
1854 }
1855
1856 for _, c := range custScan {
1857 err = c.Bind()
1858 if err != nil {
1859 return nil, err
1860 }
1861 }
1862
1863 if v, ok := v.Interface().(HasPostGet); ok {
1864 err := v.PostGet(exec)
1865 if err != nil {
1866 return nil, err
1867 }
1868 }
1869
1870 return v.Interface(), nil
1871 }
1872
1873 func delete(m *DbMap, exec SqlExecutor, list ...interface{}) (int64, error) {
1874 count := int64(0)
1875 for _, ptr := range list {
1876 table, elem, err := m.tableForPointer(ptr, true)
1877 if err != nil {
1878 return -1, err
1879 }
1880
1881 eval := elem.Addr().Interface()
1882 if v, ok := eval.(HasPreDelete); ok {
1883 err = v.PreDelete(exec)
1884 if err != nil {
1885 return -1, err
1886 }
1887 }
1888
1889 bi, err := table.bindDelete(elem)
1890 if err != nil {
1891 return -1, err
1892 }
1893
1894 res, err := exec.Exec(bi.query, bi.args...)
1895 if err != nil {
1896 return -1, err
1897 }
1898 rows, err := res.RowsAffected()
1899 if err != nil {
1900 return -1, err
1901 }
1902
1903 if rows == 0 && bi.existingVersion > 0 {
1904 return lockError(m, exec, table.TableName,
1905 bi.existingVersion, elem, bi.keys...)
1906 }
1907
1908 count += rows
1909
1910 if v, ok := eval.(HasPostDelete); ok {
1911 err := v.PostDelete(exec)
1912 if err != nil {
1913 return -1, err
1914 }
1915 }
1916 }
1917
1918 return count, nil
1919 }
1920
1921 func update(m *DbMap, exec SqlExecutor, list ...interface{}) (int64, error) {
1922 count := int64(0)
1923 for _, ptr := range list {
1924 table, elem, err := m.tableForPointer(ptr, true)
1925 if err != nil {
1926 return -1, err
1927 }
1928
1929 eval := elem.Addr().Interface()
1930 if v, ok := eval.(HasPreUpdate); ok {
1931 err = v.PreUpdate(exec)
1932 if err != nil {
1933 return -1, err
1934 }
1935 }
1936
1937 bi, err := table.bindUpdate(elem)
1938 if err != nil {
1939 return -1, err
1940 }
1941
1942 res, err := exec.Exec(bi.query, bi.args...)
1943 if err != nil {
1944 return -1, err
1945 }
1946
1947 rows, err := res.RowsAffected()
1948 if err != nil {
1949 return -1, err
1950 }
1951
1952 if rows == 0 && bi.existingVersion > 0 {
1953 return lockError(m, exec, table.TableName,
1954 bi.existingVersion, elem, bi.keys...)
1955 }
1956
1957 if bi.versField != "" {
1958 elem.FieldByName(bi.versField).SetInt(bi.existingVersion + 1)
1959 }
1960
1961 count += rows
1962
1963 if v, ok := eval.(HasPostUpdate); ok {
1964 err = v.PostUpdate(exec)
1965 if err != nil {
1966 return -1, err
1967 }
1968 }
1969 }
1970 return count, nil
1971 }
1972
1973 func insert(m *DbMap, exec SqlExecutor, list ...interface{}) error {
1974 for _, ptr := range list {
1975 table, elem, err := m.tableForPointer(ptr, false)
1976 if err != nil {
1977 return err
1978 }
1979
1980 eval := elem.Addr().Interface()
1981 if v, ok := eval.(HasPreInsert); ok {
1982 err := v.PreInsert(exec)
1983 if err != nil {
1984 return err
1985 }
1986 }
1987
1988 bi, err := table.bindInsert(elem)
1989 if err != nil {
1990 return err
1991 }
1992
1993 if bi.autoIncrIdx > -1 {
1994 f := elem.FieldByName(bi.autoIncrFieldName)
1995 switch inserter := m.Dialect.(type) {
1996 case IntegerAutoIncrInserter:
1997 id, err := inserter.InsertAutoIncr(exec, bi.query, bi.args...)
1998 if err != nil {
1999 return err
2000 }
2001 k := f.Kind()
2002 if (k == reflect.Int) || (k == reflect.Int16) || (k == reflect.Int32) || (k == reflect.Int64) {
2003 f.SetInt(id)
2004 } else if (k == reflect.Uint) || (k == reflect.Uint16) || (k == reflect.Uint32) || (k == reflect.Uint64) {
2005 f.SetUint(uint64(id))
2006 } else {
2007 return fmt.Errorf("gorp: Cannot set autoincrement value on non-Int field. SQL=%s autoIncrIdx=%d autoIncrFieldName=%s", bi.query, bi.autoIncrIdx, bi.autoIncrFieldName)
2008 }
2009 case TargetedAutoIncrInserter:
2010 err := inserter.InsertAutoIncrToTarget(exec, bi.query, f.Addr().Interface(), bi.args...)
2011 if err != nil {
2012 return err
2013 }
2014 default:
2015 return fmt.Errorf("gorp: Cannot use autoincrement fields on dialects that do not implement an autoincrementing interface")
2016 }
2017 } else {
2018 _, err := exec.Exec(bi.query, bi.args...)
2019 if err != nil {
2020 return err
2021 }
2022 }
2023
2024 if v, ok := eval.(HasPostInsert); ok {
2025 err := v.PostInsert(exec)
2026 if err != nil {
2027 return err
2028 }
2029 }
2030 }
2031 return nil
2032 }
2033
2034 func lockError(m *DbMap, exec SqlExecutor, tableName string,
2035 existingVer int64, elem reflect.Value,
2036 keys ...interface{}) (int64, error) {
2037
2038 existing, err := get(m, exec, elem.Interface(), keys...)
2039 if err != nil {
2040 return -1, err
2041 }
2042
2043 ole := OptimisticLockError{tableName, keys, true, existingVer}
2044 if existing == nil {
2045 ole.RowExists = false
2046 }
2047 return -1, ole
2048 }
2049
2050 // PostUpdate() will be executed after the GET statement.
2051 type HasPostGet interface {
2052 PostGet(SqlExecutor) error
2053 }
2054
2055 // PostUpdate() will be executed after the DELETE statement
2056 type HasPostDelete interface {
2057 PostDelete(SqlExecutor) error
2058 }
2059
2060 // PostUpdate() will be executed after the UPDATE statement
2061 type HasPostUpdate interface {
2062 PostUpdate(SqlExecutor) error
2063 }
2064
2065 // PostInsert() will be executed after the INSERT statement
2066 type HasPostInsert interface {
2067 PostInsert(SqlExecutor) error
2068 }
2069
2070 // PreDelete() will be executed before the DELETE statement.
2071 type HasPreDelete interface {
2072 PreDelete(SqlExecutor) error
2073 }
2074
2075 // PreUpdate() will be executed before UPDATE statement.
2076 type HasPreUpdate interface {
2077 PreUpdate(SqlExecutor) error
2078 }
2079
2080 // PreInsert() will be executed before INSERT statement.
2081 type HasPreInsert interface {
2082 PreInsert(SqlExecutor) error
2083 }