query.go
35.8 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
package orm
import (
"context"
"errors"
"fmt"
"io"
"reflect"
"strings"
"sync"
"time"
"github.com/go-pg/pg/v10/internal"
"github.com/go-pg/pg/v10/types"
)
const (
SelectOp = "SELECT"
InsertOp = "INSERT"
UpdateOp = "UPDATE"
DeleteOp = "DELETE"
CreateTableOp = "CREATE TABLE"
)
type queryFlag uint8
const (
implicitModelFlag queryFlag = 1 << iota
deletedFlag
allWithDeletedFlag
)
type withQuery struct {
name string
query QueryAppender
}
type joinQuery struct {
join *SafeQueryAppender
on []*condAppender
}
func (q *joinQuery) AppendOn(app *condAppender) {
q.on = append(q.on, app)
}
type columnValue struct {
column string
value *SafeQueryAppender
}
type union struct {
expr string
query *Query
}
type Query struct {
ctx context.Context
db DB
stickyErr error
model TableModel
flags queryFlag
with []withQuery
tables []QueryAppender
distinctOn []*SafeQueryAppender
columns []QueryAppender
set []QueryAppender
modelValues map[string]*SafeQueryAppender
extraValues []*columnValue
where []queryWithSepAppender
updWhere []queryWithSepAppender
group []QueryAppender
having []*SafeQueryAppender
union []*union
joins []*joinQuery
joinAppendOn func(app *condAppender)
order []QueryAppender
limit int
offset int
selFor *SafeQueryAppender
onConflict *SafeQueryAppender
returning []*SafeQueryAppender
}
func NewQuery(db DB, model ...interface{}) *Query {
ctx := context.Background()
if db != nil {
ctx = db.Context()
}
q := &Query{ctx: ctx}
return q.DB(db).Model(model...)
}
func NewQueryContext(c context.Context, db DB, model ...interface{}) *Query {
return NewQuery(db, model...).Context(c)
}
// New returns new zero Query bound to the current db.
func (q *Query) New() *Query {
cp := &Query{
ctx: q.ctx,
db: q.db,
model: q.model,
flags: q.flags,
}
return cp.withFlag(implicitModelFlag)
}
// Clone clones the Query.
func (q *Query) Clone() *Query {
var modelValues map[string]*SafeQueryAppender
if len(q.modelValues) > 0 {
modelValues = make(map[string]*SafeQueryAppender, len(q.modelValues))
for k, v := range q.modelValues {
modelValues[k] = v
}
}
copy := &Query{
ctx: q.ctx,
db: q.db,
stickyErr: q.stickyErr,
model: q.model,
flags: q.flags,
with: q.with[:len(q.with):len(q.with)],
tables: q.tables[:len(q.tables):len(q.tables)],
distinctOn: q.distinctOn[:len(q.distinctOn):len(q.distinctOn)],
columns: q.columns[:len(q.columns):len(q.columns)],
set: q.set[:len(q.set):len(q.set)],
modelValues: modelValues,
extraValues: q.extraValues[:len(q.extraValues):len(q.extraValues)],
where: q.where[:len(q.where):len(q.where)],
updWhere: q.updWhere[:len(q.updWhere):len(q.updWhere)],
joins: q.joins[:len(q.joins):len(q.joins)],
group: q.group[:len(q.group):len(q.group)],
having: q.having[:len(q.having):len(q.having)],
union: q.union[:len(q.union):len(q.union)],
order: q.order[:len(q.order):len(q.order)],
limit: q.limit,
offset: q.offset,
selFor: q.selFor,
onConflict: q.onConflict,
returning: q.returning[:len(q.returning):len(q.returning)],
}
return copy
}
func (q *Query) err(err error) *Query {
if q.stickyErr == nil {
q.stickyErr = err
}
return q
}
func (q *Query) hasFlag(flag queryFlag) bool {
return hasFlag(q.flags, flag)
}
func hasFlag(flags, flag queryFlag) bool {
return flags&flag != 0
}
func (q *Query) withFlag(flag queryFlag) *Query {
q.flags |= flag
return q
}
func (q *Query) withoutFlag(flag queryFlag) *Query {
q.flags &= ^flag
return q
}
func (q *Query) Context(c context.Context) *Query {
q.ctx = c
return q
}
func (q *Query) DB(db DB) *Query {
q.db = db
return q
}
func (q *Query) Model(model ...interface{}) *Query {
var err error
switch l := len(model); {
case l == 0:
q.model = nil
case l == 1:
q.model, err = newTableModel(model[0])
case l > 1:
q.model, err = newTableModel(&model)
}
if err != nil {
q = q.err(err)
}
return q.withoutFlag(implicitModelFlag)
}
func (q *Query) TableModel() TableModel {
return q.model
}
func (q *Query) isSoftDelete() bool {
if q.model != nil {
return q.model.Table().SoftDeleteField != nil && !q.hasFlag(allWithDeletedFlag)
}
return false
}
// Deleted adds `WHERE deleted_at IS NOT NULL` clause for soft deleted models.
func (q *Query) Deleted() *Query {
if q.model != nil {
if err := q.model.Table().mustSoftDelete(); err != nil {
return q.err(err)
}
}
return q.withFlag(deletedFlag).withoutFlag(allWithDeletedFlag)
}
// AllWithDeleted changes query to return all rows including soft deleted ones.
func (q *Query) AllWithDeleted() *Query {
if q.model != nil {
if err := q.model.Table().mustSoftDelete(); err != nil {
return q.err(err)
}
}
return q.withFlag(allWithDeletedFlag).withoutFlag(deletedFlag)
}
// With adds subq as common table expression with the given name.
func (q *Query) With(name string, subq *Query) *Query {
return q._with(name, newSelectQuery(subq))
}
func (q *Query) WithInsert(name string, subq *Query) *Query {
return q._with(name, newInsertQuery(subq))
}
func (q *Query) WithUpdate(name string, subq *Query) *Query {
return q._with(name, newUpdateQuery(subq, false))
}
func (q *Query) WithDelete(name string, subq *Query) *Query {
return q._with(name, newDeleteQuery(subq))
}
func (q *Query) _with(name string, subq QueryAppender) *Query {
q.with = append(q.with, withQuery{
name: name,
query: subq,
})
return q
}
// WrapWith creates new Query and adds to it current query as
// common table expression with the given name.
func (q *Query) WrapWith(name string) *Query {
wrapper := q.New()
wrapper.with = q.with
q.with = nil
wrapper = wrapper.With(name, q)
return wrapper
}
func (q *Query) Table(tables ...string) *Query {
for _, table := range tables {
q.tables = append(q.tables, fieldAppender{table})
}
return q
}
func (q *Query) TableExpr(expr string, params ...interface{}) *Query {
q.tables = append(q.tables, SafeQuery(expr, params...))
return q
}
func (q *Query) Distinct() *Query {
q.distinctOn = make([]*SafeQueryAppender, 0)
return q
}
func (q *Query) DistinctOn(expr string, params ...interface{}) *Query {
q.distinctOn = append(q.distinctOn, SafeQuery(expr, params...))
return q
}
// Column adds a column to the Query quoting it according to PostgreSQL rules.
// Does not expand params like ?TableAlias etc.
// ColumnExpr can be used to bypass quoting restriction or for params expansion.
// Column name can be:
// - column_name,
// - table_alias.column_name,
// - table_alias.*.
func (q *Query) Column(columns ...string) *Query {
for _, column := range columns {
if column == "_" {
if q.columns == nil {
q.columns = make([]QueryAppender, 0)
}
continue
}
q.columns = append(q.columns, fieldAppender{column})
}
return q
}
// ColumnExpr adds column expression to the Query.
func (q *Query) ColumnExpr(expr string, params ...interface{}) *Query {
q.columns = append(q.columns, SafeQuery(expr, params...))
return q
}
// ExcludeColumn excludes a column from the list of to be selected columns.
func (q *Query) ExcludeColumn(columns ...string) *Query {
if q.columns == nil {
for _, f := range q.model.Table().Fields {
q.columns = append(q.columns, fieldAppender{f.SQLName})
}
}
for _, col := range columns {
if !q.excludeColumn(col) {
return q.err(fmt.Errorf("pg: can't find column=%q", col))
}
}
return q
}
func (q *Query) excludeColumn(column string) bool {
for i := 0; i < len(q.columns); i++ {
app, ok := q.columns[i].(fieldAppender)
if ok && app.field == column {
q.columns = append(q.columns[:i], q.columns[i+1:]...)
return true
}
}
return false
}
func (q *Query) getFields() ([]*Field, error) {
return q._getFields(false)
}
func (q *Query) getDataFields() ([]*Field, error) {
return q._getFields(true)
}
func (q *Query) _getFields(omitPKs bool) ([]*Field, error) {
table := q.model.Table()
columns := make([]*Field, 0, len(q.columns))
for _, col := range q.columns {
f, ok := col.(fieldAppender)
if !ok {
continue
}
field, err := table.GetField(f.field)
if err != nil {
return nil, err
}
if omitPKs && field.hasFlag(PrimaryKeyFlag) {
continue
}
columns = append(columns, field)
}
return columns, nil
}
// Relation adds a relation to the query. Relation name can be:
// - RelationName to select all columns,
// - RelationName.column_name,
// - RelationName._ to join relation without selecting relation columns.
func (q *Query) Relation(name string, apply ...func(*Query) (*Query, error)) *Query {
var fn func(*Query) (*Query, error)
if len(apply) == 1 {
fn = apply[0]
} else if len(apply) > 1 {
panic("only one apply function is supported")
}
join := q.model.Join(name, fn)
if join == nil {
return q.err(fmt.Errorf("%s does not have relation=%q",
q.model.Table(), name))
}
if fn == nil {
return q
}
switch join.Rel.Type {
case HasOneRelation, BelongsToRelation:
q.joinAppendOn = join.AppendOn
return q.Apply(fn)
default:
q.joinAppendOn = nil
return q
}
}
func (q *Query) Set(set string, params ...interface{}) *Query {
q.set = append(q.set, SafeQuery(set, params...))
return q
}
// Value overwrites model value for the column in INSERT and UPDATE queries.
func (q *Query) Value(column string, value string, params ...interface{}) *Query {
if !q.hasModel() {
q.err(errModelNil)
return q
}
table := q.model.Table()
if _, ok := table.FieldsMap[column]; ok {
if q.modelValues == nil {
q.modelValues = make(map[string]*SafeQueryAppender)
}
q.modelValues[column] = SafeQuery(value, params...)
} else {
q.extraValues = append(q.extraValues, &columnValue{
column: column,
value: SafeQuery(value, params...),
})
}
return q
}
func (q *Query) Where(condition string, params ...interface{}) *Query {
q.addWhere(&condAppender{
sep: " AND ",
cond: condition,
params: params,
})
return q
}
func (q *Query) WhereOr(condition string, params ...interface{}) *Query {
q.addWhere(&condAppender{
sep: " OR ",
cond: condition,
params: params,
})
return q
}
// WhereGroup encloses conditions added in the function in parentheses.
//
// q.Where("TRUE").
// WhereGroup(func(q *orm.Query) (*orm.Query, error) {
// q = q.WhereOr("FALSE").WhereOr("TRUE").
// return q, nil
// })
//
// generates
//
// WHERE TRUE AND (FALSE OR TRUE)
func (q *Query) WhereGroup(fn func(*Query) (*Query, error)) *Query {
return q.whereGroup(" AND ", fn)
}
// WhereGroup encloses conditions added in the function in parentheses.
//
// q.Where("TRUE").
// WhereNotGroup(func(q *orm.Query) (*orm.Query, error) {
// q = q.WhereOr("FALSE").WhereOr("TRUE").
// return q, nil
// })
//
// generates
//
// WHERE TRUE AND NOT (FALSE OR TRUE)
func (q *Query) WhereNotGroup(fn func(*Query) (*Query, error)) *Query {
return q.whereGroup(" AND NOT ", fn)
}
// WhereOrGroup encloses conditions added in the function in parentheses.
//
// q.Where("TRUE").
// WhereOrGroup(func(q *orm.Query) (*orm.Query, error) {
// q = q.Where("FALSE").Where("TRUE").
// return q, nil
// })
//
// generates
//
// WHERE TRUE OR (FALSE AND TRUE)
func (q *Query) WhereOrGroup(fn func(*Query) (*Query, error)) *Query {
return q.whereGroup(" OR ", fn)
}
// WhereOrGroup encloses conditions added in the function in parentheses.
//
// q.Where("TRUE").
// WhereOrGroup(func(q *orm.Query) (*orm.Query, error) {
// q = q.Where("FALSE").Where("TRUE").
// return q, nil
// })
//
// generates
//
// WHERE TRUE OR NOT (FALSE AND TRUE)
func (q *Query) WhereOrNotGroup(fn func(*Query) (*Query, error)) *Query {
return q.whereGroup(" OR NOT ", fn)
}
func (q *Query) whereGroup(conj string, fn func(*Query) (*Query, error)) *Query {
saved := q.where
q.where = nil
newq, err := fn(q)
if err != nil {
q.err(err)
return q
}
if len(newq.where) == 0 {
newq.where = saved
return newq
}
f := &condGroupAppender{
sep: conj,
cond: newq.where,
}
newq.where = saved
newq.addWhere(f)
return newq
}
// WhereIn is a shortcut for Where and pg.In:
func (q *Query) WhereIn(where string, slice interface{}) *Query {
return q.Where(where, types.In(slice))
}
// WhereInMulti is a shortcut for Where and pg.InMulti:
func (q *Query) WhereInMulti(where string, values ...interface{}) *Query {
return q.Where(where, types.InMulti(values...))
}
func (q *Query) addWhere(f queryWithSepAppender) {
if q.onConflictDoUpdate() {
q.updWhere = append(q.updWhere, f)
} else {
q.where = append(q.where, f)
}
}
// WherePK adds condition based on the model primary keys.
// Usually it is the same as:
//
// Where("id = ?id")
func (q *Query) WherePK() *Query {
if !q.hasModel() {
q.err(errModelNil)
return q
}
if err := q.model.Table().checkPKs(); err != nil {
q.err(err)
return q
}
q.where = append(q.where, wherePKQuery{q})
return q
}
// WhereStruct generates conditions for the struct fields with non-zero values:
// - Foo int - Where("foo = ?", strct.Foo)
// - Foo []int - Where("foo = ANY(?)", pg.Array(strct.Foo))
// - FooNEQ int - Where("foo != ?", strct.Foo)
// - FooExclude int - Where("foo != ?", strct.Foo)
// - FooGT int - Where("foo > ?", strct.Foo)
// - FooGTE int - Where("foo >= ?", strct.Foo)
// - FooLT int - Where("foo < ?", strct.Foo)
// - FooLTE int - Where("foo <= ?", strct.Foo)
//
// urlstruct.Decode can be used to decode url.Values into the struct.
//
// Following field tags are recognized:
// - pg:"-" - field is ignored.
// - pg:",nowhere" - field is decoded but is ignored by WhereStruct.
// - pg:",nodecode" - field is not decoded but is used by WhereStruct.
// - pg:",required" - condition is added for zero values as well.
func (q *Query) WhereStruct(strct interface{}) *Query {
q.where = append(q.where, newStructFilter(strct))
return q
}
func (q *Query) Join(join string, params ...interface{}) *Query {
j := &joinQuery{
join: SafeQuery(join, params...),
}
q.joins = append(q.joins, j)
q.joinAppendOn = j.AppendOn
return q
}
// JoinOn appends join condition to the last join.
func (q *Query) JoinOn(condition string, params ...interface{}) *Query {
if q.joinAppendOn == nil {
q.err(errors.New("pg: no joins to apply JoinOn"))
return q
}
q.joinAppendOn(&condAppender{
sep: " AND ",
cond: condition,
params: params,
})
return q
}
func (q *Query) JoinOnOr(condition string, params ...interface{}) *Query {
if q.joinAppendOn == nil {
q.err(errors.New("pg: no joins to apply JoinOn"))
return q
}
q.joinAppendOn(&condAppender{
sep: " OR ",
cond: condition,
params: params,
})
return q
}
func (q *Query) Group(columns ...string) *Query {
for _, column := range columns {
q.group = append(q.group, fieldAppender{column})
}
return q
}
func (q *Query) GroupExpr(group string, params ...interface{}) *Query {
q.group = append(q.group, SafeQuery(group, params...))
return q
}
func (q *Query) Having(having string, params ...interface{}) *Query {
q.having = append(q.having, SafeQuery(having, params...))
return q
}
func (q *Query) Union(other *Query) *Query {
return q.addUnion(" UNION ", other)
}
func (q *Query) UnionAll(other *Query) *Query {
return q.addUnion(" UNION ALL ", other)
}
func (q *Query) Intersect(other *Query) *Query {
return q.addUnion(" INTERSECT ", other)
}
func (q *Query) IntersectAll(other *Query) *Query {
return q.addUnion(" INTERSECT ALL ", other)
}
func (q *Query) Except(other *Query) *Query {
return q.addUnion(" EXCEPT ", other)
}
func (q *Query) ExceptAll(other *Query) *Query {
return q.addUnion(" EXCEPT ALL ", other)
}
func (q *Query) addUnion(expr string, other *Query) *Query {
q.union = append(q.union, &union{
expr: expr,
query: other,
})
return q
}
// Order adds sort order to the Query quoting column name. Does not expand params like ?TableAlias etc.
// OrderExpr can be used to bypass quoting restriction or for params expansion.
func (q *Query) Order(orders ...string) *Query {
loop:
for _, order := range orders {
if order == "" {
continue
}
ind := strings.Index(order, " ")
if ind != -1 {
field := order[:ind]
sort := order[ind+1:]
switch internal.UpperString(sort) {
case "ASC", "DESC", "ASC NULLS FIRST", "DESC NULLS FIRST",
"ASC NULLS LAST", "DESC NULLS LAST":
q = q.OrderExpr("? ?", types.Ident(field), types.Safe(sort))
continue loop
}
}
q.order = append(q.order, fieldAppender{order})
}
return q
}
// Order adds sort order to the Query.
func (q *Query) OrderExpr(order string, params ...interface{}) *Query {
if order != "" {
q.order = append(q.order, SafeQuery(order, params...))
}
return q
}
func (q *Query) Limit(n int) *Query {
q.limit = n
return q
}
func (q *Query) Offset(n int) *Query {
q.offset = n
return q
}
func (q *Query) OnConflict(s string, params ...interface{}) *Query {
q.onConflict = SafeQuery(s, params...)
return q
}
func (q *Query) onConflictDoUpdate() bool {
return q.onConflict != nil &&
strings.HasSuffix(internal.UpperString(q.onConflict.query), "DO UPDATE")
}
// Returning adds a RETURNING clause to the query.
//
// `Returning("NULL")` can be used to suppress default returning clause
// generated by go-pg for INSERT queries to get values for null columns.
func (q *Query) Returning(s string, params ...interface{}) *Query {
q.returning = append(q.returning, SafeQuery(s, params...))
return q
}
func (q *Query) For(s string, params ...interface{}) *Query {
q.selFor = SafeQuery(s, params...)
return q
}
// Apply calls the fn passing the Query as an argument.
func (q *Query) Apply(fn func(*Query) (*Query, error)) *Query {
qq, err := fn(q)
if err != nil {
q.err(err)
return q
}
return qq
}
// Count returns number of rows matching the query using count aggregate function.
func (q *Query) Count() (int, error) {
if q.stickyErr != nil {
return 0, q.stickyErr
}
var count int
_, err := q.db.QueryOneContext(
q.ctx, Scan(&count), q.countSelectQuery("count(*)"), q.model)
return count, err
}
func (q *Query) countSelectQuery(column string) *selectQuery {
return &selectQuery{
q: q,
count: column,
}
}
// First sorts rows by primary key and selects the first row.
// It is a shortcut for:
//
// q.OrderExpr("id ASC").Limit(1)
func (q *Query) First() error {
err := q.model.Table().checkPKs()
if err != nil {
return err
}
b := appendColumns(nil, q.model.Table().Alias, q.model.Table().PKs)
return q.OrderExpr(internal.BytesToString(b)).Limit(1).Select()
}
// Last sorts rows by primary key and selects the last row.
// It is a shortcut for:
//
// q.OrderExpr("id DESC").Limit(1)
func (q *Query) Last() error {
err := q.model.Table().checkPKs()
if err != nil {
return err
}
// TODO: fix for multi columns
b := appendColumns(nil, q.model.Table().Alias, q.model.Table().PKs)
b = append(b, " DESC"...)
return q.OrderExpr(internal.BytesToString(b)).Limit(1).Select()
}
// Select selects the model.
func (q *Query) Select(values ...interface{}) error {
if q.stickyErr != nil {
return q.stickyErr
}
model, err := q.newModel(values...)
if err != nil {
return err
}
c := q.ctx
res, err := q.query(c, model, newSelectQuery(q))
if err != nil {
return err
}
if res.RowsReturned() > 0 {
if q.model != nil {
if err := q.selectJoins(q.model.GetJoins()); err != nil {
return err
}
}
}
err = model.AfterSelect(c)
if err != nil {
return err
}
return nil
}
func (q *Query) newModel(values ...interface{}) (Model, error) {
if len(values) > 0 {
return NewModel(values...)
}
return q.model, nil
}
func (q *Query) query(c context.Context, model Model, query interface{}) (Result, error) {
if _, ok := model.(useQueryOne); ok {
return q.db.QueryOneContext(c, model, query, q.model)
}
return q.db.QueryContext(c, model, query, q.model)
}
// SelectAndCount runs Select and Count in two goroutines,
// waits for them to finish and returns the result. If query limit is -1
// it does not select any data and only counts the results.
func (q *Query) SelectAndCount(values ...interface{}) (count int, firstErr error) {
if q.stickyErr != nil {
return 0, q.stickyErr
}
var wg sync.WaitGroup
var mu sync.Mutex
if q.limit >= 0 {
wg.Add(1)
go func() {
defer wg.Done()
err := q.Select(values...)
if err != nil {
mu.Lock()
if firstErr == nil {
firstErr = err
}
mu.Unlock()
}
}()
}
wg.Add(1)
go func() {
defer wg.Done()
var err error
count, err = q.Count()
if err != nil {
mu.Lock()
if firstErr == nil {
firstErr = err
}
mu.Unlock()
}
}()
wg.Wait()
return count, firstErr
}
// SelectAndCountEstimate runs Select and CountEstimate in two goroutines,
// waits for them to finish and returns the result. If query limit is -1
// it does not select any data and only counts the results.
func (q *Query) SelectAndCountEstimate(threshold int, values ...interface{}) (count int, firstErr error) {
if q.stickyErr != nil {
return 0, q.stickyErr
}
var wg sync.WaitGroup
var mu sync.Mutex
if q.limit >= 0 {
wg.Add(1)
go func() {
defer wg.Done()
err := q.Select(values...)
if err != nil {
mu.Lock()
if firstErr == nil {
firstErr = err
}
mu.Unlock()
}
}()
}
wg.Add(1)
go func() {
defer wg.Done()
var err error
count, err = q.CountEstimate(threshold)
if err != nil {
mu.Lock()
if firstErr == nil {
firstErr = err
}
mu.Unlock()
}
}()
wg.Wait()
return count, firstErr
}
// ForEach calls the function for each row returned by the query
// without loading all rows into the memory.
//
// Function can accept a struct, a pointer to a struct, an orm.Model,
// or values for the columns in a row. Function must return an error.
func (q *Query) ForEach(fn interface{}) error {
m := newFuncModel(fn)
return q.Select(m)
}
func (q *Query) forEachHasOneJoin(fn func(*join) error) error {
if q.model == nil {
return nil
}
return q._forEachHasOneJoin(fn, q.model.GetJoins())
}
func (q *Query) _forEachHasOneJoin(fn func(*join) error, joins []join) error {
for i := range joins {
j := &joins[i]
switch j.Rel.Type {
case HasOneRelation, BelongsToRelation:
err := fn(j)
if err != nil {
return err
}
err = q._forEachHasOneJoin(fn, j.JoinModel.GetJoins())
if err != nil {
return err
}
}
}
return nil
}
func (q *Query) selectJoins(joins []join) error {
var err error
for i := range joins {
j := &joins[i]
if j.Rel.Type == HasOneRelation || j.Rel.Type == BelongsToRelation {
err = q.selectJoins(j.JoinModel.GetJoins())
} else {
err = j.Select(q.db.Formatter(), q.New())
}
if err != nil {
return err
}
}
return nil
}
// Insert inserts the model.
func (q *Query) Insert(values ...interface{}) (Result, error) {
if q.stickyErr != nil {
return nil, q.stickyErr
}
model, err := q.newModel(values...)
if err != nil {
return nil, err
}
c := q.ctx
if q.model != nil && q.model.Table().hasFlag(beforeInsertHookFlag) {
c, err = q.model.BeforeInsert(c)
if err != nil {
return nil, err
}
}
query := newInsertQuery(q)
res, err := q.returningQuery(c, model, query)
if err != nil {
return nil, err
}
if q.model != nil {
err = q.model.AfterInsert(c)
if err != nil {
return nil, err
}
}
return res, nil
}
// SelectOrInsert selects the model inserting one if it does not exist.
// It returns true when model was inserted.
func (q *Query) SelectOrInsert(values ...interface{}) (inserted bool, _ error) {
if q.stickyErr != nil {
return false, q.stickyErr
}
var insertq *Query
var insertErr error
for i := 0; i < 5; i++ {
if i >= 2 {
dur := internal.RetryBackoff(i-2, 250*time.Millisecond, 5*time.Second)
if err := internal.Sleep(q.ctx, dur); err != nil {
return false, err
}
}
err := q.Select(values...)
if err == nil {
return false, nil
}
if err != internal.ErrNoRows {
return false, err
}
if insertq == nil {
insertq = q
if len(insertq.columns) > 0 {
insertq = insertq.Clone()
insertq.columns = nil
}
}
res, err := insertq.Insert(values...)
if err != nil {
insertErr = err
if err == internal.ErrNoRows {
continue
}
if pgErr, ok := err.(internal.PGError); ok {
if pgErr.IntegrityViolation() {
continue
}
if pgErr.Field('C') == "55000" {
// Retry on "#55000 attempted to delete invisible tuple".
continue
}
}
return false, err
}
if res.RowsAffected() == 1 {
return true, nil
}
}
err := fmt.Errorf(
"pg: SelectOrInsert: select returns no rows (insert fails with err=%q)",
insertErr)
return false, err
}
// Update updates the model.
func (q *Query) Update(scan ...interface{}) (Result, error) {
return q.update(scan, false)
}
// Update updates the model omitting fields with zero values such as:
// - empty string,
// - 0,
// - zero time,
// - empty map or slice,
// - byte array with all zeroes,
// - nil ptr,
// - types with method `IsZero() == true`.
func (q *Query) UpdateNotZero(scan ...interface{}) (Result, error) {
return q.update(scan, true)
}
func (q *Query) update(scan []interface{}, omitZero bool) (Result, error) {
if q.stickyErr != nil {
return nil, q.stickyErr
}
model, err := q.newModel(scan...)
if err != nil {
return nil, err
}
c := q.ctx
if q.model != nil {
c, err = q.model.BeforeUpdate(c)
if err != nil {
return nil, err
}
}
query := newUpdateQuery(q, omitZero)
res, err := q.returningQuery(c, model, query)
if err != nil {
return nil, err
}
if q.model != nil {
err = q.model.AfterUpdate(c)
if err != nil {
return nil, err
}
}
return res, nil
}
func (q *Query) returningQuery(c context.Context, model Model, query interface{}) (Result, error) {
if !q.hasReturning() {
return q.db.QueryContext(c, model, query, q.model)
}
if _, ok := model.(useQueryOne); ok {
return q.db.QueryOneContext(c, model, query, q.model)
}
return q.db.QueryContext(c, model, query, q.model)
}
// Delete deletes the model. When model has deleted_at column the row
// is soft deleted instead.
func (q *Query) Delete(values ...interface{}) (Result, error) {
if q.model == nil {
return q.ForceDelete(values...)
}
table := q.model.Table()
if table.SoftDeleteField == nil {
return q.ForceDelete(values...)
}
clone := q.Clone()
if q.model.IsNil() {
if table.SoftDeleteField.SQLType == pgTypeBigint {
clone = clone.Set("? = ?", table.SoftDeleteField.Column, time.Now().UnixNano())
} else {
clone = clone.Set("? = ?", table.SoftDeleteField.Column, time.Now())
}
} else {
clone.model.setSoftDeleteField()
clone = clone.Column(table.SoftDeleteField.SQLName)
}
return clone.Update(values...)
}
// Delete forces delete of the model with deleted_at column.
func (q *Query) ForceDelete(values ...interface{}) (Result, error) {
if q.stickyErr != nil {
return nil, q.stickyErr
}
if q.model == nil {
return nil, errModelNil
}
q = q.withFlag(deletedFlag)
model, err := q.newModel(values...)
if err != nil {
return nil, err
}
c := q.ctx
if q.model != nil {
c, err = q.model.BeforeDelete(c)
if err != nil {
return nil, err
}
}
res, err := q.returningQuery(c, model, newDeleteQuery(q))
if err != nil {
return nil, err
}
if q.model != nil {
err = q.model.AfterDelete(c)
if err != nil {
return nil, err
}
}
return res, nil
}
func (q *Query) CreateTable(opt *CreateTableOptions) error {
_, err := q.db.ExecContext(q.ctx, newCreateTableQuery(q, opt))
return err
}
func (q *Query) DropTable(opt *DropTableOptions) error {
_, err := q.db.ExecContext(q.ctx, newDropTableQuery(q, opt))
return err
}
// Exec is an alias for DB.Exec.
func (q *Query) Exec(query interface{}, params ...interface{}) (Result, error) {
params = append(params, q.model)
return q.db.ExecContext(q.ctx, query, params...)
}
// ExecOne is an alias for DB.ExecOne.
func (q *Query) ExecOne(query interface{}, params ...interface{}) (Result, error) {
params = append(params, q.model)
return q.db.ExecOneContext(q.ctx, query, params...)
}
// Query is an alias for DB.Query.
func (q *Query) Query(model, query interface{}, params ...interface{}) (Result, error) {
params = append(params, q.model)
return q.db.QueryContext(q.ctx, model, query, params...)
}
// QueryOne is an alias for DB.QueryOne.
func (q *Query) QueryOne(model, query interface{}, params ...interface{}) (Result, error) {
params = append(params, q.model)
return q.db.QueryOneContext(q.ctx, model, query, params...)
}
// CopyFrom is an alias from DB.CopyFrom.
func (q *Query) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (Result, error) {
params = append(params, q.model)
return q.db.CopyFrom(r, query, params...)
}
// CopyTo is an alias from DB.CopyTo.
func (q *Query) CopyTo(w io.Writer, query interface{}, params ...interface{}) (Result, error) {
params = append(params, q.model)
return q.db.CopyTo(w, query, params...)
}
var _ QueryAppender = (*Query)(nil)
func (q *Query) AppendQuery(fmter QueryFormatter, b []byte) ([]byte, error) {
return newSelectQuery(q).AppendQuery(fmter, b)
}
// Exists returns true or false depending if there are any rows matching the query.
func (q *Query) Exists() (bool, error) {
cp := q.Clone() // copy to not change original query
cp.columns = []QueryAppender{SafeQuery("1")}
cp.order = nil
cp.limit = 1
res, err := q.db.ExecContext(q.ctx, newSelectQuery(cp))
if err != nil {
return false, err
}
return res.RowsAffected() > 0, nil
}
func (q *Query) hasModel() bool {
return q.model != nil && !q.model.IsNil()
}
func (q *Query) hasExplicitModel() bool {
return q.model != nil && !q.hasFlag(implicitModelFlag)
}
func (q *Query) modelHasTableName() bool {
return q.hasExplicitModel() && q.model.Table().FullName != ""
}
func (q *Query) modelHasTableAlias() bool {
return q.hasExplicitModel() && q.model.Table().Alias != ""
}
func (q *Query) hasTables() bool {
return q.modelHasTableName() || len(q.tables) > 0
}
func (q *Query) appendFirstTable(fmter QueryFormatter, b []byte) ([]byte, error) {
if q.modelHasTableName() {
return fmter.FormatQuery(b, string(q.model.Table().FullName)), nil
}
if len(q.tables) > 0 {
return q.tables[0].AppendQuery(fmter, b)
}
return b, nil
}
func (q *Query) appendFirstTableWithAlias(fmter QueryFormatter, b []byte) (_ []byte, err error) {
if q.modelHasTableName() {
table := q.model.Table()
b = fmter.FormatQuery(b, string(table.FullName))
if table.Alias != table.FullName {
b = append(b, " AS "...)
b = append(b, table.Alias...)
}
return b, nil
}
if len(q.tables) > 0 {
b, err = q.tables[0].AppendQuery(fmter, b)
if err != nil {
return nil, err
}
if q.modelHasTableAlias() {
table := q.model.Table()
if table.Alias != table.FullName {
b = append(b, " AS "...)
b = append(b, table.Alias...)
}
}
}
return b, nil
}
func (q *Query) hasMultiTables() bool {
if q.modelHasTableName() {
return len(q.tables) > 0
}
return len(q.tables) > 1
}
func (q *Query) appendOtherTables(fmter QueryFormatter, b []byte) (_ []byte, err error) {
tables := q.tables
if !q.modelHasTableName() {
tables = tables[1:]
}
for i, f := range tables {
if i > 0 {
b = append(b, ", "...)
}
b, err = f.AppendQuery(fmter, b)
if err != nil {
return nil, err
}
}
return b, nil
}
func (q *Query) appendColumns(fmter QueryFormatter, b []byte) (_ []byte, err error) {
for i, f := range q.columns {
if i > 0 {
b = append(b, ", "...)
}
b, err = f.AppendQuery(fmter, b)
if err != nil {
return nil, err
}
}
return b, nil
}
func (q *Query) mustAppendWhere(fmter QueryFormatter, b []byte) ([]byte, error) {
if len(q.where) == 0 {
err := errors.New(
"pg: Update and Delete queries require Where clause (try WherePK)")
return nil, err
}
return q.appendWhere(fmter, b)
}
func (q *Query) appendWhere(fmter QueryFormatter, b []byte) (_ []byte, err error) {
isSoftDelete := q.isSoftDelete()
if len(q.where) > 0 {
if isSoftDelete {
b = append(b, '(')
}
b, err = q._appendWhere(fmter, b, q.where)
if err != nil {
return nil, err
}
if isSoftDelete {
b = append(b, ')')
}
}
if isSoftDelete {
if len(q.where) > 0 {
b = append(b, " AND "...)
}
b = append(b, q.model.Table().Alias...)
b = q.appendSoftDelete(b)
}
return b, nil
}
func (q *Query) appendSoftDelete(b []byte) []byte {
b = append(b, '.')
b = append(b, q.model.Table().SoftDeleteField.Column...)
if q.hasFlag(deletedFlag) {
b = append(b, " IS NOT NULL"...)
} else {
b = append(b, " IS NULL"...)
}
return b
}
func (q *Query) appendUpdWhere(fmter QueryFormatter, b []byte) ([]byte, error) {
return q._appendWhere(fmter, b, q.updWhere)
}
func (q *Query) _appendWhere(
fmter QueryFormatter, b []byte, where []queryWithSepAppender,
) (_ []byte, err error) {
for i, f := range where {
start := len(b)
if i > 0 {
b = f.AppendSep(b)
}
before := len(b)
b, err = f.AppendQuery(fmter, b)
if err != nil {
return nil, err
}
if len(b) == before {
b = b[:start]
}
}
return b, nil
}
func (q *Query) appendSet(fmter QueryFormatter, b []byte) (_ []byte, err error) {
b = append(b, " SET "...)
for i, f := range q.set {
if i > 0 {
b = append(b, ", "...)
}
b, err = f.AppendQuery(fmter, b)
if err != nil {
return nil, err
}
}
return b, nil
}
func (q *Query) hasReturning() bool {
if len(q.returning) == 0 {
return false
}
if len(q.returning) == 1 {
switch q.returning[0].query {
case "null", "NULL":
return false
}
}
return true
}
func (q *Query) appendReturning(fmter QueryFormatter, b []byte) (_ []byte, err error) {
if !q.hasReturning() {
return b, nil
}
b = append(b, " RETURNING "...)
for i, f := range q.returning {
if i > 0 {
b = append(b, ", "...)
}
b, err = f.AppendQuery(fmter, b)
if err != nil {
return nil, err
}
}
return b, nil
}
func (q *Query) appendWith(fmter QueryFormatter, b []byte) (_ []byte, err error) {
b = append(b, "WITH "...)
for i, with := range q.with {
if i > 0 {
b = append(b, ", "...)
}
b = types.AppendIdent(b, with.name, 1)
b = append(b, " AS ("...)
b, err = with.query.AppendQuery(fmter, b)
if err != nil {
return nil, err
}
b = append(b, ')')
}
b = append(b, ' ')
return b, nil
}
func (q *Query) isSliceModelWithData() bool {
if !q.hasModel() {
return false
}
m, ok := q.model.(*sliceTableModel)
return ok && m.sliceLen > 0
}
//------------------------------------------------------------------------------
type wherePKQuery struct {
q *Query
}
var _ queryWithSepAppender = (*wherePKQuery)(nil)
func (wherePKQuery) AppendSep(b []byte) []byte {
return append(b, " AND "...)
}
func (q wherePKQuery) AppendQuery(fmter QueryFormatter, b []byte) ([]byte, error) {
table := q.q.model.Table()
value := q.q.model.Value()
if q.q.model.Kind() == reflect.Slice {
return appendColumnAndSliceValue(fmter, b, value, table.Alias, table.PKs), nil
}
return appendColumnAndValue(fmter, b, value, table.Alias, table.PKs), nil
}
func appendColumnAndValue(
fmter QueryFormatter, b []byte, v reflect.Value, alias types.Safe, fields []*Field,
) []byte {
isPlaceholder := isPlaceholderFormatter(fmter)
for i, f := range fields {
if i > 0 {
b = append(b, " AND "...)
}
b = append(b, alias...)
b = append(b, '.')
b = append(b, f.Column...)
b = append(b, " = "...)
if isPlaceholder {
b = append(b, '?')
} else {
b = f.AppendValue(b, v, 1)
}
}
return b
}
func appendColumnAndSliceValue(
fmter QueryFormatter, b []byte, slice reflect.Value, alias types.Safe, fields []*Field,
) []byte {
if len(fields) > 1 {
b = append(b, '(')
}
b = appendColumns(b, alias, fields)
if len(fields) > 1 {
b = append(b, ')')
}
b = append(b, " IN ("...)
isPlaceholder := isPlaceholderFormatter(fmter)
sliceLen := slice.Len()
for i := 0; i < sliceLen; i++ {
if i > 0 {
b = append(b, ", "...)
}
el := indirect(slice.Index(i))
if len(fields) > 1 {
b = append(b, '(')
}
for i, f := range fields {
if i > 0 {
b = append(b, ", "...)
}
if isPlaceholder {
b = append(b, '?')
} else {
b = f.AppendValue(b, el, 1)
}
}
if len(fields) > 1 {
b = append(b, ')')
}
}
b = append(b, ')')
return b
}