-
Notifications
You must be signed in to change notification settings - Fork 52
/
hood.go
1343 lines (1229 loc) · 31.3 KB
/
hood.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
// Package hood provides a database agnostic, transactional ORM for the sql
// package
package hood
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
type (
// Hood is an ORM handle.
Hood struct {
Db *sql.DB
Dialect Dialect
Log bool
qo qo // the query object
schema Schema // keeping track of the schema
dryRun bool // if actual sql is executed or not
selectPaths []Path
selectTable string
where []interface{}
markerPos int
limit int
offset int
orderBy Path
order string
joins []*join
groupBy Path
havingCond string
havingArgs []interface{}
firstTxError error
mutex sync.Mutex
}
// Id represents a auto-incrementing integer primary key type.
Id int64
// Index represents a table index and is returned via the Indexed interface.
Index struct {
Name string
Columns []string
Unique bool
}
// Indexes represents an array of indexes.
Indexes []*Index
// Created denotes a timestamp field that is automatically set on insert.
Created struct {
time.Time
}
// Updated denotes a timestamp field that is automatically set on update.
Updated struct {
time.Time
}
// Model represents a parsed schema interface{}.
Model struct {
Pk *ModelField
Table string
Fields []*ModelField
Indexes Indexes
}
// ModelField represents a schema field of a parsed model.
ModelField struct {
Name string // Column name
Value interface{} // Value
SqlTags map[string]string // The sql struct tags for this field
ValidateTags map[string]string // The validate struct tags for this field
RawTag reflect.StructTag // The raw tag
}
// Schema is a collection of models
Schema []*Model
// Config represents an environment entry in the config.json file
Config map[string]string
// Environment represents a configuration map for each environment specified
// in the config.json file
Environment map[string]Config
// Path denotes a combined sql identifier such as 'table.column'
Path string
// Indexed defines the indexes for a table. You can invoke Add on the passed instance.
Indexed interface {
Indexes(indexes *Indexes)
}
// TODO: implement aggregate function types
//
// // Avg denotes an average aggregate function argument
// Avg interface{}
// // Min denotes an minimum aggregate function argument
// Min interface{}
// // Max denotes an maximum aggregate function argument
// Max interface{}
// // Std denotes an standard derivation aggregate function argument
// Std interface{}
// // Sum denotes an sum aggregate function argument
// Sum interface{}
qo interface {
Prepare(query string) (*sql.Stmt, error)
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
}
clause struct {
a Path
op string
b interface{}
}
whereClause clause
andClause clause
orClause clause
join struct {
join Join
table string
a Path
b Path
}
)
const (
InnerJoin = Join(iota)
LeftJoin
RightJoin
FullJoin
)
type Join int
// Add adds an index
func (ix *Indexes) Add(name string, columns ...string) {
*ix = append(*ix, &Index{Name: name, Columns: columns, Unique: false})
}
// AddUnique adds an unique index
func (ix *Indexes) AddUnique(name string, columns ...string) {
*ix = append(*ix, &Index{Name: name, Columns: columns, Unique: true})
}
// Quote quotes the path using the given dialects Quote method
func (p Path) Quote(d Dialect) string {
sep := "."
a := []string{}
c := strings.Split(string(p), sep)
for _, v := range c {
a = append(a, d.Quote(v))
}
return strings.Join(a, sep)
}
// PrimaryKey tests if the field is declared using the sql tag "pk" or is of type Id
func (field *ModelField) PrimaryKey() bool {
_, isPk := field.SqlTags["pk"]
_, isId := field.Value.(Id)
return isPk || isId
}
// NotNull tests if the field is declared as NOT NULL
func (field *ModelField) NotNull() bool {
_, ok := field.SqlTags["notnull"]
return ok
}
// Default returns the default value for the field
func (field *ModelField) Default() string {
return field.SqlTags["default"]
}
// Size returns the field size, e.g. for varchars
func (field *ModelField) Size() int {
v, ok := field.SqlTags["size"]
if ok {
i, _ := strconv.Atoi(v)
return i
}
return 0
}
// Zero tests wether or not the field is set
func (field *ModelField) Zero() bool {
x := field.Value
return x == nil || x == reflect.Zero(reflect.TypeOf(x)).Interface()
}
// String returns the field string value and a bool flag indicating if the
// conversion was successful
func (field *ModelField) String() (string, bool) {
t, ok := field.Value.(string)
return t, ok
}
// Int returns the field int value and a bool flag indication if the conversion
// was successful
func (field *ModelField) Int() (int64, bool) {
switch t := field.Value.(type) {
case int, int8, int16, int32, int64:
return reflect.ValueOf(t).Int(), true
case uint, uint8, uint16, uint32, uint64:
return int64(reflect.ValueOf(t).Uint()), true
}
return 0, false
}
func (field *ModelField) GoDeclaration() string {
t := ""
if x := field.RawTag; len(x) > 0 {
t = fmt.Sprintf("\t`%s`", x)
}
return fmt.Sprintf(
"%s\t%s%s",
snakeToUpperCamel(field.Name),
reflect.TypeOf(field.Value).String(),
t,
)
}
// Validate tests if the field conforms to it's validation constraints specified
// int the "validate" struct tag
func (field *ModelField) Validate() error {
// length
if tuple, ok := field.ValidateTags["len"]; ok {
s, ok := field.String()
if ok {
if err := validateLen(s, tuple, field.Name); err != nil {
return err
}
}
}
// range
if tuple, ok := field.ValidateTags["range"]; ok {
i, ok := field.Int()
if ok {
if err := validateRange(i, tuple, field.Name); err != nil {
return err
}
}
}
// presence
if _, ok := field.ValidateTags["presence"]; ok {
if field.Zero() {
return NewValidationError(ValidationErrorValueNotSet, field.Name)
}
}
// regexp
if reg, ok := field.ValidateTags["regexp"]; ok {
s, ok := field.String()
if ok {
if err := validateRegexp(s, reg, field.Name); err != nil {
return err
}
}
}
return nil
}
func parseTuple(tuple string) (string, string) {
c := strings.Split(tuple, ":")
a := c[0]
b := c[1]
if len(c) != 2 || (len(a) == 0 && len(b) == 0) {
panic("invalid validation tuple")
}
return a, b
}
func validateLen(s, tuple, field string) error {
a, b := parseTuple(tuple)
if len(a) > 0 {
min, err := strconv.Atoi(a)
if err != nil {
panic(err)
}
if len(s) < min {
return NewValidationError(ValidationErrorValueTooShort, field)
}
}
if len(b) > 0 {
max, err := strconv.Atoi(b)
if err != nil {
panic(err)
}
if len(s) > max {
return NewValidationError(ValidationErrorValueTooLong, field)
}
}
return nil
}
func validateRange(i int64, tuple, field string) error {
a, b := parseTuple(tuple)
if len(a) > 0 {
min, err := strconv.ParseInt(a, 10, 64)
if err != nil {
return err
}
if i < min {
return NewValidationError(ValidationErrorValueTooSmall, field)
}
}
if len(b) > 0 {
max, err := strconv.ParseInt(b, 10, 64)
if err != nil {
return err
}
if i > max {
return NewValidationError(ValidationErrorValueTooBig, field)
}
}
return nil
}
func validateRegexp(s, reg, field string) error {
matched, err := regexp.MatchString(reg, s)
if err != nil {
return err
}
if !matched {
return NewValidationError(ValidationErrorValueNotMatch, field)
}
return nil
}
func (index *Index) GoDeclaration() string {
u := ""
if index.Unique {
u = "Unique"
}
return fmt.Sprintf(
"indexes.Add%s(\"%s\", \"%s\")",
u,
index.Name,
strings.Join(index.Columns, "\", \""),
)
}
func (model *Model) Validate() error {
for _, field := range model.Fields {
err := field.Validate()
if err != nil {
return err
}
}
return nil
}
func (model *Model) GoDeclaration() string {
tableName := snakeToUpperCamel(model.Table)
a := []string{fmt.Sprintf("type %s struct {", tableName)}
for _, f := range model.Fields {
a = append(a, "\t"+f.GoDeclaration())
}
a = append(a, "}")
if len(model.Indexes) > 0 {
a = append(a,
fmt.Sprintf("\nfunc (table *%s) Indexes(indexes *hood.Indexes) {", tableName),
)
for _, i := range model.Indexes {
a = append(a, "\t"+i.GoDeclaration())
}
a = append(a, "}")
}
return strings.Join(a, "\n")
}
func (schema Schema) GoDeclaration() string {
a := []string{}
for _, m := range schema {
a = append(a, m.GoDeclaration())
}
return strings.Join(a, "\n\n")
}
var registeredDialects map[string]Dialect = make(map[string]Dialect)
// New creates a new Hood using the specified DB and dialect.
func New(database *sql.DB, dialect Dialect) *Hood {
hood := &Hood{
Db: database,
Dialect: dialect,
qo: database,
}
hood.Reset()
return hood
}
// Dry creates a new Hood instance for schema generation.
func Dry() *Hood {
hd := New(nil, nil)
hd.dryRun = true
return hd
}
// Open opens a new database connection using the specified driver and data
// source name. It matches the sql.Open method signature.
func Open(driverName, dataSourceName string) (*Hood, error) {
database, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
dialect := registeredDialects[driverName]
if dialect == nil {
return nil, errors.New("no dialect registered for driver name")
}
return New(database, dialect), nil
}
// Load opens a new database from a config.json file with the specified
// environment, or development if none is specified.
func Load(path, env string) (*Hood, error) {
if env == "" {
env = "development"
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
dec := json.NewDecoder(f)
var envs Environment
err = dec.Decode(&envs)
if err != nil {
return nil, err
}
conf, ok := envs[env]
if !ok {
return nil, fmt.Errorf("config entry for specified environment '%s' not found", env)
}
return Open(conf["driver"], conf["source"])
}
// RegisterDialect registers a new dialect using the specified name and dialect.
func RegisterDialect(name string, dialect Dialect) {
registeredDialects[name] = dialect
}
// Reset resets the internal state.
func (hood *Hood) Reset() {
hood.selectPaths = nil
hood.selectTable = ""
hood.where = []interface{}{}
hood.markerPos = 0
hood.limit = 0
hood.offset = 0
hood.orderBy = ""
hood.order = ""
hood.joins = []*join{}
hood.groupBy = ""
hood.havingCond = ""
hood.havingArgs = make([]interface{}, 0, 20)
}
// Copy copies the hood instance for safe context manipulation.
func (hood *Hood) Copy() *Hood {
c := new(Hood)
*c = *hood
return c
}
// Begin starts a new transaction and returns a copy of Hood. You have to call
// subsequent methods on the newly returned object.
func (hood *Hood) Begin() *Hood {
if hood.IsTransaction() {
panic("cannot start nested transaction")
}
c := hood.Copy()
q, err := hood.Db.Begin()
if err != nil {
panic(err)
}
c.firstTxError = nil
c.qo = q
return c
}
func (hood *Hood) logSql(sql string, args ...interface{}) {
if hood.Log {
a := make([]interface{}, 0, len(args))
for _, v := range args {
switch t := v.(type) {
case []uint8:
a = append(a, fmt.Sprintf("<[]byte#%d>", len(t)))
default:
a = append(a, v)
}
}
log.Printf("\x1b[35mSQL: %s ARGS: %v\x1b[0m\n", sql, a)
}
}
func (hood *Hood) updateTxError(e error) error {
if e != nil {
if hood.Log {
log.Println("ERROR:", e)
}
// don't shadow the first error
if hood.firstTxError == nil {
hood.firstTxError = e
}
}
return e
}
// Commit commits a started transaction and will report the first error that
// occurred inside the transaction.
func (hood *Hood) Commit() error {
if v, ok := hood.qo.(*sql.Tx); ok {
err := v.Commit()
hood.updateTxError(err)
return hood.firstTxError
}
return nil
}
// Rollback rolls back a started transaction.
func (hood *Hood) Rollback() error {
if v, ok := hood.qo.(*sql.Tx); ok {
return v.Rollback()
}
return nil
}
// IsTransaction returns wether the hood object represents an active transaction or not.
func (hood *Hood) IsTransaction() bool {
_, ok := hood.qo.(*sql.Tx)
return ok
}
// GoSchema returns a string of the schema file in Go syntax.
func (hood *Hood) GoSchema() string {
timeRequired := false
L:
for _, m := range hood.schema {
for _, f := range m.Fields {
switch f.Value.(type) {
case time.Time:
timeRequired = true
break L
}
}
}
head := []string{
"package db",
"",
"import (",
"\t\"github.com/eaigner/hood\"",
}
if timeRequired {
head = append(head, "\t\"time\"")
}
head = append(head, []string{")\n\n", hood.schema.GoDeclaration()}...)
return strings.Join(head, "\n")
}
// Select adds a SELECT clause to the query with the specified table and columns.
// The table can either be a string or it's name can be inferred from the passed
// interface{} type.
func (hood *Hood) Select(table interface{}, paths ...Path) *Hood {
hood.selectPaths = paths
switch f := table.(type) {
case string:
hood.selectTable = f
case interface{}:
hood.selectTable = interfaceToSnake(f)
default:
panic("invalid table")
}
return hood
}
// Where adds a WHERE clause to the query. You can concatenate using the
// And and Or methods.
func (hood *Hood) Where(a Path, op string, b interface{}) *Hood {
hood.where = append(hood.where, &whereClause{
a: a,
op: op,
b: b,
})
return hood
}
// Where adds a AND clause to the WHERE query. You can concatenate using the
// And and Or methods.
func (hood *Hood) And(a Path, op string, b interface{}) *Hood {
hood.where = append(hood.where, &andClause{
a: a,
op: op,
b: b,
})
return hood
}
// Where adds a OR clause to the WHERE query. You can concatenate using the
// And and Or methods.
func (hood *Hood) Or(a Path, op string, b interface{}) *Hood {
hood.where = append(hood.where, &orClause{
a: a,
op: op,
b: b,
})
return hood
}
// Limit adds a LIMIT clause to the query.
func (hood *Hood) Limit(limit int) *Hood {
hood.limit = limit
return hood
}
// Offset adds an OFFSET clause to the query.
func (hood *Hood) Offset(offset int) *Hood {
hood.offset = offset
return hood
}
// OrderBy adds an ORDER BY clause to the query.
func (hood *Hood) OrderBy(path Path) *Hood {
hood.orderBy = path
return hood
}
func (hood *Hood) Asc() *Hood {
hood.order = "ASC"
return hood
}
func (hood *Hood) Desc() *Hood {
hood.order = "DESC"
return hood
}
// Join performs a JOIN on tables, for example
// Join(hood.InnerJoin, &User{}, "user.id", "order.id")
func (hood *Hood) Join(op Join, table interface{}, a Path, b Path) *Hood {
hood.joins = append(hood.joins, &join{
join: op,
table: tableName(table),
a: a,
b: b,
})
return hood
}
// GroupBy adds a GROUP BY clause to the query.
func (hood *Hood) GroupBy(path Path) *Hood {
hood.groupBy = path
return hood
}
// Having adds a HAVING clause to the query.
func (hood *Hood) Having(condition string, args ...interface{}) *Hood {
hood.havingCond = condition
hood.havingArgs = append(hood.havingArgs, args...)
return hood
}
// Find performs a find using the previously specified query. If no explicit
// SELECT clause was specified earlier, the select is inferred from the passed
// interface type.
func (hood *Hood) Find(out interface{}) error {
// infer the select statement from the type if not set
if hood.selectTable == "" {
hood.Select(out)
}
query, args := hood.Dialect.QuerySql(hood)
return hood.FindSql(out, query, args...)
}
// FindSql performs a find using the specified custom sql query and arguments and
// writes the results to the specified out interface{}.
func (hood *Hood) FindSql(out interface{}, query string, args ...interface{}) error {
hood.mutex.Lock()
defer hood.mutex.Unlock()
defer hood.Reset()
panicMsg := errors.New("expected pointer to struct slice *[]struct")
if x := reflect.TypeOf(out).Kind(); x != reflect.Ptr {
panic(panicMsg)
}
sliceValue := reflect.Indirect(reflect.ValueOf(out))
if x := sliceValue.Kind(); x != reflect.Slice {
panic(panicMsg)
}
sliceType := sliceValue.Type().Elem()
if x := sliceType.Kind(); x != reflect.Struct {
panic(panicMsg)
}
hood.logSql(query, args...)
stmt, err := hood.qo.Prepare(query)
if err != nil {
return hood.updateTxError(err)
}
defer stmt.Close()
rows, err := stmt.Query(args...)
if err != nil {
return hood.updateTxError(err)
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return hood.updateTxError(err)
}
for rows.Next() {
containers := make([]interface{}, 0, len(cols))
for i := 0; i < cap(containers); i++ {
var v interface{}
containers = append(containers, &v)
}
err := rows.Scan(containers...)
if err != nil {
return err
}
// create a new row and fill
rowValue := reflect.New(sliceType)
for i, v := range containers {
key := cols[i]
value := reflect.Indirect(reflect.ValueOf(v))
name := snakeToUpperCamel(key)
field := rowValue.Elem().FieldByName(name)
if field.IsValid() {
err = hood.Dialect.SetModelValue(value, field)
if err != nil {
return err
}
}
}
// append to output
sliceValue.Set(reflect.Append(sliceValue, rowValue.Elem()))
}
return nil
}
// Exec executes a raw sql query.
func (hood *Hood) Exec(query string, args ...interface{}) (sql.Result, error) {
hood.mutex.Lock()
defer hood.mutex.Unlock()
defer hood.Reset()
query = hood.substituteMarkers(query)
hood.logSql(query, args...)
stmt, err := hood.qo.Prepare(query + ";")
if err != nil {
return nil, hood.updateTxError(err)
}
defer stmt.Close()
result, err := stmt.Exec(hood.convertSpecialTypes(args)...)
if err != nil {
return nil, hood.updateTxError(err)
}
return result, nil
}
// Query executes a query that returns rows, typically a SELECT
func (hood *Hood) Query(query string, args ...interface{}) (*sql.Rows, error) {
hood.mutex.Lock()
defer hood.mutex.Unlock()
hood.logSql(query, args...)
return hood.qo.Query(query, hood.convertSpecialTypes(args)...)
}
// QueryRow executes a query that is expected to return at most one row.
// QueryRow always return a non-nil value. Errors are deferred until Row's Scan
// method is called.
func (hood *Hood) QueryRow(query string, args ...interface{}) *sql.Row {
hood.mutex.Lock()
defer hood.mutex.Unlock()
hood.logSql(query, args...)
return hood.qo.QueryRow(query, hood.convertSpecialTypes(args)...)
// TODO: switch to this implementation, as soon as
//
// https://github.com/bmizerany/pq/issues/68
//
// is resolved!
//
//
// query = hood.substituteMarkers(query)
// if hood.Log {
// fmt.Println(query)
// }
// stmt, err := hood.qo.Prepare(query)
// if err != nil {
// panic(err)
// }
// defer stmt.Close()
// if hood.Log {
// fmt.Println(args...)
// }
// return stmt.QueryRow(hood.convertSpecialTypes(args)...)
}
func (hood *Hood) convertSpecialTypes(a []interface{}) []interface{} {
args := make([]interface{}, 0, len(a))
for _, v := range a {
args = append(args, hood.Dialect.ConvertHoodType(v))
}
return args
}
// Validate validates the provided struct
func (hood *Hood) Validate(f interface{}) error {
model, err := interfaceToModel(f)
if err != nil {
return err
}
err = model.Validate()
if err != nil {
return err
}
// call validate methods
err = callModelMethod(f, "Validate", true)
if err != nil {
return err
}
return nil
}
func callModelMethod(f interface{}, methodName string, isPrefix bool) error {
typ := reflect.TypeOf(f)
for i := 0; i < typ.NumMethod(); i++ {
method := typ.Method(i)
if (isPrefix && strings.HasPrefix(method.Name, methodName)) ||
(!isPrefix && method.Name == methodName) {
ft := method.Func.Type()
if ft.NumOut() == 1 &&
ft.NumIn() == 1 {
v := reflect.ValueOf(f).Method(i).Call([]reflect.Value{})
if vdErr, ok := v[0].Interface().(error); ok {
return vdErr
}
}
}
}
return nil
}
// Save performs an INSERT, or UPDATE if the passed structs Id is set.
func (hood *Hood) Save(f interface{}) (Id, error) {
var (
id Id = -1
err error
)
model, err := interfaceToModel(f)
if err != nil {
return id, err
}
err = model.Validate()
if err != nil {
return id, err
}
err = callModelMethod(f, "BeforeSave", false)
if err != nil {
return id, err
}
if model.Pk == nil {
panic("no primary key field")
}
now := time.Now()
isUpdate := model.Pk != nil && !model.Pk.Zero()
if isUpdate {
err = callModelMethod(f, "BeforeUpdate", false)
if err != nil {
return id, err
}
for _, f := range model.Fields {
switch f.Value.(type) {
case Updated:
f.Value = now
}
}
id, err = hood.Dialect.Update(hood, model)
if err == nil {
err = callModelMethod(f, "AfterUpdate", false)
}
} else {
err = callModelMethod(f, "BeforeInsert", false)
if err != nil {
return id, err
}
for _, f := range model.Fields {
switch f.Value.(type) {
case Created, Updated:
f.Value = now
}
}
id, err = hood.Dialect.Insert(hood, model)
if err == nil {
err = callModelMethod(f, "AfterInsert", false)
}
}
if err == nil {
err = callModelMethod(f, "AfterSave", false)
}
if id != -1 {
// update model id after save
structValue := reflect.Indirect(reflect.ValueOf(f))
for i := 0; i < structValue.NumField(); i++ {
field := structValue.Field(i)
switch field.Interface().(type) {
case Id:
field.SetInt(int64(id))
case Updated:
field.Set(reflect.ValueOf(Updated{now}))
case Created:
if !isUpdate {
field.Set(reflect.ValueOf(Created{now}))
}
}
}
}
return id, err
}
func (hood *Hood) doAll(f interface{}, doFunc func(f2 interface{}) (Id, error)) ([]Id, error) {
panicMsg := "expected pointer to struct slice *[]struct"
if reflect.TypeOf(f).Kind() != reflect.Ptr {
panic(panicMsg)
}
if reflect.TypeOf(f).Elem().Kind() != reflect.Slice {
panic(panicMsg)
}
sliceValue := reflect.ValueOf(f).Elem()
sliceLen := sliceValue.Len()
ids := make([]Id, 0, sliceLen)
for i := 0; i < sliceLen; i++ {
id, err := doFunc(sliceValue.Index(i).Addr().Interface())
if err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, nil
}
// SaveAll performs an INSERT or UPDATE on a slice of structs.
func (hood *Hood) SaveAll(f interface{}) ([]Id, error) {
return hood.doAll(f, func(f2 interface{}) (Id, error) {
return hood.Save(f2)
})
}
// Delete deletes the row matching the specified structs Id.
func (hood *Hood) Delete(f interface{}) (Id, error) {
model, err := interfaceToModel(f)
if err != nil {
return -1, err
}
err = callModelMethod(f, "BeforeDelete", false)
if err != nil {
return -1, err
}
if model.Pk == nil {
panic("no primary key field")
}
id, err := hood.Dialect.Delete(hood, model)
if err != nil {
return -1, err
}
return id, callModelMethod(f, "AfterDelete", false)
}
// DeleteAll deletes the rows matching the specified struct slice Ids.
func (hood *Hood) DeleteAll(f interface{}) ([]Id, error) {
return hood.doAll(f, func(f2 interface{}) (Id, error) {
return hood.Delete(f2)
})
}
// DeleteFrom deletes the rows matched by the previous Where clause. table can
// either be a table struct or a string.
//
// Example: