-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpika_psql.go
1450 lines (1200 loc) · 36.3 KB
/
pika_psql.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
// SPDX-FileCopyrightText: Copyright (c) 2023-2024, Ctrl IQ, Inc. All rights reserved
// SPDX-License-Identifier: Apache-2.0
package pika
import (
"context"
"database/sql"
"fmt"
"reflect"
"strings"
"github.com/gertd/go-pluralize"
"github.com/iancoleman/strcase"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
orderedmap "github.com/wk8/go-ordered-map/v2"
// load psql driver
_ "github.com/lib/pq"
)
// Queryable includes all methods shared by sqlx.DB and sqlx.Tx, allowing
// either type to be used interchangeably.
//
//nolint:interfacebloat
type Queryable interface {
sqlx.Ext
sqlx.ExecerContext
sqlx.PreparerContext
sqlx.QueryerContext
sqlx.Preparer
GetContext(context.Context, interface{}, string, ...interface{}) error
MustExecContext(context.Context, string, ...interface{}) sql.Result
NamedExecContext(context.Context, string, interface{}) (sql.Result, error)
PrepareNamedContext(context.Context, string) (*sqlx.NamedStmt, error)
PreparexContext(context.Context, string) (*sqlx.Stmt, error)
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
SelectContext(context.Context, interface{}, string, ...interface{}) error
}
var (
_ Queryable = (*sqlx.DB)(nil)
_ Queryable = (*sqlx.Tx)(nil)
)
type PostgreSQL struct {
*connBase
db *sqlx.DB
tx *sqlx.Tx
}
type basePsql[T any] struct {
*AIPFilter[T]
*PageToken[T]
*base
//nolint:structcheck // false positive
psql *PostgreSQL
}
type CreateOption byte
const InsertOnConflictionDoNothing CreateOption = 1 << iota
// NewPostgreSQL returns a new PostgreSQL instance.
// connectionString should be sqlx compatible.
func NewPostgreSQL(connectionString string) (*PostgreSQL, error) {
db, err := sqlx.Connect("postgres", connectionString)
if err != nil {
return nil, errors.Wrap(err, "failed to connect to database")
}
return &PostgreSQL{
connBase: &connBase{},
db: db,
}, nil
}
func NewPostgreSQLFromDB(db *sqlx.DB) *PostgreSQL {
return &PostgreSQL{
connBase: &connBase{},
db: db,
}
}
// Begin starts a new transaction.
func (p *PostgreSQL) Begin(ctx context.Context) error {
if p.tx != nil {
return errors.New("transaction already exists")
}
tx, err := p.db.BeginTxx(ctx, &sql.TxOptions{})
if err != nil {
return err
}
p.tx = tx
return nil
}
// Commit commits the current transaction.
func (p *PostgreSQL) Commit() error {
if p.tx != nil {
defer func() {
p.tx = nil
}()
return p.tx.Commit()
}
return errors.New("no transaction to commit")
}
// Rollback rolls back the current transaction.
func (p *PostgreSQL) Rollback() error {
if p.tx != nil {
defer func() {
p.tx = nil
}()
return p.tx.Rollback()
}
return nil
}
func (p *PostgreSQL) Queryable() Queryable {
if p.tx != nil {
return p.tx
}
return p.db
}
func (p *PostgreSQL) DB() *sqlx.DB {
return p.db
}
func (p *PostgreSQL) Close() error {
return p.db.Close()
}
func PSQLQuery[T any](p *PostgreSQL) QuerySet[T] {
b := &basePsql[T]{
AIPFilter: NewAIPFilter[T](),
PageToken: NewPageToken[T](),
base: newBase(),
psql: p,
}
// Initialize metadata once
metadata := getPikaMetadata[T]()
b.metadata = metadata
modelName := b.metadata[pikaMetadataModelName]
tableName := b.metadata[PikaMetadataTableName]
// Check if we have a table alias for this model
// Only applies if the table name is not explicitly set
if tableName == "" {
if x, ok := b.psql.tableAlias[modelName]; ok {
// If so, use it
tableName = x
} else {
// Otherwise, use the pluralized model name
tableName = strcase.ToSnake(pluralize.NewClient().Plural(modelName))
}
b.metadata[PikaMetadataTableName] = tableName
}
return b
}
// Filter returns a new QuerySet with the given filters applied.
// The filters are applied in the order they are given.
// Only use named parameters in the filters.
// Multiple filter calls can be made, they will be combined with AND.
// Will also work as AND combined
func (b *basePsql[T]) Filter(queries ...string) QuerySet[T] {
if b.err != nil {
return b
}
b.filter(false, false, queries...)
return b
}
// FilterOr returns a new QuerySet with the given filters applied.
// The filters are applied in the order they are given.
// Only use named parameters in the filters.
// Multiple filter calls can be made, they will be combined with AND.
// But will work as OR combined
func (b *basePsql[T]) FilterOr(queries ...string) QuerySet[T] {
if b.err != nil {
return b
}
b.filter(false, true, queries...)
return b
}
// FilterInnerOr returns a new QuerySet with the given filters applied.
// Same as Filter, but inner filters are combined with OR.
func (b *basePsql[T]) FilterInnerOr(queries ...string) QuerySet[T] {
if b.err != nil {
return b
}
b.filter(true, false, queries...)
return b
}
// FilterOrInnerOr returns a new QuerySet with the given filters applied.
// Same as FilterOr, but inner filters are combined with OR.
func (b *basePsql[T]) FilterOrInnerOr(queries ...string) QuerySet[T] {
if b.err != nil {
return b
}
b.filter(true, true, queries...)
return b
}
// Args sets named arguments for the filters.
func (b *basePsql[T]) Args(args *orderedmap.OrderedMap[string, interface{}]) QuerySet[T] {
if b.err != nil {
return b
}
b.setArgs(args)
return b
}
// ClearFiltersArgs clears the filters and args
func (b *basePsql[T]) ClearAll() QuerySet[T] {
if b.err != nil {
return b
}
b.clearAll()
return b
}
// Create creates a new record in the database.
func (b *basePsql[T]) Create(ctx context.Context, x *T, options ...CreateOption) error {
if b.err != nil {
return b.err
}
origIgnoreOrderBy := b.ignoreOrderBy
b.ignoreOrderBy = true
q, args := b.CreateQuery(x, options...)
b.ignoreOrderBy = origIgnoreOrderBy
// Execute query
err := b.psql.Queryable().GetContext(ctx, x, q, args...)
if err != nil {
// ignore no rows in resultset error when ignoreConflict is set to true, this is a normal case
if errors.Is(err, sql.ErrNoRows) && (InsertOnConflictionDoNothing&getOption(options...) != 0) {
return nil
}
return err
}
return nil
}
// Update updates a record in the database.
func (b *basePsql[T]) Update(ctx context.Context, x *T) error {
if b.err != nil {
return b.err
}
origIgnoreOrderBy := b.ignoreOrderBy
b.ignoreOrderBy = true
q, args := b.UpdateQuery(x)
b.ignoreOrderBy = origIgnoreOrderBy
// Execute query
err := b.psql.Queryable().GetContext(ctx, x, q, args...)
if err != nil {
return err
}
return nil
}
// Delete deletes a record from the database.
func (b *basePsql[T]) Delete(ctx context.Context) error {
if b.err != nil {
return b.err
}
origIgnoreOrderBy := b.ignoreOrderBy
b.ignoreOrderBy = true
q, args := b.DeleteQuery()
b.ignoreOrderBy = origIgnoreOrderBy
// Execute query
_, err := b.psql.Queryable().ExecContext(ctx, q, args...)
if err != nil {
return err
}
return nil
}
// GetOrNil returns a single value or nil
// Multiple values will return an error.
func (b *basePsql[T]) GetOrNil(ctx context.Context) (*T, error) {
if b.err != nil {
return nil, b.err
}
q, args := b.GetOrNilQuery()
if b.err != nil {
return nil, b.err
}
// Execute query
var x T
// Send arguments to prepared statement
err := b.psql.Queryable().GetContext(ctx, &x, q, args...)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, err
}
return &x, nil
}
// Get returns a single value
// Returns error if no value is found
// Returns error if multiple values are found
func (b *basePsql[T]) Get(ctx context.Context) (*T, error) {
if b.err != nil {
return nil, b.err
}
q, args := b.GetQuery()
// Execute query
var x T
// Send arguments to prepared statement
err := b.psql.Queryable().GetContext(ctx, &x, q, args...)
if err != nil {
return nil, err
}
return &x, nil
}
// All returns all values
func (b *basePsql[T]) All(ctx context.Context) ([]*T, error) {
if b.err != nil {
return nil, b.err
}
q, args := b.AllQuery()
// Execute query
var x []*T
// Send arguments to prepared statement
err := b.psql.Queryable().SelectContext(ctx, &x, q, args...)
if err != nil {
return nil, err
}
return x, nil
}
// Count returns the number of values
func (b *basePsql[T]) Count(ctx context.Context) (int, error) {
if b.err != nil {
return 0, b.err
}
// Execute query
var x int
// Fetch count without limit and offset
origIgnoreLimit := b.ignoreLimit
origIgnoreOffset := b.ignoreOffset
origIgnoreOrderBy := b.ignoreOrderBy
b.ignoreLimit = true
b.ignoreOffset = true
b.ignoreOrderBy = true
filterStatement, args := b.queryWithFilters()
preSelect := b.psqlSelectList(b.excludeColumns, b.includeColumns, false)
// Strip preSelect from filterStatement
filterStatement = strings.Replace(filterStatement, preSelect, "", -1)
b.ignoreLimit = origIgnoreLimit
b.ignoreOffset = origIgnoreOffset
b.ignoreOrderBy = origIgnoreOrderBy
// Get select query and append filter statement
selectQuery := b.psqlCountQuery()
q := fmt.Sprintf("%s%s", selectQuery, filterStatement)
logger.Debugf("Pika query: %s", q)
err := b.psql.Queryable().GetContext(ctx, &x, q, args...)
if err != nil {
return 0, err
}
return x, nil
}
// Limit sets the limit for the query
func (b *basePsql[T]) Limit(limit int) QuerySet[T] {
if b.err != nil {
return b
}
b.setLimit(limit)
return b
}
// Offset sets the offset for the query
func (b *basePsql[T]) Offset(offset int) QuerySet[T] {
if b.err != nil {
return b
}
b.setOffset(offset)
return b
}
// OrderBy sets the order for the query
// Use - to indicate descending order
// Example:
//
// OrderBy("-id", "name")
func (b *basePsql[T]) OrderBy(order ...string) QuerySet[T] {
if b.err != nil {
return b
}
b.setOrderBy(order, false)
return b
}
// ResetOrderBy resets the order for the query
func (b *basePsql[T]) ResetOrderBy() QuerySet[T] {
if b.err != nil {
return b
}
b.setOrderBy([]string{}, true)
return b
}
// CreateQuery returns the query and arguments for Create
func (b *basePsql[T]) CreateQuery(x *T, options ...CreateOption) (string, []interface{}) {
q, args := b.psqlCreateQuery(x, options...)
logger.Debugf("Pika query: %s", q)
return q, args
}
// UpdateQuery returns the query and arguments for Update
func (b *basePsql[T]) UpdateQuery(x *T) (string, []interface{}) {
q, args := b.psqlUpdateQuery(x)
logger.Debugf("Pika query: %s", q)
return q, args
}
// DeleteQuery returns the query and arguments for Delete
func (b *basePsql[T]) DeleteQuery() (string, []interface{}) {
modelName := b.metadata[pikaMetadataModelName]
filterStatement, args := b.filterStatement()
filterStatement = strings.Replace(filterStatement, fmt.Sprintf("\"%s\".", modelName), "", -1)
q := fmt.Sprintf("DELETE FROM \"%s\"", b.metadata[PikaMetadataTableName])
q += filterStatement
logger.Debugf("Pika query: %s", q)
return q, args
}
func (b *basePsql[T]) GetOrNilQuery() (string, []interface{}) {
b.ignoreLimit = true
q, args := b.queryWithFilters()
// Limit to one
q += " LIMIT 1"
logger.Debugf("Pika query: %s", q)
return q, args
}
// GetQuery returns the query and arguments for Get
func (b *basePsql[T]) GetQuery() (string, []interface{}) {
q, args := b.GetOrNilQuery()
return q, args
}
// AllQuery returns the query and arguments for All
func (b *basePsql[T]) AllQuery() (string, []interface{}) {
q, args := b.queryWithFilters()
logger.Debugf("Pika query: %s", q)
return q, args
}
// AIP160 filtering for gRPC/Proto
func (b *basePsql[T]) AIP160(filter string, options AIPFilterOptions) (QuerySet[T], error) {
if b.err != nil {
return b, b.err
}
return b.aip160(b, filter, options)
}
// Page tokens for gRPC
func (b *basePsql[T]) GetPage(ctx context.Context, paginatable Paginatable, options AIPFilterOptions, countPointer ...*int) ([]*T, string, error) {
if len(countPointer) > 1 {
return nil, "", fmt.Errorf("too many arguments (count should be one pointer or none)")
}
if b.err != nil {
return nil, "", b.err
}
// Only decode if token is not empty
if paginatable.GetPageToken() != "" {
err := b.PageToken.Decode(paginatable.GetPageToken())
if err != nil {
return nil, "", err
}
} else {
// Otherwise use initial filter
b.PageToken.Offset = 0
b.PageToken.Filter = paginatable.GetFilter()
b.PageToken.OrderBy = paginatable.GetOrderBy()
b.PageToken.PageSize = uint(paginatable.GetPageSize())
}
qs, err := b.pageToken(b, options)
if err != nil {
return nil, "", err
}
result, err := qs.All(ctx)
if err != nil {
return nil, "", err
}
b.PageToken.Offset += uint(len(result))
// Get count and check if there are more results
count, err := b.Count(ctx)
if err != nil {
return nil, "", fmt.Errorf("getting count: %w", err)
}
if len(countPointer) > 0 {
*countPointer[0] = count
}
// If no more results after this page, return empty page token
if b.PageToken.Offset >= uint(count) {
return result, "", nil
}
tk, err := b.PageToken.Encode()
if err != nil {
return nil, "", err
}
return result, tk, nil
}
func (b *basePsql[T]) InnerJoin(modelFirst, modelSecond interface{}, keyFirst, keySecond string) QuerySet[T] {
return b.commonJoin(innerJoin, modelFirst, modelSecond, keyFirst, keySecond)
}
func (b *basePsql[T]) LeftJoin(modelFirst, modelSecond interface{}, keyFirst, keySecond string) QuerySet[T] {
return b.commonJoin(leftJoin, modelFirst, modelSecond, keyFirst, keySecond)
}
func (b *basePsql[T]) RightJoin(modelFirst, modelSecond interface{}, keyFirst, keySecond string) QuerySet[T] {
return b.commonJoin(rightJoin, modelFirst, modelSecond, keyFirst, keySecond)
}
func (b *basePsql[T]) FullJoin(modelFirst, modelSecond interface{}, keyFirst, keySecond string) QuerySet[T] {
return b.commonJoin(fullJoin, modelFirst, modelSecond, keyFirst, keySecond)
}
// Exclude certain fields (Notice: should be fields defined in "db" or "pika")
func (b *basePsql[T]) Exclude(excludes ...string) QuerySet[T] {
if b.err != nil {
return b
}
if len(excludes) > 0 {
if b.excludeColumns == nil {
b.excludeColumns = make([]string, 0)
}
b.excludeColumns = append(b.excludeColumns, excludes...)
}
return b
}
// Include certain fields (Notice: should be fields defined in "db" or "pika")
func (b *basePsql[T]) Include(includes ...string) QuerySet[T] {
if b.err != nil {
return b
}
if len(includes) > 0 {
if b.includeColumns == nil {
b.includeColumns = make([]string, 0)
}
b.includeColumns = append(b.includeColumns, includes...)
}
return b
}
// Return args, used for reflection
func (b *basePsql[T]) GetArgs() *orderedmap.OrderedMap[string, interface{}] {
return b.args
}
// Return current table and module name, used for reflection
func (b *basePsql[T]) GetModel() (string, string) {
var x T
modelName := reflect.TypeOf(x).Name()
tableName := modelName
ref := reflect.ValueOf(x)
for i := 0; i < ref.NumField(); i++ {
field := ref.Type().Field(i)
if strings.Compare(field.Name, PikaMetadataTableName) == 0 {
tableName = field.Tag.Get("pika")
break
}
}
return tableName, modelName
}
type subQuery struct {
query string
args *orderedmap.OrderedMap[string, interface{}]
}
func (b *basePsql[T]) filterStatement() (string, []any) {
q := ""
// Set number args for named parameters
mapping := make(map[string]int)
reverseMapping := make(map[int]string)
// Save subquery info
subQueryMap := make(map[string]*subQuery)
// Rearranged args, as subqueries have their own place holders, so we need to rearrange the entire place holders.
newArgsMap := orderedmap.New[string, interface{}]()
// Process filters if any
if len(b.filters) > 0 {
// Map args to numbers
// And reverse mapping to easily get the name
if b.args.Len() > 0 {
start := 1
// First scan subquery
// Userd for rearrange subquery args
for pair := b.args.Oldest(); pair != nil; pair = pair.Next() {
k := pair.Key
// already processed
if _, ok := mapping[k]; ok {
continue
}
v := pair.Value
// Check if v is subquery, another QuerySet[T]
if isTarget(v) {
// Retrieve subquery type info
tname, mname := getQuerySetInfo(v)
b.replaceFields[tname] = &replaceField{
tableName: tname,
modelName: mname,
}
// Retrieve subquery details
query, args := getSubQuery(v)
if args.Len() > 0 {
// update query
oldIdx := *generateRangeSlice(1, args.Len())
newIdx := *generateRangeSlice(start, args.Len())
query = replacePlaceHolder(query, oldIdx, newIdx)
for p := args.Oldest(); p != nil; p = p.Next() {
mapping[p.Key] = start
newArgsMap.AddPairs(*p)
reverseMapping[start] = p.Key
start++
}
}
sq := subQuery{
query: query,
args: args,
}
subQueryMap[k] = &sq
}
}
// Update remaining args
for pair := b.args.Oldest(); pair != nil; pair = pair.Next() {
k := pair.Key
// If already set, re-use same number
if _, ok := mapping[k]; ok {
continue
}
v := pair.Value
if !isTarget(v) {
newArgsMap.AddPairs(*pair)
// Set number
mapping[k] = start
reverseMapping[start] = k
start++
}
}
}
// Process filters
q += " WHERE "
for _, filter := range b.filters {
// If no filters, then open with parenthesis
innerQ := "("
// Else
// If not first filter, add AND/OR
if !strings.HasSuffix(q, "WHERE ") {
innerQ = " AND ("
if filter.or {
innerQ = " OR ("
}
}
// Loop through filter entries
for pair := filter.entries.Oldest(); pair != nil; pair = pair.Next() {
// vSpace is used to determine if we need to add a space
// Required only for IS NULL and IS NOT NULL
vSpace := " "
// Whether or not to switch left-hand side with right-hand side
// This is used for IN and NOT IN where we're checking if a single value
// is present in the array column value
shouldSwitchKV := false
// kWrapper is whether to wrap the key in a function
// Mostly used for ANY and ALL when checking array columns
keyWrapper := ""
k := pair.Key
v := pair.Value
// If argument is set, use it
// Only if the value starts with a ":"
noWildcard := strings.ReplaceAll(v, "%", "")
startWildcard := strings.HasPrefix(v, "%")
endWildcard := strings.HasSuffix(v, "%")
if strings.HasPrefix(noWildcard, ":") {
// Allow a percentage sign to be used as a wildcard
// Both prefix and suffix
// Ignore it for the purposes of named parameters
if _, ok := b.args.Get(noWildcard[1:]); ok {
// If mapping found, replace with numbered parameter
v = fmt.Sprintf("$%d", mapping[noWildcard[1:]])
} else {
b.err = fmt.Errorf("missing argument: %s", noWildcard)
return "", nil
}
}
andOr := "AND"
if filter.innerOr {
andOr = "OR"
}
operator := "="
// If key contains "__", then try to find hint
if strings.Contains(k, "__") {
parts := strings.Split(k, "__")
k = parts[0]
op := fmt.Sprintf("__%s", parts[1])
// IN requires the value wrapped in ANY
// as go-pika sends the value as a slice
if op == HintIn {
// If the field type is a StringArray, then switch left-hand side and right-hand side
// This is because left-hand side cannot be ANY
origV := v
// If it's a variable pointing to subquery object
if val, ok := subQueryMap[noWildcard[1:]]; ok {
v = fmt.Sprintf("IN (%s)", val.query)
// We do not need "="
op = HintEmpty
} else {
v = fmt.Sprintf("ANY(%s)", v)
if x, ok := b.metadata[k]; ok {
if strings.HasPrefix(x, "pq.") && strings.HasSuffix(x, "Array") {
v = origV
shouldSwitchKV = true
keyWrapper = "ANY"
}
}
}
}
// NOT IN requires the value wrapped in ALL
// as go-pika sends the value as a slice
if op == HintNotIn {
// If the field type is a StringArray, then switch left-hand side and right-hand side
// This is because left-hand side cannot be ALL
origV := v
if val, ok := subQueryMap[noWildcard[1:]]; ok {
v = fmt.Sprintf("NOT IN (%s)", val.query)
op = HintEmpty
} else {
v = fmt.Sprintf("ALL(%s)", v)
if x, ok := b.metadata[k]; ok {
if strings.HasPrefix(x, "pq.") && strings.HasSuffix(x, "Array") {
v = origV
shouldSwitchKV = true
keyWrapper = "ALL"
}
}
}
}
// If LIKE or NOT LIKE, then respect wildcards
// Also for not case sensitive variants
if op == HintLike || op == HintNotLike || op == HintILike || op == HintNotILike {
// If a start wildcard was found, then add a prefix
if startWildcard {
v = fmt.Sprintf("'%%' || %s", v)
}
// If an end wildcard was found, then add a suffix
if endWildcard {
v = fmt.Sprintf("%s || '%%'", v)
}
}
// If IS NULL or IS NOT NULL, then ignore value
if op == HintIsNull || op == HintIsNotNull {
v = ""
vSpace = ""
}
extraHintOp := op
if len(parts) > 2 {
extraHintOp = fmt.Sprintf("__%s", parts[2])
}
// If AND then set andOr to AND regardless of filter.innerOr
// We do this by replacing last AND/OR with AND
if op == HintAnd || extraHintOp == HintAnd {
innerQ = strings.TrimSuffix(innerQ, "AND ")
innerQ = strings.TrimSuffix(innerQ, "OR ")
// Add if it's not start of subexpression
if !strings.HasSuffix(innerQ, "(") {
innerQ += "AND "
}
}
// If OR then set andOr to OR regardless of filter.innerOr
if op == HintOr || extraHintOp == HintOr {
innerQ = strings.TrimSuffix(innerQ, "AND ")
innerQ = strings.TrimSuffix(innerQ, "OR ")
// Add if it's not start of subexpression
if !strings.HasSuffix(innerQ, "(") {
innerQ += "OR "
}
}
// Check if operator is valid
// Only if op is not HintAnd or HintOr
if op != HintAnd && op != HintOr {
var ok bool
operator, ok = operators[op]
if !ok {
b.err = fmt.Errorf("invalid operator: %s", operator)
return "", nil
}
}
}
clean := cleanKey(k)
finalK := fmt.Sprintf("\"%s\".\"%s\"", b.metadata[pikaMetadataModelName], clean)
// If there is a dot in cleanKey, then that means we should assume that
// the caller "knows" what they're doing and we should not add the table name
if strings.Contains(clean, ".") {
// Split by dot, then join with quotes
parts := strings.Split(clean, ".")
if len(parts) != 2 {
b.err = fmt.Errorf("invalid key: %s", k)
return "", nil
}
finalK = fmt.Sprintf("\"%s\".\"%s\"", parts[0], parts[1])
}
if keyWrapper != "" {
finalK = fmt.Sprintf("%s(%s)", keyWrapper, finalK)
}
if shouldSwitchKV {
innerQ += fmt.Sprintf("%s %s %s%s%s ", v, operator, finalK, vSpace, andOr)
continue
}
innerQ += fmt.Sprintf("%s %s %s%s%s ", finalK, operator, v, vSpace, andOr)
}
// Remove last AND and OR (and first)
innerQ = strings.TrimSuffix(innerQ, " AND ")
innerQ = strings.TrimSuffix(innerQ, " OR ")
innerQ += ")"
// Add to query
q += innerQ
}
}
// Process order by
// If not ignored
if !b.ignoreOrderBy {
// Proceed if there are order bys
if len(b.orderBy) > 0 {
q += " ORDER BY "
for _, o := range b.orderBy {
if strings.HasPrefix(o, "-") {
o = fmt.Sprintf("\"%s\".\"%s\" DESC", b.metadata[pikaMetadataModelName], o[1:])
} else {
o = fmt.Sprintf("\"%s\".\"%s\" ASC", b.metadata[pikaMetadataModelName], o)
}
q += o + ", "
}
// Remove last comma
q = strings.TrimSuffix(q, ", ")
} else if orderBy := b.metadata[PikaMetadataDefaultOrderBy]; orderBy != "" {
q += " ORDER BY "
if strings.HasPrefix(orderBy, "-") {
orderBy = fmt.Sprintf("\"%s\".\"%s\" DESC", b.metadata[pikaMetadataModelName], orderBy[1:])
} else {
orderBy = fmt.Sprintf("\"%s\".\"%s\" ASC", b.metadata[pikaMetadataModelName], orderBy)
}
q += orderBy
}
}
if b.limit != nil && !b.ignoreLimit {
q += fmt.Sprintf(" LIMIT %d", *b.limit)
}
if b.offset != nil && !b.ignoreOffset {
q += fmt.Sprintf(" OFFSET %d", *b.offset)
}
// Construct argument list
// If we have subqueries, we return the newArgsMap instead of b.args, because args are already rearranged
if newArgsMap.Len() > 0 {
args := make([]interface{}, 0, newArgsMap.Len())
for pair := newArgsMap.Oldest(); pair != nil; pair = pair.Next() {
args = append(args, pair.Value)
}
logger.Debugf("Pika args: %v", args)
return q, args
}
args := make([]interface{}, 0, b.args.Len())
for pair := b.args.Oldest(); pair != nil; pair = pair.Next() {
args = append(args, pair.Value)
}
logger.Debugf("Pika args: %v", args)
return q, args