-
Notifications
You must be signed in to change notification settings - Fork 4
/
default.go
1406 lines (1282 loc) · 35.7 KB
/
default.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 hooks contains callbacks/hooks used by ngorm.
package hooks
import (
"database/sql"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/ngorm/ngorm/builder"
"github.com/ngorm/ngorm/dialects"
"github.com/ngorm/ngorm/engine"
"github.com/ngorm/ngorm/errmsg"
"github.com/ngorm/ngorm/model"
"github.com/ngorm/ngorm/scope"
"github.com/ngorm/ngorm/search"
"github.com/ngorm/ngorm/util"
)
//Query executes sql Query without transaction. This first executes QuerySQL
//which generates appropriate SQl query then QueryExec hook is executed to
//execute the generated query.
//
// If all is well HookAfterQuery is executed, if this hook is not registered
// then no error is returned.
func Query(e *engine.Engine) error {
err := QuerySQL(e)
if err != nil {
return err
}
err = QueryExec(e)
if err != nil {
return err
}
return AfterQuery(e)
}
//QueryExec executes SQL queries and scans the result to the pointer object
//that is in e.Scope.Value.
//
// The value stored in e.Scope.Value can only either be a struct or a slice
// other types are not supported.
//
// NOTE: queries are not executed in transaction context.
func QueryExec(e *engine.Engine) error {
var isSlice, isPtr bool
var resultType reflect.Type
results := reflect.ValueOf(e.Scope.Value)
if results.Kind() == reflect.Ptr {
results = results.Elem()
}
if value, ok := e.Scope.Get(model.QueryDestination); ok {
results = reflect.Indirect(reflect.ValueOf(value))
}
if kind := results.Kind(); kind == reflect.Slice {
isSlice = true
resultType = results.Type().Elem()
results.Set(reflect.MakeSlice(results.Type(), 0, 0))
if resultType.Kind() == reflect.Ptr {
isPtr = true
resultType = resultType.Elem()
}
} else if kind != reflect.Struct {
return errors.New("unsupported destination, should be slice or struct")
}
e.RowsAffected = 0
if str, ok := e.Scope.Get(model.QueryOption); ok {
e.Scope.SQL += util.AddExtraSpaceIfExist(fmt.Sprint(str))
}
rows, err := e.SQLDB.Query(e.Scope.SQL, e.Scope.SQLVars...)
if err != nil {
return err
}
defer func() {
_ = rows.Close()
}()
columns, _ := rows.Columns()
for rows.Next() {
e.RowsAffected++
elem := results
if isSlice {
elem = reflect.New(resultType).Elem()
}
fields, err := scope.Fields(e, elem.Addr().Interface())
if err != nil {
return err
}
scope.Scan(rows, columns, fields)
if isSlice {
if isPtr {
results.Set(reflect.Append(results, elem.Addr()))
} else {
results.Set(reflect.Append(results, elem))
}
}
}
if e.RowsAffected == 0 && !isSlice {
return errmsg.ErrRecordNotFound
}
return nil
}
//QuerySQL generates SQL for queries. This uses `builder.PrepareQuery` to build
//the desired SQL query.
func QuerySQL(e *engine.Engine) error {
if orderBy, ok := e.Scope.Get(model.OrderByPK); ok {
pf, err := scope.PrimaryField(e, e.Scope.ValueOf())
if err != nil {
} else {
search.Order(e, fmt.Sprintf("%v%v %v",
e.Dialect.QueryFieldName(
scope.QuotedTableName(e, e.Scope.ValueOf())),
scope.Quote(e, pf.DBName), orderBy))
}
}
return builder.PrepareQuery(e, e.Scope.ValueOf())
}
//AfterQuery executes any call back after the Query hook has been executed. Any
//callback registered with key model.HookQueryAfterFind will be executed.
func AfterQuery(e *engine.Engine) error {
if e.Search.Preload != nil {
err := Preload(e)
if err != nil {
return err
}
}
return nil
}
//Create the hook executed to create a new record.
func Create(e *engine.Engine) error {
err := CreateSQL(e)
if err != nil {
return err
}
err = CreateExec(e)
if err != nil {
return err
}
return AfterCreate(e)
}
func create(e *engine.Engine) error {
var (
cols, placeholders []string
// The blank columns with default values
cv []string
)
fds, err := scope.Fields(e, e.Scope.ValueOf())
if err != nil {
return err
}
for _, field := range fds {
if scope.ChangeableField(e, field) {
if field.IsNormal {
if field.IsBlank && field.HasDefaultValue {
cv = append(cv, scope.Quote(e, field.DBName))
e.Scope.Set(model.BlankColWithValue, cv)
} else if !field.IsPrimaryKey || !field.IsBlank {
cols = append(cols, scope.Quote(e, field.DBName))
placeholders = append(placeholders, scope.AddToVars(e, field.Field.Interface()))
}
} else if field.Relationship != nil && field.Relationship.Kind == "belongs_to" {
for _, foreignKey := range field.Relationship.ForeignDBNames {
foreignField, err := scope.FieldByName(e, e.Scope.ValueOf(), foreignKey)
if err != nil {
return err
}
if !scope.ChangeableField(e, foreignField) {
cols = append(cols, scope.Quote(e, foreignField.DBName))
placeholders = append(placeholders,
scope.AddToVars(e, foreignField.Field.Interface()))
}
}
}
}
}
var (
returningColumn = "*"
tableName = scope.QuotedTableName(e, e.Scope.ValueOf())
extraOption string
)
primaryField, err := scope.PrimaryField(e, e.Scope.ValueOf())
if err != nil {
return err
}
if str, ok := e.Scope.Get(model.InsertOptions); ok {
extraOption = fmt.Sprint(str)
}
if primaryField != nil {
returningColumn = scope.Quote(e, primaryField.DBName)
}
lastInsertIDReturningSuffix :=
e.Dialect.LastInsertIDReturningSuffix(tableName, returningColumn)
if len(cols) == 0 {
sql := fmt.Sprintf(
"INSERT INTO %v DEFAULT VALUES%v%v",
tableName,
util.AddExtraSpaceIfExist(extraOption),
util.AddExtraSpaceIfExist(lastInsertIDReturningSuffix),
)
e.Scope.SQL = strings.Replace(sql, "$$", "?", -1)
} else {
sql := fmt.Sprintf(
"INSERT INTO %v (%v) VALUES (%v)%v%v",
scope.QuotedTableName(e, e.Scope.ValueOf()),
strings.Join(cols, ","),
strings.Join(placeholders, ","),
util.AddExtraSpaceIfExist(extraOption),
util.AddExtraSpaceIfExist(lastInsertIDReturningSuffix),
)
e.Scope.SQL = strings.Replace(sql, "$$", "?", -1)
}
return nil
}
//CreateExec executes the INSERT query and assigns primary key if it is not set
//assuming the primary key is the ID field.
func CreateExec(e *engine.Engine) error {
primaryField, err := scope.PrimaryField(e, e.Scope.ValueOf())
if err != nil {
return err
}
returningColumn := "*"
if primaryField != nil {
returningColumn = scope.Quote(e, primaryField.DBName)
}
tableName := scope.QuotedTableName(e, e.Scope.ValueOf())
lastInsertIDReturningSuffix :=
e.Dialect.LastInsertIDReturningSuffix(tableName, returningColumn)
if lastInsertIDReturningSuffix == "" || primaryField == nil {
var result sql.Result
if dialects.IsQL(e.Dialect) {
tx, err := e.SQLDB.Begin()
if err != nil {
return err
}
result, err = tx.Exec(e.Scope.SQL, e.Scope.SQLVars...)
if err != nil {
rerr := tx.Rollback()
if rerr != nil {
return rerr
}
return err
}
err = tx.Commit()
if err != nil {
return err
}
} else {
result, err = e.SQLDB.Exec(e.Scope.SQL, e.Scope.SQLVars...)
if err != nil {
return err
}
}
// set rows affected count
e.RowsAffected, _ = result.RowsAffected()
// set primary value to primary field
if primaryField != nil && primaryField.IsBlank {
primaryValue, err := result.LastInsertId()
if err != nil {
return err
}
_ = primaryField.Set(primaryValue)
}
} else {
if primaryField.Field.CanAddr() {
err := e.SQLDB.QueryRow(
e.Scope.SQL,
e.Scope.SQLVars...,
).Scan(primaryField.Field.Addr().Interface())
if err != nil {
return err
}
primaryField.IsBlank = false
e.RowsAffected = 1
} else {
return errmsg.ErrUnaddressable
}
}
return nil
}
//AfterCreate executes hooks after Creating records
func AfterCreate(e *engine.Engine) error {
if dialects.IsQL(e.Dialect) {
QLAfterCreate(e)
}
return AfterAssociation(e)
}
//QLAfterCreate hook executed after a new record has been created. This is for
//ql dialect use only.
func QLAfterCreate(e *engine.Engine) error {
ne := e.Clone()
defer engine.Put(ne)
ne.Scope.Set(model.IgnoreProtectedAttrs, true)
ne.Scope.Set(model.UpdateInterface, util.ToSearchableMap(e.Scope.Value))
ne.Scope.ContextValue(e.Scope.Value)
err := UpdateSQL(ne)
if err != nil {
return err
}
err = fixWhere(ne.Scope)
if err != nil {
return err
}
return UpdateExec(ne)
}
func fixWhere(s *model.Scope) error {
src := s.SQL
i := " id = "
rep := " id()= "
w := "WHERE"
lastWhere := strings.LastIndex(src, w)
if lastWhere == -1 {
return nil
}
lastID := strings.LastIndex(src, i)
if lastID == -1 {
return nil
}
if lastID < lastWhere {
return nil
}
s.SQL = src[:lastID] + rep + src[lastID+len(i):]
n := lastID + len(i) + 1
ni, err := strconv.Atoi(string(src[n]))
if err != nil {
return err
}
ni--
nv := s.SQLVars[ni]
switch v := nv.(type) {
case uint64:
s.SQLVars[ni] = int64(v)
}
return nil
}
//BeforeUpdate handles preparations for updating records. This just calls two
//hooks.
//
// model.HookBeforeSave
//
// If this hook succeeds then It calls
//
// model.HookBeforeUpdate
func BeforeUpdate(e *engine.Engine) error {
if !scope.HasConditions(e, e.Scope.Value) {
return errors.New("missing WHERE condition for update")
}
// set timestamps if any
err := UpdateTimestamp(e)
if err != nil {
return err
}
// assign update attrs
err = AssignUpdatingAttrs(e)
if err != nil {
return err
}
// save before associations
err = SaveBeforeAssociation(e)
if err != nil {
return err
}
return nil
}
//AfterUpdate handles things needed to be done after updating records. This just
//calls two hooks
//
// model.HookAfterUpdate
//
// If this hook succeeds then It calls
//
// model.HookAfterSave
func AfterUpdate(e *engine.Engine) error {
if !scope.HasConditions(e, e.Scope.Value) {
return errors.New("missing WHERE condition for update")
}
return AfterAssociation(e)
}
//UpdateTimestamp sets the value of UpdatedAt field.
func UpdateTimestamp(e *engine.Engine) error {
if _, ok := e.Scope.Get(model.UpdateColumn); !ok {
return scope.SetColumn(e, "UpdatedAt", time.Now())
}
return nil
}
//AssignUpdatingAttrs assigns value for the attributes that are supposed to be
//updated.
func AssignUpdatingAttrs(e *engine.Engine) error {
if attrs, ok := e.Scope.Get(model.UpdateInterface); ok {
if u, uok := scope.UpdatedAttrsWithValues(e, attrs); uok {
e.Scope.Set(model.UpdateAttrs, u)
}
}
return nil
}
//SaveBeforeAssociation saves associations on the model
func SaveBeforeAssociation(e *engine.Engine) error {
if !scope.ShouldSaveAssociation(e) {
return nil
}
fds, err := scope.Fields(e, e.Scope.Value)
if err != nil {
return err
}
for _, field := range fds {
if ok, relationship := scope.SaveFieldAsAssociation(e, field); ok && relationship.Kind == "belongs_to" {
fieldValue := field.Field.Addr().Interface()
// For the fieldValue, we need to make sure the value is saved into
// the database.
//
// We have two hooks to use here, one model.HookCreateSQL which will
// build sql for creating the new record and model.HookCreateExec
// which will execute the generates SQL.
ne := e.Clone()
defer engine.Put(ne)
ne.Scope.ContextValue(fieldValue)
err = Create(ne)
if err != nil {
return err
}
if len(relationship.ForeignFieldNames) != 0 {
// set value's foreign key
for idx, fieldName := range relationship.ForeignFieldNames {
associationForeignName := relationship.AssociationForeignDBNames[idx]
foreignField, err := scope.FieldByName(e, fieldValue, associationForeignName)
if err != nil {
//TODO log this?
} else {
err = scope.SetColumn(e, fieldName, foreignField.Field.Interface())
if err != nil {
return err
}
}
}
}
}
}
return nil
}
//AfterAssociation saves associations on the model
func AfterAssociation(e *engine.Engine) error {
if !scope.ShouldSaveAssociation(e) {
return nil
}
fds, err := scope.Fields(e, e.Scope.ValueOf())
if err != nil {
return err
}
for _, field := range fds {
if ok, rel := scope.SaveFieldAsAssociation(e, field); ok {
switch rel.Kind {
case "has_many",
"has_one",
"many_to_many":
value := field.Field
switch value.Kind() {
case reflect.Slice:
for i := 0; i < value.Len(); i++ {
ne := e.Clone()
defer engine.Put(ne)
vi := value.Index(i)
var elem interface{}
if vi.Kind() == reflect.Ptr {
elem = vi.Interface()
} else {
elem = vi.Addr().Interface()
}
ne.Scope.ContextValue(elem)
if rel.JoinTableHandler == nil && len(rel.ForeignFieldNames) != 0 {
for idx, fieldName := range rel.ForeignFieldNames {
associationForeignName := rel.AssociationForeignFieldNames[idx]
for _, fd := range fds {
if fd.Name == associationForeignName {
err = scope.SetColumn(ne, fieldName, fd.Field.Interface())
if err != nil {
return err
}
}
}
}
}
if rel.PolymorphicType != "" {
err = scope.SetColumn(ne, rel.PolymorphicType, rel.PolymorphicValue)
if err != nil {
return err
}
}
err = Create(ne)
if err != nil {
return err
}
if h := rel.JoinTableHandler; h != nil {
ne.Scope.SQL = ""
ne.Scope.SQLVars = nil
expr, err := scope.AddJoinRelation(h.TableName, h, ne, e.Scope.Value, ne.Scope.Value)
if err != nil {
return err
}
if dialects.IsQL(e.Dialect) {
expr.Q = util.WrapTX(expr.Q)
tx, err := ne.SQLDB.Begin()
if err != nil {
return err
}
_, err = tx.Exec(expr.Q, expr.Args...)
if err != nil {
tx.Rollback()
return err
}
if err = tx.Commit(); err != nil {
return err
}
} else {
_, err = ne.SQLDB.Exec(expr.Q, expr.Args...)
if err != nil {
return err
}
}
}
}
default:
fieldValue := field.Field.Addr().Interface()
ne := e.Clone()
defer engine.Put(ne)
ne.Scope.ContextValue(fieldValue)
if rel.PolymorphicType != "" {
err = scope.SetColumn(ne, rel.PolymorphicType, rel.PolymorphicValue)
if err != nil {
return err
}
}
if len(rel.ForeignFieldNames) != 0 {
// set value's foreign key
for idx, fieldName := range rel.ForeignFieldNames {
associationForeignName := rel.AssociationForeignFieldNames[idx]
for _, fd := range fds {
if fd.Name == associationForeignName {
err = scope.SetColumn(ne, fieldName, fd.Field.Interface())
if err != nil {
return err
}
}
}
}
}
err = Create(ne)
if err != nil {
return err
}
}
}
}
}
return nil
}
//CreateSQL generates SQL for creating new record
func CreateSQL(e *engine.Engine) error {
if scope.ShouldSaveAssociation(e) {
err := SaveBeforeAssociation(e)
if err != nil {
return err
}
}
err := UpdateTimestamp(e)
if err != nil {
return err
}
err = create(e)
if err != nil {
return err
}
buf := util.B.Get()
defer util.B.Put(buf)
if e.Dialect.GetName() == "ql" || e.Dialect.GetName() == "ql-mem" {
_, _ = buf.WriteString("BEGIN TRANSACTION;\n")
}
if e.Scope.MultiExpr {
for _, expr := range e.Scope.Exprs {
_, _ = buf.WriteString("\t" + expr.Q + ";\n")
}
}
_, _ = buf.WriteString("\t" + e.Scope.SQL + ";\n")
if e.Dialect.GetName() == "ql" || e.Dialect.GetName() == "ql-mem" {
_, _ = buf.WriteString("COMMIT;")
}
e.Scope.SQL = buf.String()
return nil
}
//UpdateSQL builds query for updating records.
func UpdateSQL(e *engine.Engine) error {
var sqls []string
err := AssignUpdatingAttrs(e)
if err != nil {
return err
}
if updateAttrs, ok := e.Scope.Get(model.UpdateAttrs); ok {
for column, value := range updateAttrs.(map[string]interface{}) {
sqls = append(sqls, fmt.Sprintf("%v = %v",
scope.Quote(e, column),
scope.AddToVars(e, value)))
}
} else {
fds, err := scope.Fields(e, e.Scope.Value)
if err != nil {
return err
}
for _, field := range fds {
if scope.ChangeableField(e, field) {
if !field.IsPrimaryKey && field.IsNormal {
sqls = append(sqls, fmt.Sprintf("%v = %v",
scope.Quote(e, field.DBName),
scope.AddToVars(e, field.Field.Interface())))
} else if rel := field.Relationship; rel != nil && rel.Kind == "belongs_to" {
for _, foreignKey := range rel.ForeignDBNames {
foreignField, err := scope.FieldByName(e, e.Scope.Value, foreignKey)
if err != nil {
//TODO log this?
} else {
if !scope.ChangeableField(e, foreignField) {
sqls = append(sqls,
fmt.Sprintf("%v = %v",
scope.Quote(e, foreignField.DBName),
scope.AddToVars(e, foreignField.Field.Interface())))
}
}
}
}
}
}
}
var extraOption string
if str, ok := e.Scope.Get(model.UpdateOptions); ok {
extraOption = fmt.Sprint(str)
}
if len(sqls) > 0 {
c, err := builder.CombinedCondition(e, e.Scope.Value)
if err != nil {
return err
}
e.Scope.SQL = fmt.Sprintf(
"UPDATE %v SET %v%v%v",
scope.QuotedTableName(e, e.Scope.Value),
strings.Join(sqls, ", "),
util.AddExtraSpaceIfExist(c),
util.AddExtraSpaceIfExist(extraOption),
)
}
if dialects.IsQL(e.Dialect) {
e.Scope.SQL = util.WrapTX(e.Scope.SQL)
}
return nil
}
//UpdateExec executes UPDATE sql. This assumes the query is already in
//e.Scope.SQL.
func UpdateExec(e *engine.Engine) error {
if e.Scope.SQL == "" {
return errors.New("missing update sql ")
}
tx, err := e.SQLDB.Begin()
if err != nil {
return err
}
result, err := tx.Exec(e.Scope.SQL, e.Scope.SQLVars...)
if err != nil {
rerr := tx.Rollback()
if rerr != nil {
return rerr
}
return err
}
r, err := result.RowsAffected()
if err != nil {
return err
}
e.RowsAffected = r
return tx.Commit()
}
//Update generates and executes sql query for updating records.This relies on
//two hooks.
// model.HookUpdateSQL
// Which generates the sql for UPDATE
//
// model.HookUpdateExec
//which executes the UPDATE sql.
func Update(e *engine.Engine) error {
// run before update hooks
err := BeforeUpdate(e)
if err != nil {
return err
}
// generate update sql
err = UpdateSQL(e)
if err != nil {
return err
}
// execute update sql
err = UpdateExec(e)
if err != nil {
return err
}
// execute update sql
return AfterUpdate(e)
}
// DeleteSQL generatesSQL for deleting records.
func DeleteSQL(e *engine.Engine) error {
var extraOption string
if str, ok := e.Scope.Get(model.DeleteOption); ok {
extraOption = fmt.Sprint(str)
}
if e.Dialect.HasColumn(scope.TableName(e, e.Scope.Value), "DeletedAt") {
c, err := builder.CombinedCondition(e, e.Scope.Value)
if err != nil {
return err
}
e.Scope.SQL = fmt.Sprintf(
"UPDATE %v SET deleted_at=%v%v%v",
scope.QuotedTableName(e, e.Scope.Value),
scope.AddToVars(e, e.Now()),
util.AddExtraSpaceIfExist(c),
util.AddExtraSpaceIfExist(extraOption),
)
if e.Dialect.GetName() == "ql" || e.Dialect.GetName() == "ql-mem" {
e.Scope.SQL = util.WrapTX(e.Scope.SQL)
}
} else {
c, err := builder.CombinedCondition(e, e.Scope.Value)
if err != nil {
return err
}
e.Scope.SQL = fmt.Sprintf(
"DELETE FROM %v%v%v",
scope.QuotedTableName(e, e.Scope.Value),
util.AddExtraSpaceIfExist(c),
util.AddExtraSpaceIfExist(extraOption),
)
if e.Dialect.GetName() == "ql" || e.Dialect.GetName() == "ql-mem" {
e.Scope.SQL = util.WrapTX(e.Scope.SQL)
}
}
return nil
}
// BeforeDelete is called before deleting any record
func BeforeDelete(e *engine.Engine) error {
if !scope.HasConditions(e, e.Scope.Value) {
return errors.New("Missing WHERE clause while deleting")
}
return nil
}
// Delete deletes records. This makes sure to call BeforeDelete hook before
// deleting anything and also calls AfterDelete before exiting.
func Delete(e *engine.Engine) error {
err := BeforeDelete(e)
if err != nil {
return err
}
err = DeleteSQL(e)
if err != nil {
return err
}
if dialects.IsQL(e.Dialect) {
tx, err := e.SQLDB.Begin()
if err != nil {
return err
}
result, err := tx.Exec(e.Scope.SQL, e.Scope.SQLVars...)
if err != nil {
_ = tx.Rollback()
return err
}
a, err := result.RowsAffected()
if err != nil {
return err
}
e.RowsAffected = a
err = tx.Commit()
if err != nil {
return err
}
} else {
result, err := e.SQLDB.Exec(e.Scope.SQL, e.Scope.SQLVars...)
if err != nil {
return err
}
a, err := result.RowsAffected()
if err != nil {
return err
}
e.RowsAffected = a
}
return nil
}
// Preload executes preload conditions.
func Preload(e *engine.Engine) error {
if e.Search.Preload == nil {
return nil
}
preloadedMap := map[string]bool{}
fields, err := scope.Fields(e, e.Scope.Value)
if err != nil {
return err
}
for _, preload := range e.Search.Preload {
var (
preloadFields = strings.Split(preload.Schema, ".")
cs = e
currentFields = fields
)
for idx, preloadField := range preloadFields {
var conds []interface{}
if cs == nil {
continue
}
// if not preloaded
if preloadKey := strings.Join(preloadFields[:idx+1], "."); !preloadedMap[preloadKey] {
// assign search conditions to last preload
if idx == len(preloadFields)-1 {
conds = preload.Conditions
}
for _, field := range currentFields {
if field.Name != preloadField || field.Relationship == nil {
continue
}
switch field.Relationship.Kind {
case "has_one":
err = PreloadHasOne(cs, field, conds)
if err != nil {
return err
}
case "has_many":
err = PreloadHasMany(cs, field, conds)
if err != nil {
return err
}
case "belongs_to":
err = PreloadBelongsTo(cs, field, conds)
if err != nil {
return err
}
case "many_to_many":
err = PreloadManyToMany(cs, field, conds)
if err != nil {
return err
}
default:
return fmt.Errorf("hooks: can't preload %sunsupported relation",
field.Relationship.Kind)
}
preloadedMap[preloadKey] = true
break
}
if !preloadedMap[preloadKey] {
m, err := scope.GetModelStruct(e, e.Scope.Value)
if err != nil {
return err
}
return fmt.Errorf("can't preload field %s for %s",
preloadField, m.ModelType)
}
}
// preload next level
if idx < len(preloadFields)-1 {
cs, err = ColumnAsScope(cs, preloadField)
if err != nil {
return err
}
currentFields, err = scope.Fields(cs, cs.Scope.Value)
if err != nil {
return err
}
}
}
}
return nil
}
// PreloadBelongsTo preloads belongs_to relationship
func PreloadBelongsTo(e *engine.Engine, field *model.Field, conditions []interface{}) error {
relation := field.Relationship
// preload conditions
pdb, pCond := PreloadDBWithConditions(e, conditions)
// get relations's primary keys
primaryKeys := util.ColumnAsArray(relation.ForeignFieldNames, e.Scope.Value)
if len(primaryKeys) == 0 {
return nil
}
// find relations
query := fmt.Sprintf("%v IN (%v)",
scope.ToQueryCondition(e, relation.AssociationForeignDBNames),
util.ToQueryMarks(primaryKeys))
values := util.ToQueryValues(primaryKeys)
results := util.MakeSlice(field.Struct.Type)
search.Where(pdb, query, values...)
search.Inline(pdb, pCond...)
pdb.Scope.ContextValue(results)
err := Query(pdb)
if err != nil {
return err
}
// assign find results
rVal := reflect.ValueOf(results)
if rVal.Kind() == reflect.Ptr {
rVal = rVal.Elem()
}
iScopeVal := reflect.ValueOf(e.Scope.Value)
if iScopeVal.Kind() == reflect.Ptr {
iScopeVal = iScopeVal.Elem()
}
for i := 0; i < rVal.Len(); i++ {
result := rVal.Index(i)
if iScopeVal.Kind() == reflect.Slice {
value := util.GetValueFromFields(result, relation.AssociationForeignFieldNames)
for j := 0; j < iScopeVal.Len(); j++ {
object := iScopeVal.Index(j)
if object.Kind() == reflect.Ptr {
object = object.Elem()
}
if util.EqualAsString(util.GetValueFromFields(object, relation.ForeignFieldNames), value) {
object.FieldByName(field.Name).Set(result)
}
}
} else {
err := field.Set(result)
if err != nil {
return err
}
}
}
return nil
}