-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
testutils.go
1896 lines (1781 loc) · 63.2 KB
/
testutils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package rowenc
import (
"bytes"
gosql "database/sql"
"fmt"
"math"
"math/big"
"math/bits"
"math/rand"
"sort"
"strings"
"time"
"unicode"
"github.com/cockroachdb/apd/v2"
"github.com/cockroachdb/cockroach/pkg/geo"
"github.com/cockroachdb/cockroach/pkg/geo/geogen"
"github.com/cockroachdb/cockroach/pkg/geo/geopb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/bitarray"
"github.com/cockroachdb/cockroach/pkg/util/duration"
"github.com/cockroachdb/cockroach/pkg/util/ipaddr"
"github.com/cockroachdb/cockroach/pkg/util/json"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/timeofday"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil/pgdate"
"github.com/cockroachdb/cockroach/pkg/util/uint128"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
)
// This file contains utility functions for tests (in other packages).
// RandDatum generates a random Datum of the given type.
// If nullOk is true, the datum can be DNull.
// Note that if typ.Family is UNKNOWN, the datum will always be DNull,
// regardless of the null flag.
func RandDatum(rng *rand.Rand, typ *types.T, nullOk bool) tree.Datum {
nullDenominator := 10
if !nullOk {
nullDenominator = 0
}
return RandDatumWithNullChance(rng, typ, nullDenominator)
}
// RandDatumWithNullChance generates a random Datum of the given type.
// nullChance is the chance of returning null, expressed as a fraction
// denominator. For example, a nullChance of 5 means that there's a 1/5 chance
// that DNull will be returned. A nullChance of 0 means that DNull will not
// be returned.
// Note that if typ.Family is UNKNOWN, the datum will always be
// DNull, regardless of the null flag.
func RandDatumWithNullChance(rng *rand.Rand, typ *types.T, nullChance int) tree.Datum {
if nullChance != 0 && rng.Intn(nullChance) == 0 {
return tree.DNull
}
// Sometimes pick from a predetermined list of known interesting datums.
if rng.Intn(10) == 0 {
if special := randInterestingDatum(rng, typ); special != nil {
return special
}
}
switch typ.Family() {
case types.BoolFamily:
return tree.MakeDBool(rng.Intn(2) == 1)
case types.IntFamily:
switch typ.Width() {
case 64:
// int64(rng.Uint64()) to get negative numbers, too
return tree.NewDInt(tree.DInt(int64(rng.Uint64())))
case 32:
// int32(rng.Uint64()) to get negative numbers, too
return tree.NewDInt(tree.DInt(int32(rng.Uint64())))
case 16:
// int16(rng.Uint64()) to get negative numbers, too
return tree.NewDInt(tree.DInt(int16(rng.Uint64())))
case 8:
// int8(rng.Uint64()) to get negative numbers, too
return tree.NewDInt(tree.DInt(int8(rng.Uint64())))
default:
panic(errors.AssertionFailedf("int with an unexpected width %d", typ.Width()))
}
case types.FloatFamily:
switch typ.Width() {
case 64:
return tree.NewDFloat(tree.DFloat(rng.NormFloat64()))
case 32:
return tree.NewDFloat(tree.DFloat(float32(rng.NormFloat64())))
default:
panic(errors.AssertionFailedf("float with an unexpected width %d", typ.Width()))
}
case types.Box2DFamily:
b := geo.NewCartesianBoundingBox().AddPoint(rng.NormFloat64(), rng.NormFloat64()).AddPoint(rng.NormFloat64(), rng.NormFloat64())
return tree.NewDBox2D(*b)
case types.GeographyFamily:
gm, err := typ.GeoMetadata()
if err != nil {
panic(err)
}
srid := gm.SRID
if srid == 0 {
srid = geopb.DefaultGeographySRID
}
return tree.NewDGeography(geogen.RandomGeography(rng, srid))
case types.GeometryFamily:
gm, err := typ.GeoMetadata()
if err != nil {
panic(err)
}
return tree.NewDGeometry(geogen.RandomGeometry(rng, gm.SRID))
case types.DecimalFamily:
d := &tree.DDecimal{}
// int64(rng.Uint64()) to get negative numbers, too
d.Decimal.SetFinite(int64(rng.Uint64()), int32(rng.Intn(40)-20))
return d
case types.DateFamily:
d, err := pgdate.MakeDateFromUnixEpoch(int64(rng.Intn(10000)))
if err != nil {
return nil
}
return tree.NewDDate(d)
case types.TimeFamily:
return tree.MakeDTime(timeofday.Random(rng)).Round(tree.TimeFamilyPrecisionToRoundDuration(typ.Precision()))
case types.TimeTZFamily:
return tree.NewDTimeTZFromOffset(
timeofday.Random(rng),
// We cannot randomize seconds, because lib/pq does NOT print the
// second offsets making some tests break when comparing
// results in == results out using string comparison.
(rng.Int31n(28*60+59)-(14*60+59))*60,
).Round(tree.TimeFamilyPrecisionToRoundDuration(typ.Precision()))
case types.TimestampFamily:
return tree.MustMakeDTimestamp(
timeutil.Unix(rng.Int63n(2000000000), rng.Int63n(1000000)),
tree.TimeFamilyPrecisionToRoundDuration(typ.Precision()),
)
case types.IntervalFamily:
sign := 1 - rng.Int63n(2)*2
return &tree.DInterval{Duration: duration.MakeDuration(
sign*rng.Int63n(25*3600*int64(1000000000)),
sign*rng.Int63n(1000),
sign*rng.Int63n(1000),
)}
case types.UuidFamily:
gen := uuid.NewGenWithReader(rng)
return tree.NewDUuid(tree.DUuid{UUID: uuid.Must(gen.NewV4())})
case types.INetFamily:
ipAddr := ipaddr.RandIPAddr(rng)
return tree.NewDIPAddr(tree.DIPAddr{IPAddr: ipAddr})
case types.JsonFamily:
j, err := json.Random(20, rng)
if err != nil {
return nil
}
return &tree.DJSON{JSON: j}
case types.TupleFamily:
tuple := tree.DTuple{D: make(tree.Datums, len(typ.TupleContents()))}
for i := range typ.TupleContents() {
tuple.D[i] = RandDatum(rng, typ.TupleContents()[i], true)
}
// Calling ResolvedType causes the internal TupleContents types to be
// populated.
tuple.ResolvedType()
return &tuple
case types.BitFamily:
width := typ.Width()
if width == 0 {
width = rng.Int31n(100)
}
r := bitarray.Rand(rng, uint(width))
return &tree.DBitArray{BitArray: r}
case types.StringFamily:
// Generate a random ASCII string.
var length int
if typ.Oid() == oid.T_char || typ.Oid() == oid.T_bpchar {
length = 1
} else {
length = rng.Intn(10)
}
p := make([]byte, length)
for i := range p {
p[i] = byte(1 + rng.Intn(127))
}
if typ.Oid() == oid.T_name {
return tree.NewDName(string(p))
}
return tree.NewDString(string(p))
case types.BytesFamily:
p := make([]byte, rng.Intn(10))
_, _ = rng.Read(p)
return tree.NewDBytes(tree.DBytes(p))
case types.TimestampTZFamily:
return tree.MustMakeDTimestampTZ(
timeutil.Unix(rng.Int63n(2000000000), rng.Int63n(1000000)),
tree.TimeFamilyPrecisionToRoundDuration(typ.Precision()),
)
case types.CollatedStringFamily:
// Generate a random Unicode string.
var buf bytes.Buffer
n := rng.Intn(10)
for i := 0; i < n; i++ {
var r rune
for {
r = rune(rng.Intn(unicode.MaxRune + 1))
if !unicode.Is(unicode.C, r) {
break
}
}
buf.WriteRune(r)
}
d, err := tree.NewDCollatedString(buf.String(), typ.Locale(), &tree.CollationEnvironment{})
if err != nil {
panic(err)
}
return d
case types.OidFamily:
return tree.NewDOid(tree.DInt(rng.Uint32()))
case types.UnknownFamily:
return tree.DNull
case types.ArrayFamily:
return RandArray(rng, typ, 0)
case types.AnyFamily:
return RandDatumWithNullChance(rng, RandType(rng), nullChance)
case types.EnumFamily:
// If the input type is not hydrated with metadata, or doesn't contain
// any enum values, then return NULL.
if typ.TypeMeta.EnumData == nil {
return tree.DNull
}
reps := typ.TypeMeta.EnumData.LogicalRepresentations
if len(reps) == 0 {
return tree.DNull
}
// Otherwise, pick a random enum value.
d, err := tree.MakeDEnumFromLogicalRepresentation(typ, reps[rng.Intn(len(reps))])
if err != nil {
panic(err)
}
return d
default:
panic(errors.AssertionFailedf("invalid type %v", typ.DebugString()))
}
}
// RandArray generates a random DArray where the contents have nullChance
// of being null.
func RandArray(rng *rand.Rand, typ *types.T, nullChance int) tree.Datum {
contents := typ.ArrayContents()
if contents.Family() == types.AnyFamily {
contents = RandArrayContentsType(rng)
}
arr := tree.NewDArray(contents)
for i := 0; i < rng.Intn(10); i++ {
if err := arr.Append(RandDatumWithNullChance(rng, contents, nullChance)); err != nil {
panic(err)
}
}
return arr
}
const simpleRange = 10
// RandDatumSimple generates a random Datum of the given type. The generated
// datums will be simple (i.e., only one character or an integer between 0
// and 9), such that repeated calls to this function will regularly return a
// previously generated datum.
func RandDatumSimple(rng *rand.Rand, typ *types.T) tree.Datum {
datum := tree.DNull
switch typ.Family() {
case types.BitFamily:
datum, _ = tree.NewDBitArrayFromInt(rng.Int63n(simpleRange), uint(bits.Len(simpleRange)))
case types.BoolFamily:
if rng.Intn(2) == 1 {
datum = tree.DBoolTrue
} else {
datum = tree.DBoolFalse
}
case types.BytesFamily:
datum = tree.NewDBytes(tree.DBytes(randStringSimple(rng)))
case types.DateFamily:
date, _ := pgdate.MakeDateFromPGEpoch(rng.Int31n(simpleRange))
datum = tree.NewDDate(date)
case types.DecimalFamily:
datum = &tree.DDecimal{
Decimal: apd.Decimal{
Coeff: *big.NewInt(rng.Int63n(simpleRange)),
},
}
case types.IntFamily:
datum = tree.NewDInt(tree.DInt(rng.Intn(simpleRange)))
case types.IntervalFamily:
datum = &tree.DInterval{Duration: duration.MakeDuration(
rng.Int63n(simpleRange)*1e9,
0,
0,
)}
case types.FloatFamily:
datum = tree.NewDFloat(tree.DFloat(rng.Intn(simpleRange)))
case types.INetFamily:
datum = tree.NewDIPAddr(tree.DIPAddr{
IPAddr: ipaddr.IPAddr{
Addr: ipaddr.Addr(uint128.FromInts(0, uint64(rng.Intn(simpleRange)))),
},
})
case types.JsonFamily:
datum = tree.NewDJSON(randJSONSimple(rng))
case types.OidFamily:
datum = tree.NewDOid(tree.DInt(rng.Intn(simpleRange)))
case types.StringFamily:
datum = tree.NewDString(randStringSimple(rng))
case types.TimeFamily:
datum = tree.MakeDTime(timeofday.New(0, rng.Intn(simpleRange), 0, 0))
case types.TimestampFamily:
datum = tree.MustMakeDTimestamp(time.Date(2000, 1, 1, rng.Intn(simpleRange), 0, 0, 0, time.UTC), time.Microsecond)
case types.TimestampTZFamily:
datum = tree.MustMakeDTimestampTZ(time.Date(2000, 1, 1, rng.Intn(simpleRange), 0, 0, 0, time.UTC), time.Microsecond)
case types.UuidFamily:
datum = tree.NewDUuid(tree.DUuid{
UUID: uuid.FromUint128(uint128.FromInts(0, uint64(rng.Intn(simpleRange)))),
})
}
return datum
}
func randStringSimple(rng *rand.Rand) string {
return string(rune('A' + rng.Intn(simpleRange)))
}
func randJSONSimple(rng *rand.Rand) json.JSON {
switch rng.Intn(10) {
case 0:
return json.NullJSONValue
case 1:
return json.FalseJSONValue
case 2:
return json.TrueJSONValue
case 3:
return json.FromInt(rng.Intn(simpleRange))
case 4:
return json.FromString(randStringSimple(rng))
case 5:
a := json.NewArrayBuilder(0)
for i := rng.Intn(3); i >= 0; i-- {
a.Add(randJSONSimple(rng))
}
return a.Build()
default:
a := json.NewObjectBuilder(0)
for i := rng.Intn(3); i >= 0; i-- {
a.Add(randStringSimple(rng), randJSONSimple(rng))
}
return a.Build()
}
}
// GenerateRandInterestingTable takes a gosql.DB connection and creates
// a table with all the types in randInterestingDatums and rows of the
// interesting datums.
func GenerateRandInterestingTable(db *gosql.DB, dbName, tableName string) error {
var (
randTypes []*types.T
colNames []string
)
numRows := 0
for _, v := range randInterestingDatums {
colTyp := v[0].ResolvedType()
randTypes = append(randTypes, colTyp)
colNames = append(colNames, colTyp.Name())
if len(v) > numRows {
numRows = len(v)
}
}
var columns strings.Builder
comma := ""
for i, typ := range randTypes {
columns.WriteString(comma)
columns.WriteString(colNames[i])
columns.WriteString(" ")
columns.WriteString(typ.SQLString())
comma = ", "
}
createStatement := fmt.Sprintf("CREATE TABLE %s.%s (%s)", dbName, tableName, columns.String())
if _, err := db.Exec(createStatement); err != nil {
return err
}
row := make([]string, len(randTypes))
for i := 0; i < numRows; i++ {
for j, typ := range randTypes {
datums := randInterestingDatums[typ.Family()]
var d tree.Datum
if i < len(datums) {
d = datums[i]
} else {
d = tree.DNull
}
row[j] = tree.AsStringWithFlags(d, tree.FmtParsable)
}
var builder strings.Builder
comma := ""
for _, d := range row {
builder.WriteString(comma)
builder.WriteString(d)
comma = ", "
}
insertStmt := fmt.Sprintf("INSERT INTO %s.%s VALUES (%s)", dbName, tableName, builder.String())
if _, err := db.Exec(insertStmt); err != nil {
return err
}
}
return nil
}
var (
// randInterestingDatums is a collection of interesting datums that can be
// used for random testing.
randInterestingDatums = map[types.Family][]tree.Datum{
types.BoolFamily: {
tree.DBoolTrue,
tree.DBoolFalse,
},
types.IntFamily: {
tree.NewDInt(tree.DInt(0)),
tree.NewDInt(tree.DInt(-1)),
tree.NewDInt(tree.DInt(1)),
tree.NewDInt(tree.DInt(math.MaxInt8)),
tree.NewDInt(tree.DInt(math.MinInt8)),
tree.NewDInt(tree.DInt(math.MaxInt16)),
tree.NewDInt(tree.DInt(math.MinInt16)),
tree.NewDInt(tree.DInt(math.MaxInt32)),
tree.NewDInt(tree.DInt(math.MinInt32)),
tree.NewDInt(tree.DInt(math.MaxInt64)),
// Use +1 because that's the SQL range.
tree.NewDInt(tree.DInt(math.MinInt64 + 1)),
},
types.FloatFamily: {
tree.NewDFloat(tree.DFloat(0)),
tree.NewDFloat(tree.DFloat(1)),
tree.NewDFloat(tree.DFloat(-1)),
tree.NewDFloat(tree.DFloat(math.SmallestNonzeroFloat32)),
tree.NewDFloat(tree.DFloat(math.MaxFloat32)),
tree.NewDFloat(tree.DFloat(math.SmallestNonzeroFloat64)),
tree.NewDFloat(tree.DFloat(math.MaxFloat64)),
tree.NewDFloat(tree.DFloat(math.Inf(1))),
tree.NewDFloat(tree.DFloat(math.Inf(-1))),
tree.NewDFloat(tree.DFloat(math.NaN())),
},
types.DecimalFamily: func() []tree.Datum {
var res []tree.Datum
for _, s := range []string{
"0",
"1",
"-1",
"Inf",
"-Inf",
"NaN",
"-12.34e400",
} {
d, err := tree.ParseDDecimal(s)
if err != nil {
panic(err)
}
res = append(res, d)
}
return res
}(),
types.DateFamily: {
tree.NewDDate(pgdate.MakeCompatibleDateFromDisk(0)),
tree.NewDDate(pgdate.LowDate),
tree.NewDDate(pgdate.HighDate),
tree.NewDDate(pgdate.PosInfDate),
tree.NewDDate(pgdate.NegInfDate),
},
types.TimeFamily: {
tree.MakeDTime(timeofday.Min),
tree.MakeDTime(timeofday.Max),
tree.MakeDTime(timeofday.Time2400),
},
types.TimeTZFamily: {
tree.DMinTimeTZ,
tree.DMaxTimeTZ,
},
types.TimestampFamily: func() []tree.Datum {
res := make([]tree.Datum, len(randTimestampSpecials))
for i, t := range randTimestampSpecials {
res[i] = tree.MustMakeDTimestamp(t, time.Microsecond)
}
return res
}(),
types.TimestampTZFamily: func() []tree.Datum {
res := make([]tree.Datum, len(randTimestampSpecials))
for i, t := range randTimestampSpecials {
res[i] = tree.MustMakeDTimestampTZ(t, time.Microsecond)
}
return res
}(),
types.IntervalFamily: {
&tree.DInterval{Duration: duration.MakeDuration(0, 0, 0)},
&tree.DInterval{Duration: duration.MakeDuration(0, 1, 0)},
&tree.DInterval{Duration: duration.MakeDuration(1, 0, 0)},
&tree.DInterval{Duration: duration.MakeDuration(1, 1, 1)},
// TODO(mjibson): fix intervals to stop overflowing then this can be larger.
&tree.DInterval{Duration: duration.MakeDuration(0, 0, 290*12)},
},
types.Box2DFamily: {
&tree.DBox2D{CartesianBoundingBox: geo.CartesianBoundingBox{BoundingBox: geopb.BoundingBox{LoX: -10, HiX: 10, LoY: -10, HiY: 10}}},
},
types.GeographyFamily: {
// NOTE(otan): we cannot use WKT here because roachtests do not have geos uploaded.
// If we parse WKT ourselves or upload GEOS on every roachtest, we may be able to avoid this.
// POINT(1.0 1.0)
&tree.DGeography{Geography: geo.MustParseGeography("0101000000000000000000F03F000000000000F03F")},
// LINESTRING(1.0 1.0, 2.0 2.0)
&tree.DGeography{Geography: geo.MustParseGeography("010200000002000000000000000000F03F000000000000F03F00000000000000400000000000000040")},
// POLYGON((0.0 0.0, 1.0 0.0, 1.0 1.0, 0.0 1.0, 0.0 0.0))
&tree.DGeography{Geography: geo.MustParseGeography("0103000000010000000500000000000000000000000000000000000000000000000000F03F0000000000000000000000000000F03F000000000000F03F0000000000000000000000000000F03F00000000000000000000000000000000")},
// POLYGON((0.0 0.0, 1.0 0.0, 1.0 1.0, 0.0 1.0, 0.0 0.0), (0.2 0.2, 0.2 0.4, 0.4 0.4, 0.4 0.2, 0.2 0.2))
&tree.DGeography{Geography: geo.MustParseGeography("0103000000020000000500000000000000000000000000000000000000000000000000F03F0000000000000000000000000000F03F000000000000F03F0000000000000000000000000000F03F00000000000000000000000000000000050000009A9999999999C93F9A9999999999C93F9A9999999999C93F9A9999999999D93F9A9999999999D93F9A9999999999D93F9A9999999999D93F9A9999999999C93F9A9999999999C93F9A9999999999C93F")},
// MULTIPOINT ((10 40), (40 30), (20 20), (30 10))
&tree.DGeography{Geography: geo.MustParseGeography("010400000004000000010100000000000000000024400000000000004440010100000000000000000044400000000000003E4001010000000000000000003440000000000000344001010000000000000000003E400000000000002440")},
// MULTILINESTRING ((10 10, 20 20, 10 40), (40 40, 30 30, 40 20, 30 10))
&tree.DGeography{Geography: geo.MustParseGeography("010500000002000000010200000003000000000000000000244000000000000024400000000000003440000000000000344000000000000024400000000000004440010200000004000000000000000000444000000000000044400000000000003E400000000000003E40000000000000444000000000000034400000000000003E400000000000002440")},
// MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)),((20 35, 10 30, 10 10, 30 5, 45 20, 20 35),(30 20, 20 15, 20 25, 30 20)))
&tree.DGeography{Geography: geo.MustParseGeography("01060000000200000001030000000100000004000000000000000000444000000000000044400000000000003440000000000080464000000000008046400000000000003E4000000000000044400000000000004440010300000002000000060000000000000000003440000000000080414000000000000024400000000000003E40000000000000244000000000000024400000000000003E4000000000000014400000000000804640000000000000344000000000000034400000000000804140040000000000000000003E40000000000000344000000000000034400000000000002E40000000000000344000000000000039400000000000003E400000000000003440")},
// GEOMETRYCOLLECTION (POINT (40 10),LINESTRING (10 10, 20 20, 10 40),POLYGON ((40 40, 20 45, 45 30, 40 40)))
&tree.DGeography{Geography: geo.MustParseGeography("01070000000300000001010000000000000000004440000000000000244001020000000300000000000000000024400000000000002440000000000000344000000000000034400000000000002440000000000000444001030000000100000004000000000000000000444000000000000044400000000000003440000000000080464000000000008046400000000000003E4000000000000044400000000000004440")},
// POINT EMPTY
&tree.DGeography{Geography: geo.MustParseGeography("0101000000000000000000F87F000000000000F87F")},
// LINESTRING EMPTY
&tree.DGeography{Geography: geo.MustParseGeography("010200000000000000")},
// POLYGON EMPTY
&tree.DGeography{Geography: geo.MustParseGeography("010300000000000000")},
// MULTIPOINT EMPTY
&tree.DGeography{Geography: geo.MustParseGeography("010400000000000000")},
// MULTILINESTRING EMPTY
&tree.DGeography{Geography: geo.MustParseGeography("010500000000000000")},
// MULTIPOLYGON EMPTY
&tree.DGeography{Geography: geo.MustParseGeography("010600000000000000")},
// GEOMETRYCOLLECTION EMPTY
&tree.DGeography{Geography: geo.MustParseGeography("010700000000000000")},
},
types.GeometryFamily: {
// NOTE(otan): we cannot use WKT here because roachtests do not have geos uploaded.
// If we parse WKT ourselves or upload GEOS on every roachtest, we may be able to avoid this.
// POINT(1.0 1.0)
&tree.DGeometry{Geometry: geo.MustParseGeometry("0101000000000000000000F03F000000000000F03F")},
// LINESTRING(1.0 1.0, 2.0 2.0)
&tree.DGeometry{Geometry: geo.MustParseGeometry("010200000002000000000000000000F03F000000000000F03F00000000000000400000000000000040")},
// POLYGON((0.0 0.0, 1.0 0.0, 1.0 1.0, 0.0 1.0, 0.0 0.0))
&tree.DGeometry{Geometry: geo.MustParseGeometry("0103000000010000000500000000000000000000000000000000000000000000000000F03F0000000000000000000000000000F03F000000000000F03F0000000000000000000000000000F03F00000000000000000000000000000000")},
// POLYGON((0.0 0.0, 1.0 0.0, 1.0 1.0, 0.0 1.0, 0.0 0.0), (0.2 0.2, 0.2 0.4, 0.4 0.4, 0.4 0.2, 0.2 0.2))
&tree.DGeometry{Geometry: geo.MustParseGeometry("0103000000020000000500000000000000000000000000000000000000000000000000F03F0000000000000000000000000000F03F000000000000F03F0000000000000000000000000000F03F00000000000000000000000000000000050000009A9999999999C93F9A9999999999C93F9A9999999999C93F9A9999999999D93F9A9999999999D93F9A9999999999D93F9A9999999999D93F9A9999999999C93F9A9999999999C93F9A9999999999C93F")},
// MULTIPOINT ((10 40), (40 30), (20 20), (30 10))
&tree.DGeometry{Geometry: geo.MustParseGeometry("010400000004000000010100000000000000000024400000000000004440010100000000000000000044400000000000003E4001010000000000000000003440000000000000344001010000000000000000003E400000000000002440")},
// MULTILINESTRING ((10 10, 20 20, 10 40), (40 40, 30 30, 40 20, 30 10))
&tree.DGeometry{Geometry: geo.MustParseGeometry("010500000002000000010200000003000000000000000000244000000000000024400000000000003440000000000000344000000000000024400000000000004440010200000004000000000000000000444000000000000044400000000000003E400000000000003E40000000000000444000000000000034400000000000003E400000000000002440")},
// MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)),((20 35, 10 30, 10 10, 30 5, 45 20, 20 35),(30 20, 20 15, 20 25, 30 20)))
&tree.DGeometry{Geometry: geo.MustParseGeometry("01060000000200000001030000000100000004000000000000000000444000000000000044400000000000003440000000000080464000000000008046400000000000003E4000000000000044400000000000004440010300000002000000060000000000000000003440000000000080414000000000000024400000000000003E40000000000000244000000000000024400000000000003E4000000000000014400000000000804640000000000000344000000000000034400000000000804140040000000000000000003E40000000000000344000000000000034400000000000002E40000000000000344000000000000039400000000000003E400000000000003440")},
// GEOMETRYCOLLECTION (POINT (40 10),LINESTRING (10 10, 20 20, 10 40),POLYGON ((40 40, 20 45, 45 30, 40 40)))
&tree.DGeometry{Geometry: geo.MustParseGeometry("01070000000300000001010000000000000000004440000000000000244001020000000300000000000000000024400000000000002440000000000000344000000000000034400000000000002440000000000000444001030000000100000004000000000000000000444000000000000044400000000000003440000000000080464000000000008046400000000000003E4000000000000044400000000000004440")},
// POINT EMPTY
&tree.DGeometry{Geometry: geo.MustParseGeometry("0101000000000000000000F87F000000000000F87F")},
// LINESTRING EMPTY
&tree.DGeometry{Geometry: geo.MustParseGeometry("010200000000000000")},
// POLYGON EMPTY
&tree.DGeometry{Geometry: geo.MustParseGeometry("010300000000000000")},
// MULTIPOINT EMPTY
&tree.DGeometry{Geometry: geo.MustParseGeometry("010400000000000000")},
// MULTILINESTRING EMPTY
&tree.DGeometry{Geometry: geo.MustParseGeometry("010500000000000000")},
// MULTIPOLYGON EMPTY
&tree.DGeometry{Geometry: geo.MustParseGeometry("010600000000000000")},
// GEOMETRYCOLLECTION EMPTY
&tree.DGeometry{Geometry: geo.MustParseGeometry("010700000000000000")},
},
types.StringFamily: {
tree.NewDString(""),
tree.NewDString("X"),
tree.NewDString(`"`),
tree.NewDString(`'`),
tree.NewDString("\x00"),
tree.NewDString("\u2603"), // unicode snowman
},
types.BytesFamily: {
tree.NewDBytes(""),
tree.NewDBytes("X"),
tree.NewDBytes(`"`),
tree.NewDBytes(`'`),
tree.NewDBytes("\x00"),
tree.NewDBytes("\u2603"), // unicode snowman
tree.NewDBytes("\xFF"), // invalid utf-8 sequence, but a valid bytes
},
types.OidFamily: {
tree.NewDOid(0),
},
types.UuidFamily: {
tree.DMinUUID,
tree.DMaxUUID,
},
types.INetFamily: {
tree.DMinIPAddr,
tree.DMaxIPAddr,
},
types.JsonFamily: func() []tree.Datum {
var res []tree.Datum
for _, s := range []string{
`{}`,
`1`,
`{"test": "json"}`,
} {
d, err := tree.ParseDJSON(s)
if err != nil {
panic(err)
}
res = append(res, d)
}
return res
}(),
types.BitFamily: func() []tree.Datum {
var res []tree.Datum
for _, i := range []int64{
0,
1<<63 - 1,
} {
d, err := tree.NewDBitArrayFromInt(i, 64)
if err != nil {
panic(err)
}
res = append(res, d)
}
return res
}(),
}
randTimestampSpecials = []time.Time{
{},
time.Date(-2000, time.January, 1, 0, 0, 0, 0, time.UTC),
time.Date(3000, time.January, 1, 0, 0, 0, 0, time.UTC),
// NOTE(otan): we cannot support this as it does not work with colexec in tests.
tree.MinSupportedTime,
tree.MaxSupportedTime,
}
)
var (
// SeedTypes includes the following types that form the basis of randomly
// generated types:
// - All scalar types, except UNKNOWN and ANY
// - ARRAY of ANY, where the ANY will be replaced with one of the legal
// array element types in RandType
// - OIDVECTOR and INT2VECTOR types
SeedTypes []*types.T
// arrayContentsTypes contains all of the types that are valid to store within
// an array.
arrayContentsTypes []*types.T
collationLocales = [...]string{"da", "de", "en"}
)
func init() {
for _, typ := range types.OidToType {
switch typ.Oid() {
case oid.T_unknown, oid.T_anyelement:
// Don't include these.
case oid.T_anyarray, oid.T_oidvector, oid.T_int2vector:
// Include these.
SeedTypes = append(SeedTypes, typ)
default:
// Only include scalar types.
if typ.Family() != types.ArrayFamily {
SeedTypes = append(SeedTypes, typ)
}
}
}
for _, typ := range types.OidToType {
// Don't include un-encodable types.
encTyp, err := datumTypeToArrayElementEncodingType(typ)
if err != nil || encTyp == 0 {
continue
}
// Don't include reg types, since parser currently doesn't allow them to
// be declared as array element types.
if typ.Family() == types.OidFamily && typ.Oid() != oid.T_oid {
continue
}
arrayContentsTypes = append(arrayContentsTypes, typ)
}
// Sort these so randomly chosen indexes always point to the same element.
sort.Slice(SeedTypes, func(i, j int) bool {
return SeedTypes[i].String() < SeedTypes[j].String()
})
sort.Slice(arrayContentsTypes, func(i, j int) bool {
return arrayContentsTypes[i].String() < arrayContentsTypes[j].String()
})
}
// randInterestingDatum returns an interesting Datum of type typ.
// If there are no such Datums for a scalar type, it panics. Otherwise,
// it returns nil if there are no such Datums. Note that it pays attention
// to the width of the requested type for Int and Float type families.
func randInterestingDatum(rng *rand.Rand, typ *types.T) tree.Datum {
specials, ok := randInterestingDatums[typ.Family()]
if !ok || len(specials) == 0 {
for _, sc := range types.Scalar {
// Panic if a scalar type doesn't have an interesting datum.
if sc == typ {
panic(errors.AssertionFailedf("no interesting datum for type %s found", typ.String()))
}
}
return nil
}
special := specials[rng.Intn(len(specials))]
switch typ.Family() {
case types.IntFamily:
switch typ.Width() {
case 64:
return special
case 32:
return tree.NewDInt(tree.DInt(int32(tree.MustBeDInt(special))))
case 16:
return tree.NewDInt(tree.DInt(int16(tree.MustBeDInt(special))))
case 8:
return tree.NewDInt(tree.DInt(int8(tree.MustBeDInt(special))))
default:
panic(errors.AssertionFailedf("int with an unexpected width %d", typ.Width()))
}
case types.FloatFamily:
switch typ.Width() {
case 64:
return special
case 32:
return tree.NewDFloat(tree.DFloat(float32(*special.(*tree.DFloat))))
default:
panic(errors.AssertionFailedf("float with an unexpected width %d", typ.Width()))
}
case types.BitFamily:
// A width of 64 is used by all special BitFamily datums in randInterestingDatums.
// If the provided bit type, typ, has a width of 0 (representing an arbitrary width) or 64 exactly,
// then the special datum will be valid for the provided type. Otherwise, the special type
// must be resized to match the width of the provided type.
if typ.Width() == 0 || typ.Width() == 64 {
return special
}
return &tree.DBitArray{BitArray: special.(*tree.DBitArray).ToWidth(uint(typ.Width()))}
default:
return special
}
}
// RandCollationLocale returns a random element of collationLocales.
func RandCollationLocale(rng *rand.Rand) *string {
return &collationLocales[rng.Intn(len(collationLocales))]
}
// RandType returns a random type value.
func RandType(rng *rand.Rand) *types.T {
return RandTypeFromSlice(rng, SeedTypes)
}
// RandArrayContentsType returns a random type that's guaranteed to be valid to
// use as the contents of an array.
func RandArrayContentsType(rng *rand.Rand) *types.T {
return RandTypeFromSlice(rng, arrayContentsTypes)
}
// RandTypeFromSlice returns a random type from the input slice of types.
func RandTypeFromSlice(rng *rand.Rand, typs []*types.T) *types.T {
typ := typs[rng.Intn(len(typs))]
switch typ.Family() {
case types.BitFamily:
return types.MakeBit(int32(rng.Intn(50)))
case types.CollatedStringFamily:
return types.MakeCollatedString(types.String, *RandCollationLocale(rng))
case types.ArrayFamily:
if typ.ArrayContents().Family() == types.AnyFamily {
inner := RandArrayContentsType(rng)
if inner.Family() == types.CollatedStringFamily {
// TODO(justin): change this when collated arrays are supported.
inner = types.String
}
return types.MakeArray(inner)
}
case types.TupleFamily:
// Generate tuples between 0 and 4 datums in length
len := rng.Intn(5)
contents := make([]*types.T, len)
for i := range contents {
contents[i] = RandType(rng)
}
return types.MakeTuple(contents)
}
return typ
}
// RandColumnType returns a random type that is a legal column type (e.g. no
// nested arrays or tuples).
func RandColumnType(rng *rand.Rand) *types.T {
for {
typ := RandType(rng)
if err := colinfo.ValidateColumnDefType(typ); err == nil {
return typ
}
}
}
// RandArrayType generates a random array type.
func RandArrayType(rng *rand.Rand) *types.T {
for {
typ := RandColumnType(rng)
resTyp := types.MakeArray(typ)
if err := colinfo.ValidateColumnDefType(resTyp); err == nil {
return resTyp
}
}
}
// RandColumnTypes returns a slice of numCols random types. These types must be
// legal table column types.
func RandColumnTypes(rng *rand.Rand, numCols int) []*types.T {
types := make([]*types.T, numCols)
for i := range types {
types[i] = RandColumnType(rng)
}
return types
}
// RandSortingType returns a column type which can be key-encoded.
func RandSortingType(rng *rand.Rand) *types.T {
typ := RandType(rng)
for colinfo.MustBeValueEncoded(typ) {
typ = RandType(rng)
}
return typ
}
// RandSortingTypes returns a slice of numCols random ColumnType values
// which are key-encodable.
func RandSortingTypes(rng *rand.Rand, numCols int) []*types.T {
types := make([]*types.T, numCols)
for i := range types {
types[i] = RandSortingType(rng)
}
return types
}
// RandDatumEncoding returns a random DatumEncoding value.
func RandDatumEncoding(rng *rand.Rand) descpb.DatumEncoding {
return descpb.DatumEncoding(rng.Intn(len(descpb.DatumEncoding_value)))
}
// RandEncodableType wraps RandType in order to workaround #36736, which fails
// when name[] (or other type using DTypeWrapper) is encoded.
//
// TODO(andyk): Remove this workaround once #36736 is resolved. Also, RandDatum
// really should be extended to create DTypeWrapper datums with alternate OIDs
// like oid.T_varchar for better testing.
func RandEncodableType(rng *rand.Rand) *types.T {
var isEncodableType func(t *types.T) bool
isEncodableType = func(t *types.T) bool {
switch t.Family() {
case types.ArrayFamily:
// Due to #36736, any type returned by RandType that gets turned into
// a DTypeWrapper random datum will not work. Currently, that's just
// types.Name.
if t.ArrayContents().Oid() == oid.T_name {
return false
}
return isEncodableType(t.ArrayContents())
case types.TupleFamily:
for i := range t.TupleContents() {
if !isEncodableType(t.TupleContents()[i]) {
return false
}
}
}
return true
}
for {
typ := RandType(rng)
if isEncodableType(typ) {
return typ
}
}
}
// RandEncodableColumnTypes works around #36736, which fails when name[] (or
// other type using DTypeWrapper) is encoded.
//
// TODO(andyk): Remove this workaround once #36736 is resolved. Replace calls to
// it with calls to RandColumnTypes.
func RandEncodableColumnTypes(rng *rand.Rand, numCols int) []*types.T {
types := make([]*types.T, numCols)
for i := range types {
for {
types[i] = RandEncodableType(rng)
if err := colinfo.ValidateColumnDefType(types[i]); err == nil {
break
}
}
}
return types
}
// RandEncDatum generates a random EncDatum (of a random type).
func RandEncDatum(rng *rand.Rand) (EncDatum, *types.T) {
typ := RandEncodableType(rng)
datum := RandDatum(rng, typ, true /* nullOk */)
return DatumToEncDatum(typ, datum), typ
}
// RandSortingEncDatumSlice generates a slice of random EncDatum values of the
// same random type which is key-encodable.
func RandSortingEncDatumSlice(rng *rand.Rand, numVals int) ([]EncDatum, *types.T) {
typ := RandSortingType(rng)
vals := make([]EncDatum, numVals)
for i := range vals {
vals[i] = DatumToEncDatum(typ, RandDatum(rng, typ, true))
}
return vals, typ
}
// RandSortingEncDatumSlices generates EncDatum slices, each slice with values of the same
// random type which is key-encodable.
func RandSortingEncDatumSlices(
rng *rand.Rand, numSets, numValsPerSet int,
) ([][]EncDatum, []*types.T) {
vals := make([][]EncDatum, numSets)
types := make([]*types.T, numSets)
for i := range vals {
val, typ := RandSortingEncDatumSlice(rng, numValsPerSet)
vals[i], types[i] = val, typ
}
return vals, types
}
// RandEncDatumRowOfTypes generates a slice of random EncDatum values for the
// corresponding type in types.
func RandEncDatumRowOfTypes(rng *rand.Rand, types []*types.T) EncDatumRow {
vals := make([]EncDatum, len(types))
for i := range types {
vals[i] = DatumToEncDatum(types[i], RandDatum(rng, types[i], true))
}
return vals
}
// RandEncDatumRows generates EncDatumRows where all rows follow the same random
// []ColumnType structure.
func RandEncDatumRows(rng *rand.Rand, numRows, numCols int) (EncDatumRows, []*types.T) {
types := RandEncodableColumnTypes(rng, numCols)
return RandEncDatumRowsOfTypes(rng, numRows, types), types
}
// RandEncDatumRowsOfTypes generates EncDatumRows, each row with values of the
// corresponding type in types.
func RandEncDatumRowsOfTypes(rng *rand.Rand, numRows int, types []*types.T) EncDatumRows {
vals := make(EncDatumRows, numRows)
for i := range vals {
vals[i] = RandEncDatumRowOfTypes(rng, types)
}
return vals
}
// TestingMakePrimaryIndexKey creates a key prefix that corresponds to
// a table row (in the primary index); it is intended for tests.
//
// It is exported because it is used by tests outside of this package.
//
// The value types must match the primary key columns (or a prefix of them);
// supported types are: - Datum
// - bool (converts to DBool)
// - int (converts to DInt)