-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathqwp_query_batch_test.go
More file actions
1704 lines (1569 loc) · 58.5 KB
/
Copy pathqwp_query_batch_test.go
File metadata and controls
1704 lines (1569 loc) · 58.5 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
/*+*****************************************************************************
* ___ _ ____ ____
* / _ \ _ _ ___ ___| |_| _ \| __ )
* | | | | | | |/ _ \/ __| __| | | | _ \
* | |_| | |_| | __/\__ \ |_| |_| | |_) |
* \__\_\\__,_|\___||___/\__|____/|____/
*
* Copyright (c) 2014-2019 Appsicle
* Copyright (c) 2019-2026 QuestDB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package questdb
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"strings"
"sync"
"testing"
)
// buildFixedLayout produces a qwpColumnLayout with no nulls and the
// given values region. Used as a helper across the fixed-width tests.
func buildFixedLayout(info *qwpColumnSchemaInfo, values []byte, rowCount int) qwpColumnLayout {
return qwpColumnLayout{
info: info,
values: values,
nonNullCount: rowCount,
}
}
// buildNullableLayout produces a qwpColumnLayout with the given null
// pattern (true = NULL) and a dense values region assembled from the
// non-null rows of `rowBytes`. `rowBytes` must contain one entry per
// row (nil for NULL rows, fixed-size bytes for non-null).
func buildNullableLayout(info *qwpColumnSchemaInfo, rowBytes [][]byte) qwpColumnLayout {
rowCount := len(rowBytes)
bitmap := make([]byte, (rowCount+7)>>3)
nonNullIdx := make([]int32, rowCount)
var dense int32
var values []byte
for i, b := range rowBytes {
if b == nil {
bitmap[i>>3] |= 1 << (i & 7)
nonNullIdx[i] = -1
} else {
nonNullIdx[i] = dense
dense++
values = append(values, b...)
}
}
return qwpColumnLayout{
info: info,
nullBitmap: bitmap,
nonNullIdx: nonNullIdx,
values: values,
nonNullCount: int(dense),
}
}
// newSingleColumnBatch assembles a QwpColumnBatch with one column for
// tests that only care about a single accessor path.
func newSingleColumnBatch(info qwpColumnSchemaInfo, layout qwpColumnLayout, rowCount int) *QwpColumnBatch {
return &QwpColumnBatch{
requestId: 1,
batchSeq: 0,
rowCount: rowCount,
columnCount: 1,
columns: []qwpColumnSchemaInfo{info},
layouts: []qwpColumnLayout{layout},
}
}
// --- Fixed-width accessor coverage ---
func TestQwpColumnBatchFixedWidth(t *testing.T) {
t.Run("Bool_bitpacked", func(t *testing.T) {
info := qwpColumnSchemaInfo{name: "b", wireType: qwpTypeBoolean}
// 10 rows, pattern: T F T F T F T F T F.
// Packed: byte 0 bits 0..7 = 0b01010101 = 0x55, byte 1 bits 0..1 = 0b01 = 0x01.
layout := buildFixedLayout(&info, []byte{0x55, 0x01}, 10)
batch := newSingleColumnBatch(info, layout, 10)
for i := 0; i < 10; i++ {
want := i%2 == 0
if got := batch.Bool(0, i); got != want {
t.Fatalf("Bool(0, %d) = %v, want %v", i, got, want)
}
}
})
t.Run("Int8", func(t *testing.T) {
info := qwpColumnSchemaInfo{name: "b", wireType: qwpTypeByte}
layout := buildFixedLayout(&info, []byte{0x01, 0xFF, 0x7F}, 3)
batch := newSingleColumnBatch(info, layout, 3)
if got := batch.Int8(0, 0); got != 1 {
t.Fatalf("Int8(0, 0) = %d", got)
}
if got := batch.Int8(0, 1); got != -1 {
t.Fatalf("Int8(0, 1) = %d", got)
}
if got := batch.Int8(0, 2); got != 127 {
t.Fatalf("Int8(0, 2) = %d", got)
}
})
t.Run("Int16", func(t *testing.T) {
info := qwpColumnSchemaInfo{name: "s", wireType: qwpTypeShort}
values := make([]byte, 4)
var negShort int16 = -1000
binary.LittleEndian.PutUint16(values[0:], uint16(negShort))
binary.LittleEndian.PutUint16(values[2:], 32767)
layout := buildFixedLayout(&info, values, 2)
batch := newSingleColumnBatch(info, layout, 2)
if got := batch.Int16(0, 0); got != -1000 {
t.Fatalf("Int16[0] = %d", got)
}
if got := batch.Int16(0, 1); got != 32767 {
t.Fatalf("Int16[1] = %d", got)
}
})
t.Run("Char", func(t *testing.T) {
info := qwpColumnSchemaInfo{name: "c", wireType: qwpTypeChar}
values := make([]byte, 4)
binary.LittleEndian.PutUint16(values[0:], 0x0041) // 'A'
binary.LittleEndian.PutUint16(values[2:], 0x00E9) // 'é'
layout := buildFixedLayout(&info, values, 2)
batch := newSingleColumnBatch(info, layout, 2)
if got := batch.Char(0, 0); got != 'A' {
t.Fatalf("Char[0] = %c (%d)", got, got)
}
if got := batch.Char(0, 1); got != 'é' {
t.Fatalf("Char[1] = %c (%d)", got, got)
}
})
t.Run("Int32_and_IPv4", func(t *testing.T) {
// INT and IPv4 share the 4-byte LE wire layout.
values := make([]byte, 8)
var negInt int32 = -42
binary.LittleEndian.PutUint32(values[0:], uint32(negInt))
binary.LittleEndian.PutUint32(values[4:], 0x7F_00_00_01) // 127.0.0.1 LE
for _, wt := range []qwpTypeCode{qwpTypeInt, qwpTypeIPv4} {
info := qwpColumnSchemaInfo{name: "i", wireType: wt}
layout := buildFixedLayout(&info, values, 2)
batch := newSingleColumnBatch(info, layout, 2)
if got := batch.Int32(0, 0); got != -42 {
t.Fatalf("Int32 (%#x) [0] = %d", wt, got)
}
if got := batch.Int32(0, 1); got != int32(0x7F_00_00_01) {
t.Fatalf("Int32 (%#x) [1] = %#x", wt, got)
}
}
})
t.Run("Int64", func(t *testing.T) {
// LONG, DATE, TIMESTAMP, TIMESTAMP_NANOS, DECIMAL64 all share
// the int64 LE layout. Spot-check the dispatch through the
// single accessor.
values := make([]byte, 16)
var negLong int64 = -1
binary.LittleEndian.PutUint64(values[0:], uint64(negLong))
binary.LittleEndian.PutUint64(values[8:], uint64(math.MaxInt64))
for _, wt := range []qwpTypeCode{qwpTypeLong, qwpTypeDate, qwpTypeTimestamp, qwpTypeTimestampNano, qwpTypeDecimal64} {
info := qwpColumnSchemaInfo{name: "l", wireType: wt}
layout := buildFixedLayout(&info, values, 2)
batch := newSingleColumnBatch(info, layout, 2)
if got := batch.Int64(0, 0); got != -1 {
t.Fatalf("Int64 (%#x) [0] = %d", wt, got)
}
if got := batch.Int64(0, 1); got != math.MaxInt64 {
t.Fatalf("Int64 (%#x) [1] = %d", wt, got)
}
}
})
t.Run("Float32", func(t *testing.T) {
info := qwpColumnSchemaInfo{name: "f", wireType: qwpTypeFloat}
values := make([]byte, 8)
binary.LittleEndian.PutUint32(values[0:], math.Float32bits(3.14))
binary.LittleEndian.PutUint32(values[4:], math.Float32bits(-0.5))
layout := buildFixedLayout(&info, values, 2)
batch := newSingleColumnBatch(info, layout, 2)
if got := batch.Float32(0, 0); got != 3.14 {
t.Fatalf("Float32[0] = %v", got)
}
if got := batch.Float32(0, 1); got != -0.5 {
t.Fatalf("Float32[1] = %v", got)
}
})
t.Run("Float64", func(t *testing.T) {
info := qwpColumnSchemaInfo{name: "d", wireType: qwpTypeDouble}
values := make([]byte, 16)
binary.LittleEndian.PutUint64(values[0:], math.Float64bits(1.3))
binary.LittleEndian.PutUint64(values[8:], math.Float64bits(-2.5))
layout := buildFixedLayout(&info, values, 2)
batch := newSingleColumnBatch(info, layout, 2)
if got := batch.Float64(0, 0); got != 1.3 {
t.Fatalf("Float64[0] = %v", got)
}
if got := batch.Float64(0, 1); got != -2.5 {
t.Fatalf("Float64[1] = %v", got)
}
})
t.Run("Uuid", func(t *testing.T) {
info := qwpColumnSchemaInfo{name: "u", wireType: qwpTypeUuid}
values := make([]byte, 16)
binary.LittleEndian.PutUint64(values[0:], 0x0706050403020100)
binary.LittleEndian.PutUint64(values[8:], 0x0F0E0D0C0B0A0908)
layout := buildFixedLayout(&info, values, 1)
batch := newSingleColumnBatch(info, layout, 1)
if lo := batch.UuidLo(0, 0); lo != 0x0706050403020100 {
t.Fatalf("UuidLo = %#x", lo)
}
if hi := batch.UuidHi(0, 0); hi != 0x0F0E0D0C0B0A0908 {
t.Fatalf("UuidHi = %#x", hi)
}
})
t.Run("Decimal128", func(t *testing.T) {
info := qwpColumnSchemaInfo{name: "d128", wireType: qwpTypeDecimal128}
values := make([]byte, 16)
binary.LittleEndian.PutUint64(values[0:], 0xAAAA_BBBB_CCCC_DDDD)
binary.LittleEndian.PutUint64(values[8:], 0x1111_2222_3333_4444)
layout := buildFixedLayout(&info, values, 1)
layout.scale = 4
batch := newSingleColumnBatch(info, layout, 1)
if got := batch.Decimal128Lo(0, 0); uint64(got) != 0xAAAA_BBBB_CCCC_DDDD {
t.Fatalf("Decimal128Lo = %#x", uint64(got))
}
if got := batch.Decimal128Hi(0, 0); uint64(got) != 0x1111_2222_3333_4444 {
t.Fatalf("Decimal128Hi = %#x", uint64(got))
}
if s := batch.DecimalScale(0); s != 4 {
t.Fatalf("DecimalScale = %d, want 4", s)
}
})
t.Run("Long256_and_Decimal256", func(t *testing.T) {
for _, wt := range []qwpTypeCode{qwpTypeLong256, qwpTypeDecimal256} {
info := qwpColumnSchemaInfo{name: "l256", wireType: wt}
values := make([]byte, 32)
for i := 0; i < 4; i++ {
binary.LittleEndian.PutUint64(values[i*8:], uint64(i+1)*0x1111111111111111)
}
layout := buildFixedLayout(&info, values, 1)
batch := newSingleColumnBatch(info, layout, 1)
for w := 0; w < 4; w++ {
want := int64(uint64(w+1) * 0x1111111111111111)
if got := batch.Long256Word(0, 0, w); got != want {
t.Fatalf("%#x word %d = %#x", wt, w, got)
}
}
}
})
}
// --- Null handling ---
func TestQwpColumnBatchNullsDenseIndex(t *testing.T) {
// Pattern N V V N V (rowCount=5, denseCount=3). Non-null values:
// int32 values 100, 200, 300 at dense indices 0, 1, 2.
info := qwpColumnSchemaInfo{name: "i", wireType: qwpTypeInt}
values := make([]byte, 12)
binary.LittleEndian.PutUint32(values[0:], 100)
binary.LittleEndian.PutUint32(values[4:], 200)
binary.LittleEndian.PutUint32(values[8:], 300)
rowBytes := [][]byte{
nil, // row 0 NULL
values[0:4],
values[4:8],
nil, // row 3 NULL
values[8:12],
}
layout := buildNullableLayout(&info, rowBytes)
batch := newSingleColumnBatch(info, layout, 5)
if !batch.IsNull(0, 0) || !batch.IsNull(0, 3) {
t.Fatal("row 0 and 3 should be NULL")
}
if batch.IsNull(0, 1) || batch.IsNull(0, 2) || batch.IsNull(0, 4) {
t.Fatal("non-null rows must not report as NULL")
}
want := []int32{0, 100, 200, 0, 300}
for i, w := range want {
if got := batch.Int32(0, i); got != w {
t.Fatalf("Int32(0, %d) = %d, want %d", i, got, w)
}
}
if c := batch.NonNullCount(0); c != 3 {
t.Fatalf("NonNullCount = %d, want 3", c)
}
}
func TestQwpColumnBatchNullableAllNulls(t *testing.T) {
// Every row NULL: nonNullCount=0, every accessor returns zero.
info := qwpColumnSchemaInfo{name: "x", wireType: qwpTypeLong}
rowBytes := [][]byte{nil, nil, nil}
layout := buildNullableLayout(&info, rowBytes)
batch := newSingleColumnBatch(info, layout, 3)
for i := 0; i < 3; i++ {
if !batch.IsNull(0, i) {
t.Fatalf("row %d should be NULL", i)
}
if v := batch.Int64(0, i); v != 0 {
t.Fatalf("Int64(0, %d) = %d, want 0", i, v)
}
}
if c := batch.NonNullCount(0); c != 0 {
t.Fatalf("NonNullCount = %d, want 0", c)
}
}
// --- Strings, varchars, binary ---
func buildStringLayout(info *qwpColumnSchemaInfo, values []string) qwpColumnLayout {
// Offsets array: (len(values)+1) uint32 LE, then concatenated bytes.
offsets := make([]byte, 4*(len(values)+1))
var heap []byte
var cur uint32
for i, s := range values {
binary.LittleEndian.PutUint32(offsets[i*4:], cur)
heap = append(heap, s...)
cur += uint32(len(s))
}
binary.LittleEndian.PutUint32(offsets[len(values)*4:], cur)
return qwpColumnLayout{
info: info,
values: offsets,
stringBytes: heap,
nonNullCount: len(values),
}
}
func TestQwpColumnBatchStringsAndVarcharsAndBinary(t *testing.T) {
for _, tc := range []struct {
name string
wt qwpTypeCode
}{
{"VARCHAR", qwpTypeVarchar},
{"BINARY", qwpTypeBinary},
} {
t.Run(tc.name, func(t *testing.T) {
info := qwpColumnSchemaInfo{name: "s", wireType: tc.wt}
vals := []string{"", "hello", "日本語", "x"}
layout := buildStringLayout(&info, vals)
batch := newSingleColumnBatch(info, layout, len(vals))
for i, v := range vals {
var got []byte
if tc.wt == qwpTypeBinary {
got = batch.Binary(0, i)
} else {
got = batch.Str(0, i)
}
if !bytes.Equal(got, []byte(v)) {
t.Fatalf("%s row %d: got %q, want %q", tc.name, i, got, v)
}
}
// Two accessor calls return independent slice values
// (different Go slice headers), even though they alias
// the same backing bytes.
if tc.wt == qwpTypeVarchar {
a := batch.Str(0, 1)
b := batch.Str(0, 2)
if bytes.Equal(a, b) {
t.Fatalf("independent views should differ: a=%q b=%q", a, b)
}
}
})
}
}
func TestQwpColumnBatchStringAllocatingHelper(t *testing.T) {
info := qwpColumnSchemaInfo{name: "s", wireType: qwpTypeVarchar}
vals := []string{"hello", "", "world"}
layout := buildStringLayout(&info, vals)
batch := newSingleColumnBatch(info, layout, len(vals))
if got := batch.String(0, 0); got != "hello" {
t.Fatalf("String[0] = %q", got)
}
if got := batch.String(0, 2); got != "world" {
t.Fatalf("String[2] = %q", got)
}
}
// --- Symbol ---
func TestQwpColumnBatchSymbol(t *testing.T) {
info := qwpColumnSchemaInfo{name: "sy", wireType: qwpTypeSymbol}
// Dict: ["alpha", "beta", "gamma"], one heap region with packed
// (offset, length) entries.
heap := []byte("alphabetagamma")
entries := []qwpSymbolEntry{
{offset: 0, length: 5},
{offset: 5, length: 4},
{offset: 9, length: 5},
}
dict := qwpSymbolDictView{heap: heap, entries: entries}
// Four rows: alpha, beta, NULL, gamma.
rowCount := 4
bitmap := make([]byte, 1)
bitmap[0] = 1 << 2 // row 2 NULL
nonNullIdx := []int32{0, 1, -1, 2}
symbolRowIds := []int32{0, 1, 0 /* stale, row is NULL */, 2}
layout := qwpColumnLayout{
info: &info,
nullBitmap: bitmap,
nonNullIdx: nonNullIdx,
nonNullCount: 3,
symbolRowIds: symbolRowIds,
symbolDict: dict,
}
batch := newSingleColumnBatch(info, layout, rowCount)
want := []string{"alpha", "beta", "", "gamma"}
for i, w := range want {
if got := batch.String(0, i); got != w {
t.Fatalf("Symbol row %d: got %q, want %q", i, got, w)
}
}
if !batch.IsNull(0, 2) {
t.Fatalf("row 2 must be NULL")
}
}
// --- Arrays ---
func TestQwpColumnBatchFloat64Array1D(t *testing.T) {
// One row: 1D array [1.5, 2.5, 3.5].
info := qwpColumnSchemaInfo{name: "a", wireType: qwpTypeDoubleArray}
var buf bytes.Buffer
buf.WriteByte(1) // nDims
_ = binary.Write(&buf, binary.LittleEndian, int32(3))
_ = binary.Write(&buf, binary.LittleEndian, 1.5)
_ = binary.Write(&buf, binary.LittleEndian, 2.5)
_ = binary.Write(&buf, binary.LittleEndian, 3.5)
values := buf.Bytes()
layout := qwpColumnLayout{
info: &info,
values: values,
arrayRowStart: []int32{0},
arrayElems: []int32{3},
nonNullCount: 1,
}
batch := newSingleColumnBatch(info, layout, 1)
if n := batch.ArrayNDims(0, 0); n != 1 {
t.Fatalf("ArrayNDims = %d", n)
}
if d := batch.ArrayDim(0, 0, 0); d != 3 {
t.Fatalf("ArrayDim(0) = %d", d)
}
got := batch.Float64Array(0, 0)
want := []float64{1.5, 2.5, 3.5}
for i := range want {
if got[i] != want[i] {
t.Fatalf("Float64Array[%d] = %v, want %v", i, got[i], want[i])
}
}
}
func TestQwpColumnBatchInt64Array2D(t *testing.T) {
// One row: 2×3 array, row-major: [[1,2,3],[4,5,6]].
info := qwpColumnSchemaInfo{name: "a", wireType: qwpTypeLongArray}
var buf bytes.Buffer
buf.WriteByte(2) // nDims
_ = binary.Write(&buf, binary.LittleEndian, int32(2))
_ = binary.Write(&buf, binary.LittleEndian, int32(3))
for _, v := range []int64{1, 2, 3, 4, 5, 6} {
_ = binary.Write(&buf, binary.LittleEndian, v)
}
values := buf.Bytes()
layout := qwpColumnLayout{
info: &info,
values: values,
arrayRowStart: []int32{0},
arrayElems: []int32{6},
nonNullCount: 1,
}
batch := newSingleColumnBatch(info, layout, 1)
if n := batch.ArrayNDims(0, 0); n != 2 {
t.Fatalf("ArrayNDims = %d", n)
}
if d0, d1 := batch.ArrayDim(0, 0, 0), batch.ArrayDim(0, 0, 1); d0 != 2 || d1 != 3 {
t.Fatalf("ArrayDim = %dx%d", d0, d1)
}
got := batch.Int64Array(0, 0)
want := []int64{1, 2, 3, 4, 5, 6}
for i := range want {
if got[i] != want[i] {
t.Fatalf("Int64Array[%d] = %d", i, got[i])
}
}
}
func TestQwpColumnBatchEmptyArrayViaZeroShape(t *testing.T) {
// A non-null 1-D empty array is encoded as (nDims=1, dim0=0): 5
// bytes of shape, 0 bytes of elements. Distinct from a NULL row
// (null bitmap bit set, no inline bytes) — accessors should
// report a real 1-D array with zero length.
info := qwpColumnSchemaInfo{name: "a", wireType: qwpTypeDoubleArray}
var buf bytes.Buffer
buf.WriteByte(1) // nDims
_ = binary.Write(&buf, binary.LittleEndian, int32(0))
values := buf.Bytes()
layout := qwpColumnLayout{
info: &info,
values: values,
arrayRowStart: []int32{0},
arrayElems: []int32{0},
nonNullCount: 1,
}
batch := newSingleColumnBatch(info, layout, 1)
if n := batch.ArrayNDims(0, 0); n != 1 {
t.Fatalf("ArrayNDims = %d, want 1", n)
}
if d := batch.ArrayDim(0, 0, 0); d != 0 {
t.Fatalf("ArrayDim(0) = %d, want 0", d)
}
if got := batch.Float64Array(0, 0); len(got) != 0 {
t.Fatalf("Float64Array len = %d, want 0", len(got))
}
}
// TestQwpColumnFloat64ArrayInto exercises the append-into-dst variant
// of Float64Array: it must extend dst with the row's elements, leave
// dst unchanged on a NULL row, and reuse dst's backing array across
// successive calls (the hot-loop pattern this accessor exists for).
func TestQwpColumnFloat64ArrayInto(t *testing.T) {
// Two non-null rows back-to-back: row 0 = [1.5, 2.5], row 1 = [3.5].
info := qwpColumnSchemaInfo{name: "a", wireType: qwpTypeDoubleArray}
var buf bytes.Buffer
buf.WriteByte(1) // row 0 nDims
_ = binary.Write(&buf, binary.LittleEndian, int32(2))
_ = binary.Write(&buf, binary.LittleEndian, 1.5)
_ = binary.Write(&buf, binary.LittleEndian, 2.5)
row1Start := int32(buf.Len())
buf.WriteByte(1) // row 1 nDims
_ = binary.Write(&buf, binary.LittleEndian, int32(1))
_ = binary.Write(&buf, binary.LittleEndian, 3.5)
values := buf.Bytes()
layout := qwpColumnLayout{
info: &info,
values: values,
arrayRowStart: []int32{0, row1Start},
arrayElems: []int32{2, 1},
nonNullCount: 2,
}
batch := newSingleColumnBatch(info, layout, 2)
col := batch.Column(0)
dst := make([]float64, 0, 8)
dst = col.Float64ArrayInto(0, dst)
if len(dst) != 2 || dst[0] != 1.5 || dst[1] != 2.5 {
t.Fatalf("row 0 into dst = %v", dst)
}
// Append-style: a second call without truncating extends dst.
dst = col.Float64ArrayInto(1, dst)
if len(dst) != 3 || dst[2] != 3.5 {
t.Fatalf("row 1 appended dst = %v", dst)
}
// Hot-loop pattern: truncate before each row to reuse the backing
// array. Capacity must be preserved across the truncation.
beforeCap := cap(dst)
dst = dst[:0]
dst = col.Float64ArrayInto(0, dst)
if len(dst) != 2 || cap(dst) != beforeCap {
t.Fatalf("reuse: len=%d cap=%d (was %d)", len(dst), cap(dst), beforeCap)
}
}
// TestQwpColumnFloat64ArrayIntoNull verifies that a NULL row leaves
// dst unchanged (no zero-fill, no truncation) — distinct from the
// per-cell Float64Array which returns nil for NULL.
func TestQwpColumnFloat64ArrayIntoNull(t *testing.T) {
info := qwpColumnSchemaInfo{name: "a", wireType: qwpTypeDoubleArray}
// Null bitmap has bit 0 set → row 0 is NULL.
layout := qwpColumnLayout{
info: &info,
values: []byte{},
arrayRowStart: []int32{0},
arrayElems: []int32{0},
nullBitmap: []byte{0x01},
nonNullCount: 0,
}
batch := newSingleColumnBatch(info, layout, 1)
col := batch.Column(0)
dst := []float64{99.0, 99.0}
got := col.Float64ArrayInto(0, dst)
if len(got) != 2 || got[0] != 99.0 || got[1] != 99.0 {
t.Fatalf("NULL row mutated dst = %v", got)
}
}
// TestQwpColumnInt64ArrayInto mirrors the Float64ArrayInto test for
// LONG_ARRAY columns.
func TestQwpColumnInt64ArrayInto(t *testing.T) {
info := qwpColumnSchemaInfo{name: "a", wireType: qwpTypeLongArray}
var buf bytes.Buffer
buf.WriteByte(1)
_ = binary.Write(&buf, binary.LittleEndian, int32(3))
for _, v := range []int64{10, 20, 30} {
_ = binary.Write(&buf, binary.LittleEndian, v)
}
values := buf.Bytes()
layout := qwpColumnLayout{
info: &info,
values: values,
arrayRowStart: []int32{0},
arrayElems: []int32{3},
nonNullCount: 1,
}
batch := newSingleColumnBatch(info, layout, 1)
col := batch.Column(0)
dst := col.Int64ArrayInto(0, nil)
want := []int64{10, 20, 30}
if len(dst) != len(want) {
t.Fatalf("Int64ArrayInto len = %d, want %d", len(dst), len(want))
}
for i, w := range want {
if dst[i] != w {
t.Fatalf("Int64ArrayInto[%d] = %d, want %d", i, dst[i], w)
}
}
}
// --- CopyAll ---
// TestQwpColumnBatchCopyAllSurvivesPoolReuse is the contract CopyAll
// exists to satisfy: a snapshot taken from batch N remains valid and
// correct after batch N's pool-owned layout slices are reused for
// batch N+1. The live batch aliases the decoder's layout pool, so
// without the copy the snapshot's nonNullIdx / symbolRowIds /
// timestampBuf entries would read batch N+1 data.
func TestQwpColumnBatchCopyAllSurvivesPoolReuse(t *testing.T) {
// Build a nullable Int64 column so nonNullIdx is non-trivial and
// we can observe it getting overwritten.
info := qwpColumnSchemaInfo{name: "v", wireType: qwpTypeLong}
rowBytes := [][]byte{
binary.LittleEndian.AppendUint64(nil, uint64(100)),
nil, // NULL
binary.LittleEndian.AppendUint64(nil, uint64(300)),
}
layout := buildNullableLayout(&info, rowBytes)
batch := newSingleColumnBatch(info, layout, 3)
snapshot := batch.CopyAll()
// Simulate the decoder overwriting the pool-owned fields in place,
// the same way qwpColumnLayout.clear() + parseNullSection would.
for i := range batch.layouts[0].nonNullIdx {
batch.layouts[0].nonNullIdx[i] = 0xBAD
}
batch.layouts[0].values = []byte{0xDE, 0xAD, 0xBE, 0xEF, 0, 0, 0, 0}
// Snapshot must still see the original values.
if got := snapshot.Int64(0, 0); got != 100 {
t.Fatalf("snapshot.Int64(0,0) = %d, want 100", got)
}
if !snapshot.IsNull(0, 1) {
t.Fatal("snapshot row 1 should be NULL")
}
if got := snapshot.Int64(0, 2); got != 300 {
t.Fatalf("snapshot.Int64(0,2) = %d, want 300", got)
}
if snapshot.RowCount() != 3 || snapshot.ColumnCount() != 1 {
t.Fatalf("snapshot row/col count = (%d, %d), want (3, 1)",
snapshot.RowCount(), snapshot.ColumnCount())
}
if snapshot.ColumnName(0) != "v" {
t.Fatalf("snapshot column name = %q", snapshot.ColumnName(0))
}
}
// TestQwpColumnBatchCopyAllGorillaTimestampSurvivesPoolReuse covers
// the Gorilla-TIMESTAMP corner of CopyAll. For Gorilla-encoded
// columns the decoder sets layout.values to alias layout.timestampBuf
// (see parseTimestamp), so the snapshot must re-point values at the
// CLONED timestampBuf. Without that re-point, decoding a second frame
// into the same QwpColumnBatch overwrites the source's timestampBuf
// in place and the snapshot's Int64 accessor starts reading batch
// N+1 values.
func TestQwpColumnBatchCopyAllGorillaTimestampSurvivesPoolReuse(t *testing.T) {
// Small, regular DoDs push the encoder onto the Gorilla path;
// nonNullCount >= 3 is required for Gorilla (parseTimestamp
// rejects otherwise).
orig := []int64{1_000_000, 1_000_100, 1_000_200, 1_000_310, 1_000_520}
origRows := make([]func(*qwpColumnBuffer), len(orig))
for i, v := range orig {
v := v
origRows[i] = func(c *qwpColumnBuffer) { c.addLong(v) }
}
frame1 := encodeSingleColumnBatch(t, "ts", qwpTypeTimestamp, false, origRows)
// A second batch whose values are nowhere near the first, so a
// stale alias produces obviously-wrong reads rather than
// coincidentally-matching values.
fresh := []int64{5_000_000, 5_000_999, 5_001_888, 5_002_555, 5_003_333}
freshRows := make([]func(*qwpColumnBuffer), len(fresh))
for i, v := range fresh {
v := v
freshRows[i] = func(c *qwpColumnBuffer) { c.addLong(v) }
}
frame2 := encodeSingleColumnBatch(t, "ts", qwpTypeTimestamp, false, freshRows)
dec := newTestQueryDecoder()
var batch QwpColumnBatch
if err := dec.decode(frame1, &batch); err != nil {
t.Fatalf("decode 1: %v", err)
}
// Precondition: the first decode must actually have taken the
// Gorilla path. If encoder heuristics change and this falls back
// to the uncompressed branch, the test no longer covers the bug.
if len(batch.layouts[0].timestampBuf) == 0 {
t.Fatal("test precondition: expected Gorilla path to populate timestampBuf")
}
snapshot := batch.CopyAll()
// Decode a second frame into the SAME batch. The decoder reuses
// batch.layouts[0].timestampBuf in place, so the source's backing
// array is now clobbered.
if err := dec.decode(frame2, &batch); err != nil {
t.Fatalf("decode 2: %v", err)
}
for i, w := range orig {
if got := snapshot.Int64(0, i); got != w {
t.Fatalf("snapshot.Int64(0, %d) = %d, want %d", i, got, w)
}
}
}
// TestQwpColumnBatchCopyAllRawSurvivesPayloadReuse covers the raw
// (non-zstd) sibling of TestQwpColumnBatchCopyAllZstdSurvivesPoolReuse.
// The egress I/O loop reads each WS frame into a buffer borrowed from
// qwpEgressIO.readBufPool; on the raw path the decoded batch's column
// slices (values, stringBytes, nullBitmap) alias that pooled buffer
// directly. releaseBuffer returns the buffer to the pool, and the next
// inbound frame is decoded into the same backing array in place. A
// CopyAll result the caller retained from the released batch must
// remain valid across that recycle — i.e. CopyAll must deep-clone the
// payload bytes on the raw path the same way it already does on the
// zstd path.
//
// Reproduces the in-place clobber without touching the I/O loop:
// allocate one backing array, write frame 1 into it, hand the slice to
// the decoder, snapshot, then overwrite the array's bytes with frame 2.
// snapshot.Int64 reads its values from the same backing array the
// decoder aliased; without the fix the post-clobber read returns the
// frame-2 little-endian word at that offset, not the original.
func TestQwpColumnBatchCopyAllRawSurvivesPayloadReuse(t *testing.T) {
frame1 := encodeSingleColumnBatch(t, "v", qwpTypeLong, false,
[]func(*qwpColumnBuffer){
func(c *qwpColumnBuffer) { c.addLong(111) },
func(c *qwpColumnBuffer) { c.addLong(222) },
})
frame2 := encodeSingleColumnBatch(t, "v", qwpTypeLong, false,
[]func(*qwpColumnBuffer){
func(c *qwpColumnBuffer) { c.addLong(-9999) },
func(c *qwpColumnBuffer) { c.addLong(-8888) },
})
if len(frame2) < len(frame1) {
t.Fatalf("test precondition: frame2 (%d) must be >= frame1 (%d) so the clobber overlaps the column data", len(frame2), len(frame1))
}
// One backing array that stands in for a recycled readBufPool
// buffer: it holds frame1 first, then the next frame is read into
// the same memory in place.
pooled := make([]byte, len(frame2))
copy(pooled, frame1)
payload := pooled[:len(frame1)]
dec := newTestQueryDecoder()
var b QwpColumnBatch
if err := dec.decode(payload, &b); err != nil {
t.Fatalf("decode 1: %v", err)
}
if len(b.zstdScratch) != 0 {
t.Fatalf("test precondition: expected raw (non-zstd) path; zstdScratch=%d", len(b.zstdScratch))
}
snapshot := b.CopyAll()
if got := snapshot.Int64(0, 0); got != 111 {
t.Fatalf("pre-clobber snapshot.Int64(0,0) = %d, want 111", got)
}
if got := snapshot.Int64(0, 1); got != 222 {
t.Fatalf("pre-clobber snapshot.Int64(0,1) = %d, want 222", got)
}
// Recycle: the I/O loop hands the buffer back to readBufPool and
// the reader's qwpReadFrameInto writes the next frame into the
// same backing array. Simulate that with a copy().
copy(pooled, frame2)
// Snapshot must still report frame-1 values.
if got := snapshot.Int64(0, 0); got != 111 {
t.Fatalf("post-clobber snapshot.Int64(0,0) = %d, want 111 (CopyAll didn't clone the raw payload)", got)
}
if got := snapshot.Int64(0, 1); got != 222 {
t.Fatalf("post-clobber snapshot.Int64(0,1) = %d, want 222 (CopyAll didn't clone the raw payload)", got)
}
}
// TestQwpGeohashAccessorWithNulls verifies the Geohash accessors on both
// the batch and the cached-column surface at a sub-8-byte precision with
// interleaved nulls. Precision 12 packs 2 bytes per non-null value, so the
// dense stride is 2, not 8, and the nulls route every read through the
// null-bitmap / denseIndex mapping. A wrong (Int64-style *8) stride would
// index the wrong cell or run past the dense region; this pins the
// precision-sized stride the accessor must use.
func TestQwpGeohashAccessorWithNulls(t *testing.T) {
const prec = 12
type row struct {
val uint64
null bool
}
rows := []row{
{0xABC, false},
{0, true},
{0x123, false},
{0, true},
{0xFFF, false},
}
tb := newQwpTableBuffer("t")
for _, r := range rows {
col, err := tb.getOrCreateColumn("g", qwpTypeGeohash, true)
if err != nil {
t.Fatalf("getOrCreateColumn: %v", err)
}
if r.null {
col.addNull()
} else if err := col.addGeohash(r.val, prec); err != nil {
t.Fatalf("addGeohash: %v", err)
}
tb.commitRow()
}
var enc qwpEncoder
frame := wrapAsResultBatch(enc.encodeTable(tb), 1, 0)
dec := newTestQueryDecoder()
var batch QwpColumnBatch
if err := dec.decode(frame, &batch); err != nil {
t.Fatalf("decode: %v", err)
}
if got := batch.GeohashPrecisionBits(0); got != prec {
t.Fatalf("GeohashPrecisionBits = %d, want %d", got, prec)
}
col := batch.Column(0)
for i, r := range rows {
if got := batch.IsNull(0, i); got != r.null {
t.Errorf("IsNull(0,%d) = %v, want %v", i, got, r.null)
}
want := r.val
if r.null {
want = 0 // NULL rows read as 0 on both surfaces.
}
if got := batch.Geohash(0, i); got != want {
t.Errorf("batch.Geohash(0,%d) = %#x, want %#x", i, got, want)
}
if got := col.Geohash(i); got != want {
t.Errorf("col.Geohash(%d) = %#x, want %#x", i, got, want)
}
}
}
// buildDecimalGeohashFrame produces a one-row RESULT_BATCH frame with
// a DECIMAL64 column (given scale) and a GEOHASH column (given precision
// bits). The decoder reads the per-batch scale / precision off the DATA
// section and stores them on qwpColumnLayout, which is what the race
// test below observes concurrently.
func buildDecimalGeohashFrame(t *testing.T, scale uint32, precision int8, unscaled int64) []byte {
t.Helper()
tb := newQwpTableBuffer("t")
dcol, err := tb.getOrCreateColumn("d", qwpTypeDecimal64, false)
if err != nil {
t.Fatalf("getOrCreateColumn d: %v", err)
}
if err := dcol.addDecimal(NewDecimalFromInt64(unscaled, scale)); err != nil {
t.Fatalf("addDecimal: %v", err)
}
gcol, err := tb.getOrCreateColumn("g", qwpTypeGeohash, false)
if err != nil {
t.Fatalf("getOrCreateColumn g: %v", err)
}
if err := gcol.addGeohash(uint64(unscaled), precision); err != nil {
t.Fatalf("addGeohash: %v", err)
}
tb.commitRow()
var enc qwpEncoder
ingress := enc.encodeTable(tb)
return wrapAsResultBatch(ingress, 1, 0)
}
// TestQwpColumnBatchCopyAllScaleAndPrecisionAreRaceFree exercises the
// concurrency invariant that commit 58e1915 ("Fix data race on decimal
// scale and geohash precision") added: a held CopyAll snapshot
// must be safe to read while the decoder writes the next batch's scale
// / precision into the source QwpColumnBatch.
//
// Before that fix both fields lived on the connection-scoped
// qwpColumnSchemaInfo, which the decoder mutated per batch and which
// every snapshot aliased via layouts[i].info — so this test paired
// with `go test -race` flagged the write/read overlap. Post-fix the
// fields are on qwpColumnLayout and CopyAll takes value copies, so the
// snapshot's accessors read memory the decoder never touches again.
//
// Without -race this test is still meaningful: a snapshot must keep
// its frame-A values even after frame B is decoded into the source
// batch.
func TestQwpColumnBatchCopyAllScaleAndPrecisionAreRaceFree(t *testing.T) {
frameA := buildDecimalGeohashFrame(t, 2, 20, 12345)
frameB := buildDecimalGeohashFrame(t, 7, 40, 99999)
dec := newTestQueryDecoder()
var batch QwpColumnBatch
if err := dec.decode(frameA, &batch); err != nil {
t.Fatalf("decode A: %v", err)
}
if s := batch.DecimalScale(0); s != 2 {
t.Fatalf("A scale = %d, want 2", s)
}
if p := batch.GeohashPrecisionBits(1); p != 20 {
t.Fatalf("A precision = %d, want 20", p)
}
snapshot := batch.CopyAll()
const readers = 4
var wg sync.WaitGroup
stop := make(chan struct{})
for r := 0; r < readers; r++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-stop:
return
default:
}
if s := snapshot.DecimalScale(0); s != 2 {
t.Errorf("snapshot.DecimalScale = %d, want 2", s)
return
}
if p := snapshot.GeohashPrecisionBits(1); p != 20 {
t.Errorf("snapshot.GeohashPrecisionBits = %d, want 20", p)
return
}
}
}()
}
// Repeatedly re-decode frame B into the same batch. Each decode
// writes frame-B scale / precision into the layout; -race catches
// any overlap with the readers above.
for i := 0; i < 200; i++ {
if err := dec.decode(frameB, &batch); err != nil {
close(stop)
wg.Wait()
t.Fatalf("decode B [%d]: %v", i, err)
}
if s := batch.DecimalScale(0); s != 7 {
close(stop)
wg.Wait()
t.Fatalf("live batch scale = %d, want 7", s)
}
if p := batch.GeohashPrecisionBits(1); p != 40 {
close(stop)
wg.Wait()
t.Fatalf("live batch precision = %d, want 40", p)
}
}