-
Notifications
You must be signed in to change notification settings - Fork 19
/
genmai.go
1432 lines (1324 loc) · 39.1 KB
/
genmai.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Naoya Inada. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
// Package genmai provides simple, better and easy-to-use Object-Relational Mapper.
package genmai
import (
"database/sql"
"errors"
"fmt"
"io"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"github.com/naoina/go-stringutil"
)
var ErrTxDone = errors.New("genmai: transaction hasn't been started or already committed or rolled back")
// DB represents a database object.
type DB struct {
db *sql.DB
dialect Dialect
tx *sql.Tx
m sync.Mutex
logger logger
}
// New returns a new DB.
// If any error occurs, it returns nil and error.
func New(dialect Dialect, dsn string) (*DB, error) {
db, err := sql.Open(dialect.Name(), dsn)
if err != nil {
return nil, err
}
return &DB{db: db, dialect: dialect, logger: defaultLogger}, nil
}
// Select fetch data into the output from the database.
// output argument must be pointer to a slice of struct. If not a pointer or not a slice of struct, It returns error.
// The table name of the database will be determined from name of struct. e.g. If *[]ATableName passed to output argument, table name will be "a_table_name".
// If args are not given, fetch the all data like "SELECT * FROM table" SQL.
func (db *DB) Select(output interface{}, args ...interface{}) (err error) {
defer func() {
if e := recover(); e != nil {
buf := make([]byte, 4096)
n := runtime.Stack(buf, false)
err = fmt.Errorf("%v\n%v", e, string(buf[:n]))
}
}()
rv := reflect.ValueOf(output)
if rv.Kind() != reflect.Ptr {
return fmt.Errorf("Select: first argument must be a pointer")
}
for rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
var tableName string
for _, arg := range args {
if f, ok := arg.(*From); ok {
if tableName != "" {
return fmt.Errorf("Select: From statement specified more than once")
}
tableName = f.TableName
}
}
var selectFunc selectFunc
ptrN := 0
switch rv.Kind() {
case reflect.Slice:
t := rv.Type().Elem()
for ; t.Kind() == reflect.Ptr; ptrN++ {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return fmt.Errorf("Select: argument of slice must be slice of struct, but %v", rv.Type())
}
if tableName == "" {
tableName = db.tableName(t)
}
selectFunc = db.selectToSlice
case reflect.Invalid:
return fmt.Errorf("Select: nil pointer dereference")
default:
if tableName == "" {
return fmt.Errorf("Select: From statement must be given if any Function is given")
}
selectFunc = db.selectToValue
}
col, from, conditions, err := db.classify(tableName, args)
if err != nil {
return err
}
queries := []string{`SELECT`, col, `FROM`, db.dialect.Quote(from)}
var values []interface{}
for _, cond := range conditions {
q, a := cond.build(0, false)
queries = append(queries, q...)
values = append(values, a...)
}
query := strings.Join(queries, " ")
stmt, err := db.prepare(query, values...)
if err != nil {
return err
}
defer stmt.Close()
rows, err := stmt.Query(values...)
if err != nil {
return err
}
defer rows.Close()
value, err := selectFunc(rows, rv.Type())
if err != nil {
return err
}
rv.Set(value)
return nil
}
// From returns a "FROM" statement.
// A table name will be determined from name of struct of arg.
// If arg argument is not struct type, it panics.
func (db *DB) From(arg interface{}) *From {
t := reflect.Indirect(reflect.ValueOf(arg)).Type()
if t.Kind() != reflect.Struct {
panic(fmt.Errorf("From: argument must be struct (or that pointer) type, got %v", t))
}
return &From{TableName: db.tableName(t)}
}
// Where returns a new Condition of "WHERE" clause.
func (db *DB) Where(cond interface{}, args ...interface{}) *Condition {
return newCondition(db).Where(cond, args...)
}
// OrderBy returns a new Condition of "ORDER BY" clause.
func (db *DB) OrderBy(table interface{}, column interface{}, order ...interface{}) *Condition {
return newCondition(db).OrderBy(table, column, order...)
}
// Limit returns a new Condition of "LIMIT" clause.
func (db *DB) Limit(lim int) *Condition {
return newCondition(db).Limit(lim)
}
// Offset returns a new Condition of "OFFSET" clause.
func (db *DB) Offset(offset int) *Condition {
return newCondition(db).Offset(offset)
}
// Distinct returns a representation object of "DISTINCT" statement.
func (db *DB) Distinct(columns ...string) *Distinct {
return &Distinct{columns: columns}
}
// Join returns a new JoinCondition of "JOIN" clause.
func (db *DB) Join(table interface{}) *JoinCondition {
return (&JoinCondition{db: db}).Join(table)
}
func (db *DB) LeftJoin(table interface{}) *JoinCondition {
return (&JoinCondition{db: db}).LeftJoin(table)
}
// Count returns "COUNT" function.
func (db *DB) Count(column ...interface{}) *Function {
switch len(column) {
case 0, 1:
// do nothing.
default:
panic(fmt.Errorf("Count: a number of argument must be 0 or 1, got %v", len(column)))
}
return &Function{
Name: "COUNT",
Args: column,
}
}
const (
dbTag = "db"
dbColumnTag = "column"
dbDefaultTag = "default"
dbSizeTag = "size"
skipTag = "-"
)
// CreateTable creates the table into database.
// If table isn't direct/indirect struct, it returns error.
func (db *DB) CreateTable(table interface{}) error {
return db.createTable(table, false)
}
// CreateTableIfNotExists creates the table into database if table isn't exists.
// If table isn't direct/indirect struct, it returns error.
func (db *DB) CreateTableIfNotExists(table interface{}) error {
return db.createTable(table, true)
}
func (db *DB) createTable(table interface{}, ifNotExists bool) error {
_, t, tableName, err := db.tableValueOf("CreateTable", table)
if err != nil {
return err
}
fields, err := db.collectTableFields(t)
if err != nil {
return err
}
var query string
if ifNotExists {
query = "CREATE TABLE IF NOT EXISTS %s (%s)"
} else {
query = "CREATE TABLE %s (%s)"
}
query = fmt.Sprintf(query, db.dialect.Quote(tableName), strings.Join(fields, ", "))
stmt, err := db.prepare(query)
if err != nil {
return err
}
defer stmt.Close()
if _, err := stmt.Exec(); err != nil {
return err
}
return nil
}
// DropTable removes the table from database.
// If table isn't direct/indirect struct, it returns error.
func (db *DB) DropTable(table interface{}) error {
_, _, tableName, err := db.tableValueOf("DropTable", table)
if err != nil {
return err
}
query := fmt.Sprintf("DROP TABLE %s", db.dialect.Quote(tableName))
stmt, err := db.prepare(query)
if err != nil {
return err
}
defer stmt.Close()
if _, err = stmt.Exec(); err != nil {
return err
}
return nil
}
// CreateIndex creates the index into database.
// If table isn't direct/indirect struct, it returns error.
func (db *DB) CreateIndex(table interface{}, name string, names ...string) error {
return db.createIndex(table, false, name, names...)
}
// CreateUniqueIndex creates the unique index into database.
// If table isn't direct/indirect struct, it returns error.
func (db *DB) CreateUniqueIndex(table interface{}, name string, names ...string) error {
return db.createIndex(table, true, name, names...)
}
func (db *DB) createIndex(table interface{}, unique bool, name string, names ...string) error {
_, _, tableName, err := db.tableValueOf("CreateIndex", table)
if err != nil {
return err
}
names = append([]string{name}, names...)
indexes := make([]string, len(names))
for i, name := range names {
indexes[i] = db.dialect.Quote(name)
}
indexName := strings.Join(append([]string{"index", tableName}, names...), "_")
var query string
if unique {
query = "CREATE UNIQUE INDEX %s ON %s (%s)"
} else {
query = "CREATE INDEX %s ON %s (%s)"
}
query = fmt.Sprintf(query,
db.dialect.Quote(indexName),
db.dialect.Quote(tableName),
strings.Join(indexes, ", "))
stmt, err := db.prepare(query)
if err != nil {
return err
}
defer stmt.Close()
if _, err := stmt.Exec(); err != nil {
return err
}
return nil
}
// Update updates the one record.
// The obj must be struct, and must have field that specified "pk" struct tag.
// Update will try to update record which searched by value of primary key in obj.
// Update returns the number of rows affected by an update.
func (db *DB) Update(obj interface{}) (affected int64, err error) {
rv, rtype, tableName, err := db.tableValueOf("Update", obj)
if err != nil {
return -1, err
}
if hook, ok := obj.(BeforeUpdater); ok {
if err := hook.BeforeUpdate(); err != nil {
return -1, err
}
}
fieldIndexes := db.collectFieldIndexes(rtype, nil)
pkIdx := db.findPKIndex(rtype, nil)
if len(pkIdx) < 1 {
return -1, fmt.Errorf(`Update: fields of struct doesn't have primary key: "pk" struct tag must be specified for update`)
}
sets := make([]string, len(fieldIndexes))
var args []interface{}
for i, index := range fieldIndexes {
col := db.columnFromTag(rtype.FieldByIndex(index))
sets[i] = fmt.Sprintf("%s = %s", db.dialect.Quote(col), db.dialect.PlaceHolder(i))
args = append(args, rv.FieldByIndex(index).Interface())
}
query := fmt.Sprintf("UPDATE %s SET %s WHERE %s = %s",
db.dialect.Quote(tableName),
strings.Join(sets, ", "),
db.dialect.Quote(db.columnFromTag(rtype.FieldByIndex(pkIdx))),
db.dialect.PlaceHolder(len(fieldIndexes)))
args = append(args, rv.FieldByIndex(pkIdx).Interface())
stmt, err := db.prepare(query, args...)
if err != nil {
return -1, err
}
defer stmt.Close()
result, err := stmt.Exec(args...)
if err != nil {
return -1, err
}
affected, _ = result.RowsAffected()
if hook, ok := obj.(AfterUpdater); ok {
if err := hook.AfterUpdate(); err != nil {
return affected, err
}
}
return affected, nil
}
// Insert inserts one or more records to the database table.
// The obj must be pointer to struct or slice of struct. If a struct have a
// field which specified "pk" struct tag on type of autoincrementable, it
// won't be used to as an insert value.
// Insert sets the last inserted id to the primary key of the instance of the given obj if obj is single.
// Insert returns the number of rows affected by insert.
func (db *DB) Insert(obj interface{}) (affected int64, err error) {
objs, rtype, tableName, err := db.tableObjs("Insert", obj)
if err != nil {
return -1, err
}
if len(objs) < 1 {
return 0, nil
}
for _, obj := range objs {
if hook, ok := obj.(BeforeInserter); ok {
if err := hook.BeforeInsert(); err != nil {
return -1, err
}
}
}
fieldIndexes := db.collectFieldIndexes(rtype, nil)
cols := make([]string, len(fieldIndexes))
for i, index := range fieldIndexes {
cols[i] = db.dialect.Quote(db.columnFromTag(rtype.FieldByIndex(index)))
}
var args []interface{}
for _, obj := range objs {
rv := reflect.Indirect(reflect.ValueOf(obj))
for _, index := range fieldIndexes {
args = append(args, rv.FieldByIndex(index).Interface())
}
}
numHolders := 0
values := make([]string, len(objs))
holders := make([]string, len(cols))
for i := 0; i < len(values); i++ {
for j := 0; j < len(holders); j++ {
holders[j] = db.dialect.PlaceHolder(numHolders)
numHolders++
}
values[i] = fmt.Sprintf("(%s)", strings.Join(holders, ", "))
}
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s",
db.dialect.Quote(tableName),
strings.Join(cols, ", "),
strings.Join(values, ", "),
)
stmt, err := db.prepare(query, args...)
if err != nil {
return -1, err
}
defer stmt.Close()
result, err := stmt.Exec(args...)
if err != nil {
return -1, err
}
affected, _ = result.RowsAffected()
if len(objs) == 1 {
if pkIdx := db.findPKIndex(rtype, nil); len(pkIdx) > 0 {
field := rtype.FieldByIndex(pkIdx)
if db.isAutoIncrementable(&field) {
id, err := db.LastInsertId()
if err != nil {
return affected, err
}
rv := reflect.Indirect(reflect.ValueOf(objs[0])).FieldByIndex(pkIdx)
for rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
rv.Set(reflect.ValueOf(id).Convert(rv.Type()))
}
}
}
for _, obj := range objs {
if hook, ok := obj.(AfterInserter); ok {
if err := hook.AfterInsert(); err != nil {
return affected, err
}
}
}
return affected, nil
}
// Delete deletes the records from database table.
// The obj must be pointer to struct or slice of struct, and must have field that specified "pk" struct tag.
// Delete will try to delete record which searched by value of primary key in obj.
// Delete returns teh number of rows affected by a delete.
func (db *DB) Delete(obj interface{}) (affected int64, err error) {
objs, rtype, tableName, err := db.tableObjs("Delete", obj)
if err != nil {
return -1, err
}
if len(objs) < 1 {
return 0, nil
}
for _, obj := range objs {
if hook, ok := obj.(BeforeDeleter); ok {
if err := hook.BeforeDelete(); err != nil {
return -1, err
}
}
}
pkIdx := db.findPKIndex(rtype, nil)
if len(pkIdx) < 1 {
return -1, fmt.Errorf(`Delete: fields of struct doesn't have primary key: "pk" struct tag must be specified for delete`)
}
var args []interface{}
for _, obj := range objs {
rv := reflect.Indirect(reflect.ValueOf(obj))
args = append(args, rv.FieldByIndex(pkIdx).Interface())
}
holders := make([]string, len(args))
for i := 0; i < len(holders); i++ {
holders[i] = db.dialect.PlaceHolder(i)
}
query := fmt.Sprintf("DELETE FROM %s WHERE %s IN (%s)",
db.dialect.Quote(tableName),
db.dialect.Quote(db.columnFromTag(rtype.FieldByIndex(pkIdx))),
strings.Join(holders, ", "))
stmt, err := db.prepare(query, args...)
if err != nil {
return -1, err
}
defer stmt.Close()
result, err := stmt.Exec(args...)
if err != nil {
return -1, err
}
affected, _ = result.RowsAffected()
for _, obj := range objs {
if hook, ok := obj.(AfterDeleter); ok {
if err := hook.AfterDelete(); err != nil {
return affected, err
}
}
}
return affected, nil
}
// Begin starts a transaction.
func (db *DB) Begin() error {
tx, err := db.db.Begin()
if err != nil {
return err
}
db.m.Lock()
defer db.m.Unlock()
db.tx = tx
return nil
}
// Commit commits the transaction.
// If Begin still not called, or Commit or Rollback already called, Commit returns ErrTxDone.
func (db *DB) Commit() error {
db.m.Lock()
defer db.m.Unlock()
if db.tx == nil {
return ErrTxDone
}
err := db.tx.Commit()
db.tx = nil
return err
}
// Rollback rollbacks the transaction.
// If Begin still not called, or Commit or Rollback already called, Rollback returns ErrTxDone.
func (db *DB) Rollback() error {
db.m.Lock()
defer db.m.Unlock()
if db.tx == nil {
return ErrTxDone
}
err := db.tx.Rollback()
db.tx = nil
return err
}
func (db *DB) LastInsertId() (int64, error) {
stmt, err := db.prepare(db.dialect.LastInsertId())
if err != nil {
return 0, err
}
defer stmt.Close()
var id int64
return id, stmt.QueryRow().Scan(&id)
}
// Raw returns a value that is wrapped with Raw.
func (db *DB) Raw(v interface{}) Raw {
return Raw(&v)
}
// Close closes the database.
func (db *DB) Close() error {
return db.db.Close()
}
// Quote returns a quoted s.
// It is for a column name, not a value.
func (db *DB) Quote(s string) string {
return db.dialect.Quote(s)
}
// DB returns a *sql.DB that is associated to DB.
func (db *DB) DB() *sql.DB {
return db.db
}
// SetLogOutput sets output destination for logging.
// If w is nil, it unsets output of logging.
func (db *DB) SetLogOutput(w io.Writer) {
if w == nil {
db.logger = defaultLogger
} else {
db.logger = &templateLogger{w: w, t: defaultLoggerTemplate}
}
}
// SetLogFormat sets format for logging.
//
// Format syntax uses Go's template. And you can use the following data object in that template.
//
// - .time time.Time object in current time.
// - .duration Processing time of SQL. It will format to "%.2fms".
// - .query string of SQL query. If it using placeholder,
// placeholder parameters will append to the end of query.
//
// The default format is:
//
// [{{.time.Format "2006-01-02 15:04:05"}}] [{{.duration}}] {{.query}}
func (db *DB) SetLogFormat(format string) error {
return db.logger.SetFormat(format)
}
// selectToSlice returns a slice value fetched from rows.
func (db *DB) selectToSlice(rows *sql.Rows, t reflect.Type) (reflect.Value, error) {
columns, err := rows.Columns()
if err != nil {
return reflect.Value{}, err
}
t = t.Elem()
ptrN := 0
for ; t.Kind() == reflect.Ptr; ptrN++ {
t = t.Elem()
}
fieldIndexes := make([][]int, len(columns))
for i, column := range columns {
index := db.fieldIndexByName(t, column, nil)
if len(index) < 1 {
return reflect.Value{}, fmt.Errorf("`%v` field isn't defined in %v or embedded struct", stringutil.ToUpperCamelCase(column), t)
}
fieldIndexes[i] = index
}
dest := make([]interface{}, len(columns))
var result []reflect.Value
for rows.Next() {
v := reflect.New(t).Elem()
for i, index := range fieldIndexes {
field := v.FieldByIndex(index)
dest[i] = field.Addr().Interface()
}
if err := rows.Scan(dest...); err != nil {
return reflect.Value{}, err
}
result = append(result, v)
}
if err := rows.Err(); err != nil {
return reflect.Value{}, err
}
for i := 0; i < ptrN; i++ {
t = reflect.PtrTo(t)
}
slice := reflect.MakeSlice(reflect.SliceOf(t), len(result), len(result))
for i, v := range result {
for j := 0; j < ptrN; j++ {
v = v.Addr()
}
slice.Index(i).Set(v)
}
return slice, nil
}
// selectToValue returns a single value fetched from rows.
func (db *DB) selectToValue(rows *sql.Rows, t reflect.Type) (reflect.Value, error) {
ptrN := 0
for ; t.Kind() == reflect.Ptr; ptrN++ {
t = t.Elem()
}
dest := reflect.New(t).Elem()
if rows.Next() {
if err := rows.Scan(dest.Addr().Interface()); err != nil {
return reflect.Value{}, err
}
}
for i := 0; i < ptrN; i++ {
dest = dest.Addr()
}
return dest, nil
}
// fieldIndexByName returns the nested field corresponding to the index sequence.
func (db *DB) fieldIndexByName(t reflect.Type, name string, index []int) []int {
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if candidate := db.columnFromTag(field); candidate == name {
return append(index, i)
}
if field.Anonymous {
if idx := db.fieldIndexByName(field.Type, name, append(index, i)); len(idx) > 0 {
return append(index, idx...)
}
}
}
return nil
}
func (db *DB) classify(tableName string, args []interface{}) (column, from string, conditions []*Condition, err error) {
if len(args) == 0 {
return ColumnName(db.dialect, tableName, "*"), tableName, nil, nil
}
offset := 1
switch t := args[0].(type) {
case string:
if t != "" {
column = ColumnName(db.dialect, tableName, t)
}
case []string:
column = db.columns(tableName, ToInterfaceSlice(t))
case *Distinct:
column = fmt.Sprintf("DISTINCT %s", db.columns(tableName, ToInterfaceSlice(t.columns)))
case *Function:
var col string
if len(t.Args) == 0 {
col = "*"
} else {
col = db.columns(tableName, t.Args)
}
column = fmt.Sprintf("%s(%s)", t.Name, col)
default:
offset--
}
for i := offset; i < len(args); i++ {
switch t := args[i].(type) {
case *Condition:
t.tableName = tableName
conditions = append(conditions, t)
case string, []string:
return "", "", nil, fmt.Errorf("argument of %T type must be before the *Condition arguments", t)
case *From:
// ignore.
case *Function:
return "", "", nil, fmt.Errorf("%s function must be specified to the first argument", t.Name)
default:
return "", "", nil, fmt.Errorf("unsupported argument type: %T", t)
}
}
if column == "" {
column = ColumnName(db.dialect, tableName, "*")
}
return column, tableName, conditions, nil
}
// columns returns the comma-separated column name with quoted.
func (db *DB) columns(tableName string, columns []interface{}) string {
if len(columns) == 0 {
return ColumnName(db.dialect, tableName, "*")
}
names := make([]string, len(columns))
for i, col := range columns {
switch c := col.(type) {
case Raw:
names[i] = fmt.Sprint(*c)
case string:
names[i] = ColumnName(db.dialect, tableName, c)
case *Distinct:
names[i] = fmt.Sprintf("DISTINCT %s", db.columns(tableName, ToInterfaceSlice(c.columns)))
default:
panic(fmt.Errorf("column name must be string, Raw or *Distinct, got %T", c))
}
}
return strings.Join(names, ", ")
}
func (db *DB) collectTableFields(t reflect.Type) (fields []string, err error) {
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if IsUnexportedField(field) {
continue
}
if db.hasSkipTag(&field) {
continue
}
if field.Anonymous {
fs, err := db.collectTableFields(field.Type)
if err != nil {
return nil, err
}
fields = append(fields, fs...)
continue
}
var options []string
autoIncrement := false
for _, tag := range db.tagsFromField(&field) {
switch tag {
case "pk":
options = append(options, "PRIMARY KEY")
if db.isAutoIncrementable(&field) {
options = append(options, db.dialect.AutoIncrement())
autoIncrement = true
}
case "unique":
options = append(options, "UNIQUE")
default:
return nil, fmt.Errorf(`CreateTable: unsupported field tag: "%v"`, tag)
}
}
size, err := db.sizeFromTag(&field)
if err != nil {
return nil, err
}
typName, allowNull := db.dialect.SQLType(reflect.Zero(field.Type).Interface(), autoIncrement, size)
if !allowNull {
options = append(options, "NOT NULL")
}
line := append([]string{db.dialect.Quote(db.columnFromTag(field)), typName}, options...)
def, err := db.defaultFromTag(&field)
if err != nil {
return nil, err
}
if def != "" {
line = append(line, def)
}
fields = append(fields, strings.Join(line, " "))
}
return fields, nil
}
// tagsFromField returns a slice of option strings.
func (db *DB) tagsFromField(field *reflect.StructField) (options []string) {
if db.hasSkipTag(field) {
return nil
}
for _, tag := range strings.Split(field.Tag.Get(dbTag), ",") {
if t := strings.ToLower(strings.TrimSpace(tag)); t != "" {
options = append(options, t)
}
}
return options
}
// hasSkipTag returns whether the struct field has the "-" tag.
func (db *DB) hasSkipTag(field *reflect.StructField) bool {
if field.Tag.Get(dbTag) == skipTag {
return true
}
return false
}
// hasPKTag returns whether the struct field has the "pk" tag.
func (db *DB) hasPKTag(field *reflect.StructField) bool {
for _, tag := range db.tagsFromField(field) {
if tag == "pk" {
return true
}
}
return false
}
// isAutoIncrementable returns whether the struct field is integer.
func (db *DB) isAutoIncrementable(field *reflect.StructField) bool {
switch field.Type.Kind() {
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return true
}
return false
}
// collectFieldIndexes returns the indexes of field which doesn't have skip tag and pk tag.
func (db *DB) collectFieldIndexes(typ reflect.Type, index []int) (indexes [][]int) {
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if IsUnexportedField(field) {
continue
}
if !(db.hasSkipTag(&field) || (db.hasPKTag(&field) && db.isAutoIncrementable(&field))) {
tmp := make([]int, len(index)+1)
copy(tmp, index)
tmp[len(tmp)-1] = i
if field.Anonymous {
indexes = append(indexes, db.collectFieldIndexes(field.Type, tmp)...)
} else {
indexes = append(indexes, tmp)
}
}
}
return indexes
}
// findPKIndex returns the nested field corresponding to the index sequence of field of primary key.
func (db *DB) findPKIndex(typ reflect.Type, index []int) []int {
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if IsUnexportedField(field) {
continue
}
if field.Anonymous {
if idx := db.findPKIndex(field.Type, append(index, i)); idx != nil {
return append(index, idx...)
}
continue
}
if db.hasPKTag(&field) {
return append(index, i)
}
}
return nil
}
// sizeFromTag returns a size from tag.
// If "size" tag specified to struct field, it will converted to uint64 and returns it.
// If it doesn't specify, it returns 0.
// If value of "size" tag cannot convert to uint64, it returns 0 and error.
func (db *DB) sizeFromTag(field *reflect.StructField) (size uint64, err error) {
if s := field.Tag.Get(dbSizeTag); s != "" {
size, err = strconv.ParseUint(s, 10, 64)
}
return size, err
}
func (db *DB) tableName(t reflect.Type) string {
if table, ok := reflect.New(t).Interface().(TableNamer); ok {
return table.TableName()
}
return stringutil.ToSnakeCase(t.Name())
}
// columnFromTag returns the column name.
// If "column" tag specified to struct field, returns it.
// Otherwise, it returns snake-cased field name as column name.
func (db *DB) columnFromTag(field reflect.StructField) string {
col := field.Tag.Get(dbColumnTag)
if col == "" {
return stringutil.ToSnakeCase(field.Name)
}
return col
}
// defaultFromTag returns a "DEFAULT ..." keyword.
// If "default" tag specified to struct field, it use as the default value.
// If it doesn't specify, it returns empty string.
func (db *DB) defaultFromTag(field *reflect.StructField) (string, error) {
def := field.Tag.Get(dbDefaultTag)
if def == "" {
return "", nil
}
switch field.Type.Kind() {
case reflect.Bool:
b, err := strconv.ParseBool(def)
if err != nil {
return "", err
}
return fmt.Sprintf("DEFAULT %v", db.dialect.FormatBool(b)), nil
}
return fmt.Sprintf("DEFAULT %v", def), nil
}
func (db *DB) tableObjs(name string, obj interface{}) (objs []interface{}, rtype reflect.Type, tableName string, err error) {
switch v := reflect.Indirect(reflect.ValueOf(obj)); v.Kind() {
case reflect.Slice:
if v.Len() < 1 {
return objs, nil, "", nil
}
for i := 0; i < v.Len(); i++ {
sv := v.Index(i)
for sv.Kind() == reflect.Ptr {
sv = sv.Elem()
}
if sv.Kind() == reflect.Interface {
svk := reflect.Indirect(reflect.ValueOf(sv)).Kind()
if svk != reflect.Struct {
goto Error
}
objs = append(objs, sv.Interface())
} else {
if sv.Kind() != reflect.Struct {
goto Error
}
objs = append(objs, sv.Addr().Interface())
}
}
case reflect.Struct:
if !v.CanAddr() {
goto Error
}
objs = append(objs, v.Addr().Interface())
}
_, rtype, tableName, err = db.tableValueOf(name, objs[0])
return objs, rtype, tableName, err
Error:
return nil, nil, "", fmt.Errorf("%s: argument must be pointer to struct or slice of struct, got %T", name, obj)
}
func (db *DB) tableValueOf(name string, table interface{}) (rv reflect.Value, rt reflect.Type, tableName string, err error) {
rv = reflect.Indirect(reflect.ValueOf(table))
rt = rv.Type()
if rt.Kind() != reflect.Struct {
return rv, rt, "", fmt.Errorf("%s: a table must be struct type, got %v", name, rt)
}
tableName = db.tableName(rt)
if tableName == "" {
return rv, rt, "", fmt.Errorf("%s: a table isn't named", name)
}
return rv, rt, tableName, nil
}
func (db *DB) prepare(query string, args ...interface{}) (*sql.Stmt, error) {
defer db.logger.Print(now(), query, args...)
db.m.Lock()
defer db.m.Unlock()
if db.tx == nil {
return db.db.Prepare(query)
} else {
return db.tx.Prepare(query)
}
}
type selectFunc func(*sql.Rows, reflect.Type) (reflect.Value, error)
// TableNamer is an interface that is used to use a different table name.
type TableNamer interface {
// TableName returns the table name on DB.
TableName() string
}
// BeforeUpdater is an interface that hook for before Update.
type BeforeUpdater interface {
// BeforeUpdate called before an update by DB.Update.
// If it returns error, the update will be cancelled.
BeforeUpdate() error
}
// AfterUpdater is an interface that hook for after Update.
type AfterUpdater interface {
// AfterUpdate called after an update by DB.Update.
AfterUpdate() error
}
// BeforeInserter is an interface that hook for before Insert.
type BeforeInserter interface {
// BeforeInsert called before an insert by DB.Insert.
// If it returns error, the insert will be cancelled.
BeforeInsert() error
}
// AfterInserter is an interface that hook for after Insert.