Debian Codegraph @

gorp_test.go

raw
1 package gorp
2
3 import (
4 "bytes"
5 "database/sql"
6 "encoding/json"
7 "errors"
8 "fmt"
9 _ "github.com/go-sql-driver/mysql"
10 _ "github.com/lib/pq"
11 _ "github.com/mattn/go-sqlite3"
12 _ "github.com/ziutek/mymysql/godrv"
13 "log"
14 "math/rand"
15 "os"
16 "reflect"
17 "strings"
18 "testing"
19 "time"
20 )
21
22 // verify interface compliance
23 var _ Dialect = SqliteDialect{}
24 var _ Dialect = PostgresDialect{}
25 var _ Dialect = MySQLDialect{}
26 var _ Dialect = SqlServerDialect{}
27 var _ Dialect = OracleDialect{}
28
29 type testable interface {
30 GetId() int64
31 Rand()
32 }
33
34 type Invoice struct {
35 Id int64
36 Created int64
37 Updated int64
38 Memo string
39 PersonId int64
40 IsPaid bool
41 }
42
43 func (me *Invoice) GetId() int64 { return me.Id }
44 func (me *Invoice) Rand() {
45 me.Memo = fmt.Sprintf("random %d", rand.Int63())
46 me.Created = rand.Int63()
47 me.Updated = rand.Int63()
48 }
49
50 type InvoiceTag struct {
51 Id int64 `db:"myid"`
52 Created int64 `db:"myCreated"`
53 Updated int64 `db:"date_updated"`
54 Memo string
55 PersonId int64 `db:"person_id"`
56 IsPaid bool `db:"is_Paid"`
57 }
58
59 func (me *InvoiceTag) GetId() int64 { return me.Id }
60 func (me *InvoiceTag) Rand() {
61 me.Memo = fmt.Sprintf("random %d", rand.Int63())
62 me.Created = rand.Int63()
63 me.Updated = rand.Int63()
64 }
65
66 // See: https://github.com/coopernurse/gorp/issues/175
67 type AliasTransientField struct {
68 Id int64 `db:"id"`
69 Bar int64 `db:"-"`
70 BarStr string `db:"bar"`
71 }
72
73 func (me *AliasTransientField) GetId() int64 { return me.Id }
74 func (me *AliasTransientField) Rand() {
75 me.BarStr = fmt.Sprintf("random %d", rand.Int63())
76 }
77
78 type OverriddenInvoice struct {
79 Invoice
80 Id string
81 }
82
83 type Person struct {
84 Id int64
85 Created int64
86 Updated int64
87 FName string
88 LName string
89 Version int64
90 }
91
92 type FNameOnly struct {
93 FName string
94 }
95
96 type InvoicePersonView struct {
97 InvoiceId int64
98 PersonId int64
99 Memo string
100 FName string
101 LegacyVersion int64
102 }
103
104 type TableWithNull struct {
105 Id int64
106 Str sql.NullString
107 Int64 sql.NullInt64
108 Float64 sql.NullFloat64
109 Bool sql.NullBool
110 Bytes []byte
111 }
112
113 type WithIgnoredColumn struct {
114 internal int64 `db:"-"`
115 Id int64
116 Created int64
117 }
118
119 type IdCreated struct {
120 Id int64
121 Created int64
122 }
123
124 type IdCreatedExternal struct {
125 IdCreated
126 External int64
127 }
128
129 type WithStringPk struct {
130 Id string
131 Name string
132 }
133
134 type CustomStringType string
135
136 type TypeConversionExample struct {
137 Id int64
138 PersonJSON Person
139 Name CustomStringType
140 }
141
142 type PersonUInt32 struct {
143 Id uint32
144 Name string
145 }
146
147 type PersonUInt64 struct {
148 Id uint64
149 Name string
150 }
151
152 type PersonUInt16 struct {
153 Id uint16
154 Name string
155 }
156
157 type WithEmbeddedStruct struct {
158 Id int64
159 Names
160 }
161
162 type WithEmbeddedStructBeforeAutoincrField struct {
163 Names
164 Id int64
165 }
166
167 type WithEmbeddedAutoincr struct {
168 WithEmbeddedStruct
169 MiddleName string
170 }
171
172 type Names struct {
173 FirstName string
174 LastName string
175 }
176
177 type UniqueColumns struct {
178 FirstName string
179 LastName string
180 City string
181 ZipCode int64
182 }
183
184 type SingleColumnTable struct {
185 SomeId string
186 }
187
188 type CustomDate struct {
189 time.Time
190 }
191
192 type WithCustomDate struct {
193 Id int64
194 Added CustomDate
195 }
196
197 type testTypeConverter struct{}
198
199 func (me testTypeConverter) ToDb(val interface{}) (interface{}, error) {
200
201 switch t := val.(type) {
202 case Person:
203 b, err := json.Marshal(t)
204 if err != nil {
205 return "", err
206 }
207 return string(b), nil
208 case CustomStringType:
209 return string(t), nil
210 case CustomDate:
211 return t.Time, nil
212 }
213
214 return val, nil
215 }
216
217 func (me testTypeConverter) FromDb(target interface{}) (CustomScanner, bool) {
218 switch target.(type) {
219 case *Person:
220 binder := func(holder, target interface{}) error {
221 s, ok := holder.(*string)
222 if !ok {
223 return errors.New("FromDb: Unable to convert Person to *string")
224 }
225 b := []byte(*s)
226 return json.Unmarshal(b, target)
227 }
228 return CustomScanner{new(string), target, binder}, true
229 case *CustomStringType:
230 binder := func(holder, target interface{}) error {
231 s, ok := holder.(*string)
232 if !ok {
233 return errors.New("FromDb: Unable to convert CustomStringType to *string")
234 }
235 st, ok := target.(*CustomStringType)
236 if !ok {
237 return errors.New(fmt.Sprint("FromDb: Unable to convert target to *CustomStringType: ", reflect.TypeOf(target)))
238 }
239 *st = CustomStringType(*s)
240 return nil
241 }
242 return CustomScanner{new(string), target, binder}, true
243 case *CustomDate:
244 binder := func(holder, target interface{}) error {
245 t, ok := holder.(*time.Time)
246 if !ok {
247 return errors.New("FromDb: Unable to convert CustomDate to *time.Time")
248 }
249 dateTarget, ok := target.(*CustomDate)
250 if !ok {
251 return errors.New(fmt.Sprint("FromDb: Unable to convert target to *CustomDate: ", reflect.TypeOf(target)))
252 }
253 dateTarget.Time = *t
254 return nil
255 }
256 return CustomScanner{new(time.Time), target, binder}, true
257 }
258
259 return CustomScanner{}, false
260 }
261
262 func (p *Person) PreInsert(s SqlExecutor) error {
263 p.Created = time.Now().UnixNano()
264 p.Updated = p.Created
265 if p.FName == "badname" {
266 return fmt.Errorf("Invalid name: %s", p.FName)
267 }
268 return nil
269 }
270
271 func (p *Person) PostInsert(s SqlExecutor) error {
272 p.LName = "postinsert"
273 return nil
274 }
275
276 func (p *Person) PreUpdate(s SqlExecutor) error {
277 p.FName = "preupdate"
278 return nil
279 }
280
281 func (p *Person) PostUpdate(s SqlExecutor) error {
282 p.LName = "postupdate"
283 return nil
284 }
285
286 func (p *Person) PreDelete(s SqlExecutor) error {
287 p.FName = "predelete"
288 return nil
289 }
290
291 func (p *Person) PostDelete(s SqlExecutor) error {
292 p.LName = "postdelete"
293 return nil
294 }
295
296 func (p *Person) PostGet(s SqlExecutor) error {
297 p.LName = "postget"
298 return nil
299 }
300
301 type PersistentUser struct {
302 Key int32
303 Id string
304 PassedTraining bool
305 }
306
307 func TestCreateTablesIfNotExists(t *testing.T) {
308 dbmap := initDbMap()
309 defer dropAndClose(dbmap)
310
311 err := dbmap.CreateTablesIfNotExists()
312 if err != nil {
313 t.Error(err)
314 }
315 }
316
317 func TestTruncateTables(t *testing.T) {
318 dbmap := initDbMap()
319 defer dropAndClose(dbmap)
320 err := dbmap.CreateTablesIfNotExists()
321 if err != nil {
322 t.Error(err)
323 }
324
325 // Insert some data
326 p1 := &Person{0, 0, 0, "Bob", "Smith", 0}
327 dbmap.Insert(p1)
328 inv := &Invoice{0, 0, 1, "my invoice", 0, true}
329 dbmap.Insert(inv)
330
331 err = dbmap.TruncateTables()
332 if err != nil {
333 t.Error(err)
334 }
335
336 // Make sure all rows are deleted
337 rows, _ := dbmap.Select(Person{}, "SELECT * FROM person_test")
338 if len(rows) != 0 {
339 t.Errorf("Expected 0 person rows, got %d", len(rows))
340 }
341 rows, _ = dbmap.Select(Invoice{}, "SELECT * FROM invoice_test")
342 if len(rows) != 0 {
343 t.Errorf("Expected 0 invoice rows, got %d", len(rows))
344 }
345 }
346
347 func TestCustomDateType(t *testing.T) {
348 dbmap := newDbMap()
349 dbmap.TypeConverter = testTypeConverter{}
350 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
351 dbmap.AddTable(WithCustomDate{}).SetKeys(true, "Id")
352 err := dbmap.CreateTables()
353 if err != nil {
354 panic(err)
355 }
356 defer dropAndClose(dbmap)
357
358 test1 := &WithCustomDate{Added: CustomDate{Time: time.Now().Truncate(time.Second)}}
359 err = dbmap.Insert(test1)
360 if err != nil {
361 t.Errorf("Could not insert struct with custom date field: %s", err)
362 t.FailNow()
363 }
364 // Unfortunately, the mysql driver doesn't handle time.Time
365 // values properly during Get(). I can't find a way to work
366 // around that problem - every other type that I've tried is just
367 // silently converted. time.Time is the only type that causes
368 // the issue that this test checks for. As such, if the driver is
369 // mysql, we'll just skip the rest of this test.
370 if _, driver := dialectAndDriver(); driver == "mysql" {
371 t.Skip("TestCustomDateType can't run Get() with the mysql driver; skipping the rest of this test...")
372 }
373 result, err := dbmap.Get(new(WithCustomDate), test1.Id)
374 if err != nil {
375 t.Errorf("Could not get struct with custom date field: %s", err)
376 t.FailNow()
377 }
378 test2 := result.(*WithCustomDate)
379 if test2.Added.UTC() != test1.Added.UTC() {
380 t.Errorf("Custom dates do not match: %v != %v", test2.Added.UTC(), test1.Added.UTC())
381 }
382 }
383
384 func TestUIntPrimaryKey(t *testing.T) {
385 dbmap := newDbMap()
386 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
387 dbmap.AddTable(PersonUInt64{}).SetKeys(true, "Id")
388 dbmap.AddTable(PersonUInt32{}).SetKeys(true, "Id")
389 dbmap.AddTable(PersonUInt16{}).SetKeys(true, "Id")
390 err := dbmap.CreateTablesIfNotExists()
391 if err != nil {
392 panic(err)
393 }
394 defer dropAndClose(dbmap)
395
396 p1 := &PersonUInt64{0, "name1"}
397 p2 := &PersonUInt32{0, "name2"}
398 p3 := &PersonUInt16{0, "name3"}
399 err = dbmap.Insert(p1, p2, p3)
400 if err != nil {
401 t.Error(err)
402 }
403 if p1.Id != 1 {
404 t.Errorf("%d != 1", p1.Id)
405 }
406 if p2.Id != 1 {
407 t.Errorf("%d != 1", p2.Id)
408 }
409 if p3.Id != 1 {
410 t.Errorf("%d != 1", p3.Id)
411 }
412 }
413
414 func TestSetUniqueTogether(t *testing.T) {
415 dbmap := newDbMap()
416 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
417 dbmap.AddTable(UniqueColumns{}).SetUniqueTogether("FirstName", "LastName").SetUniqueTogether("City", "ZipCode")
418 err := dbmap.CreateTablesIfNotExists()
419 if err != nil {
420 panic(err)
421 }
422 defer dropAndClose(dbmap)
423
424 n1 := &UniqueColumns{"Steve", "Jobs", "Cupertino", 95014}
425 err = dbmap.Insert(n1)
426 if err != nil {
427 t.Error(err)
428 }
429
430 // Should fail because of the first constraint
431 n2 := &UniqueColumns{"Steve", "Jobs", "Sunnyvale", 94085}
432 err = dbmap.Insert(n2)
433 if err == nil {
434 t.Error(err)
435 }
436 // "unique" for Postgres/SQLite, "Duplicate entry" for MySQL
437 errLower := strings.ToLower(err.Error())
438 if !strings.Contains(errLower, "unique") && !strings.Contains(errLower, "duplicate entry") {
439 t.Error(err)
440 }
441
442 // Should also fail because of the second unique-together
443 n3 := &UniqueColumns{"Steve", "Wozniak", "Cupertino", 95014}
444 err = dbmap.Insert(n3)
445 if err == nil {
446 t.Error(err)
447 }
448 // "unique" for Postgres/SQLite, "Duplicate entry" for MySQL
449 errLower = strings.ToLower(err.Error())
450 if !strings.Contains(errLower, "unique") && !strings.Contains(errLower, "duplicate entry") {
451 t.Error(err)
452 }
453
454 // This one should finally succeed
455 n4 := &UniqueColumns{"Steve", "Wozniak", "Sunnyvale", 94085}
456 err = dbmap.Insert(n4)
457 if err != nil {
458 t.Error(err)
459 }
460 }
461
462 func TestPersistentUser(t *testing.T) {
463 dbmap := newDbMap()
464 dbmap.Exec("drop table if exists PersistentUser")
465 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
466 table := dbmap.AddTable(PersistentUser{}).SetKeys(false, "Key")
467 table.ColMap("Key").Rename("mykey")
468 err := dbmap.CreateTablesIfNotExists()
469 if err != nil {
470 panic(err)
471 }
472 defer dropAndClose(dbmap)
473 pu := &PersistentUser{43, "33r", false}
474 err = dbmap.Insert(pu)
475 if err != nil {
476 panic(err)
477 }
478
479 // prove we can pass a pointer into Get
480 pu2, err := dbmap.Get(pu, pu.Key)
481 if err != nil {
482 panic(err)
483 }
484 if !reflect.DeepEqual(pu, pu2) {
485 t.Errorf("%v!=%v", pu, pu2)
486 }
487
488 arr, err := dbmap.Select(pu, "select * from PersistentUser")
489 if err != nil {
490 panic(err)
491 }
492 if !reflect.DeepEqual(pu, arr[0]) {
493 t.Errorf("%v!=%v", pu, arr[0])
494 }
495
496 // prove we can get the results back in a slice
497 var puArr []*PersistentUser
498 _, err = dbmap.Select(&puArr, "select * from PersistentUser")
499 if err != nil {
500 panic(err)
501 }
502 if len(puArr) != 1 {
503 t.Errorf("Expected one persistentuser, found none")
504 }
505 if !reflect.DeepEqual(pu, puArr[0]) {
506 t.Errorf("%v!=%v", pu, puArr[0])
507 }
508
509 // prove we can get the results back in a non-pointer slice
510 var puValues []PersistentUser
511 _, err = dbmap.Select(&puValues, "select * from PersistentUser")
512 if err != nil {
513 panic(err)
514 }
515 if len(puValues) != 1 {
516 t.Errorf("Expected one persistentuser, found none")
517 }
518 if !reflect.DeepEqual(*pu, puValues[0]) {
519 t.Errorf("%v!=%v", *pu, puValues[0])
520 }
521
522 // prove we can get the results back in a string slice
523 var idArr []*string
524 _, err = dbmap.Select(&idArr, "select Id from PersistentUser")
525 if err != nil {
526 panic(err)
527 }
528 if len(idArr) != 1 {
529 t.Errorf("Expected one persistentuser, found none")
530 }
531 if !reflect.DeepEqual(pu.Id, *idArr[0]) {
532 t.Errorf("%v!=%v", pu.Id, *idArr[0])
533 }
534
535 // prove we can get the results back in an int slice
536 var keyArr []*int32
537 _, err = dbmap.Select(&keyArr, "select mykey from PersistentUser")
538 if err != nil {
539 panic(err)
540 }
541 if len(keyArr) != 1 {
542 t.Errorf("Expected one persistentuser, found none")
543 }
544 if !reflect.DeepEqual(pu.Key, *keyArr[0]) {
545 t.Errorf("%v!=%v", pu.Key, *keyArr[0])
546 }
547
548 // prove we can get the results back in a bool slice
549 var passedArr []*bool
550 _, err = dbmap.Select(&passedArr, "select PassedTraining from PersistentUser")
551 if err != nil {
552 panic(err)
553 }
554 if len(passedArr) != 1 {
555 t.Errorf("Expected one persistentuser, found none")
556 }
557 if !reflect.DeepEqual(pu.PassedTraining, *passedArr[0]) {
558 t.Errorf("%v!=%v", pu.PassedTraining, *passedArr[0])
559 }
560
561 // prove we can get the results back in a non-pointer slice
562 var stringArr []string
563 _, err = dbmap.Select(&stringArr, "select Id from PersistentUser")
564 if err != nil {
565 panic(err)
566 }
567 if len(stringArr) != 1 {
568 t.Errorf("Expected one persistentuser, found none")
569 }
570 if !reflect.DeepEqual(pu.Id, stringArr[0]) {
571 t.Errorf("%v!=%v", pu.Id, stringArr[0])
572 }
573 }
574
575 func TestNamedQueryMap(t *testing.T) {
576 dbmap := newDbMap()
577 dbmap.Exec("drop table if exists PersistentUser")
578 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
579 table := dbmap.AddTable(PersistentUser{}).SetKeys(false, "Key")
580 table.ColMap("Key").Rename("mykey")
581 err := dbmap.CreateTablesIfNotExists()
582 if err != nil {
583 panic(err)
584 }
585 defer dropAndClose(dbmap)
586 pu := &PersistentUser{43, "33r", false}
587 pu2 := &PersistentUser{500, "abc", false}
588 err = dbmap.Insert(pu, pu2)
589 if err != nil {
590 panic(err)
591 }
592
593 // Test simple case
594 var puArr []*PersistentUser
595 _, err = dbmap.Select(&puArr, "select * from PersistentUser where mykey = :Key", map[string]interface{}{
596 "Key": 43,
597 })
598 if err != nil {
599 t.Errorf("Failed to select: %s", err)
600 t.FailNow()
601 }
602 if len(puArr) != 1 {
603 t.Errorf("Expected one persistentuser, found none")
604 }
605 if !reflect.DeepEqual(pu, puArr[0]) {
606 t.Errorf("%v!=%v", pu, puArr[0])
607 }
608
609 // Test more specific map value type is ok
610 puArr = nil
611 _, err = dbmap.Select(&puArr, "select * from PersistentUser where mykey = :Key", map[string]int{
612 "Key": 43,
613 })
614 if err != nil {
615 t.Errorf("Failed to select: %s", err)
616 t.FailNow()
617 }
618 if len(puArr) != 1 {
619 t.Errorf("Expected one persistentuser, found none")
620 }
621
622 // Test multiple parameters set.
623 puArr = nil
624 _, err = dbmap.Select(&puArr, `
625 select * from PersistentUser
626 where mykey = :Key
627 and PassedTraining = :PassedTraining
628 and Id = :Id`, map[string]interface{}{
629 "Key": 43,
630 "PassedTraining": false,
631 "Id": "33r",
632 })
633 if err != nil {
634 t.Errorf("Failed to select: %s", err)
635 t.FailNow()
636 }
637 if len(puArr) != 1 {
638 t.Errorf("Expected one persistentuser, found none")
639 }
640
641 // Test colon within a non-key string
642 // Test having extra, unused properties in the map.
643 puArr = nil
644 _, err = dbmap.Select(&puArr, `
645 select * from PersistentUser
646 where mykey = :Key
647 and Id != 'abc:def'`, map[string]interface{}{
648 "Key": 43,
649 "PassedTraining": false,
650 })
651 if err != nil {
652 t.Errorf("Failed to select: %s", err)
653 t.FailNow()
654 }
655 if len(puArr) != 1 {
656 t.Errorf("Expected one persistentuser, found none")
657 }
658 }
659
660 func TestNamedQueryStruct(t *testing.T) {
661 dbmap := newDbMap()
662 dbmap.Exec("drop table if exists PersistentUser")
663 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
664 table := dbmap.AddTable(PersistentUser{}).SetKeys(false, "Key")
665 table.ColMap("Key").Rename("mykey")
666 err := dbmap.CreateTablesIfNotExists()
667 if err != nil {
668 panic(err)
669 }
670 defer dropAndClose(dbmap)
671 pu := &PersistentUser{43, "33r", false}
672 pu2 := &PersistentUser{500, "abc", false}
673 err = dbmap.Insert(pu, pu2)
674 if err != nil {
675 panic(err)
676 }
677
678 // Test select self
679 var puArr []*PersistentUser
680 _, err = dbmap.Select(&puArr, `
681 select * from PersistentUser
682 where mykey = :Key
683 and PassedTraining = :PassedTraining
684 and Id = :Id`, pu)
685 if err != nil {
686 t.Errorf("Failed to select: %s", err)
687 t.FailNow()
688 }
689 if len(puArr) != 1 {
690 t.Errorf("Expected one persistentuser, found none")
691 }
692 if !reflect.DeepEqual(pu, puArr[0]) {
693 t.Errorf("%v!=%v", pu, puArr[0])
694 }
695 }
696
697 // Ensure that the slices containing SQL results are non-nil when the result set is empty.
698 func TestReturnsNonNilSlice(t *testing.T) {
699 dbmap := initDbMap()
700 defer dropAndClose(dbmap)
701 noResultsSQL := "select * from invoice_test where id=99999"
702 var r1 []*Invoice
703 _rawselect(dbmap, &r1, noResultsSQL)
704 if r1 == nil {
705 t.Errorf("r1==nil")
706 }
707
708 r2 := _rawselect(dbmap, Invoice{}, noResultsSQL)
709 if r2 == nil {
710 t.Errorf("r2==nil")
711 }
712 }
713
714 func TestOverrideVersionCol(t *testing.T) {
715 dbmap := newDbMap()
716 t1 := dbmap.AddTable(InvoicePersonView{}).SetKeys(false, "InvoiceId", "PersonId")
717 err := dbmap.CreateTables()
718 if err != nil {
719 panic(err)
720 }
721 defer dropAndClose(dbmap)
722 c1 := t1.SetVersionCol("LegacyVersion")
723 if c1.ColumnName != "LegacyVersion" {
724 t.Errorf("Wrong col returned: %v", c1)
725 }
726
727 ipv := &InvoicePersonView{1, 2, "memo", "fname", 0}
728 _update(dbmap, ipv)
729 if ipv.LegacyVersion != 1 {
730 t.Errorf("LegacyVersion not updated: %d", ipv.LegacyVersion)
731 }
732 }
733
734 func TestOptimisticLocking(t *testing.T) {
735 dbmap := initDbMap()
736 defer dropAndClose(dbmap)
737
738 p1 := &Person{0, 0, 0, "Bob", "Smith", 0}
739 dbmap.Insert(p1) // Version is now 1
740 if p1.Version != 1 {
741 t.Errorf("Insert didn't incr Version: %d != %d", 1, p1.Version)
742 return
743 }
744 if p1.Id == 0 {
745 t.Errorf("Insert didn't return a generated PK")
746 return
747 }
748
749 obj, err := dbmap.Get(Person{}, p1.Id)
750 if err != nil {
751 panic(err)
752 }
753 p2 := obj.(*Person)
754 p2.LName = "Edwards"
755 dbmap.Update(p2) // Version is now 2
756 if p2.Version != 2 {
757 t.Errorf("Update didn't incr Version: %d != %d", 2, p2.Version)
758 }
759
760 p1.LName = "Howard"
761 count, err := dbmap.Update(p1)
762 if _, ok := err.(OptimisticLockError); !ok {
763 t.Errorf("update - Expected OptimisticLockError, got: %v", err)
764 }
765 if count != -1 {
766 t.Errorf("update - Expected -1 count, got: %d", count)
767 }
768
769 count, err = dbmap.Delete(p1)
770 if _, ok := err.(OptimisticLockError); !ok {
771 t.Errorf("delete - Expected OptimisticLockError, got: %v", err)
772 }
773 if count != -1 {
774 t.Errorf("delete - Expected -1 count, got: %d", count)
775 }
776 }
777
778 // what happens if a legacy table has a null value?
779 func TestDoubleAddTable(t *testing.T) {
780 dbmap := newDbMap()
781 t1 := dbmap.AddTable(TableWithNull{}).SetKeys(false, "Id")
782 t2 := dbmap.AddTable(TableWithNull{})
783 if t1 != t2 {
784 t.Errorf("%v != %v", t1, t2)
785 }
786 }
787
788 // what happens if a legacy table has a null value?
789 func TestNullValues(t *testing.T) {
790 dbmap := initDbMapNulls()
791 defer dropAndClose(dbmap)
792
793 // insert a row directly
794 _rawexec(dbmap, "insert into TableWithNull values (10, null, "+
795 "null, null, null, null)")
796
797 // try to load it
798 expected := &TableWithNull{Id: 10}
799 obj := _get(dbmap, TableWithNull{}, 10)
800 t1 := obj.(*TableWithNull)
801 if !reflect.DeepEqual(expected, t1) {
802 t.Errorf("%v != %v", expected, t1)
803 }
804
805 // update it
806 t1.Str = sql.NullString{"hi", true}
807 expected.Str = t1.Str
808 t1.Int64 = sql.NullInt64{999, true}
809 expected.Int64 = t1.Int64
810 t1.Float64 = sql.NullFloat64{53.33, true}
811 expected.Float64 = t1.Float64
812 t1.Bool = sql.NullBool{true, true}
813 expected.Bool = t1.Bool
814 t1.Bytes = []byte{1, 30, 31, 33}
815 expected.Bytes = t1.Bytes
816 _update(dbmap, t1)
817
818 obj = _get(dbmap, TableWithNull{}, 10)
819 t1 = obj.(*TableWithNull)
820 if t1.Str.String != "hi" {
821 t.Errorf("%s != hi", t1.Str.String)
822 }
823 if !reflect.DeepEqual(expected, t1) {
824 t.Errorf("%v != %v", expected, t1)
825 }
826 }
827
828 func TestColumnProps(t *testing.T) {
829 dbmap := newDbMap()
830 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
831 t1 := dbmap.AddTable(Invoice{}).SetKeys(true, "Id")
832 t1.ColMap("Created").Rename("date_created")
833 t1.ColMap("Updated").SetTransient(true)
834 t1.ColMap("Memo").SetMaxSize(10)
835 t1.ColMap("PersonId").SetUnique(true)
836
837 err := dbmap.CreateTables()
838 if err != nil {
839 panic(err)
840 }
841 defer dropAndClose(dbmap)
842
843 // test transient
844 inv := &Invoice{0, 0, 1, "my invoice", 0, true}
845 _insert(dbmap, inv)
846 obj := _get(dbmap, Invoice{}, inv.Id)
847 inv = obj.(*Invoice)
848 if inv.Updated != 0 {
849 t.Errorf("Saved transient column 'Updated'")
850 }
851
852 // test max size
853 inv.Memo = "this memo is too long"
854 err = dbmap.Insert(inv)
855 if err == nil {
856 t.Errorf("max size exceeded, but Insert did not fail.")
857 }
858
859 // test unique - same person id
860 inv = &Invoice{0, 0, 1, "my invoice2", 0, false}
861 err = dbmap.Insert(inv)
862 if err == nil {
863 t.Errorf("same PersonId inserted, but Insert did not fail.")
864 }
865 }
866
867 func TestRawSelect(t *testing.T) {
868 dbmap := initDbMap()
869 defer dropAndClose(dbmap)
870
871 p1 := &Person{0, 0, 0, "bob", "smith", 0}
872 _insert(dbmap, p1)
873
874 inv1 := &Invoice{0, 0, 0, "xmas order", p1.Id, true}
875 _insert(dbmap, inv1)
876
877 expected := &InvoicePersonView{inv1.Id, p1.Id, inv1.Memo, p1.FName, 0}
878
879 query := "select i.Id InvoiceId, p.Id PersonId, i.Memo, p.FName " +
880 "from invoice_test i, person_test p " +
881 "where i.PersonId = p.Id"
882 list := _rawselect(dbmap, InvoicePersonView{}, query)
883 if len(list) != 1 {
884 t.Errorf("len(list) != 1: %d", len(list))
885 } else if !reflect.DeepEqual(expected, list[0]) {
886 t.Errorf("%v != %v", expected, list[0])
887 }
888 }
889
890 func TestHooks(t *testing.T) {
891 dbmap := initDbMap()
892 defer dropAndClose(dbmap)
893
894 p1 := &Person{0, 0, 0, "bob", "smith", 0}
895 _insert(dbmap, p1)
896 if p1.Created == 0 || p1.Updated == 0 {
897 t.Errorf("p1.PreInsert() didn't run: %v", p1)
898 } else if p1.LName != "postinsert" {
899 t.Errorf("p1.PostInsert() didn't run: %v", p1)
900 }
901
902 obj := _get(dbmap, Person{}, p1.Id)
903 p1 = obj.(*Person)
904 if p1.LName != "postget" {
905 t.Errorf("p1.PostGet() didn't run: %v", p1)
906 }
907
908 _update(dbmap, p1)
909 if p1.FName != "preupdate" {
910 t.Errorf("p1.PreUpdate() didn't run: %v", p1)
911 } else if p1.LName != "postupdate" {
912 t.Errorf("p1.PostUpdate() didn't run: %v", p1)
913 }
914
915 var persons []*Person
916 bindVar := dbmap.Dialect.BindVar(0)
917 _rawselect(dbmap, &persons, "select * from person_test where id = "+bindVar, p1.Id)
918 if persons[0].LName != "postget" {
919 t.Errorf("p1.PostGet() didn't run after select: %v", p1)
920 }
921
922 _del(dbmap, p1)
923 if p1.FName != "predelete" {
924 t.Errorf("p1.PreDelete() didn't run: %v", p1)
925 } else if p1.LName != "postdelete" {
926 t.Errorf("p1.PostDelete() didn't run: %v", p1)
927 }
928
929 // Test error case
930 p2 := &Person{0, 0, 0, "badname", "", 0}
931 err := dbmap.Insert(p2)
932 if err == nil {
933 t.Errorf("p2.PreInsert() didn't return an error")
934 }
935 }
936
937 func TestTransaction(t *testing.T) {
938 dbmap := initDbMap()
939 defer dropAndClose(dbmap)
940
941 inv1 := &Invoice{0, 100, 200, "t1", 0, true}
942 inv2 := &Invoice{0, 100, 200, "t2", 0, false}
943
944 trans, err := dbmap.Begin()
945 if err != nil {
946 panic(err)
947 }
948 trans.Insert(inv1, inv2)
949 err = trans.Commit()
950 if err != nil {
951 panic(err)
952 }
953
954 obj, err := dbmap.Get(Invoice{}, inv1.Id)
955 if err != nil {
956 panic(err)
957 }
958 if !reflect.DeepEqual(inv1, obj) {
959 t.Errorf("%v != %v", inv1, obj)
960 }
961 obj, err = dbmap.Get(Invoice{}, inv2.Id)
962 if err != nil {
963 panic(err)
964 }
965 if !reflect.DeepEqual(inv2, obj) {
966 t.Errorf("%v != %v", inv2, obj)
967 }
968 }
969
970 func TestSavepoint(t *testing.T) {
971 dbmap := initDbMap()
972 defer dropAndClose(dbmap)
973
974 inv1 := &Invoice{0, 100, 200, "unpaid", 0, false}
975
976 trans, err := dbmap.Begin()
977 if err != nil {
978 panic(err)
979 }
980 trans.Insert(inv1)
981
982 var checkMemo = func(want string) {
983 memo, err := trans.SelectStr("select memo from invoice_test")
984 if err != nil {
985 panic(err)
986 }
987 if memo != want {
988 t.Errorf("%q != %q", want, memo)
989 }
990 }
991 checkMemo("unpaid")
992
993 err = trans.Savepoint("foo")
994 if err != nil {
995 panic(err)
996 }
997 checkMemo("unpaid")
998
999 inv1.Memo = "paid"
1000 _, err = trans.Update(inv1)
1001 if err != nil {
1002 panic(err)
1003 }
1004 checkMemo("paid")
1005
1006 err = trans.RollbackToSavepoint("foo")
1007 if err != nil {
1008 panic(err)
1009 }
1010 checkMemo("unpaid")
1011
1012 err = trans.Rollback()
1013 if err != nil {
1014 panic(err)
1015 }
1016 }
1017
1018 func TestMultiple(t *testing.T) {
1019 dbmap := initDbMap()
1020 defer dropAndClose(dbmap)
1021
1022 inv1 := &Invoice{0, 100, 200, "a", 0, false}
1023 inv2 := &Invoice{0, 100, 200, "b", 0, true}
1024 _insert(dbmap, inv1, inv2)
1025
1026 inv1.Memo = "c"
1027 inv2.Memo = "d"
1028 _update(dbmap, inv1, inv2)
1029
1030 count := _del(dbmap, inv1, inv2)
1031 if count != 2 {
1032 t.Errorf("%d != 2", count)
1033 }
1034 }
1035
1036 func TestCrud(t *testing.T) {
1037 dbmap := initDbMap()
1038 defer dropAndClose(dbmap)
1039
1040 inv := &Invoice{0, 100, 200, "first order", 0, true}
1041 testCrudInternal(t, dbmap, inv)
1042
1043 invtag := &InvoiceTag{0, 300, 400, "some order", 33, false}
1044 testCrudInternal(t, dbmap, invtag)
1045
1046 foo := &AliasTransientField{BarStr: "some bar"}
1047 testCrudInternal(t, dbmap, foo)
1048 }
1049
1050 func testCrudInternal(t *testing.T, dbmap *DbMap, val testable) {
1051 table, _, err := dbmap.tableForPointer(val, false)
1052 if err != nil {
1053 t.Errorf("couldn't call TableFor: val=%v err=%v", val, err)
1054 }
1055
1056 _, err = dbmap.Exec("delete from " + table.TableName)
1057 if err != nil {
1058 t.Errorf("couldn't delete rows from: val=%v err=%v", val, err)
1059 }
1060
1061 // INSERT row
1062 _insert(dbmap, val)
1063 if val.GetId() == 0 {
1064 t.Errorf("val.GetId() was not set on INSERT")
1065 return
1066 }
1067
1068 // SELECT row
1069 val2 := _get(dbmap, val, val.GetId())
1070 if !reflect.DeepEqual(val, val2) {
1071 t.Errorf("%v != %v", val, val2)
1072 }
1073
1074 // UPDATE row and SELECT
1075 val.Rand()
1076 count := _update(dbmap, val)
1077 if count != 1 {
1078 t.Errorf("update 1 != %d", count)
1079 }
1080 val2 = _get(dbmap, val, val.GetId())
1081 if !reflect.DeepEqual(val, val2) {
1082 t.Errorf("%v != %v", val, val2)
1083 }
1084
1085 // Select *
1086 rows, err := dbmap.Select(val, "select * from "+table.TableName)
1087 if err != nil {
1088 t.Errorf("couldn't select * from %s err=%v", table.TableName, err)
1089 } else if len(rows) != 1 {
1090 t.Errorf("unexpected row count in %s: %d", table.TableName, len(rows))
1091 } else if !reflect.DeepEqual(val, rows[0]) {
1092 t.Errorf("select * result: %v != %v", val, rows[0])
1093 }
1094
1095 // DELETE row
1096 deleted := _del(dbmap, val)
1097 if deleted != 1 {
1098 t.Errorf("Did not delete row with Id: %d", val.GetId())
1099 return
1100 }
1101
1102 // VERIFY deleted
1103 val2 = _get(dbmap, val, val.GetId())
1104 if val2 != nil {
1105 t.Errorf("Found invoice with id: %d after Delete()", val.GetId())
1106 }
1107 }
1108
1109 func TestWithIgnoredColumn(t *testing.T) {
1110 dbmap := initDbMap()
1111 defer dropAndClose(dbmap)
1112
1113 ic := &WithIgnoredColumn{-1, 0, 1}
1114 _insert(dbmap, ic)
1115 expected := &WithIgnoredColumn{0, 1, 1}
1116 ic2 := _get(dbmap, WithIgnoredColumn{}, ic.Id).(*WithIgnoredColumn)
1117
1118 if !reflect.DeepEqual(expected, ic2) {
1119 t.Errorf("%v != %v", expected, ic2)
1120 }
1121 if _del(dbmap, ic) != 1 {
1122 t.Errorf("Did not delete row with Id: %d", ic.Id)
1123 return
1124 }
1125 if _get(dbmap, WithIgnoredColumn{}, ic.Id) != nil {
1126 t.Errorf("Found id: %d after Delete()", ic.Id)
1127 }
1128 }
1129
1130 func TestTypeConversionExample(t *testing.T) {
1131 dbmap := initDbMap()
1132 defer dropAndClose(dbmap)
1133
1134 p := Person{FName: "Bob", LName: "Smith"}
1135 tc := &TypeConversionExample{-1, p, CustomStringType("hi")}
1136 _insert(dbmap, tc)
1137
1138 expected := &TypeConversionExample{1, p, CustomStringType("hi")}
1139 tc2 := _get(dbmap, TypeConversionExample{}, tc.Id).(*TypeConversionExample)
1140 if !reflect.DeepEqual(expected, tc2) {
1141 t.Errorf("tc2 %v != %v", expected, tc2)
1142 }
1143
1144 tc2.Name = CustomStringType("hi2")
1145 tc2.PersonJSON = Person{FName: "Jane", LName: "Doe"}
1146 _update(dbmap, tc2)
1147
1148 expected = &TypeConversionExample{1, tc2.PersonJSON, CustomStringType("hi2")}
1149 tc3 := _get(dbmap, TypeConversionExample{}, tc.Id).(*TypeConversionExample)
1150 if !reflect.DeepEqual(expected, tc3) {
1151 t.Errorf("tc3 %v != %v", expected, tc3)
1152 }
1153
1154 if _del(dbmap, tc) != 1 {
1155 t.Errorf("Did not delete row with Id: %d", tc.Id)
1156 }
1157
1158 }
1159
1160 func TestWithEmbeddedStruct(t *testing.T) {
1161 dbmap := initDbMap()
1162 defer dropAndClose(dbmap)
1163
1164 es := &WithEmbeddedStruct{-1, Names{FirstName: "Alice", LastName: "Smith"}}
1165 _insert(dbmap, es)
1166 expected := &WithEmbeddedStruct{1, Names{FirstName: "Alice", LastName: "Smith"}}
1167 es2 := _get(dbmap, WithEmbeddedStruct{}, es.Id).(*WithEmbeddedStruct)
1168 if !reflect.DeepEqual(expected, es2) {
1169 t.Errorf("%v != %v", expected, es2)
1170 }
1171
1172 es2.FirstName = "Bob"
1173 expected.FirstName = "Bob"
1174 _update(dbmap, es2)
1175 es2 = _get(dbmap, WithEmbeddedStruct{}, es.Id).(*WithEmbeddedStruct)
1176 if !reflect.DeepEqual(expected, es2) {
1177 t.Errorf("%v != %v", expected, es2)
1178 }
1179
1180 ess := _rawselect(dbmap, WithEmbeddedStruct{}, "select * from embedded_struct_test")
1181 if !reflect.DeepEqual(es2, ess[0]) {
1182 t.Errorf("%v != %v", es2, ess[0])
1183 }
1184 }
1185
1186 func TestWithEmbeddedStructBeforeAutoincr(t *testing.T) {
1187 dbmap := initDbMap()
1188 defer dropAndClose(dbmap)
1189
1190 esba := &WithEmbeddedStructBeforeAutoincrField{Names: Names{FirstName: "Alice", LastName: "Smith"}}
1191 _insert(dbmap, esba)
1192 var expectedAutoincrId int64 = 1
1193 if esba.Id != expectedAutoincrId {
1194 t.Errorf("%d != %d", expectedAutoincrId, esba.Id)
1195 }
1196 }
1197
1198 func TestWithEmbeddedAutoincr(t *testing.T) {
1199 dbmap := initDbMap()
1200 defer dropAndClose(dbmap)
1201
1202 esa := &WithEmbeddedAutoincr{
1203 WithEmbeddedStruct: WithEmbeddedStruct{Names: Names{FirstName: "Alice", LastName: "Smith"}},
1204 MiddleName: "Rose",
1205 }
1206 _insert(dbmap, esa)
1207 var expectedAutoincrId int64 = 1
1208 if esa.Id != expectedAutoincrId {
1209 t.Errorf("%d != %d", expectedAutoincrId, esa.Id)
1210 }
1211 }
1212
1213 func TestSelectVal(t *testing.T) {
1214 dbmap := initDbMapNulls()
1215 defer dropAndClose(dbmap)
1216
1217 bindVar := dbmap.Dialect.BindVar(0)
1218
1219 t1 := TableWithNull{Str: sql.NullString{"abc", true},
1220 Int64: sql.NullInt64{78, true},
1221 Float64: sql.NullFloat64{32.2, true},
1222 Bool: sql.NullBool{true, true},
1223 Bytes: []byte("hi")}
1224 _insert(dbmap, &t1)
1225
1226 // SelectInt
1227 i64 := selectInt(dbmap, "select Int64 from TableWithNull where Str='abc'")
1228 if i64 != 78 {
1229 t.Errorf("int64 %d != 78", i64)
1230 }
1231 i64 = selectInt(dbmap, "select count(*) from TableWithNull")
1232 if i64 != 1 {
1233 t.Errorf("int64 count %d != 1", i64)
1234 }
1235 i64 = selectInt(dbmap, "select count(*) from TableWithNull where Str="+bindVar, "asdfasdf")
1236 if i64 != 0 {
1237 t.Errorf("int64 no rows %d != 0", i64)
1238 }
1239
1240 // SelectNullInt
1241 n := selectNullInt(dbmap, "select Int64 from TableWithNull where Str='notfound'")
1242 if !reflect.DeepEqual(n, sql.NullInt64{0, false}) {
1243 t.Errorf("nullint %v != 0,false", n)
1244 }
1245
1246 n = selectNullInt(dbmap, "select Int64 from TableWithNull where Str='abc'")
1247 if !reflect.DeepEqual(n, sql.NullInt64{78, true}) {
1248 t.Errorf("nullint %v != 78, true", n)
1249 }
1250
1251 // SelectFloat
1252 f64 := selectFloat(dbmap, "select Float64 from TableWithNull where Str='abc'")
1253 if f64 != 32.2 {
1254 t.Errorf("float64 %d != 32.2", f64)
1255 }
1256 f64 = selectFloat(dbmap, "select min(Float64) from TableWithNull")
1257 if f64 != 32.2 {
1258 t.Errorf("float64 min %d != 32.2", f64)
1259 }
1260 f64 = selectFloat(dbmap, "select count(*) from TableWithNull where Str="+bindVar, "asdfasdf")
1261 if f64 != 0 {
1262 t.Errorf("float64 no rows %d != 0", f64)
1263 }
1264
1265 // SelectNullFloat
1266 nf := selectNullFloat(dbmap, "select Float64 from TableWithNull where Str='notfound'")
1267 if !reflect.DeepEqual(nf, sql.NullFloat64{0, false}) {
1268 t.Errorf("nullfloat %v != 0,false", nf)
1269 }
1270
1271 nf = selectNullFloat(dbmap, "select Float64 from TableWithNull where Str='abc'")
1272 if !reflect.DeepEqual(nf, sql.NullFloat64{32.2, true}) {
1273 t.Errorf("nullfloat %v != 32.2, true", nf)
1274 }
1275
1276 // SelectStr
1277 s := selectStr(dbmap, "select Str from TableWithNull where Int64="+bindVar, 78)
1278 if s != "abc" {
1279 t.Errorf("s %s != abc", s)
1280 }
1281 s = selectStr(dbmap, "select Str from TableWithNull where Str='asdfasdf'")
1282 if s != "" {
1283 t.Errorf("s no rows %s != ''", s)
1284 }
1285
1286 // SelectNullStr
1287 ns := selectNullStr(dbmap, "select Str from TableWithNull where Int64="+bindVar, 78)
1288 if !reflect.DeepEqual(ns, sql.NullString{"abc", true}) {
1289 t.Errorf("nullstr %v != abc,true", ns)
1290 }
1291 ns = selectNullStr(dbmap, "select Str from TableWithNull where Str='asdfasdf'")
1292 if !reflect.DeepEqual(ns, sql.NullString{"", false}) {
1293 t.Errorf("nullstr no rows %v != '',false", ns)
1294 }
1295
1296 // SelectInt/Str with named parameters
1297 i64 = selectInt(dbmap, "select Int64 from TableWithNull where Str=:abc", map[string]string{"abc": "abc"})
1298 if i64 != 78 {
1299 t.Errorf("int64 %d != 78", i64)
1300 }
1301 ns = selectNullStr(dbmap, "select Str from TableWithNull where Int64=:num", map[string]int{"num": 78})
1302 if !reflect.DeepEqual(ns, sql.NullString{"abc", true}) {
1303 t.Errorf("nullstr %v != abc,true", ns)
1304 }
1305 }
1306
1307 func TestVersionMultipleRows(t *testing.T) {
1308 dbmap := initDbMap()
1309 defer dropAndClose(dbmap)
1310
1311 persons := []*Person{
1312 &Person{0, 0, 0, "Bob", "Smith", 0},
1313 &Person{0, 0, 0, "Jane", "Smith", 0},
1314 &Person{0, 0, 0, "Mike", "Smith", 0},
1315 }
1316
1317 _insert(dbmap, persons[0], persons[1], persons[2])
1318
1319 for x, p := range persons {
1320 if p.Version != 1 {
1321 t.Errorf("person[%d].Version != 1: %d", x, p.Version)
1322 }
1323 }
1324 }
1325
1326 func TestWithStringPk(t *testing.T) {
1327 dbmap := newDbMap()
1328 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
1329 dbmap.AddTableWithName(WithStringPk{}, "string_pk_test").SetKeys(true, "Id")
1330 _, err := dbmap.Exec("create table string_pk_test (Id varchar(255), Name varchar(255));")
1331 if err != nil {
1332 t.Errorf("couldn't create string_pk_test: %v", err)
1333 }
1334 defer dropAndClose(dbmap)
1335
1336 row := &WithStringPk{"1", "foo"}
1337 err = dbmap.Insert(row)
1338 if err == nil {
1339 t.Errorf("Expected error when inserting into table w/non Int PK and autoincr set true")
1340 }
1341 }
1342
1343 // TestSqlExecutorInterfaceSelects ensures that all DbMap methods starting with Select...
1344 // are also exposed in the SqlExecutor interface. Select... functions can always
1345 // run on Pre/Post hooks.
1346 func TestSqlExecutorInterfaceSelects(t *testing.T) {
1347 dbMapType := reflect.TypeOf(&DbMap{})
1348 sqlExecutorType := reflect.TypeOf((*SqlExecutor)(nil)).Elem()
1349 numDbMapMethods := dbMapType.NumMethod()
1350 for i := 0; i < numDbMapMethods; i += 1 {
1351 dbMapMethod := dbMapType.Method(i)
1352 if !strings.HasPrefix(dbMapMethod.Name, "Select") {
1353 continue
1354 }
1355 if _, found := sqlExecutorType.MethodByName(dbMapMethod.Name); !found {
1356 t.Errorf("Method %s is defined on DbMap but not implemented in SqlExecutor",
1357 dbMapMethod.Name)
1358 }
1359 }
1360 }
1361
1362 type WithTime struct {
1363 Id int64
1364 Time time.Time
1365 }
1366
1367 type Times struct {
1368 One time.Time
1369 Two time.Time
1370 }
1371
1372 type EmbeddedTime struct {
1373 Id string
1374 Times
1375 }
1376
1377 func parseTimeOrPanic(format, date string) time.Time {
1378 t1, err := time.Parse(format, date)
1379 if err != nil {
1380 panic(err)
1381 }
1382 return t1
1383 }
1384
1385 // TODO: re-enable next two tests when this is merged:
1386 // https://github.com/ziutek/mymysql/pull/77
1387 //
1388 // This test currently fails w/MySQL b/c tz info is lost
1389 func testWithTime(t *testing.T) {
1390 dbmap := initDbMap()
1391 defer dropAndClose(dbmap)
1392
1393 t1 := parseTimeOrPanic("2006-01-02 15:04:05 -0700 MST",
1394 "2013-08-09 21:30:43 +0800 CST")
1395 w1 := WithTime{1, t1}
1396 _insert(dbmap, &w1)
1397
1398 obj := _get(dbmap, WithTime{}, w1.Id)
1399 w2 := obj.(*WithTime)
1400 if w1.Time.UnixNano() != w2.Time.UnixNano() {
1401 t.Errorf("%v != %v", w1, w2)
1402 }
1403 }
1404
1405 // See: https://github.com/coopernurse/gorp/issues/86
1406 func testEmbeddedTime(t *testing.T) {
1407 dbmap := newDbMap()
1408 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
1409 dbmap.AddTable(EmbeddedTime{}).SetKeys(false, "Id")
1410 defer dropAndClose(dbmap)
1411 err := dbmap.CreateTables()
1412 if err != nil {
1413 t.Fatal(err)
1414 }
1415
1416 time1 := parseTimeOrPanic("2006-01-02 15:04:05", "2013-08-09 21:30:43")
1417
1418 t1 := &EmbeddedTime{Id: "abc", Times: Times{One: time1, Two: time1.Add(10 * time.Second)}}
1419 _insert(dbmap, t1)
1420
1421 x := _get(dbmap, EmbeddedTime{}, t1.Id)
1422 t2, _ := x.(*EmbeddedTime)
1423 if t1.One.UnixNano() != t2.One.UnixNano() || t1.Two.UnixNano() != t2.Two.UnixNano() {
1424 t.Errorf("%v != %v", t1, t2)
1425 }
1426 }
1427
1428 func TestWithTimeSelect(t *testing.T) {
1429 dbmap := initDbMap()
1430 defer dropAndClose(dbmap)
1431
1432 halfhourago := time.Now().UTC().Add(-30 * time.Minute)
1433
1434 w1 := WithTime{1, halfhourago.Add(time.Minute * -1)}
1435 w2 := WithTime{2, halfhourago.Add(time.Second)}
1436 _insert(dbmap, &w1, &w2)
1437
1438 var caseIds []int64
1439 _, err := dbmap.Select(&caseIds, "SELECT id FROM time_test WHERE Time < "+dbmap.Dialect.BindVar(0), halfhourago)
1440
1441 if err != nil {
1442 t.Error(err)
1443 }
1444 if len(caseIds) != 1 {
1445 t.Errorf("%d != 1", len(caseIds))
1446 }
1447 if caseIds[0] != w1.Id {
1448 t.Errorf("%d != %d", caseIds[0], w1.Id)
1449 }
1450 }
1451
1452 func TestInvoicePersonView(t *testing.T) {
1453 dbmap := initDbMap()
1454 defer dropAndClose(dbmap)
1455
1456 // Create some rows
1457 p1 := &Person{0, 0, 0, "bob", "smith", 0}
1458 dbmap.Insert(p1)
1459
1460 // notice how we can wire up p1.Id to the invoice easily
1461 inv1 := &Invoice{0, 0, 0, "xmas order", p1.Id, false}
1462 dbmap.Insert(inv1)
1463
1464 // Run your query
1465 query := "select i.Id InvoiceId, p.Id PersonId, i.Memo, p.FName " +
1466 "from invoice_test i, person_test p " +
1467 "where i.PersonId = p.Id"
1468
1469 // pass a slice of pointers to Select()
1470 // this avoids the need to type assert after the query is run
1471 var list []*InvoicePersonView
1472 _, err := dbmap.Select(&list, query)
1473 if err != nil {
1474 panic(err)
1475 }
1476
1477 // this should test true
1478 expected := &InvoicePersonView{inv1.Id, p1.Id, inv1.Memo, p1.FName, 0}
1479 if !reflect.DeepEqual(list[0], expected) {
1480 t.Errorf("%v != %v", list[0], expected)
1481 }
1482 }
1483
1484 func TestQuoteTableNames(t *testing.T) {
1485 dbmap := initDbMap()
1486 defer dropAndClose(dbmap)
1487
1488 quotedTableName := dbmap.Dialect.QuoteField("person_test")
1489
1490 // Use a buffer to hold the log to check generated queries
1491 logBuffer := &bytes.Buffer{}
1492 dbmap.TraceOn("", log.New(logBuffer, "gorptest:", log.Lmicroseconds))
1493
1494 // Create some rows
1495 p1 := &Person{0, 0, 0, "bob", "smith", 0}
1496 errorTemplate := "Expected quoted table name %v in query but didn't find it"
1497
1498 // Check if Insert quotes the table name
1499 id := dbmap.Insert(p1)
1500 if !bytes.Contains(logBuffer.Bytes(), []byte(quotedTableName)) {
1501 t.Errorf(errorTemplate, quotedTableName)
1502 }
1503 logBuffer.Reset()
1504
1505 // Check if Get quotes the table name
1506 dbmap.Get(Person{}, id)
1507 if !bytes.Contains(logBuffer.Bytes(), []byte(quotedTableName)) {
1508 t.Errorf(errorTemplate, quotedTableName)
1509 }
1510 logBuffer.Reset()
1511 }
1512
1513 func TestSelectTooManyCols(t *testing.T) {
1514 dbmap := initDbMap()
1515 defer dropAndClose(dbmap)
1516
1517 p1 := &Person{0, 0, 0, "bob", "smith", 0}
1518 p2 := &Person{0, 0, 0, "jane", "doe", 0}
1519 _insert(dbmap, p1)
1520 _insert(dbmap, p2)
1521
1522 obj := _get(dbmap, Person{}, p1.Id)
1523 p1 = obj.(*Person)
1524 obj = _get(dbmap, Person{}, p2.Id)
1525 p2 = obj.(*Person)
1526
1527 params := map[string]interface{}{
1528 "Id": p1.Id,
1529 }
1530
1531 var p3 FNameOnly
1532 err := dbmap.SelectOne(&p3, "select * from person_test where Id=:Id", params)
1533 if err != nil {
1534 if !NonFatalError(err) {
1535 t.Error(err)
1536 }
1537 } else {
1538 t.Errorf("Non-fatal error expected")
1539 }
1540
1541 if p1.FName != p3.FName {
1542 t.Errorf("%v != %v", p1.FName, p3.FName)
1543 }
1544
1545 var pSlice []FNameOnly
1546 _, err = dbmap.Select(&pSlice, "select * from person_test order by fname asc")
1547 if err != nil {
1548 if !NonFatalError(err) {
1549 t.Error(err)
1550 }
1551 } else {
1552 t.Errorf("Non-fatal error expected")
1553 }
1554
1555 if p1.FName != pSlice[0].FName {
1556 t.Errorf("%v != %v", p1.FName, pSlice[0].FName)
1557 }
1558 if p2.FName != pSlice[1].FName {
1559 t.Errorf("%v != %v", p2.FName, pSlice[1].FName)
1560 }
1561 }
1562
1563 func TestSelectSingleVal(t *testing.T) {
1564 dbmap := initDbMap()
1565 defer dropAndClose(dbmap)
1566
1567 p1 := &Person{0, 0, 0, "bob", "smith", 0}
1568 _insert(dbmap, p1)
1569
1570 obj := _get(dbmap, Person{}, p1.Id)
1571 p1 = obj.(*Person)
1572
1573 params := map[string]interface{}{
1574 "Id": p1.Id,
1575 }
1576
1577 var p2 Person
1578 err := dbmap.SelectOne(&p2, "select * from person_test where Id=:Id", params)
1579 if err != nil {
1580 t.Error(err)
1581 }
1582
1583 if !reflect.DeepEqual(p1, &p2) {
1584 t.Errorf("%v != %v", p1, &p2)
1585 }
1586
1587 // verify SelectOne allows non-struct holders
1588 var s string
1589 err = dbmap.SelectOne(&s, "select FName from person_test where Id=:Id", params)
1590 if err != nil {
1591 t.Error(err)
1592 }
1593 if s != "bob" {
1594 t.Error("Expected bob but got: " + s)
1595 }
1596
1597 // verify SelectOne requires pointer receiver
1598 err = dbmap.SelectOne(s, "select FName from person_test where Id=:Id", params)
1599 if err == nil {
1600 t.Error("SelectOne should have returned error for non-pointer holder")
1601 }
1602
1603 // verify SelectOne works with uninitialized pointers
1604 var p3 *Person
1605 err = dbmap.SelectOne(&p3, "select * from person_test where Id=:Id", params)
1606 if err != nil {
1607 t.Error(err)
1608 }
1609
1610 if !reflect.DeepEqual(p1, p3) {
1611 t.Errorf("%v != %v", p1, p3)
1612 }
1613
1614 // verify that the receiver is still nil if nothing was found
1615 var p4 *Person
1616 dbmap.SelectOne(&p3, "select * from person_test where 2<1 AND Id=:Id", params)
1617 if p4 != nil {
1618 t.Error("SelectOne should not have changed a nil receiver when no rows were found")
1619 }
1620
1621 // verify that the error is set to sql.ErrNoRows if not found
1622 err = dbmap.SelectOne(&p2, "select * from person_test where Id=:Id", map[string]interface{}{
1623 "Id": -2222,
1624 })
1625 if err == nil || err != sql.ErrNoRows {
1626 t.Error("SelectOne should have returned an sql.ErrNoRows")
1627 }
1628
1629 _insert(dbmap, &Person{0, 0, 0, "bob", "smith", 0})
1630 err = dbmap.SelectOne(&p2, "select * from person_test where Fname='bob'")
1631 if err == nil {
1632 t.Error("Expected error when two rows found")
1633 }
1634
1635 // tests for #150
1636 var tInt int64
1637 var tStr string
1638 var tBool bool
1639 var tFloat float64
1640 primVals := []interface{}{tInt, tStr, tBool, tFloat}
1641 for _, prim := range primVals {
1642 err = dbmap.SelectOne(&prim, "select * from person_test where Id=-123")
1643 if err == nil || err != sql.ErrNoRows {
1644 t.Error("primVals: SelectOne should have returned sql.ErrNoRows")
1645 }
1646 }
1647 }
1648
1649 func TestSelectAlias(t *testing.T) {
1650 dbmap := initDbMap()
1651 defer dropAndClose(dbmap)
1652
1653 p1 := &IdCreatedExternal{IdCreated: IdCreated{Id: 1, Created: 3}, External: 2}
1654
1655 // Insert using embedded IdCreated, which reflects the structure of the table
1656 _insert(dbmap, &p1.IdCreated)
1657
1658 // Select into IdCreatedExternal type, which includes some fields not present
1659 // in id_created_test
1660 var p2 IdCreatedExternal
1661 err := dbmap.SelectOne(&p2, "select * from id_created_test where Id=1")
1662 if err != nil {
1663 t.Error(err)
1664 }
1665 if p2.Id != 1 || p2.Created != 3 || p2.External != 0 {
1666 t.Error("Expected ignored field defaults to not set")
1667 }
1668
1669 // Prove that we can supply an aliased value in the select, and that it will
1670 // automatically map to IdCreatedExternal.External
1671 err = dbmap.SelectOne(&p2, "SELECT *, 1 AS external FROM id_created_test")
1672 if err != nil {
1673 t.Error(err)
1674 }
1675 if p2.External != 1 {
1676 t.Error("Expected select as can map to exported field.")
1677 }
1678
1679 var rows *sql.Rows
1680 var cols []string
1681 rows, err = dbmap.Db.Query("SELECT * FROM id_created_test")
1682 cols, err = rows.Columns()
1683 if err != nil || len(cols) != 2 {
1684 t.Error("Expected ignored column not created")
1685 }
1686 }
1687
1688 func TestMysqlPanicIfDialectNotInitialized(t *testing.T) {
1689 _, driver := dialectAndDriver()
1690 // this test only applies to MySQL
1691 if os.Getenv("GORP_TEST_DIALECT") != "mysql" {
1692 return
1693 }
1694
1695 // The expected behaviour is to catch a panic.
1696 // Here is the deferred function which will check if a panic has indeed occurred :
1697 defer func() {
1698 r := recover()
1699 if r == nil {
1700 t.Error("db.CreateTables() should panic if db is initialized with an incorrect MySQLDialect")
1701 }
1702 }()
1703
1704 // invalid MySQLDialect : does not contain Engine or Encoding specification
1705 dialect := MySQLDialect{}
1706 db := &DbMap{Db: connect(driver), Dialect: dialect}
1707 db.AddTableWithName(Invoice{}, "invoice")
1708 // the following call should panic :
1709 db.CreateTables()
1710 }
1711
1712 func TestSingleColumnKeyDbReturnsZeroRowsUpdatedOnPKChange(t *testing.T) {
1713 dbmap := initDbMap()
1714 defer dropAndClose(dbmap)
1715 dbmap.AddTableWithName(SingleColumnTable{}, "single_column_table").SetKeys(false, "SomeId")
1716 err := dbmap.DropTablesIfExists()
1717 if err != nil {
1718 t.Error("Drop tables failed")
1719 }
1720 err = dbmap.CreateTablesIfNotExists()
1721 if err != nil {
1722 t.Error("Create tables failed")
1723 }
1724 err = dbmap.TruncateTables()
1725 if err != nil {
1726 t.Error("Truncate tables failed")
1727 }
1728
1729 sct := SingleColumnTable{
1730 SomeId: "A Unique Id String",
1731 }
1732
1733 count, err := dbmap.Update(&sct)
1734 if err != nil {
1735 t.Error(err)
1736 }
1737 if count != 0 {
1738 t.Errorf("Expected 0 updated rows, got %d", count)
1739 }
1740
1741 }
1742
1743 func TestPrepare(t *testing.T) {
1744 dbmap := initDbMap()
1745 defer dropAndClose(dbmap)
1746
1747 inv1 := &Invoice{0, 100, 200, "prepare-foo", 0, false}
1748 inv2 := &Invoice{0, 100, 200, "prepare-bar", 0, false}
1749 _insert(dbmap, inv1, inv2)
1750
1751 bindVar0 := dbmap.Dialect.BindVar(0)
1752 bindVar1 := dbmap.Dialect.BindVar(1)
1753 stmt, err := dbmap.Prepare(fmt.Sprintf("UPDATE invoice_test SET Memo=%s WHERE Id=%s", bindVar0, bindVar1))
1754 if err != nil {
1755 t.Error(err)
1756 }
1757 defer stmt.Close()
1758 _, err = stmt.Exec("prepare-baz", inv1.Id)
1759 if err != nil {
1760 t.Error(err)
1761 }
1762 err = dbmap.SelectOne(inv1, "SELECT * from invoice_test WHERE Memo='prepare-baz'")
1763 if err != nil {
1764 t.Error(err)
1765 }
1766
1767 trans, err := dbmap.Begin()
1768 if err != nil {
1769 t.Error(err)
1770 }
1771 transStmt, err := trans.Prepare(fmt.Sprintf("UPDATE invoice_test SET IsPaid=%s WHERE Id=%s", bindVar0, bindVar1))
1772 if err != nil {
1773 t.Error(err)
1774 }
1775 defer transStmt.Close()
1776 _, err = transStmt.Exec(true, inv2.Id)
1777 if err != nil {
1778 t.Error(err)
1779 }
1780 err = dbmap.SelectOne(inv2, fmt.Sprintf("SELECT * from invoice_test WHERE IsPaid=%s", bindVar0), true)
1781 if err == nil || err != sql.ErrNoRows {
1782 t.Error("SelectOne should have returned an sql.ErrNoRows")
1783 }
1784 err = trans.SelectOne(inv2, fmt.Sprintf("SELECT * from invoice_test WHERE IsPaid=%s", bindVar0), true)
1785 if err != nil {
1786 t.Error(err)
1787 }
1788 err = trans.Commit()
1789 if err != nil {
1790 t.Error(err)
1791 }
1792 err = dbmap.SelectOne(inv2, fmt.Sprintf("SELECT * from invoice_test WHERE IsPaid=%s", bindVar0), true)
1793 if err != nil {
1794 t.Error(err)
1795 }
1796 }
1797
1798 func BenchmarkNativeCrud(b *testing.B) {
1799 b.StopTimer()
1800 dbmap := initDbMapBench()
1801 defer dropAndClose(dbmap)
1802 b.StartTimer()
1803
1804 insert := "insert into invoice_test (Created, Updated, Memo, PersonId) values (?, ?, ?, ?)"
1805 sel := "select Id, Created, Updated, Memo, PersonId from invoice_test where Id=?"
1806 update := "update invoice_test set Created=?, Updated=?, Memo=?, PersonId=? where Id=?"
1807 delete := "delete from invoice_test where Id=?"
1808
1809 inv := &Invoice{0, 100, 200, "my memo", 0, false}
1810
1811 for i := 0; i < b.N; i++ {
1812 res, err := dbmap.Db.Exec(insert, inv.Created, inv.Updated,
1813 inv.Memo, inv.PersonId)
1814 if err != nil {
1815 panic(err)
1816 }
1817
1818 newid, err := res.LastInsertId()
1819 if err != nil {
1820 panic(err)
1821 }
1822 inv.Id = newid
1823
1824 row := dbmap.Db.QueryRow(sel, inv.Id)
1825 err = row.Scan(&inv.Id, &inv.Created, &inv.Updated, &inv.Memo,
1826 &inv.PersonId)
1827 if err != nil {
1828 panic(err)
1829 }
1830
1831 inv.Created = 1000
1832 inv.Updated = 2000
1833 inv.Memo = "my memo 2"
1834 inv.PersonId = 3000
1835
1836 _, err = dbmap.Db.Exec(update, inv.Created, inv.Updated, inv.Memo,
1837 inv.PersonId, inv.Id)
1838 if err != nil {
1839 panic(err)
1840 }
1841
1842 _, err = dbmap.Db.Exec(delete, inv.Id)
1843 if err != nil {
1844 panic(err)
1845 }
1846 }
1847
1848 }
1849
1850 func BenchmarkGorpCrud(b *testing.B) {
1851 b.StopTimer()
1852 dbmap := initDbMapBench()
1853 defer dropAndClose(dbmap)
1854 b.StartTimer()
1855
1856 inv := &Invoice{0, 100, 200, "my memo", 0, true}
1857 for i := 0; i < b.N; i++ {
1858 err := dbmap.Insert(inv)
1859 if err != nil {
1860 panic(err)
1861 }
1862
1863 obj, err := dbmap.Get(Invoice{}, inv.Id)
1864 if err != nil {
1865 panic(err)
1866 }
1867
1868 inv2, ok := obj.(*Invoice)
1869 if !ok {
1870 panic(fmt.Sprintf("expected *Invoice, got: %v", obj))
1871 }
1872
1873 inv2.Created = 1000
1874 inv2.Updated = 2000
1875 inv2.Memo = "my memo 2"
1876 inv2.PersonId = 3000
1877 _, err = dbmap.Update(inv2)
1878 if err != nil {
1879 panic(err)
1880 }
1881
1882 _, err = dbmap.Delete(inv2)
1883 if err != nil {
1884 panic(err)
1885 }
1886
1887 }
1888 }
1889
1890 func initDbMapBench() *DbMap {
1891 dbmap := newDbMap()
1892 dbmap.Db.Exec("drop table if exists invoice_test")
1893 dbmap.AddTableWithName(Invoice{}, "invoice_test").SetKeys(true, "Id")
1894 err := dbmap.CreateTables()
1895 if err != nil {
1896 panic(err)
1897 }
1898 return dbmap
1899 }
1900
1901 func initDbMap() *DbMap {
1902 dbmap := newDbMap()
1903 dbmap.AddTableWithName(Invoice{}, "invoice_test").SetKeys(true, "Id")
1904 dbmap.AddTableWithName(InvoiceTag{}, "invoice_tag_test").SetKeys(true, "myid")
1905 dbmap.AddTableWithName(AliasTransientField{}, "alias_trans_field_test").SetKeys(true, "id")
1906 dbmap.AddTableWithName(OverriddenInvoice{}, "invoice_override_test").SetKeys(false, "Id")
1907 dbmap.AddTableWithName(Person{}, "person_test").SetKeys(true, "Id")
1908 dbmap.AddTableWithName(WithIgnoredColumn{}, "ignored_column_test").SetKeys(true, "Id")
1909 dbmap.AddTableWithName(IdCreated{}, "id_created_test").SetKeys(true, "Id")
1910 dbmap.AddTableWithName(TypeConversionExample{}, "type_conv_test").SetKeys(true, "Id")
1911 dbmap.AddTableWithName(WithEmbeddedStruct{}, "embedded_struct_test").SetKeys(true, "Id")
1912 dbmap.AddTableWithName(WithEmbeddedStructBeforeAutoincrField{}, "embedded_struct_before_autoincr_test").SetKeys(true, "Id")
1913 dbmap.AddTableWithName(WithEmbeddedAutoincr{}, "embedded_autoincr_test").SetKeys(true, "Id")
1914 dbmap.AddTableWithName(WithTime{}, "time_test").SetKeys(true, "Id")
1915 dbmap.TypeConverter = testTypeConverter{}
1916 err := dbmap.DropTablesIfExists()
1917 if err != nil {
1918 panic(err)
1919 }
1920 err = dbmap.CreateTables()
1921 if err != nil {
1922 panic(err)
1923 }
1924
1925 // See #146 and TestSelectAlias - this type is mapped to the same
1926 // table as IdCreated, but includes an extra field that isn't in the table
1927 dbmap.AddTableWithName(IdCreatedExternal{}, "id_created_test").SetKeys(true, "Id")
1928
1929 return dbmap
1930 }
1931
1932 func initDbMapNulls() *DbMap {
1933 dbmap := newDbMap()
1934 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
1935 dbmap.AddTable(TableWithNull{}).SetKeys(false, "Id")
1936 err := dbmap.CreateTables()
1937 if err != nil {
1938 panic(err)
1939 }
1940 return dbmap
1941 }
1942
1943 func newDbMap() *DbMap {
1944 dialect, driver := dialectAndDriver()
1945 dbmap := &DbMap{Db: connect(driver), Dialect: dialect}
1946 dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
1947 return dbmap
1948 }
1949
1950 func dropAndClose(dbmap *DbMap) {
1951 dbmap.DropTablesIfExists()
1952 dbmap.Db.Close()
1953 }
1954
1955 func connect(driver string) *sql.DB {
1956 dsn := os.Getenv("GORP_TEST_DSN")
1957 if dsn == "" {
1958 panic("GORP_TEST_DSN env variable is not set. Please see README.md")
1959 }
1960
1961 db, err := sql.Open(driver, dsn)
1962 if err != nil {
1963 panic("Error connecting to db: " + err.Error())
1964 }
1965 return db
1966 }
1967
1968 func dialectAndDriver() (Dialect, string) {
1969 switch os.Getenv("GORP_TEST_DIALECT") {
1970 case "mysql":
1971 return MySQLDialect{"InnoDB", "UTF8"}, "mymysql"
1972 case "gomysql":
1973 return MySQLDialect{"InnoDB", "UTF8"}, "mysql"
1974 case "postgres":
1975 return PostgresDialect{}, "postgres"
1976 case "sqlite":
1977 return SqliteDialect{}, "sqlite3"
1978 }
1979 panic("GORP_TEST_DIALECT env variable is not set or is invalid. Please see README.md")
1980 }
1981
1982 func _insert(dbmap *DbMap, list ...interface{}) {
1983 err := dbmap.Insert(list...)
1984 if err != nil {
1985 panic(err)
1986 }
1987 }
1988
1989 func _update(dbmap *DbMap, list ...interface{}) int64 {
1990 count, err := dbmap.Update(list...)
1991 if err != nil {
1992 panic(err)
1993 }
1994 return count
1995 }
1996
1997 func _del(dbmap *DbMap, list ...interface{}) int64 {
1998 count, err := dbmap.Delete(list...)
1999 if err != nil {
2000 panic(err)
2001 }
2002
2003 return count
2004 }
2005
2006 func _get(dbmap *DbMap, i interface{}, keys ...interface{}) interface{} {
2007 obj, err := dbmap.Get(i, keys...)
2008 if err != nil {
2009 panic(err)
2010 }
2011
2012 return obj
2013 }
2014
2015 func selectInt(dbmap *DbMap, query string, args ...interface{}) int64 {
2016 i64, err := SelectInt(dbmap, query, args...)
2017 if err != nil {
2018 panic(err)
2019 }
2020
2021 return i64
2022 }
2023
2024 func selectNullInt(dbmap *DbMap, query string, args ...interface{}) sql.NullInt64 {
2025 i64, err := SelectNullInt(dbmap, query, args...)
2026 if err != nil {
2027 panic(err)
2028 }
2029
2030 return i64
2031 }
2032
2033 func selectFloat(dbmap *DbMap, query string, args ...interface{}) float64 {
2034 f64, err := SelectFloat(dbmap, query, args...)
2035 if err != nil {
2036 panic(err)
2037 }
2038
2039 return f64
2040 }
2041
2042 func selectNullFloat(dbmap *DbMap, query string, args ...interface{}) sql.NullFloat64 {
2043 f64, err := SelectNullFloat(dbmap, query, args...)
2044 if err != nil {
2045 panic(err)
2046 }
2047
2048 return f64
2049 }
2050
2051 func selectStr(dbmap *DbMap, query string, args ...interface{}) string {
2052 s, err := SelectStr(dbmap, query, args...)
2053 if err != nil {
2054 panic(err)
2055 }
2056
2057 return s
2058 }
2059
2060 func selectNullStr(dbmap *DbMap, query string, args ...interface{}) sql.NullString {
2061 s, err := SelectNullStr(dbmap, query, args...)
2062 if err != nil {
2063 panic(err)
2064 }
2065
2066 return s
2067 }
2068
2069 func _rawexec(dbmap *DbMap, query string, args ...interface{}) sql.Result {
2070 res, err := dbmap.Exec(query, args...)
2071 if err != nil {
2072 panic(err)
2073 }
2074 return res
2075 }
2076
2077 func _rawselect(dbmap *DbMap, i interface{}, query string, args ...interface{}) []interface{} {
2078 list, err := dbmap.Select(i, query, args...)
2079 if err != nil {
2080 panic(err)
2081 }
2082 return list
2083 }