-
Notifications
You must be signed in to change notification settings - Fork 5
/
query.go
804 lines (712 loc) · 19.1 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
package orm
import (
"database/sql"
"fmt"
"strings"
)
const (
queryTypeSELECT = iota + 1
queryTypeUPDATE
queryTypeDelete
)
// QueryBuilder is our query builder, almost all methods and functions in GoLobby ORM
// create or configure instance of QueryBuilder.
type QueryBuilder[OUTPUT any] struct {
typ int
schema *schema
// general parts
where *whereClause
table string
placeholderGenerator func(n int) []string
// select parts
orderBy *orderByClause
groupBy *GroupBy
selected *selected
subQuery *struct {
q string
args []interface{}
placeholderGenerator func(n int) []string
}
joins []*Join
limit *Limit
offset *Offset
// update parts
sets [][2]interface{}
// execution parts
db *sql.DB
err error
}
// Finisher APIs
// execute is a finisher executes QueryBuilder query, remember to use this when you have an Update
// or Delete Query.
func (q *QueryBuilder[OUTPUT]) execute() (sql.Result, error) {
if q.err != nil {
return nil, q.err
}
if q.typ == queryTypeSELECT {
return nil, fmt.Errorf("query type is SELECT")
}
query, args, err := q.ToSql()
if err != nil {
return nil, err
}
return q.schema.getConnection().exec(query, args...)
}
// Get limit results to 1, runs query generated by query builder, scans result into OUTPUT.
func (q *QueryBuilder[OUTPUT]) Get() (OUTPUT, error) {
if q.err != nil {
return *new(OUTPUT), q.err
}
queryString, args, err := q.ToSql()
if err != nil {
return *new(OUTPUT), err
}
rows, err := q.schema.getConnection().query(queryString, args...)
if err != nil {
return *new(OUTPUT), err
}
var output OUTPUT
err = newBinder(q.schema).bind(rows, &output)
if err != nil {
return *new(OUTPUT), err
}
return output, nil
}
// All is a finisher, create the Select query based on QueryBuilder and scan results into
// slice of type parameter E.
func (q *QueryBuilder[OUTPUT]) All() ([]OUTPUT, error) {
if q.err != nil {
return nil, q.err
}
q.SetSelect()
queryString, args, err := q.ToSql()
if err != nil {
return nil, err
}
rows, err := q.schema.getConnection().query(queryString, args...)
if err != nil {
return nil, err
}
var output []OUTPUT
err = newBinder(q.schema).bind(rows, &output)
if err != nil {
return nil, err
}
return output, nil
}
// Delete is a finisher, creates a delete query from query builder and executes it.
func (q *QueryBuilder[OUTPUT]) Delete() (rowsAffected int64, err error) {
if q.err != nil {
return 0, q.err
}
q.SetDelete()
res, err := q.execute()
if err != nil {
return 0, q.err
}
return res.RowsAffected()
}
// Update is a finisher, creates an Update query from QueryBuilder and executes in into database, returns
func (q *QueryBuilder[OUTPUT]) Update() (rowsAffected int64, err error) {
if q.err != nil {
return 0, q.err
}
q.SetUpdate()
res, err := q.execute()
if err != nil {
return 0, err
}
return res.RowsAffected()
}
func copyQueryBuilder[T1 any, T2 any](q *QueryBuilder[T1], q2 *QueryBuilder[T2]) {
q2.db = q.db
q2.err = q.err
q2.groupBy = q.groupBy
q2.joins = q.joins
q2.limit = q.limit
q2.offset = q.offset
q2.orderBy = q.orderBy
q2.placeholderGenerator = q.placeholderGenerator
q2.schema = q.schema
q2.selected = q.selected
q2.sets = q.sets
q2.subQuery = q.subQuery
q2.table = q.table
q2.typ = q.typ
q2.where = q.where
}
// Count creates and execute a select query from QueryBuilder and set it's field list of selection
// to COUNT(id).
func (q *QueryBuilder[OUTPUT]) Count() *QueryBuilder[int] {
q.selected = &selected{Columns: []string{"COUNT(id)"}}
q.SetSelect()
qCount := NewQueryBuilder[int](q.schema)
copyQueryBuilder(q, qCount)
return qCount
}
// First returns first record of database using OrderBy primary key
// ascending order.
func (q *QueryBuilder[OUTPUT]) First() *QueryBuilder[OUTPUT] {
q.OrderBy(q.schema.pkName(), ASC).Limit(1)
return q
}
// Latest is like Get but it also do a OrderBy(primary key, DESC)
func (q *QueryBuilder[OUTPUT]) Latest() *QueryBuilder[OUTPUT] {
q.OrderBy(q.schema.pkName(), DESC).Limit(1)
return q
}
// WherePK adds a where clause to QueryBuilder and also gets primary key name
// from type parameter schema.
func (q *QueryBuilder[OUTPUT]) WherePK(value interface{}) *QueryBuilder[OUTPUT] {
return q.Where(q.schema.pkName(), value)
}
func (d *QueryBuilder[OUTPUT]) toSqlDelete() (string, []interface{}, error) {
base := fmt.Sprintf("DELETE FROM %s", d.table)
var args []interface{}
if d.where != nil {
d.where.PlaceHolderGenerator = d.placeholderGenerator
where, whereArgs, err := d.where.ToSql()
if err != nil {
return "", nil, err
}
base += " WHERE " + where
args = append(args, whereArgs...)
}
return base, args, nil
}
func pop(phs *[]string) string {
top := (*phs)[len(*phs)-1]
*phs = (*phs)[:len(*phs)-1]
return top
}
func (u *QueryBuilder[OUTPUT]) kvString() string {
phs := u.placeholderGenerator(len(u.sets))
var sets []string
for _, pair := range u.sets {
sets = append(sets, fmt.Sprintf("%s=%s", pair[0], pop(&phs)))
}
return strings.Join(sets, ",")
}
func (u *QueryBuilder[OUTPUT]) args() []interface{} {
var values []interface{}
for _, pair := range u.sets {
values = append(values, pair[1])
}
return values
}
func (u *QueryBuilder[OUTPUT]) toSqlUpdate() (string, []interface{}, error) {
if u.table == "" {
return "", nil, fmt.Errorf("table cannot be empty")
}
base := fmt.Sprintf("UPDATE %s SET %s", u.table, u.kvString())
args := u.args()
if u.where != nil {
u.where.PlaceHolderGenerator = u.placeholderGenerator
where, whereArgs, err := u.where.ToSql()
if err != nil {
return "", nil, err
}
args = append(args, whereArgs...)
base += " WHERE " + where
}
return base, args, nil
}
func (s *QueryBuilder[OUTPUT]) toSqlSelect() (string, []interface{}, error) {
if s.err != nil {
return "", nil, s.err
}
base := "SELECT"
var args []interface{}
// select
if s.selected == nil {
s.selected = &selected{
Columns: []string{"*"},
}
}
base += " " + s.selected.String()
// from
if s.table == "" && s.subQuery == nil {
return "", nil, fmt.Errorf("Table name cannot be empty")
} else if s.table != "" && s.subQuery != nil {
return "", nil, fmt.Errorf("cannot have both Table and subquery")
}
if s.table != "" {
base += " " + "FROM " + s.table
}
if s.subQuery != nil {
s.subQuery.placeholderGenerator = s.placeholderGenerator
base += " " + "FROM (" + s.subQuery.q + " )"
args = append(args, s.subQuery.args...)
}
// Joins
if s.joins != nil {
for _, join := range s.joins {
base += " " + join.String()
}
}
// whereClause
if s.where != nil {
s.where.PlaceHolderGenerator = s.placeholderGenerator
where, whereArgs, err := s.where.ToSql()
if err != nil {
return "", nil, err
}
base += " WHERE " + where
args = append(args, whereArgs...)
}
// orderByClause
if s.orderBy != nil {
base += " " + s.orderBy.String()
}
// GroupBy
if s.groupBy != nil {
base += " " + s.groupBy.String()
}
// Limit
if s.limit != nil {
base += " " + s.limit.String()
}
// Offset
if s.offset != nil {
base += " " + s.offset.String()
}
return base, args, nil
}
// ToSql creates sql query from QueryBuilder based on internal fields it would decide what kind
// of query to build.
func (q *QueryBuilder[OUTPUT]) ToSql() (string, []interface{}, error) {
if q.err != nil {
return "", nil, q.err
}
if q.typ == queryTypeSELECT {
return q.toSqlSelect()
} else if q.typ == queryTypeDelete {
return q.toSqlDelete()
} else if q.typ == queryTypeUPDATE {
return q.toSqlUpdate()
} else {
return "", nil, fmt.Errorf("no sql type matched")
}
}
type orderByOrder string
const (
ASC = "ASC"
DESC = "DESC"
)
type orderByClause struct {
Columns [][2]string
}
func (o orderByClause) String() string {
var tuples []string
for _, pair := range o.Columns {
tuples = append(tuples, fmt.Sprintf("%s %s", pair[0], pair[1]))
}
return fmt.Sprintf("ORDER BY %s", strings.Join(tuples, ","))
}
type GroupBy struct {
Columns []string
}
func (g GroupBy) String() string {
return fmt.Sprintf("GROUP BY %s", strings.Join(g.Columns, ","))
}
type joinType string
const (
JoinTypeInner = "INNER"
JoinTypeLeft = "LEFT"
JoinTypeRight = "RIGHT"
JoinTypeFull = "FULL OUTER"
JoinTypeSelf = "SELF"
)
type JoinOn struct {
Lhs string
Rhs string
}
func (j JoinOn) String() string {
return fmt.Sprintf("%s = %s", j.Lhs, j.Rhs)
}
type Join struct {
Type joinType
Table string
On JoinOn
}
func (j Join) String() string {
return fmt.Sprintf("%s JOIN %s ON %s", j.Type, j.Table, j.On.String())
}
type Limit struct {
N int
}
func (l Limit) String() string {
return fmt.Sprintf("LIMIT %d", l.N)
}
type Offset struct {
N int
}
func (o Offset) String() string {
return fmt.Sprintf("OFFSET %d", o.N)
}
type selected struct {
Columns []string
}
func (s selected) String() string {
return fmt.Sprintf("%s", strings.Join(s.Columns, ","))
}
// OrderBy adds an OrderBy section to QueryBuilder.
func (q *QueryBuilder[OUTPUT]) OrderBy(column string, how string) *QueryBuilder[OUTPUT] {
q.SetSelect()
if q.orderBy == nil {
q.orderBy = &orderByClause{}
}
q.orderBy.Columns = append(q.orderBy.Columns, [2]string{column, how})
return q
}
// LeftJoin adds a left join section to QueryBuilder.
func (q *QueryBuilder[OUTPUT]) LeftJoin(table string, onLhs string, onRhs string) *QueryBuilder[OUTPUT] {
q.SetSelect()
q.joins = append(q.joins, &Join{
Type: JoinTypeLeft,
Table: table,
On: JoinOn{
Lhs: onLhs,
Rhs: onRhs,
},
})
return q
}
// RightJoin adds a right join section to QueryBuilder.
func (q *QueryBuilder[OUTPUT]) RightJoin(table string, onLhs string, onRhs string) *QueryBuilder[OUTPUT] {
q.SetSelect()
q.joins = append(q.joins, &Join{
Type: JoinTypeRight,
Table: table,
On: JoinOn{
Lhs: onLhs,
Rhs: onRhs,
},
})
return q
}
// InnerJoin adds a inner join section to QueryBuilder.
func (q *QueryBuilder[OUTPUT]) InnerJoin(table string, onLhs string, onRhs string) *QueryBuilder[OUTPUT] {
q.SetSelect()
q.joins = append(q.joins, &Join{
Type: JoinTypeInner,
Table: table,
On: JoinOn{
Lhs: onLhs,
Rhs: onRhs,
},
})
return q
}
// Join adds a inner join section to QueryBuilder.
func (q *QueryBuilder[OUTPUT]) Join(table string, onLhs string, onRhs string) *QueryBuilder[OUTPUT] {
return q.InnerJoin(table, onLhs, onRhs)
}
// FullOuterJoin adds a full outer join section to QueryBuilder.
func (q *QueryBuilder[OUTPUT]) FullOuterJoin(table string, onLhs string, onRhs string) *QueryBuilder[OUTPUT] {
q.SetSelect()
q.joins = append(q.joins, &Join{
Type: JoinTypeFull,
Table: table,
On: JoinOn{
Lhs: onLhs,
Rhs: onRhs,
},
})
return q
}
// Where Adds a where clause to query, if already have where clause append to it
// as AndWhere.
func (q *QueryBuilder[OUTPUT]) Where(parts ...interface{}) *QueryBuilder[OUTPUT] {
if q.where != nil {
return q.addWhere("AND", parts...)
}
if len(parts) == 1 {
if r, isRaw := parts[0].(*raw); isRaw {
q.where = &whereClause{raw: r.sql, args: r.args, PlaceHolderGenerator: q.placeholderGenerator}
return q
} else {
q.err = fmt.Errorf("when you have one argument passed to where, it should be *raw")
return q
}
} else if len(parts) == 2 {
if strings.Index(parts[0].(string), " ") == -1 {
// Equal mode
q.where = &whereClause{cond: cond{Lhs: parts[0].(string), Op: Eq, Rhs: parts[1]}, PlaceHolderGenerator: q.placeholderGenerator}
}
return q
} else if len(parts) == 3 {
// operator mode
q.where = &whereClause{cond: cond{Lhs: parts[0].(string), Op: binaryOp(parts[1].(string)), Rhs: parts[2]}, PlaceHolderGenerator: q.placeholderGenerator}
return q
} else if len(parts) > 3 && parts[1].(string) == "IN" {
q.where = &whereClause{cond: cond{Lhs: parts[0].(string), Op: binaryOp(parts[1].(string)), Rhs: parts[2:]}, PlaceHolderGenerator: q.placeholderGenerator}
return q
} else {
q.err = fmt.Errorf("wrong number of arguments passed to Where")
return q
}
}
type binaryOp string
const (
Eq = "="
GT = ">"
LT = "<"
GE = ">="
LE = "<="
NE = "!="
Between = "BETWEEN"
Like = "LIKE"
In = "IN"
)
type cond struct {
PlaceHolderGenerator func(n int) []string
Lhs string
Op binaryOp
Rhs interface{}
}
func (b cond) ToSql() (string, []interface{}, error) {
var phs []string
if b.Op == In {
rhs, isInterfaceSlice := b.Rhs.([]interface{})
if isInterfaceSlice {
phs = b.PlaceHolderGenerator(len(rhs))
return fmt.Sprintf("%s IN (%s)", b.Lhs, strings.Join(phs, ",")), rhs, nil
} else if rawThing, isRaw := b.Rhs.(*raw); isRaw {
return fmt.Sprintf("%s IN (%s)", b.Lhs, rawThing.sql), rawThing.args, nil
} else {
return "", nil, fmt.Errorf("Right hand side of Cond when operator is IN should be either a interface{} slice or *raw")
}
} else {
phs = b.PlaceHolderGenerator(1)
return fmt.Sprintf("%s %s %s", b.Lhs, b.Op, pop(&phs)), []interface{}{b.Rhs}, nil
}
}
const (
nextType_AND = "AND"
nextType_OR = "OR"
)
type whereClause struct {
PlaceHolderGenerator func(n int) []string
nextTyp string
next *whereClause
cond
raw string
args []interface{}
}
func (w whereClause) ToSql() (string, []interface{}, error) {
var base string
var args []interface{}
var err error
if w.raw != "" {
base = w.raw
args = w.args
} else {
w.cond.PlaceHolderGenerator = w.PlaceHolderGenerator
base, args, err = w.cond.ToSql()
if err != nil {
return "", nil, err
}
}
if w.next == nil {
return base, args, nil
}
if w.next != nil {
next, nextArgs, err := w.next.ToSql()
if err != nil {
return "", nil, err
}
base += " " + w.nextTyp + " " + next
args = append(args, nextArgs...)
return base, args, nil
}
return base, args, nil
}
//func (q *QueryBuilder[OUTPUT]) WhereKeyValue(m map) {}
// WhereIn adds a where clause to QueryBuilder using In operator.
func (q *QueryBuilder[OUTPUT]) WhereIn(column string, values ...interface{}) *QueryBuilder[OUTPUT] {
return q.Where(append([]interface{}{column, In}, values...)...)
}
// AndWhere appends a where clause to query builder as And where clause.
func (q *QueryBuilder[OUTPUT]) AndWhere(parts ...interface{}) *QueryBuilder[OUTPUT] {
return q.addWhere(nextType_AND, parts...)
}
// OrWhere appends a where clause to query builder as Or where clause.
func (q *QueryBuilder[OUTPUT]) OrWhere(parts ...interface{}) *QueryBuilder[OUTPUT] {
return q.addWhere(nextType_OR, parts...)
}
func (q *QueryBuilder[OUTPUT]) addWhere(typ string, parts ...interface{}) *QueryBuilder[OUTPUT] {
w := q.where
for {
if w == nil {
break
} else if w.next == nil {
w.next = &whereClause{PlaceHolderGenerator: q.placeholderGenerator}
w.nextTyp = typ
w = w.next
break
} else {
w = w.next
}
}
if w == nil {
w = &whereClause{PlaceHolderGenerator: q.placeholderGenerator}
}
if len(parts) == 1 {
w.raw = parts[0].(*raw).sql
w.args = parts[0].(*raw).args
return q
} else if len(parts) == 2 {
// Equal mode
w.cond = cond{Lhs: parts[0].(string), Op: Eq, Rhs: parts[1]}
return q
} else if len(parts) == 3 {
// operator mode
w.cond = cond{Lhs: parts[0].(string), Op: binaryOp(parts[1].(string)), Rhs: parts[2]}
return q
} else {
panic("wrong number of arguments passed to Where")
}
}
// Offset adds offset section to query builder.
func (q *QueryBuilder[OUTPUT]) Offset(n int) *QueryBuilder[OUTPUT] {
q.SetSelect()
q.offset = &Offset{N: n}
return q
}
// Limit adds limit section to query builder.
func (q *QueryBuilder[OUTPUT]) Limit(n int) *QueryBuilder[OUTPUT] {
q.SetSelect()
q.limit = &Limit{N: n}
return q
}
// Table sets table of QueryBuilder.
func (q *QueryBuilder[OUTPUT]) Table(t string) *QueryBuilder[OUTPUT] {
q.table = t
return q
}
// SetSelect sets query type of QueryBuilder to Select.
func (q *QueryBuilder[OUTPUT]) SetSelect() *QueryBuilder[OUTPUT] {
q.typ = queryTypeSELECT
return q
}
// GroupBy adds a group by section to QueryBuilder.
func (q *QueryBuilder[OUTPUT]) GroupBy(columns ...string) *QueryBuilder[OUTPUT] {
q.SetSelect()
if q.groupBy == nil {
q.groupBy = &GroupBy{}
}
q.groupBy.Columns = append(q.groupBy.Columns, columns...)
return q
}
// Select adds columns to QueryBuilder select field list.
func (q *QueryBuilder[OUTPUT]) Select(columns ...string) *QueryBuilder[OUTPUT] {
q.SetSelect()
if q.selected == nil {
q.selected = &selected{}
}
q.selected.Columns = append(q.selected.Columns, columns...)
return q
}
// FromQuery sets subquery of QueryBuilder to be given subquery so
// when doing select instead of from table we do from(subquery).
func (q *QueryBuilder[OUTPUT]) FromQuery(subQuery *QueryBuilder[OUTPUT]) *QueryBuilder[OUTPUT] {
q.SetSelect()
subQuery.SetSelect()
subQuery.placeholderGenerator = q.placeholderGenerator
subQueryString, args, err := subQuery.ToSql()
q.err = err
q.subQuery = &struct {
q string
args []interface{}
placeholderGenerator func(n int) []string
}{
subQueryString, args, q.placeholderGenerator,
}
return q
}
func (q *QueryBuilder[OUTPUT]) SetUpdate() *QueryBuilder[OUTPUT] {
q.typ = queryTypeUPDATE
return q
}
func (q *QueryBuilder[OUTPUT]) Set(keyValues ...any) *QueryBuilder[OUTPUT] {
if len(keyValues)%2 != 0 {
q.err = fmt.Errorf("when using Set, passed argument count should be even: %w", q.err)
return q
}
q.SetUpdate()
for i := 0; i < len(keyValues); i++ {
if i != 0 && i%2 == 1 {
q.sets = append(q.sets, [2]any{keyValues[i-1], keyValues[i]})
}
}
return q
}
func (q *QueryBuilder[OUTPUT]) SetDialect(dialect *Dialect) *QueryBuilder[OUTPUT] {
q.placeholderGenerator = dialect.PlaceHolderGenerator
return q
}
func (q *QueryBuilder[OUTPUT]) SetDelete() *QueryBuilder[OUTPUT] {
q.typ = queryTypeDelete
return q
}
type raw struct {
sql string
args []interface{}
}
// Raw creates a Raw sql query chunk that you can add to several components of QueryBuilder like
// Wheres.
func Raw(sql string, args ...interface{}) *raw {
return &raw{sql: sql, args: args}
}
func NewQueryBuilder[OUTPUT any](s *schema) *QueryBuilder[OUTPUT] {
return &QueryBuilder[OUTPUT]{schema: s}
}
type insertStmt struct {
PlaceHolderGenerator func(n int) []string
Table string
Columns []string
Values [][]interface{}
Returning string
}
func (i insertStmt) flatValues() []interface{} {
var values []interface{}
for _, row := range i.Values {
values = append(values, row...)
}
return values
}
func (i insertStmt) getValuesStr() string {
phs := i.PlaceHolderGenerator(len(i.Values) * len(i.Values[0]))
var output []string
for _, valueRow := range i.Values {
output = append(output, fmt.Sprintf("(%s)", strings.Join(phs[:len(valueRow)], ",")))
phs = phs[len(valueRow):]
}
return strings.Join(output, ",")
}
func (i insertStmt) ToSql() (string, []interface{}) {
base := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s",
i.Table,
strings.Join(i.Columns, ","),
i.getValuesStr(),
)
if i.Returning != "" {
base += "RETURNING " + i.Returning
}
return base, i.flatValues()
}
func postgresPlaceholder(n int) []string {
output := []string{}
for i := 1; i < n+1; i++ {
output = append(output, fmt.Sprintf("$%d", i))
}
return output
}
func questionMarks(n int) []string {
output := []string{}
for i := 0; i < n; i++ {
output = append(output, "?")
}
return output
}