-
Notifications
You must be signed in to change notification settings - Fork 4
/
query.go
1293 lines (1086 loc) · 35 KB
/
query.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 actions
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"github.com/samber/lo"
"github.com/teamkeel/keel/casing"
"github.com/teamkeel/keel/db"
"github.com/teamkeel/keel/proto"
"github.com/teamkeel/keel/runtime/auth"
"github.com/teamkeel/keel/runtime/common"
"github.com/teamkeel/keel/schema/parser"
"go.opentelemetry.io/otel/trace"
)
// Some field on the query builder's model.
func Field(field string) *QueryOperand {
return &QueryOperand{
column: casing.ToSnake(field),
}
}
// The identifier field on the query builder's model.
func IdField() *QueryOperand {
return &QueryOperand{
column: casing.ToSnake(parser.ImplicitFieldNameId),
}
}
// All fields on the query builder's model.
func AllFields() *QueryOperand {
return &QueryOperand{
column: "*",
}
}
// Some field from the fragments of an expression or input.
func ExpressionField(fragments []string, field string) *QueryOperand {
return &QueryOperand{
table: casing.ToSnake(strings.Join(fragments, "$")),
column: casing.ToSnake(field),
}
}
// Represents an inline query.
// column refers to the single column to select from the inline query statement.
func InlineQuery(query *QueryBuilder, column *QueryOperand) *QueryOperand {
return &QueryOperand{
query: query,
table: column.table,
column: column.column,
}
}
// Represents a raw SQL operand.
func Raw(sql string) *QueryOperand {
return &QueryOperand{raw: sql}
}
// Represents a value operand.
func Value(value any) *QueryOperand {
return &QueryOperand{value: value}
}
// Represents a null value operand.
func Null() *QueryOperand {
return &QueryOperand{}
}
type QueryOperand struct {
query *QueryBuilder
raw string
table string
column string
value any
}
// A query builder to be evaluated and injected as an operand.
func (o *QueryOperand) IsInlineQuery() bool {
return o.query != nil
}
// Raw SQL to be used as a operand.
func (o *QueryOperand) IsRaw() bool {
return o.raw != ""
}
func (o *QueryOperand) IsField() bool {
return o.column != "" && o.query == nil
}
func (o *QueryOperand) IsValue() bool {
return o.value != nil && o.query == nil
}
func (o *QueryOperand) IsNull() bool {
return o.query == nil && o.table == "" && o.column == "" && o.value == nil && o.raw == ""
}
func (o *QueryOperand) toSqlOperandString(query *QueryBuilder) string {
switch {
case o.IsValue():
return "?"
case o.IsField():
table := o.table
// If no model table is specified, then use the base model in the query builder
if table == "" {
table = query.table
}
return sqlQuote(table, o.column)
case o.IsNull():
return "NULL"
case o.IsRaw():
return o.raw
case o.IsInlineQuery():
return fmt.Sprintf("(%s)", o.query.SelectStatement().SqlTemplate())
default:
return ""
}
}
func (o *QueryOperand) toSqlArgs() []any {
switch {
case o.IsValue():
return []any{o.value}
case o.IsField(), o.IsNull(), o.IsRaw():
return []any{}
case o.IsInlineQuery():
return o.query.SelectStatement().SqlArgs()
default:
return nil
}
}
// The templated SQL statement and associated values, ready to be executed.
type Statement struct {
// The generated SQL template.
template string
// The arguments associated with the generated SQL template.
args []any
}
func (statement *Statement) SqlTemplate() string {
return statement.template
}
func (statement *Statement) SqlArgs() []any {
return statement.args
}
type QueryBuilder struct {
context context.Context
// The base model this query builder is acting on.
Model *proto.Model
// The table name in the database.
table string
// The columns and clauses in SELECT.
selection []string
// The columns and clause in DISTINCT ON.
distinctOn []string
// The join clauses required for the query.
joins []joinClause
// The filter fragments used to construct WHERE.
filters []string
// The columns and clauses in ORDER BY.
orderBy []*orderClause
// The columns and clauses in RETURNING.
returning []string
// The value for LIMIT.
limit *int
// The ordered slice of arguments for the SQL statement template.
args []any
// The graph of rows to be written during an INSERT or UPDATE.
writeValues *Row
// The type of SQL join to use.
joinType JoinType
}
type JoinType string
const (
JoinTypeInner JoinType = "INNER"
JoinTypeLeft JoinType = "LEFT"
)
type JoinOption struct {
Type JoinType
}
type joinClause struct {
table string
alias string
condition string
joinType JoinType
}
type orderClause struct {
field *QueryOperand
direction string
}
type Row struct {
// The schema model which this row represents data for.
model *proto.Model
// The target fragments that this row represents in the input.
target []string
// The values of the fields to insert.
values map[string]*QueryOperand
// Other rows to insert which this row depends on.
references []*Relationship
// Other rows to insert which are dependent on this row.
referencedBy []*Relationship
}
type Relationship struct {
// The row which is either referenced to or by in a relationship.
row *Row
// The foreign key in the relationship.
foreignKey *proto.Field
}
type QueryBuilderOption func(qb *QueryBuilder)
func WithJoinType(joinType JoinType) QueryBuilderOption {
return func(qb *QueryBuilder) {
qb.joinType = joinType
}
}
func NewQuery(ctx context.Context, model *proto.Model, opts ...QueryBuilderOption) *QueryBuilder {
qb := &QueryBuilder{
context: ctx,
Model: model,
table: casing.ToSnake(model.Name),
selection: []string{},
distinctOn: []string{},
joins: []joinClause{},
filters: []string{},
orderBy: []*orderClause{},
limit: nil,
returning: []string{},
args: []any{},
writeValues: &Row{
model: nil,
target: nil,
values: map[string]*QueryOperand{},
referencedBy: []*Relationship{},
references: []*Relationship{},
},
joinType: JoinTypeLeft,
}
if len(opts) > 0 {
for _, o := range opts {
o(qb)
}
}
return qb
}
// Creates a copy of the query builder.
func (query *QueryBuilder) Copy() *QueryBuilder {
return &QueryBuilder{
Model: query.Model,
table: query.table,
selection: copySlice(query.selection),
distinctOn: copySlice(query.distinctOn),
joins: copySlice(query.joins),
filters: copySlice(query.filters),
orderBy: copySlice(query.orderBy),
limit: query.limit,
returning: copySlice(query.returning),
args: query.args,
}
}
// Includes a value to be written during an INSERT or UPDATE.
func (query *QueryBuilder) AddWriteValue(operand *QueryOperand, value *QueryOperand) {
query.writeValues.values[operand.column] = value
}
// Includes values to be written during an INSERT or UPDATE.
func (query *QueryBuilder) AddWriteValues(values map[string]*QueryOperand) {
query.writeValues.model = query.Model
for k, v := range values {
query.AddWriteValue(Field(k), v)
}
}
// Includes a column in SELECT.
func (query *QueryBuilder) AppendSelect(operand *QueryOperand) {
c := operand.toSqlOperandString(query)
if !lo.Contains(query.selection, c) {
query.selection = append(query.selection, c)
}
}
// Include a clause in SELECT.
func (query *QueryBuilder) AppendSelectClause(clause string) {
if !lo.Contains(query.selection, clause) {
query.selection = append(query.selection, clause)
}
}
// Include a column in this table in DISTINCT ON.
func (query *QueryBuilder) AppendDistinctOn(operand *QueryOperand) {
c := operand.toSqlOperandString(query)
if !lo.Contains(query.distinctOn, c) {
query.distinctOn = append(query.distinctOn, c)
}
}
// Include a WHERE condition, ANDed to the existing filters (unless an OR has been specified)
func (query *QueryBuilder) Where(left *QueryOperand, operator ActionOperator, right *QueryOperand) error {
template, args, err := query.generateConditionTemplate(left, operator, right)
if err != nil {
return err
}
query.filters = append(query.filters, template)
query.args = append(query.args, args...)
return nil
}
// Appends the next condition with a logical AND.
func (query *QueryBuilder) And() {
query.filters = trimRhsOperators(query.filters)
if len(query.filters) > 0 {
query.filters = append(query.filters, "AND")
}
}
// Appends the next condition with a logical OR.
func (query *QueryBuilder) Or() {
query.filters = trimRhsOperators(query.filters)
if len(query.filters) > 0 {
query.filters = append(query.filters, "OR")
}
}
// Opens a new conditional scope in the where expression (i.e. open parethesis).
func (query *QueryBuilder) OpenParenthesis() {
query.filters = append(query.filters, "(")
}
// Closes the current conditional scope in the where expression (i.e. close parethesis).
func (query *QueryBuilder) CloseParenthesis() {
query.filters = trimRhsOperators(query.filters)
query.filters = append(query.filters, ")")
}
// Trims an excess OR / AND operators from the rhs side of the filter conditions.
func trimRhsOperators(filters []string) []string {
return lo.DropRightWhile(filters, func(s string) bool { return s == "OR" || s == "AND" })
}
// Include an JOIN clause.
func (query *QueryBuilder) Join(joinModel string, joinField *QueryOperand, modelField *QueryOperand) {
join := joinClause{
table: sqlQuote(casing.ToSnake(joinModel)),
alias: sqlQuote(joinField.table),
condition: fmt.Sprintf("%s = %s", joinField.toSqlOperandString(query), modelField.toSqlOperandString(query)),
joinType: query.joinType,
}
if !lo.Contains(query.joins, join) {
query.joins = append(query.joins, join)
}
}
// Include a column in ORDER BY.
// If the column already exists, then just update the sort direction.
func (query *QueryBuilder) AppendOrderBy(operand *QueryOperand, direction string) {
order := &orderClause{field: operand, direction: strings.ToUpper(direction)}
existing, found := lo.Find(query.orderBy, func(o *orderClause) bool {
return o.field.column == order.field.column
})
if found {
existing.direction = strings.ToUpper(direction)
} else {
query.orderBy = append(query.orderBy, order)
query.AppendDistinctOn(operand)
}
}
// Set the LIMIT to a number.
func (query *QueryBuilder) Limit(limit int) {
query.limit = &limit
}
// Include a column in RETURNING.
func (query *QueryBuilder) AppendReturning(operand *QueryOperand) {
c := operand.toSqlOperandString(query)
if !lo.Contains(query.returning, c) {
query.returning = append(query.returning, c)
}
}
// Apply pagination filters to the query.
func (query *QueryBuilder) ApplyPaging(page Page) error {
// Paging condition is ANDed to any existing conditions
query.And()
// Add where condition to implement the page size
switch {
case page.First != 0:
query.Limit(page.First)
case page.Last != 0:
query.Limit(page.Last)
}
// Specify the ORDER BY - but also a "LEAD" extra column to harvest extra data
// that helps to determine "hasNextPage"
query.AppendOrderBy(IdField(), "ASC")
// Select hasNext clause
orderByClausesAsSql := []string{}
for _, o := range query.orderBy {
orderByClausesAsSql = append(orderByClausesAsSql, fmt.Sprintf("%s %s", o.field.toSqlOperandString(query), o.direction))
}
hasNext := fmt.Sprintf("CASE WHEN LEAD(%s) OVER (ORDER BY %s) IS NOT NULL THEN true ELSE false END AS hasNext", IdField().toSqlOperandString(query), strings.Join(orderByClausesAsSql, ", "))
query.AppendSelectClause(hasNext)
// We add a subquery to the select list that fetches the total count of records
// matching the constraints specified by the main query without the offset/limit applied
// This is actually more performant than COUNT(*) OVER() [window function]
totalResults := fmt.Sprintf("(%s) AS totalCount", query.countQuery())
query.AppendSelectClause(totalResults)
// Because we are essentially performing the same query again within the subquery, we need to duplicate the query parameters again as they will be used twice in the course of the whole query
query.args = append(query.args, query.args...)
// Add where condition to implement the after/before paging request
switch {
case page.After != "":
err := query.applyCursorFilter(page.After, false)
if err != nil {
return err
}
case page.Before != "":
err := query.applyCursorFilter(page.Before, true)
if err != nil {
return err
}
}
return nil
}
// Apply forward pagination 'after' cursor filter to the query.
func (query *QueryBuilder) applyCursorFilter(cursor string, isBackwards bool) error {
query.And()
var err error
if len(query.orderBy) > 1 {
query.OpenParenthesis()
}
// For each column being ordered, we need to filter those which proceed the cursor row.
for i := 0; i < len(query.orderBy); i++ {
if i > 0 {
query.OpenParenthesis()
}
for j := 0; j < i; j++ {
orderClause := query.orderBy[j]
inline := NewQuery(query.context, query.Model)
inline.AppendSelect(orderClause.field)
err = inline.Where(IdField(), Equals, Value(cursor))
if err != nil {
return err
}
err = query.Where(orderClause.field, Equals, InlineQuery(inline, orderClause.field))
if err != nil {
return err
}
query.And()
}
orderClause := query.orderBy[i]
inline := NewQuery(query.context, query.Model)
inline.AppendSelect(orderClause.field)
err = inline.Where(IdField(), Equals, Value(cursor))
if err != nil {
return err
}
var operator ActionOperator
switch {
case strings.EqualFold(orderClause.direction, "ASC") && !isBackwards:
operator = GreaterThan
case strings.EqualFold(orderClause.direction, "ASC") && isBackwards:
operator = LessThan
case strings.EqualFold(orderClause.direction, "DESC") && !isBackwards:
operator = LessThan
case strings.EqualFold(orderClause.direction, "DESC") && isBackwards:
operator = GreaterThan
default:
return errors.New("unknown order by direction")
}
err = query.Where(orderClause.field, operator, InlineQuery(inline, orderClause.field))
if err != nil {
return err
}
if i > 0 {
query.CloseParenthesis()
}
query.Or()
}
if len(query.orderBy) > 1 {
query.CloseParenthesis()
}
return nil
}
func (query *QueryBuilder) countQuery() string {
selection := "COUNT("
joins := ""
filters := ""
if len(query.distinctOn) > 0 {
distinctFields := strings.Join(query.distinctOn, ", ")
if len(query.distinctOn) > 1 {
distinctFields = fmt.Sprintf("(%s)", distinctFields)
}
selection += fmt.Sprintf("DISTINCT %s", distinctFields)
} else {
selection += "*"
}
selection += ")"
if len(query.joins) > 0 {
for _, j := range query.joins {
joins += fmt.Sprintf("%s JOIN %s AS %s ON %s ", query.joinType, j.table, j.alias, j.condition)
}
}
conditions := trimRhsOperators(query.filters)
if len(conditions) > 0 {
filters = fmt.Sprintf("WHERE %s", strings.Join(conditions, " "))
}
sql := fmt.Sprintf("SELECT %s FROM %s %s %s",
selection,
sqlQuote(query.table),
joins,
filters)
return sql
}
// Generates an executable SELECT statement with the list of arguments.
func (query *QueryBuilder) SelectStatement() *Statement {
distinctOn := ""
selection := ""
joins := ""
filters := ""
orderBy := ""
limit := ""
if len(query.distinctOn) > 0 {
distinctOn = fmt.Sprintf("DISTINCT ON(%s)", strings.Join(query.distinctOn, ", "))
}
if len(query.selection) == 0 {
query.AppendSelect(AllFields())
}
selection = strings.Join(query.selection, ", ")
if len(query.joins) > 0 {
for _, j := range query.joins {
joins += fmt.Sprintf("%s JOIN %s AS %s ON %s ", query.joinType, j.table, j.alias, j.condition)
}
}
conditions := trimRhsOperators(query.filters)
if len(conditions) > 0 {
filters = fmt.Sprintf("WHERE %s", strings.Join(conditions, " "))
}
if len(query.orderBy) > 0 {
orderByClausesAsSql := []string{}
for _, o := range query.orderBy {
orderByClausesAsSql = append(orderByClausesAsSql, fmt.Sprintf("%s %s", o.field.toSqlOperandString(query), o.direction))
}
orderBy = fmt.Sprintf("ORDER BY %s", strings.Join(orderByClausesAsSql, ", "))
}
if query.limit != nil {
limit = "LIMIT ?"
query.args = append(query.args, *query.limit)
}
sql := fmt.Sprintf("SELECT %s %s FROM %s %s %s %s %s",
distinctOn,
selection,
sqlQuote(query.table),
joins,
filters,
orderBy,
limit)
return &Statement{
template: sql,
args: query.args,
}
}
// Generates an executable INSERT statement with the list of arguments.
func (query *QueryBuilder) InsertStatement() *Statement {
ctes := []string{}
args := []any{}
ctes, args, alias := query.generateInsertCte(ctes, args, query.writeValues, nil, "")
selection := []string{"*"}
if auth.IsAuthenticated(query.context) {
identity, _ := auth.GetIdentity(query.context)
selection = append(selection, setIdentityIdClause(identity.Id))
}
spanContext := trace.SpanContextFromContext(query.context)
if spanContext.IsValid() {
selection = append(selection, setTraceIdClause(spanContext.TraceID().String()))
}
statement := fmt.Sprintf("WITH %s SELECT %s FROM %s",
strings.Join(ctes, ", "),
strings.Join(selection, ", "),
alias)
return &Statement{
template: statement,
args: args,
}
}
// Recursively generates in common table expression insert query for the write values graph.
func (query *QueryBuilder) generateInsertCte(ctes []string, args []any, row *Row, foreignKey *proto.Field, primaryKeyTableAlias string) ([]string, []any, string) {
alias := fmt.Sprintf("new_%v_%s", makeAlias(query.writeValues, row), casing.ToSnake(row.model.Name))
columnNames := []string{}
// Rows which this row references need to created first, and the primary needs to be extracted (as a SELECT statement from them to insert into this row.
// The foreign key field for this row is returned, along with the alias of the table needed to extract the primary key from.
for _, r := range row.references {
var primaryKeyTable string
ctes, args, primaryKeyTable = query.generateInsertCte(ctes, args, r.row, nil, alias)
// For every row that this references, we need to set the foreign key.
// For example, on the Sale row; customerId = (SELECT id FROM new_customer_1)
row.values[r.foreignKey.ForeignKeyFieldName.Value] = Raw(fmt.Sprintf("(SELECT id FROM %s)", primaryKeyTable))
}
// Does this foreign key of the relationship exist on this row?
// This means this row exists as a referencedBy row for another.
// For example, on the SaleItem row; saleId = (SELECT id FROM new_sale_1)
if foreignKey != nil && row.model.Name == foreignKey.ModelName {
row.values[foreignKey.ForeignKeyFieldName.Value] = Raw(fmt.Sprintf("(SELECT id FROM %s)", primaryKeyTableAlias))
}
// Make iterating through the map with deterministic ordering
orderedKeys := make([]string, 0, len(row.values))
for k := range row.values {
orderedKeys = append(orderedKeys, k)
}
sort.Strings(orderedKeys)
columnValues := []string{}
// For any inline query operands (such as with backlinks),
// we want to create the common table expressions first,
// and ensure we only create the CTE once (as there may be more
// than once reference by other fields).
for _, col := range orderedKeys {
operand := row.values[col]
if !operand.IsInlineQuery() {
continue
}
cteAlias := fmt.Sprintf("select_%s", operand.query.table)
cteExists := false
for _, c := range ctes {
if strings.HasPrefix(c, cteAlias) {
cteExists = true
break
}
}
if !cteExists {
cteAliases := []string{}
for i := range operand.query.selection {
cteAliases = append(cteAliases, fmt.Sprintf("column_%v", i))
}
cte := fmt.Sprintf("%s (%s) AS (%s)",
cteAlias,
strings.Join(cteAliases, ", "),
operand.query.SelectStatement().SqlTemplate())
ctes = append(ctes, cte)
args = append(args, operand.query.SelectStatement().SqlArgs()...)
}
}
for _, col := range orderedKeys {
colName := casing.ToSnake(col)
columnNames = append(columnNames, colName)
operand := row.values[col]
switch {
case operand.IsField(), operand.IsValue(), operand.IsNull(), operand.IsRaw():
sql := operand.toSqlOperandString(query)
opArgs := operand.toSqlArgs()
columnValues = append(columnValues, sql)
args = append(args, opArgs...)
case operand.IsInlineQuery():
cteAlias := fmt.Sprintf("select_%s", operand.query.table)
columnAlias := ""
for i, s := range operand.query.selection {
if s == sqlQuote(operand.table, operand.column) {
columnAlias = fmt.Sprintf("column_%v", i)
break
}
}
sql := fmt.Sprintf("(SELECT %s FROM %s)", columnAlias, cteAlias)
columnValues = append(columnValues, sql)
default:
panic("no handling for rhs QueryOperand type")
}
}
// If there are no values to insert then we use "DEFAULT VALUES" which means:
// "All columns will be filled with their default values"
values := "DEFAULT VALUES"
if len(columnNames) > 0 {
values = fmt.Sprintf("(%s) VALUES (%s)",
strings.Join(columnNames, ", "),
strings.Join(columnValues, ", "))
}
cte := fmt.Sprintf("%s AS (INSERT INTO %s %s RETURNING *)",
alias,
sqlQuote(casing.ToSnake(row.model.Name)),
values)
ctes = append(ctes, cte)
// If this row is referenced by other rows, then we need to create these rows afterwards. We need to pass in this row table alias in order to extract the primary key.
for _, r := range row.referencedBy {
ctes, args, _ = query.generateInsertCte(ctes, args, r.row, r.foreignKey, alias)
}
return ctes, args, alias
}
// Generates a unique alias for this row in the graph.
func makeAlias(graph *Row, row *Row) int {
rows := orderGraphNodes(graph)
modelCount := map[string]int{}
for _, r := range rows {
modelCount[r.model.Name] += 1
if r == row {
return modelCount[r.model.Name]
}
}
panic("the row does not exist within this graph")
}
// Generates an ordered slice of rows by insertion order.
func orderGraphNodes(graph *Row) []*Row {
rows := []*Row{}
for _, r := range graph.references {
g := orderGraphNodes(r.row)
rows = append(rows, g...)
}
rows = append(rows, graph)
for _, r := range graph.referencedBy {
g := orderGraphNodes(r.row)
rows = append(rows, g...)
}
return rows
}
// Generates an executable UPDATE statement with the list of arguments.
func (query *QueryBuilder) UpdateStatement() *Statement {
queryFilters := query.filters
joins := ""
filters := ""
returning := ""
sets := []string{}
args := []any{}
ctes := []string{}
// Make iteratng through the writeValues map deterministically ordered
orderedKeys := make([]string, 0, len(query.writeValues.values))
for k := range query.writeValues.values {
orderedKeys = append(orderedKeys, k)
}
sort.Strings(orderedKeys)
for _, v := range orderedKeys {
operand := query.writeValues.values[v]
if !operand.IsInlineQuery() {
continue
}
cteAlias := fmt.Sprintf("select_%s", operand.query.table)
cteExists := false
for _, c := range ctes {
if strings.HasPrefix(c, cteAlias) {
cteExists = true
break
}
}
if !cteExists {
cteAliases := []string{}
for i := range operand.query.selection {
cteAliases = append(cteAliases, fmt.Sprintf("column_%v", i))
}
cte := fmt.Sprintf("%s (%s) AS (%s)",
cteAlias,
strings.Join(cteAliases, ", "),
operand.query.SelectStatement().SqlTemplate())
ctes = append(ctes, cte)
args = append(args, operand.query.SelectStatement().SqlArgs()...)
}
}
for _, v := range orderedKeys {
operand := query.writeValues.values[v]
if operand.IsInlineQuery() {
cteAlias := fmt.Sprintf("select_%s", operand.query.table)
columnAlias := ""
for i, s := range operand.query.selection {
if s == sqlQuote(operand.table, operand.column) {
columnAlias = fmt.Sprintf("column_%v", i)
break
}
}
sql := fmt.Sprintf("(SELECT %s FROM %s)", columnAlias, cteAlias)
sets = append(sets, fmt.Sprintf("%s = %s", casing.ToSnake(v), sql))
} else {
sqlOperand := operand.toSqlOperandString(query)
sqlArgs := operand.toSqlArgs()
args = append(args, sqlArgs...)
sets = append(sets, fmt.Sprintf("%s = %s", casing.ToSnake(v), sqlOperand))
}
}
args = append(args, query.args...)
var from string
if len(query.joins) > 0 {
for i, j := range query.joins {
if i == 0 {
from = fmt.Sprintf("FROM %s AS %s", j.table, j.alias)
queryFilters = append([]string{j.condition, "AND"}, queryFilters...)
} else {
joins += fmt.Sprintf("%s JOIN %s AS %s ON %s ", query.joinType, j.table, j.alias, j.condition)
}
}
}
conditions := trimRhsOperators(queryFilters)
if len(conditions) > 0 {
filters = fmt.Sprintf("WHERE %s", strings.Join(conditions, " "))
}
if auth.IsAuthenticated(query.context) {
identity, _ := auth.GetIdentity(query.context)
query.returning = append(query.returning, setIdentityIdClause(identity.Id))
}
spanContext := trace.SpanContextFromContext(query.context)
if spanContext.IsValid() {
query.returning = append(query.returning, setTraceIdClause(spanContext.TraceID().String()))
}
if len(query.returning) > 0 {
returning = fmt.Sprintf("RETURNING %s", strings.Join(query.returning, ", "))
}
commonTableExpressions := ""
if len(ctes) > 0 {
commonTableExpressions = fmt.Sprintf("WITH %s", strings.Join(ctes, ", "))
}
template := fmt.Sprintf("%s UPDATE %s SET %s %s %s %s %s",
commonTableExpressions,
sqlQuote(query.table),
strings.Join(sets, ", "),
from,
joins,
filters,
returning)
return &Statement{
template: template,
args: args,
}
}
// Generates an executable DELETE statement with the list of arguments.
func (query *QueryBuilder) DeleteStatement() *Statement {
usings := ""
filters := ""
returning := ""
if len(query.joins) > 0 {
usingTables := lo.Map(query.joins, func(j joinClause, _ int) string {
return fmt.Sprintf("%s AS %s", j.table, j.alias)
})
usings = fmt.Sprintf("USING %s", strings.Join(usingTables, ", "))
filters = strings.Join(lo.Map(query.joins, func(j joinClause, _ int) string { return j.condition }), " AND ")
// If there are also filters, then append another AND
if len(query.filters) > 0 {
filters += " AND "
}
}
conditions := trimRhsOperators(query.filters)
if len(conditions) > 0 {
filters = fmt.Sprintf("WHERE %s", strings.Join(conditions, " "))
}
if auth.IsAuthenticated(query.context) {
identity, _ := auth.GetIdentity(query.context)
query.returning = append(query.returning, setIdentityIdClause(identity.Id))
}
spanContext := trace.SpanContextFromContext(query.context)
if spanContext.IsValid() {
query.returning = append(query.returning, setTraceIdClause(spanContext.TraceID().String()))
}
if len(query.returning) > 0 {
returning = fmt.Sprintf("RETURNING %s", strings.Join(query.returning, ", "))
}
template := fmt.Sprintf("DELETE FROM %s %s %s %s",
sqlQuote(query.table),
usings,
filters,
returning)
return &Statement{
template: template,
args: query.args,
}
}
// Execute the SQL statement against the database, returning the number of rows affected.
func (statement *Statement) Execute(ctx context.Context) (int, error) {
database, err := db.GetDatabase(ctx)
if err != nil {
return 0, err
}
result, err := database.ExecuteStatement(ctx, statement.template, statement.args...)
if err != nil {
return 0, toRuntimeError(err)