-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser_test.go
More file actions
executable file
·2700 lines (2468 loc) · 86.2 KB
/
parser_test.go
File metadata and controls
executable file
·2700 lines (2468 loc) · 86.2 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
package sqlr
import (
"bytes"
"database/sql/driver"
"errors"
"fmt"
"math/rand"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"testing"
)
// --------------------------------
// Tests: simple queries
// --------------------------------
// TestSimpleQueries_AllDialects verifies basic substitution, duplicated names, IN expansion,
// ignoring casts/quoted text, struct field resolution by name/tag, and that unexported fields
// cannot be bound.
func TestSimpleQueries_AllDialects(t *testing.T) {
for _, dc := range allDialects() {
dc := dc
t.Run(dc.name, func(t *testing.T) {
// 1) Simple substitution + duplication
out, args := mustBuild(t, dc.d,
"SELECT * FROM t WHERE a = :x OR b = :x AND c = :y",
map[string]any{"x": 7, "y": "ok"},
)
if got, want := countPlaceholders(out, dc.d), 3; got != want {
t.Fatalf("placeholder count=%d, want %d\nquery=%s", got, want, out)
}
assertArgsEqual(t, args, []any{7, 7, "ok"})
// 2) IN with slice (automatic expansion)
out, args = mustBuild(t, dc.d,
"SELECT * FROM users WHERE id IN (:ids) AND status=:s",
map[string]any{"ids": []int{10, 11, 12}, "s": "active"},
)
if got, want := countPlaceholders(out, dc.d), 4; got != want {
t.Fatalf("placeholder count=%d, want %d\nquery=%s", got, want, out)
}
assertArgsEqual(t, args, []any{10, 11, 12, "active"})
// 3) Do not match casts '::' and content inside quotes
out, args = mustBuild(t, dc.d,
"SELECT ':: not a cast :nope', col::int, :x",
map[string]any{"x": 99},
)
if !strings.Contains(out, "::int") {
t.Fatalf("missing '::int' in query: %s", out)
}
if strings.Contains(out, ":nope") == false {
// ok: placeholder inside string must remain untouched
}
assertArgsEqual(t, args, []any{99})
// 4) Fallback to field name when no `db` tag is present
type simpleS struct {
Title string // no tag -> use field name
}
_, args = mustBuild(t, dc.d,
"SELECT :Title",
simpleS{Title: "ok"},
)
assertArgsEqual(t, args, []any{"ok"})
// 5) Priority: `db` tag must match when present; unexported fields ignored
type mixS struct {
ID int `db:"id"`
Name string // without tag, use "Name"
secret int // unexported -> ignored
}
_, args = mustBuild(t, dc.d,
"SELECT :id, :Name",
mixS{ID: 5, Name: "n"},
)
assertArgsEqual(t, args, []any{5, "n"})
// 6) Placeholder trying to use unexported field -> error
s := New(dc.d)
_, _, err := s.Write("SELECT :secret").
Bind(mixS{ID: 1, Name: "x"}).
Build()
if err == nil {
t.Fatalf("expected error: unexported field must not be resolvable")
}
})
}
}
// TestStructTagDash_IgnoreField_AllDialects ensures fields tagged with `db:"-"` are skipped
// and that attempting to bind them results in ErrParamMissing.
func TestStructTagDash_IgnoreField_AllDialects(t *testing.T) {
type S struct {
A int `db:"-"` // must be ignored
B int // available as :B
}
for _, dc := range allDialects() {
// ok: :B exists
out, args, err := New(dc.d).
Write("SELECT :B").
Bind(S{A: 1, B: 2}).
Build()
assertNoError(t, err)
if got := countPlaceholders(out, dc.d); got != 1 {
t.Fatalf("[%s] placeholders=%d, want 1", dc.name, got)
}
assertArgsEqual(t, args, []any{2})
// error: :A must not be resolvable
_, _, err = New(dc.d).
Write("SELECT :A").
Bind(S{A: 1, B: 2}).
Build()
if err == nil || !errors.Is(err, ErrParamMissing) {
t.Fatalf("[%s] expected ErrParamMissing for :A, got: %v", dc.name, err)
}
}
}
// TestBackslashEscapes_SingleQuoted_MySQLCompat_AllDialects verifies that backslash escapes
// within single-quoted strings are preserved and placeholders inside them are ignored.
func TestBackslashEscapes_SingleQuoted_MySQLCompat_AllDialects(t *testing.T) {
// :in is inside a string with escaped quote \', it must NOT be bound; :out must be bound
sql := "SELECT 'it\\'s just text :in', :out"
for _, dc := range allDialects() {
out, args, err := New(dc.d).
Write(sql).
Bind(map[string]any{"out": 7}).
Build()
assertNoError(t, err)
if !strings.Contains(out, ":in") {
t.Fatalf("[%s] ':in' inside the string should remain textual:\n%s", dc.name, out)
}
if got := countPlaceholders(out, dc.d); got != 1 {
t.Fatalf("[%s] placeholders=%d, want 1\nOUT:\n%s", dc.name, got, out)
}
assertArgsEqual(t, args, []any{7})
}
}
// TestBackslashEscapes_DoubleQuoted_AllDialects verifies that backslash escapes within
// double-quoted strings are preserved and placeholders inside them are ignored.
func TestBackslashEscapes_DoubleQuoted_AllDialects(t *testing.T) {
// inside double quotes there is :in and also an escaped \"; only :ok should be bound
sql := "SELECT \":in\\\"side\", :ok"
for _, dc := range allDialects() {
out, args, err := New(dc.d).
Write(sql).
Bind(map[string]any{"ok": 1}).
Build()
assertNoError(t, err)
if !strings.Contains(out, ":in") {
t.Fatalf("[%s] ':in' inside \"...\" should remain textual:\n%s", dc.name, out)
}
if got := countPlaceholders(out, dc.d); got != 1 {
t.Fatalf("[%s] placeholders=%d, want 1\nOUT:\n%s", dc.name, got, out)
}
assertArgsEqual(t, args, []any{1})
}
}
// TestAliasP_FastPathLike_Behavior checks that alias P binds values and auto-expands
// IN-lists (including duplication) through the fast-path-like behavior.
func TestAliasP_FastPathLike_Behavior(t *testing.T) {
out, args, err := New(Postgres).
Write("SELECT :a, :b, :ids").
Bind(P{"a": 1, "b": "x", "ids": []int{7, 8}}).
Build()
assertNoError(t, err)
if got := countPlaceholders(out, Postgres); got != 4 { // 1 + 1 + 2 (IN)
t.Fatalf("placeholders=%d, want 4", got)
}
assertArgsEqual(t, args, []any{1, "x", 7, 8})
}
// TestAliasP_WithRows verifies alias P with :rows fast-path precomputes rows and arguments.
func TestAliasP_WithRows(t *testing.T) {
type Row struct {
ID int `db:"id"`
Name string `db:"name"`
}
rows := []Row{{1, "A"}, {2, "B"}}
out, args, err := New(MySQL).
Write("INSERT INTO t(id,name) VALUES :rows{id,name}").
Bind(P{"rows": rows}).
Build()
assertNoError(t, err)
if got := countPlaceholders(out, MySQL); got != 4 {
t.Fatalf("got %d", got)
}
assertArgsEqual(t, args, []any{1, "A", 2, "B"})
}
// TestWritef_FormatsAndNoAutoSpace_AllDialects ensures Writef formatting works,
// args order matches placeholders, and no auto-spacing is introduced.
func TestWritef_FormatsAndNoAutoSpace_AllDialects(t *testing.T) {
for _, dc := range allDialects() {
t.Run(dc.name, func(t *testing.T) {
// Note: no space after '=' to verify Writef does not add spaces
b := New(dc.d).
Write("SELECT * FROM t WHERE a=").
Writef(":%s AND id IN (:%s)", "a", "ids").
Bind(P{"a": 7, "ids": []int{1, 2, 3}})
out, args, err := b.Build()
assertNoError(t, err)
// 1) #placeholders == len(args)
if got, want := countPlaceholders(out, dc.d), len(args); got != want {
t.Fatalf("placeholder=%d, len(args)=%d\nOUT:\n%s", got, want, out)
}
// 2) argument order: :a then expanded :ids
assertArgsEqual(t, args, []any{7, 1, 2, 3})
// 3) NO auto-space: placeholder must appear immediately after "a="
ph := placeholderRegex(dc.d).String()
re := regexp.MustCompile("a=" + ph)
if !re.MatchString(out) {
t.Fatalf("[%s] expected placeholder immediately after 'a='; OUT:\n%s", dc.name, out)
}
})
}
}
// TestWritef_SingleUse_ErrorAfterBuild ensures a Builder is single-use and returns
// a "builder already released" error if reused after Build.
func TestWritef_SingleUse_ErrorAfterBuild(t *testing.T) {
s := New(Postgres)
// first build ok
b := s.Write("SELECT :x").Writef(" /*%s*/", "hint").Bind(P{"x": 1})
_, _, err := b.Build()
assertNoError(t, err)
// reusing the builder must yield the "already released" error, not panic
q, args, err := b.Writef("-- again %d", 2).Build()
if err == nil || !regexp.MustCompile(`builder already released`).MatchString(err.Error()) {
t.Fatalf("expected ErrBuilderReleased, got: q=%q args=%v err=%v", q, args, err)
}
}
// ----------------------------------------------------------------
// Tests: complex queries (multi VALUES, multiple IN, bulk :rows)
// ----------------------------------------------------------------
type userRow struct {
ID int64 `db:"id"`
Name string `db:"name"`
Active bool `db:"active"`
Note string `db:"note"`
}
// TestComplexQueries_AllDialects exercises multi-VALUES inserts, multiple IN lists,
// repeated params, :rows bulk expansion, pointer rows, and error paths for malformed
// and missing params across all dialects.
func TestComplexQueries_AllDialects(t *testing.T) {
rows := []userRow{
{1, "Anna", true, "note 1"},
{2, "Luca", false, ""},
{3, "Mia", true, "note 3"},
}
for _, dc := range allDialects() {
dc := dc
t.Run(dc.name, func(t *testing.T) {
// INSERT bulk with :rows{id,name}
out, args := mustBuild(t, dc.d,
"INSERT INTO users (id,name) VALUES :rows{id,name}",
map[string]any{"rows": rows},
)
phCount := countPlaceholders(out, dc.d)
if phCount != len(rows)*2 {
t.Fatalf("placeholder count=%d, want %d\nquery=%s", phCount, len(rows)*2, out)
}
assertArgsEqual(t, args, []any{1, "Anna", 2, "Luca", 3, "Mia"})
// Multiple IN + repeated param + bulk
out, args = mustBuild(t, dc.d,
"WITH x AS (SELECT 1) "+
"INSERT INTO ord (uid, pid) VALUES :rows{id,name}; "+
"SELECT * FROM ord WHERE uid IN (:uids) AND pid IN (:pids) AND flag=:f OR flag=:f",
map[string]any{
"rows": rows,
"uids": []int64{10, 11, 12, 13},
"pids": []string{"p1", "p2"},
"f": true,
},
)
wantArgs := []any{1, "Anna", 2, "Luca", 3, "Mia", int64(10), int64(11), int64(12), int64(13), "p1", "p2", true, true}
assertArgsEqual(t, args, wantArgs)
if got, want := countPlaceholders(out, dc.d), len(wantArgs); got != want {
t.Fatalf("placeholder count=%d, want %d\nquery=%s", got, want, out)
}
// :rows{...} with bare slice (convention name == "rows")
out, _ = mustBuild(t, dc.d,
"INSERT INTO users (id,name) VALUES :rows{id,name}",
rows, // direct bind
)
if got, want := countPlaceholders(out, dc.d), len(rows)*2; got != want {
t.Fatalf("placeholder=%d, want %d\n%s", got, want, out)
}
// :vals{...} with map (name different than 'rows')
out, _ = mustBuild(t, dc.d,
"INSERT INTO users (id,name) VALUES :vals{id,name}",
map[string]any{"vals": rows},
)
if got, want := countPlaceholders(out, dc.d), len(rows)*2; got != want {
t.Fatalf("placeholder=%d, want %d\n%s", got, want, out)
}
// :rows{...} with interface that wraps the slice
var asAny any = rows
out, _, err := New(dc.d).
Write("INSERT INTO users (id,name) VALUES :rows{id,name}").
Bind(map[string]any{"rows": asAny}).
Build()
assertNoError(t, err)
if got, want := countPlaceholders(out, dc.d), len(rows)*2; got != want {
t.Fatalf("placeholder=%d, want %d\n%s", got, want, out)
}
// :rows{...} with pointers to structs -> SUPPORTED
ptrRows := []*userRow{{1, "P1", false, "note P1"}, {2, "P2", true, ""}}
out, args, err = New(dc.d).
Write("INSERT INTO users (id,name) VALUES :rows{id,name}").
Bind(map[string]any{"rows": ptrRows}).
Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{1, "P1", 2, "P2"})
_ = out
// ERROR: malformed :rows{...} placeholder (missing '}')
_, _, err = New(dc.d).
Write("INSERT INTO users (id,name) VALUES :rows{id,name").
Bind(map[string]any{"rows": rows}).
Build()
if err == nil || !errors.Is(err, ErrRowsMalformed) {
t.Fatalf("expected 'malformed' error, got: %v", err)
}
// ERROR: name different than 'rows' but argument absent -> missing parameter
_, _, err = New(dc.d).
Write("INSERT INTO users (id,name) VALUES :vals{id,name}").
// no Bind for 'vals'
Build()
if err == nil || !errors.Is(err, ErrParamMissing) {
t.Fatalf("expected 'missing parameter', got: %v", err)
}
})
}
}
// ------------------------------------------------------------------------------------------------
// Tests: dynamic queries (multiple Write/Bind, reset after Build())
// ------------------------------------------------------------------------------------------------
// TestDynamicQueries_AllDialects ensures dynamic construction works with multiple Write/Bind
// calls and that the builder resets its placeholder state after Build().
func TestDynamicQueries_AllDialects(t *testing.T) {
for _, dc := range allDialects() {
dc := dc
t.Run(dc.name, func(t *testing.T) {
s := New(dc.d)
b := s.Write("SELECT * FROM orders WHERE 1=1 ")
cond := true
if cond {
b.Write(" AND customer_id = :cid")
b.Bind(map[string]any{"cid": 42})
} else {
b.Write(" AND created_at >= :from")
b.Bind(struct {
From string `db:"from"`
}{"2025-01-01"})
}
q1, args1, err := b.Build()
assertNoError(t, err)
if got := countPlaceholders(q1, dc.d); got != 1 {
t.Fatalf("placeholder count=%d, want 1\n%s", got, q1)
}
assertArgsEqual(t, args1, []any{42})
// Builder has been reset: second query starts again at $1/@p1/?
b = s.Write("SELECT * FROM orders WHERE status=:s AND id IN (:ids)")
b.Bind(map[string]any{"s": "open", "ids": []int{1, 2}})
q2, args2, err := b.Build()
assertNoError(t, err)
assertArgsEqual(t, args2, []any{"open", 1, 2})
// Verify placeholder numbering restarts from 1..n
switch dc.d {
case Postgres:
mustContainInOrder(t, q2, "$1", "$2", "$3")
case SQLServer:
mustContainInOrder(t, q2, "@p1", "@p2", "@p3")
default: // MySQL, SQLite
if got := strings.Count(q2, "?"); got != 3 {
t.Fatalf("count '?'=%d, want 3\n%s", got, q2)
}
}
// "last one wins" resolution
s = New(dc.d)
b = s.Write("SELECT :x, :y")
b.Bind(map[string]any{"x": 1, "y": 2})
b.Bind(map[string]any{"x": 9}) // override
q3, a3, err := b.Build()
assertNoError(t, err)
assertArgsEqual(t, a3, []any{9, 2})
_ = q3
})
}
}
// ------------------------------------------------------------------------------------------------
// Tests: edge cases (empties, nil, []byte, placeholders inside quotes/comments/dollar-quoted)
// ------------------------------------------------------------------------------------------------
// TestEdgeCases_AllDialects covers an exhaustive set of edge-case behaviors including empty IN slices,
// missing params, empty :rows, []byte non-expansion, placeholders inside quotes/comments, and
// dollar-quoted blocks (closed and unclosed).
func TestEdgeCases_AllDialects(t *testing.T) {
for _, dc := range allDialects() {
dc := dc
t.Run(dc.name, func(t *testing.T) {
// Empty slice -> error
_, _, err := New(dc.d).
Write("SELECT * FROM t WHERE id IN (:ids)").
Bind(map[string]any{"ids": []int{}}).
Build()
if err == nil {
t.Fatalf("expected error for empty slice")
}
// Missing parameter -> error
_, _, err = New(dc.d).
Write("SELECT * FROM t WHERE a=:x AND b=:y").
Bind(map[string]any{"x": 1}).
Build()
if err == nil {
t.Fatalf("expected error for missing parameter")
}
// Empty :rows -> error
_, _, err = New(dc.d).
Write("INSERT INTO t (id,name) VALUES :rows{id,name}").
Bind(map[string]any{"rows": []userRow{}}).
Build()
if err == nil {
t.Fatalf("expected error for empty :rows")
}
// []byte must NOT expand into a list
payload := []byte{0x01, 0x02, 0x03}
out, args, err := New(dc.d).
Write("UPDATE t SET bin=:p WHERE id=:id").
Bind(map[string]any{"p": payload, "id": 10}).
Build()
assertNoError(t, err)
if got, want := countPlaceholders(out, dc.d), 2; got != want {
t.Fatalf("placeholder count=%d, want %d\nquery=%s", got, want, out)
}
assertArgsEqual(t, args, []any{payload, 10})
// Placeholder-like tokens within comments and quotes must not match
out, args, err = New(dc.d).
Write(`SELECT ':skip' AS s -- :skip
/* also :skip */
, col FROM t WHERE a=:ok AND b=':also'`).
Bind(map[string]any{"ok": 5}).
Build()
assertNoError(t, err)
if strings.Contains(out, ":skip") == false {
// ok: remained inside string/comment
}
assertArgsEqual(t, args, []any{5})
// Dollar-quoted (Postgres) must be ignored
out, args, err = New(dc.d).
Write(`SELECT $tag$:not a param :nope$tag$, :x`).
Bind(map[string]any{"x": 123}).
Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{123})
if !strings.Contains(out, ":nope") {
t.Fatalf("content inside dollar-quoted should remain textual, ':nope' missing in:\n%s", out)
}
// Dollar-quoted with empty tag "$$" NOT closed: everything after is considered textual
out, args, err = New(dc.d).
Write(`SELECT $$ not closed :inside , :x`).
Bind(map[string]any{"x": 1}).
Build()
assertNoError(t, err)
// No bound args because :x remains inside unclosed dollar-quoted
if len(args) != 0 {
t.Fatalf("len(args)=%d, want 0 (unclosed dollar-quoted)", len(args))
}
// Both :inside and :x should remain textual
if !strings.Contains(out, ":inside") || !strings.Contains(out, ":x") {
t.Fatalf("content inside $$... should remain textual:\n%s", out)
}
// '$' that does NOT open dollar-quote (no second '$')
out, _, err = New(dc.d).
Write(`SELECT $ not_a_tag ':nope' , :y`).
Bind(map[string]any{"y": 2}).
Build()
assertNoError(t, err)
if got, want := countPlaceholders(out, dc.d), 1; got != want {
t.Fatalf("placeholder count=%d, want %d\nquery=%s", got, want, out)
}
if !strings.Contains(out, ":nope") {
t.Fatalf("':nope' is quoted and should remain textual:\n%s", out)
}
})
}
}
// TestBindPointerStruct_AllDialects ensures pointer-to-struct binding works and resolves
// both tagged and untagged fields across dialects.
func TestBindPointerStruct_AllDialects(t *testing.T) {
type S struct {
A int `db:"a"`
B string
}
v := &S{A: 7, B: "x"}
for _, dc := range allDialects() {
out, args, err := New(dc.d).Write("SELECT :a, :B").Bind(v).Build()
assertNoError(t, err)
if got, want := countPlaceholders(out, dc.d), 2; got != want {
t.Fatalf("[%s] placeholders=%d, want 2", dc.name, got)
}
assertArgsEqual(t, args, []any{7, "x"})
}
}
// TestAmbiguousField_Bind_AllDialects ensures ambiguous field names (same `db` tag in
// embedded structs) cause ErrFieldAmbiguous and mention the field name.
func TestAmbiguousField_Bind_AllDialects(t *testing.T) {
type A struct {
ID int `db:"id"`
}
type B struct {
ID int `db:"id"`
}
type C struct {
A A
B B
}
for _, dc := range allDialects() {
_, _, err := New(dc.d).Write("SELECT :id").Bind(C{A: A{1}, B: B{2}}).Build()
if err == nil || !errors.Is(err, ErrFieldAmbiguous) {
t.Fatalf("[%s] expected ErrFieldAmbiguous, got %v", dc.name, err)
}
if err != nil && !strings.Contains(err.Error(), `"id"`) {
t.Fatalf("[%s] error should mention the field name: %v", dc.name, err)
}
}
}
// TestAmbiguousField_RowsBlock_AllDialects ensures ambiguous field names in :rows precompute
// error out with ErrFieldAmbiguous and mention the conflicting column name.
func TestAmbiguousField_RowsBlock_AllDialects(t *testing.T) {
type A struct {
ID int `db:"id"`
}
type B struct {
ID int `db:"id"`
}
type Row struct {
A A
B B
}
rows := []Row{{A: A{1}, B: B{2}}}
for _, dc := range allDialects() {
_, _, err := New(dc.d).
Write("INSERT INTO t(id) VALUES :rows{id}").
Bind(P{"rows": rows}).
Build()
if err == nil || !errors.Is(err, ErrFieldAmbiguous) {
t.Fatalf("[%s] expected ErrFieldAmbiguous in :rows precompute, got %v", dc.name, err)
}
if err != nil && !strings.Contains(err.Error(), `"id"`) {
t.Fatalf("[%s] error should mention the column: %v", dc.name, err)
}
}
}
// TestRowsBlock_Heterogeneous_MissingColumn_PerRow_AllDialects ensures heterogeneous :rows
// with a missing column reports ErrColumnNotFound and includes the failing row index.
func TestRowsBlock_Heterogeneous_MissingColumn_PerRow_AllDialects(t *testing.T) {
// Row 0 has "id"; Row 1 does NOT have "id" → ErrColumnNotFound at record 1
type R0 struct {
ID int `db:"id"`
}
type R1 struct {
Name string `db:"name"`
}
rows := []any{
R0{ID: 1},
R1{Name: "x"},
}
for _, dc := range allDialects() {
_, _, err := New(dc.d).
Write("INSERT INTO t(id) VALUES :rows{id}").
Bind(map[string]any{"rows": rows}).
Build()
if err == nil || !errors.Is(err, ErrColumnNotFound) {
t.Fatalf("[%s] expected ErrColumnNotFound, got %v", dc.name, err)
}
if err != nil && !strings.Contains(err.Error(), "(record 1)") {
t.Fatalf("[%s] error should mention the row index (record 1), got: %v", dc.name, err)
}
}
}
// TestRowsBlock_Heterogeneous_Ambiguous_PerRow_AllDialects ensures heterogeneous :rows
// with ambiguous columns reports ErrFieldAmbiguous and includes the row index.
func TestRowsBlock_Heterogeneous_Ambiguous_PerRow_AllDialects(t *testing.T) {
// Row 0 has a unique "id"; Row 1 has TWO fields both named/tagged "id"
// → ErrFieldAmbiguous at record 1
type R0 struct {
ID int `db:"id"`
}
type R1 struct {
X int `db:"id"`
Y int `db:"id"`
}
rows := []any{
R0{ID: 1},
R1{X: 2, Y: 3},
}
for _, dc := range allDialects() {
_, _, err := New(dc.d).
Write("INSERT INTO t(id) VALUES :rows{id}").
Bind(map[string]any{"rows": rows}).
Build()
if err == nil || !errors.Is(err, ErrFieldAmbiguous) {
t.Fatalf("[%s] expected ErrFieldAmbiguous, got %v", dc.name, err)
}
if err != nil && !strings.Contains(err.Error(), "(record 1)") {
t.Fatalf("[%s] error should mention the row index (record 1), got: %v", dc.name, err)
}
}
}
// TestWritePlaceholder_NoAllocs_Postgres is a smoke test that also ensures placeholder
// numbering correctness in Postgres without unexpected allocations.
func TestWritePlaceholder_NoAllocs_Postgres(t *testing.T) {
out, _, err := New(Postgres).
Write("SELECT :a,:b,:c,:a").
Bind(map[string]any{"a": 1, "b": 2, "c": 3}).Build()
assertNoError(t, err)
mustContainInOrder(t, out, "$1", "$2", "$3", "$4") // duplicate to keep cross-dialect compatibility
}
// TestSingleLookup_ReflectMapAndPointers_AllDialects ensures map-based and pointer/interface-based
// lookups work using reflection paths in single placeholder binds.
func TestSingleLookup_ReflectMapAndPointers_AllDialects(t *testing.T) {
type MM map[string]any // defined type (skips fast-path and forces reflect.Map)
for _, dc := range allDialects() {
// a) map[string]int
out, args, err := New(dc.d).
Write("SELECT :x").
Bind(map[string]int{"x": 5}).
Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{5})
_ = out
// b) defined type on map[string]any
mm := MM{"y": "ok"}
_, args, err = New(dc.d).
Write("SELECT :y").
Bind(mm).
Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{"ok"})
// c) *map[string]int (pointer -> unwrap -> reflect.Map)
mp := map[string]int{"z": 9}
_, args, err = New(dc.d).
Write("SELECT :z").
Bind(&mp).
Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{9})
// d) interface{} containing map[string]int
var anyMap any = map[string]int{"w": 42}
_, args, err = New(dc.d).
Write("SELECT :w").
Bind(anyMap).
Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{42})
// e) map with non-string key type -> should error (reflect.Map negative branch)
_, _, err = New(dc.d).
Write("SELECT :bad").
Bind(map[int]any{1: "nope"}).
Build()
if err == nil {
t.Fatalf("[%s] expected error for non-string map key", dc.name)
}
}
}
// TestRows_StructFastPath_PrecomputeIndices_AllDialects ensures :rows struct fast-path
// precomputes indices correctly for both []T and []*T rows.
func TestRows_StructFastPath_PrecomputeIndices_AllDialects(t *testing.T) {
type Row struct {
A int `db:"a"`
B string `db:"b"`
C int64 `db:"c"`
}
rows := []Row{
{A: 1, B: "x", C: 10},
{A: 2, B: "y", C: 20},
}
ptrRows := []*Row{
{A: 3, B: "k", C: 30},
{A: 4, B: "w", C: 40},
}
for _, dc := range allDialects() {
dc := dc
t.Run(dc.name+"/struct", func(t *testing.T) {
out, args, err := New(dc.d).
Write("INSERT INTO t(a,b,c) VALUES :rows{a,b,c}").
Bind(map[string]any{"rows": rows}).
Build()
assertNoError(t, err)
// 2 rows x 3 columns = 6 placeholders/args
if got := countPlaceholders(out, dc.d); got != 6 {
t.Fatalf("[%s] placeholders=%d, want 6\nOUT:\n%s", dc.name, got, out)
}
assertArgsEqual(t, args, []any{1, "x", int64(10), 2, "y", int64(20)})
})
t.Run(dc.name+"/ptr-struct", func(t *testing.T) {
out, args, err := New(dc.d).
Write("INSERT INTO t(a,b,c) VALUES :rows{a,b,c}").
Bind(map[string]any{"rows": ptrRows}).
Build()
assertNoError(t, err)
// 2 rows x 3 columns = 6 placeholders/args
if got := countPlaceholders(out, dc.d); got != 6 {
t.Fatalf("[%s] placeholders=%d, want 6\nOUT:\n%s", dc.name, got, out)
}
assertArgsEqual(t, args, []any{3, "k", int64(30), 4, "w", int64(40)})
})
}
}
// TestRows_StructFastPath_MissingColumn_ErrorIsForRecord0_AllDialects ensures that when a column
// is missing in struct precompute for :rows, the error refers to "record 0".
func TestRows_StructFastPath_MissingColumn_ErrorIsForRecord0_AllDialects(t *testing.T) {
type Row struct {
A int `db:"a"`
B string `db:"b"`
}
rows := []Row{
{A: 1, B: "x"},
{A: 2, B: "y"},
}
// Column "zzz" does not exist in struct: fast-path must fail immediately
// during precomputation, indicating "record 0".
sql := "INSERT INTO t(a,zzz) VALUES :rows{a,zzz}"
for _, dc := range allDialects() {
_, _, err := New(dc.d).
Write(sql).
Bind(map[string]any{"rows": rows}).
Build()
if err == nil {
t.Fatalf("[%s] expected error for missing column 'zzz'", dc.name)
}
// Must be ErrColumnNotFound and message should mention "zzz" and "record 0"
if !errors.Is(err, ErrColumnNotFound) {
t.Fatalf("[%s] got err=%v, want ErrColumnNotFound", dc.name, err)
}
msg := err.Error()
if !(strings.Contains(msg, `"zzz"`) && strings.Contains(msg, "record 0")) {
t.Fatalf("[%s] unexpected error message: %q (expected to contain \"zzz\" and \"record 0\")", dc.name, msg)
}
}
}
// TestRows_ReflectMap_Positive_AllDialects validates map-based :rows expansion across
// plain maps, defined map types, and pointer-to-slice wrappers.
func TestRows_ReflectMap_Positive_AllDialects(t *testing.T) {
type M map[string]int // defined type forces reflect.Map
rowsInt := []map[string]int{
{"a": 1, "b": 2},
{"a": 3, "b": 4},
}
rowsDef := []M{
{"a": 10, "b": 20},
{"a": 30, "b": 40},
}
ptrRows := &rowsInt // *([]map[string]int)
for _, dc := range allDialects() {
// a) []map[string]int
out, args, err := New(dc.d).
Write("INSERT INTO t(a,b) VALUES :rows{a,b}").
Bind(map[string]any{"rows": rowsInt}).
Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{1, 2, 3, 4})
_ = out
// b) []M (defined type)
_, args, err = New(dc.d).
Write("INSERT INTO t(a,b) VALUES :rows{a,b}").
Bind(map[string]any{"rows": rowsDef}).
Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{10, 20, 30, 40})
// c) *([]map[string]int) (pointer to slice)
_, args, err = New(dc.d).
Write("INSERT INTO t(a,b) VALUES :rows{a,b}").
Bind(map[string]any{"rows": ptrRows}).
Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{1, 2, 3, 4})
}
}
// TestRows_ReflectMap_NegativeKeyType_AllDialects ensures non-string map key types in :rows
// result in ErrColumnNotFound during column extraction.
func TestRows_ReflectMap_NegativeKeyType_AllDialects(t *testing.T) {
rows := []map[int]any{
{1: "x"},
}
for _, dc := range allDialects() {
_, _, err := New(dc.d).
Write("INSERT INTO t(a) VALUES :rows{a}").
Bind(map[string]any{"rows": rows}).
Build()
if err == nil || !errors.Is(err, ErrColumnNotFound) {
t.Fatalf("[%s] expected ErrColumnNotFound for non-string key, got: %v", dc.name, err)
}
}
}
// TestRows_HeterogeneousStructs_AllDialects verifies that :rows accepts heterogeneous
// struct types (including pointers) as long as the requested columns exist.
func TestRows_HeterogeneousStructs_AllDialects(t *testing.T) {
type A struct {
X int `db:"x"`
Y string `db:"y"`
}
type B struct {
X int `db:"x"`
Y string `db:"y"`
}
rows := []any{
A{X: 1, Y: "a"},
B{X: 2, Y: "b"},
&A{X: 3, Y: "c"}, // pointer ok
}
for _, dc := range allDialects() {
out, args, err := New(dc.d).
Write("INSERT INTO t(x,y) VALUES :rows{x,y}").
Bind(map[string]any{"rows": rows}).
Build()
assertNoError(t, err)
if got := countPlaceholders(out, dc.d); got != 6 {
t.Fatalf("[%s] placeholders=%d, want 6\nOUT:\n%s", dc.name, got, out)
}
assertArgsEqual(t, args, []any{1, "a", 2, "b", 3, "c"})
}
}
// TestDollarQuoted_EmptyTag_Closed_AllDialects verifies that content inside $$...$$
// is ignored by the parser and placeholders there are not bound.
func TestDollarQuoted_EmptyTag_Closed_AllDialects(t *testing.T) {
for _, dc := range allDialects() {
out, args, err := New(dc.d).
Write(`SELECT $$ :inside $$, :x`).
Bind(map[string]any{"x": 7}).
Build()
assertNoError(t, err)
if !strings.Contains(out, ":inside") {
t.Fatalf("[%s] ':inside' inside $$...$$ should remain textual:\n%s", dc.name, out)
}
assertArgsEqual(t, args, []any{7})
}
}
// TestDollarQuoted_LongTag_Multiple_AllDialects verifies multiple dollar-quoted tags/blocks
// are handled correctly and placeholders inside them are ignored.
func TestDollarQuoted_LongTag_Multiple_AllDialects(t *testing.T) {
q := `SELECT $tag_with_123$ :skip $tag_with_123$, $X$ keep :skip $X$, :ok`
for _, dc := range allDialects() {
out, args, err := New(dc.d).
Write(q).
Bind(map[string]any{"ok": 1}).
Build()
assertNoError(t, err)
if !strings.Contains(out, ":skip") { // must remain inside the dollar-quoted regions
t.Fatalf("[%s] ':skip' should remain textual:\n%s", dc.name, out)
}
assertArgsEqual(t, args, []any{1})
}
}
// TestDollarQuoted_ConsecutiveBlocks_AllDialects ensures consecutive dollar-quoted blocks
// are handled independently and placeholders outside them still bind.
func TestDollarQuoted_ConsecutiveBlocks_AllDialects(t *testing.T) {
q := `SELECT $a$one$a$ $a$two$a$, :x`
for _, dc := range allDialects() {
_, args, err := New(dc.d).Write(q).Bind(map[string]any{"x": 1}).Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{1})
}
}
// TestRows_Unwrap_InterfaceThenPointer_AllDialects verifies :rows input is unwrapped when
// passed as interface{} that contains a pointer to the slice.
func TestRows_Unwrap_InterfaceThenPointer_AllDialects(t *testing.T) {
rows := []map[string]any{{"a": 1}, {"a": 2}}
ptr := &rows
var asAny any = ptr // interface{} -> *([]map[string]any)
for _, dc := range allDialects() {
out, args, err := New(dc.d).
Write("INSERT INTO t(a) VALUES :rows{a}").
Bind(map[string]any{"rows": asAny}).
Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{1, 2})
_ = out
}
}
// TestSingleLookup_ReflectMapVariants_AllDialects ensures singleLookup supports string-convertible
// key variants (aliases/defined types), pointers to maps, and interfaces containing maps.
func TestSingleLookup_ReflectMapVariants_AllDialects(t *testing.T) {
type KS string // alias of string
type MAny map[KS]any // defined type
for _, dc := range allDialects() {
// a) key is alias of string -> OK
m1 := map[KS]any{KS("a"): 7}
out, args, err := New(dc.d).Write("SELECT :a").Bind(m1).Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{7})
_ = out
// b) defined map type -> OK
m2 := MAny{KS("b"): "x"}
_, args, err = New(dc.d).Write("SELECT :b").Bind(m2).Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{"x"})
// c) pointer to map -> unwrap -> OK
m3 := map[KS]int{KS("c"): 9}
_, args, err = New(dc.d).Write("SELECT :c").Bind(&m3).Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{9})
// d) interface{} containing map[KS]any -> OK
var anyMap any = map[KS]any{KS("d"): true}
_, args, err = New(dc.d).Write("SELECT :d").Bind(anyMap).Build()
assertNoError(t, err)
assertArgsEqual(t, args, []any{true})
// e) non-string-convertible key type -> should fail (parameter missing)
_, _, err = New(dc.d).Write("SELECT :z").Bind(map[int]any{1: "no"}).Build()
if err == nil {
t.Fatalf("[%s] expected error for non-string map key in singleLookup", dc.name)
}
}
}
// TestRows_GetColValue_MapKeyVariants_AllDialects verifies :rows with map key aliases/defined
// types and pointer-to-slice variants, and errors on non-string keys.
func TestRows_GetColValue_MapKeyVariants_AllDialects(t *testing.T) {