-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
types.go
1851 lines (1705 loc) · 62.5 KB
/
types.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 2015 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 types
import (
"bytes"
"fmt"
"strings"
"github.com/cockroachdb/cockroach/pkg/sql/lex"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
)
// T is an instance of a SQL scalar, array, or tuple type. It describes the
// domain of possible values which a column can return, or to which an
// expression can evaluate. The type system does not differentiate between
// nullable and non-nullable types. It is up to the caller to store that
// information separately if it is needed. Here are some example types:
//
// INT4 - any 32-bit integer
// DECIMAL(10, 3) - any base-10 value with at most 10 digits, with
// up to 3 to right of decimal point
// FLOAT[] - array of 64-bit IEEE 754 floating-point values
// TUPLE[TIME, VARCHAR(20)] - any pair of values where first value is a time
// of day and the second value is a string having
// up to 20 characters
//
// Fundamentally, a type consists of the following attributes, each of which has
// a corresponding accessor method. Some of these attributes are only defined
// for a subset of types. See the method comments for more details.
//
// Family - equivalence group of the type (enumeration)
// Oid - Postgres Object ID that describes the type (enumeration)
// Precision - maximum accuracy of the type (numeric)
// Width - maximum size or scale of the type (numeric)
// Locale - location which governs sorting, formatting, etc. (string)
// ArrayContents - array element type (T)
// TupleContents - slice of types of each tuple field ([]T)
// TupleLabels - slice of labels of each tuple field ([]string)
//
// Some types are not currently allowed as the type of a column (e.g. nested
// arrays). Other usages of the types package may have similar restrictions.
// Each such caller is responsible for enforcing their own restrictions; it's
// not the concern of the types package.
//
// Implementation-wise, types.T wraps a protobuf-generated InternalType struct.
// The generated protobuf code defines the struct fields, marshals/unmarshals
// them, formats a string representation, etc. Meanwhile, the wrapper types.T
// struct overrides the Marshal/Unmarshal methods in order to map to/from older
// persisted InternalType representations. For example, older versions of
// InternalType (previously called ColumnType) used a VisibleType field to
// represent INT2, whereas newer versions use Width/Oid. Unmarshal upgrades from
// this old format to the new, and Marshal downgrades, thus preserving backwards
// compatibility.
//
// Simple (unary) scalars types
// ----------------------------
//
// | SQL type | Family | Oid | Precision | Width |
// |-------------------|----------------|---------------|-----------|-------|
// | NULL (unknown) | UNKNOWN | T_unknown | 0 | 0 |
// | BOOL | BOOL | T_bool | 0 | 0 |
// | DATE | DATE | T_date | 0 | 0 |
// | TIMESTAMP | TIMESTAMP | T_timestamp | 0 | 0 |
// | INTERVAL | INTERVAL | T_interval | 0 | 0 |
// | TIMESTAMPTZ | TIMESTAMPTZ | T_timestamptz | 0 | 0 |
// | OID | OID | T_oid | 0 | 0 |
// | UUID | UUID | T_uuid | 0 | 0 |
// | INET | INET | T_inet | 0 | 0 |
// | TIME | TIME | T_time | 0 | 0 |
// | JSON | JSONB | T_jsonb | 0 | 0 |
// | JSONB | JSONB | T_jsonb | 0 | 0 |
// | | | | | |
// | BYTES | BYTES | T_bytea | 0 | 0 |
// | | | | | |
// | STRING | STRING | T_text | 0 | 0 |
// | STRING(N) | STRING | T_text | 0 | N |
// | VARCHAR | STRING | T_varchar | 0 | 0 |
// | VARCHAR(N) | STRING | T_varchar | 0 | N |
// | CHAR | STRING | T_bpchar | 0 | 1 |
// | CHAR(N) | STRING | T_bpchar | 0 | N |
// | "char" | STRING | T_char | 0 | 0 |
// | NAME | STRING | T_name | 0 | 0 |
// | | | | | |
// | STRING COLLATE en | COLLATEDSTRING | T_text | 0 | 0 |
// | STRING(N) COL... | COLLATEDSTRING | T_text | 0 | N |
// | VARCHAR COL... | COLLATEDSTRING | T_varchar | 0 | N |
// | VARCHAR(N) COL... | COLLATEDSTRING | T_varchar | 0 | N |
// | CHAR COL... | COLLATEDSTRING | T_bpchar | 0 | 1 |
// | CHAR(N) COL... | COLLATEDSTRING | T_bpchar | 0 | N |
// | "char" COL... | COLLATEDSTRING | T_char | 0 | 0 |
// | | | | | |
// | DECIMAL | DECIMAL | T_decimal | 0 | 0 |
// | DECIMAL(N) | DECIMAL | T_decimal | N | 0 |
// | DECIMAL(N,M) | DECIMAL | T_decimal | N | M |
// | | | | | |
// | FLOAT8 | FLOAT | T_float8 | 0 | 0 |
// | FLOAT4 | FLOAT | T_float4 | 0 | 0 |
// | | | | | |
// | BIT | BIT | T_bit | 0 | 1 |
// | BIT(N) | BIT | T_bit | 0 | N |
// | VARBIT | BIT | T_varbit | 0 | 0 |
// | VARBIT(N) | BIT | T_varbit | 0 | N |
// | | | | | |
// | INT,INTEGER | INT | T_int8 | 0 | 64 |
// | INT2,SMALLINT | INT | T_int2 | 0 | 16 |
// | INT4 | INT | T_int4 | 0 | 32 |
// | INT8,INT64,BIGINT | INT | T_int8 | 0 | 64 |
//
// Tuple types
// -----------
//
// These cannot (yet) be used in tables but are used in DistSQL flow
// processors for queries that have tuple-typed intermediate results.
//
// | Field | Description |
// |-----------------|---------------------------------------------------------|
// | Family | TupleFamily |
// | Oid | T_record |
// | TupleContents | Contains tuple field types (can be recursively defined) |
// | TupleLabels | Contains labels for each tuple field |
//
// Array types
// -----------
//
// | Field | Description |
// |-----------------|---------------------------------------------------------|
// | Family | ArrayFamily |
// | Oid | T__XXX (double underscores), where XXX is the Oid name |
// | | of a scalar type |
// | ArrayContents | Type of array elements (scalar, array, or tuple) |
//
// There are two special ARRAY types:
//
// | SQL type | Family | Oid | ArrayContents |
// |-------------------|----------------|---------------|---------------|
// | INT2VECTOR | ARRAY | T_int2vector | Int |
// | OIDVECTOR | ARRAY | T_oidvector | Oid |
//
// When these types are themselves made into arrays, the Oids become T__int2vector and
// T__oidvector, respectively.
//
type T struct {
// InternalType should never be directly referenced outside this package. The
// only reason it is exported is because gogoproto panics when printing the
// string representation of an unexported field. This is a problem when this
// struct is embedded in a larger struct (like a ColumnDescriptor).
InternalType InternalType
}
// Convenience list of pre-constructed types. Caller code can use any of these
// types, or use the MakeXXX methods to construct a custom type that is not
// listed here (e.g. if a custom width is needed).
var (
// Unknown is the type of an expression that statically evaluates to NULL.
// This type should never be returned for an expression that does not *always*
// evaluate to NULL.
Unknown = &T{InternalType: InternalType{
Family: UnknownFamily, Oid: oid.T_unknown, Locale: &emptyLocale}}
// Bool is the type of a boolean true/false value.
Bool = &T{InternalType: InternalType{
Family: BoolFamily, Oid: oid.T_bool, Locale: &emptyLocale}}
// VarBit is the type of an ordered list of bits (0 or 1 valued), with no
// specified limit on the count of bits.
VarBit = &T{InternalType: InternalType{
Family: BitFamily, Oid: oid.T_varbit, Locale: &emptyLocale}}
// Int is the type of a 64-bit signed integer. This is the canonical type
// for IntFamily.
Int = &T{InternalType: InternalType{
Family: IntFamily, Width: 64, Oid: oid.T_int8, Locale: &emptyLocale}}
// Int4 is the type of a 32-bit signed integer.
Int4 = &T{InternalType: InternalType{
Family: IntFamily, Width: 32, Oid: oid.T_int4, Locale: &emptyLocale}}
// Int2 is the type of a 16-bit signed integer.
Int2 = &T{InternalType: InternalType{
Family: IntFamily, Width: 16, Oid: oid.T_int2, Locale: &emptyLocale}}
// Float is the type of a 64-bit base-2 floating-point number (IEEE 754).
// This is the canonical type for FloatFamily.
Float = &T{InternalType: InternalType{
Family: FloatFamily, Width: 64, Oid: oid.T_float8, Locale: &emptyLocale}}
// Float4 is the type of a 32-bit base-2 floating-point number (IEEE 754).
Float4 = &T{InternalType: InternalType{
Family: FloatFamily, Width: 32, Oid: oid.T_float4, Locale: &emptyLocale}}
// Decimal is the type of a base-10 floating-point number, with no specified
// limit on precision (number of digits) or scale (digits to right of decimal
// point).
Decimal = &T{InternalType: InternalType{
Family: DecimalFamily, Oid: oid.T_numeric, Locale: &emptyLocale}}
// String is the type of a Unicode string, with no specified limit on the
// count of characters. This is the canonical type for StringFamily. It is
// reported as STRING in SHOW CREATE but "text" in introspection for
// compatibility with PostgreSQL.
String = &T{InternalType: InternalType{
Family: StringFamily, Oid: oid.T_text, Locale: &emptyLocale}}
// VarChar is equivalent to String, but has a differing OID (T_varchar),
// which makes it show up differently when displayed. It is reported as
// VARCHAR in SHOW CREATE and "character varying" in introspection for
// compatibility with PostgreSQL.
VarChar = &T{InternalType: InternalType{
Family: StringFamily, Oid: oid.T_varchar, Locale: &emptyLocale}}
// Name is a type-alias for String with a different OID (T_name). It is
// reported as NAME in SHOW CREATE and "name" in introspection for
// compatibility with PostgreSQL.
Name = &T{InternalType: InternalType{
Family: StringFamily, Oid: oid.T_name, Locale: &emptyLocale}}
// Bytes is the type of a list of raw byte values.
Bytes = &T{InternalType: InternalType{
Family: BytesFamily, Oid: oid.T_bytea, Locale: &emptyLocale}}
// Date is the type of a value specifying year, month, day (with no time
// component). There is no timezone associated with it. For example:
//
// YYYY-MM-DD
//
Date = &T{InternalType: InternalType{
Family: DateFamily, Oid: oid.T_date, Locale: &emptyLocale}}
// Time is the type of a value specifying hour, minute, second (with no date
// component). By default, it has microsecond precision. There is no timezone
// associated with it. For example:
//
// HH:MM:SS.ssssss
//
Time = &T{InternalType: InternalType{
Family: TimeFamily, Oid: oid.T_time, Locale: &emptyLocale}}
// Timestamp is the type of a value specifying year, month, day, hour, minute,
// and second, but with no associated timezone. By default, it has microsecond
// precision. For example:
//
// YYYY-MM-DD HH:MM:SS.ssssss
Timestamp = &T{InternalType: InternalType{
Family: TimestampFamily, Precision: -1, Oid: oid.T_timestamp, Locale: &emptyLocale}}
// TimestampTZ is the type of a value specifying year, month, day, hour,
// minute, and second, as well as an associated timezone. By default, it has
// microsecond precision. For example:
//
// YYYY-MM-DD HH:MM:SS.ssssss+-ZZ:ZZ
//
TimestampTZ = &T{InternalType: InternalType{
Family: TimestampTZFamily, Precision: -1, Oid: oid.T_timestamptz, Locale: &emptyLocale}}
// Interval is the type of a value describing a duration of time. By default,
// it has microsecond precision.
Interval = &T{InternalType: InternalType{
Family: IntervalFamily, Oid: oid.T_interval, Locale: &emptyLocale}}
// Jsonb is the type of a JavaScript Object Notation (JSON) value that is
// stored in a decomposed binary format (hence the "b" in jsonb).
Jsonb = &T{InternalType: InternalType{
Family: JsonFamily, Oid: oid.T_jsonb, Locale: &emptyLocale}}
// Uuid is the type of a universally unique identifier (UUID), which is a
// 128-bit quantity that is very unlikely to ever be generated again, and so
// can be relied on to be distinct from all other UUID values.
Uuid = &T{InternalType: InternalType{
Family: UuidFamily, Oid: oid.T_uuid, Locale: &emptyLocale}}
// INet is the type of an IPv4 or IPv6 network address. For example:
//
// 192.168.100.128/25
// FE80:CD00:0:CDE:1257:0:211E:729C
//
INet = &T{InternalType: InternalType{
Family: INetFamily, Oid: oid.T_inet, Locale: &emptyLocale}}
// Scalar contains all types that meet this criteria:
//
// 1. Scalar type (no ArrayFamily or TupleFamily types).
// 2. Non-ambiguous type (no UnknownFamily or AnyFamily types).
// 3. Canonical type for one of the type families.
//
Scalar = []*T{
Bool,
Int,
Float,
Decimal,
Date,
Timestamp,
Interval,
String,
Bytes,
TimestampTZ,
Oid,
Uuid,
INet,
Time,
Jsonb,
VarBit,
}
// Any is a special type used only during static analysis as a wildcard type
// that matches any other type, including scalar, array, and tuple types.
// Execution-time values should never have this type. As an example of its
// use, many SQL builtin functions allow an input value to be of any type,
// and so use this type in their static definitions.
Any = &T{InternalType: InternalType{
Family: AnyFamily, Oid: oid.T_anyelement, Locale: &emptyLocale}}
// AnyArray is a special type used only during static analysis as a wildcard
// type that matches an array having elements of any (uniform) type (including
// nested array types). Execution-time values should never have this type.
AnyArray = &T{InternalType: InternalType{
Family: ArrayFamily, ArrayContents: Any, Oid: oid.T_anyarray, Locale: &emptyLocale}}
// AnyTuple is a special type used only during static analysis as a wildcard
// type that matches a tuple with any number of fields of any type (including
// tuple types). Execution-time values should never have this type.
AnyTuple = &T{InternalType: InternalType{
Family: TupleFamily, TupleContents: []T{*Any}, Oid: oid.T_record, Locale: &emptyLocale}}
// AnyCollatedString is a special type used only during static analysis as a
// wildcard type that matches a collated string with any locale. Execution-
// time values should never have this type.
AnyCollatedString = &T{InternalType: InternalType{
Family: CollatedStringFamily, Oid: oid.T_text, Locale: &emptyLocale}}
// EmptyTuple is the tuple type with no fields. Note that this is different
// than AnyTuple, which is a wildcard type.
EmptyTuple = &T{InternalType: InternalType{
Family: TupleFamily, Oid: oid.T_record, Locale: &emptyLocale}}
// StringArray is the type of an array value having String-typed elements.
StringArray = &T{InternalType: InternalType{
Family: ArrayFamily, ArrayContents: String, Oid: oid.T__text, Locale: &emptyLocale}}
// IntArray is the type of an array value having Int-typed elements.
IntArray = &T{InternalType: InternalType{
Family: ArrayFamily, ArrayContents: Int, Oid: oid.T__int8, Locale: &emptyLocale}}
// DecimalArray is the type of an array value having Decimal-typed elements.
DecimalArray = &T{InternalType: InternalType{
Family: ArrayFamily, ArrayContents: Decimal, Oid: oid.T__numeric, Locale: &emptyLocale}}
// Int2Vector is a type-alias for an array of Int2 values with a different
// OID (T_int2vector instead of T__int2). It is a special VECTOR type used
// by Postgres in system tables.
Int2Vector = &T{InternalType: InternalType{
Family: ArrayFamily, Oid: oid.T_int2vector, ArrayContents: Int2, Locale: &emptyLocale}}
)
// Unexported wrapper types.
var (
// typeBit is the SQL BIT type. It is not exported to avoid confusion with
// the VarBit type, and confusion over whether its default Width is
// unspecified or is 1. More commonly used instead is the VarBit type.
typeBit = &T{InternalType: InternalType{
Family: BitFamily, Oid: oid.T_bit, Locale: &emptyLocale}}
// typeBpChar is the "standard SQL" string type of fixed length, where "bp"
// stands for "blank padded". It is not exported to avoid confusion with
// typeQChar, as well as confusion over its default width.
//
// It is reported as CHAR in SHOW CREATE and "character" in introspection for
// compatibility with PostgreSQL.
//
// Its default maximum with is 1. It always has a maximum width.
typeBpChar = &T{InternalType: InternalType{
Family: StringFamily, Oid: oid.T_bpchar, Locale: &emptyLocale}}
// typeQChar is a special PostgreSQL-only type supported for compatibility.
// It behaves like VARCHAR, its maximum width cannot be modified, and has a
// peculiar name in the syntax and introspection. It is not exported to avoid
// confusion with typeBpChar, as well as confusion over its default width.
//
// It is reported as "char" (with double quotes included) in SHOW CREATE and
// "char" in introspection for compatibility with PostgreSQL.
typeQChar = &T{InternalType: InternalType{
Family: StringFamily, Oid: oid.T_char, Locale: &emptyLocale}}
)
const (
// Deprecated after 19.1, since it's now represented using the Oid field.
name Family = 11
// Deprecated after 19.1, since it's now represented using the Oid field.
int2vector Family = 200
// Deprecated after 19.1, since it's now represented using the Oid field.
oidvector Family = 201
visibleNONE = 0
// Deprecated after 2.1, since it's no longer used.
visibleINTEGER = 1
// Deprecated after 2.1, since it's now represented using the Width field.
visibleSMALLINT = 2
// Deprecated after 2.1, since it's now represented using the Width field.
visibleBIGINT = 3
// Deprecated after 2.0, since the original BIT representation was buggy.
visibleBIT = 4
// Deprecated after 19.1, since it's now represented using the Width field.
visibleREAL = 5
// Deprecated after 2.1, since it's now represented using the Width field.
visibleDOUBLE = 6
// Deprecated after 19.1, since it's now represented using the Oid field.
visibleVARCHAR = 7
// Deprecated after 19.1, since it's now represented using the Oid field.
visibleCHAR = 8
// Deprecated after 19.1, since it's now represented using the Oid field.
visibleQCHAR = 9
// Deprecated after 19.1, since it's now represented using the Oid field.
visibleVARBIT = 10
// OID returned for the unknown[] array type. PG has no OID for this case.
unknownArrayOid = 0
)
var (
emptyLocale = ""
)
// MakeScalar constructs a new instance of a scalar type (i.e. not array or
// tuple types) using the provided fields.
func MakeScalar(family Family, o oid.Oid, precision, width int32, locale string) *T {
t := OidToType[o]
if family != t.Family() {
if family != CollatedStringFamily || StringFamily != t.Family() {
panic(errors.AssertionFailedf(
"oid %s does not match %s", oid.TypeName[o], family))
}
}
if family == ArrayFamily || family == TupleFamily {
panic(errors.AssertionFailedf("cannot make non-scalar type %s", family))
}
if family != CollatedStringFamily && locale != "" {
panic(errors.AssertionFailedf("non-collation type cannot have locale %s", locale))
}
if precision < 0 {
panic(errors.AssertionFailedf("negative precision is not allowed"))
}
switch family {
case DecimalFamily, TimeFamily, TimestampFamily, TimestampTZFamily:
default:
if precision != 0 {
panic(errors.AssertionFailedf("type %s cannot have precision", family))
}
}
if width < 0 {
panic(errors.AssertionFailedf("negative width is not allowed"))
}
switch family {
case IntFamily:
switch width {
case 16, 32, 64:
default:
panic(errors.AssertionFailedf("invalid width %d for IntFamily type", width))
}
case FloatFamily:
switch width {
case 32, 64:
default:
panic(errors.AssertionFailedf("invalid width %d for FloatFamily type", width))
}
case DecimalFamily:
if width > precision {
panic(errors.AssertionFailedf(
"decimal scale %d cannot be larger than precision %d", width, precision))
}
case StringFamily, BytesFamily, CollatedStringFamily, BitFamily:
// These types can have any width.
default:
if width != 0 {
panic(errors.AssertionFailedf("type %s cannot have width", family))
}
}
return &T{InternalType: InternalType{
Family: family,
Oid: o,
Precision: precision,
Width: width,
Locale: &locale,
}}
}
// MakeBit constructs a new instance of the BIT type (oid = T_bit) having the
// given max # bits (0 = unspecified number).
func MakeBit(width int32) *T {
if width == 0 {
return typeBit
}
if width < 0 {
panic(errors.AssertionFailedf("width %d cannot be negative", width))
}
return &T{InternalType: InternalType{
Family: BitFamily, Oid: oid.T_bit, Width: width, Locale: &emptyLocale}}
}
// MakeVarBit constructs a new instance of the BIT type (oid = T_varbit) having
// the given max # bits (0 = unspecified number).
func MakeVarBit(width int32) *T {
if width == 0 {
return VarBit
}
if width < 0 {
panic(errors.AssertionFailedf("width %d cannot be negative", width))
}
return &T{InternalType: InternalType{
Family: BitFamily, Width: width, Oid: oid.T_varbit, Locale: &emptyLocale}}
}
// MakeString constructs a new instance of the STRING type (oid = T_text) having
// the given max # characters (0 = unspecified number).
func MakeString(width int32) *T {
if width == 0 {
return String
}
if width < 0 {
panic(errors.AssertionFailedf("width %d cannot be negative", width))
}
return &T{InternalType: InternalType{
Family: StringFamily, Oid: oid.T_text, Width: width, Locale: &emptyLocale}}
}
// MakeVarChar constructs a new instance of the VARCHAR type (oid = T_varchar)
// having the given max # characters (0 = unspecified number).
func MakeVarChar(width int32) *T {
if width == 0 {
return VarChar
}
if width < 0 {
panic(errors.AssertionFailedf("width %d cannot be negative", width))
}
return &T{InternalType: InternalType{
Family: StringFamily, Oid: oid.T_varchar, Width: width, Locale: &emptyLocale}}
}
// MakeChar constructs a new instance of the CHAR type (oid = T_bpchar) having
// the given max # characters (0 = unspecified number).
func MakeChar(width int32) *T {
if width == 0 {
return typeBpChar
}
if width < 0 {
panic(errors.AssertionFailedf("width %d cannot be negative", width))
}
return &T{InternalType: InternalType{
Family: StringFamily, Oid: oid.T_bpchar, Width: width, Locale: &emptyLocale}}
}
// MakeQChar constructs a new instance of the "char" type (oid = T_char) having
// the given max # characters (0 = unspecified number).
func MakeQChar(width int32) *T {
if width == 0 {
return typeQChar
}
return &T{InternalType: InternalType{
Family: StringFamily, Oid: oid.T_char, Width: width, Locale: &emptyLocale}}
}
// MakeCollatedString constructs a new instance of a CollatedStringFamily type
// that is collated according to the given locale. The new type is based upon
// the given string type, having the same oid and width values. For example:
//
// STRING => STRING COLLATE EN
// VARCHAR(20) => VARCHAR(20) COLLATE EN
//
func MakeCollatedString(strType *T, locale string) *T {
switch strType.Oid() {
case oid.T_text, oid.T_varchar, oid.T_bpchar, oid.T_char:
return &T{InternalType: InternalType{
Family: CollatedStringFamily, Oid: strType.Oid(), Width: strType.Width(), Locale: &locale}}
}
panic(errors.AssertionFailedf("cannot apply collation to non-string type: %s", strType))
}
// MakeDecimal constructs a new instance of a DECIMAL type (oid = T_numeric)
// that has at most "precision" # of decimal digits (0 = unspecified number of
// digits) and at most "scale" # of decimal digits after the decimal point
// (0 = unspecified number of digits). scale must be <= precision.
func MakeDecimal(precision, scale int32) *T {
if precision == 0 && scale == 0 {
return Decimal
}
if precision < 0 {
panic(errors.AssertionFailedf("precision %d cannot be negative", precision))
}
if scale < 0 {
panic(errors.AssertionFailedf("scale %d cannot be negative", scale))
}
if scale > precision {
panic(errors.AssertionFailedf(
"scale %d cannot be larger than precision %d", scale, precision))
}
return &T{InternalType: InternalType{
Family: DecimalFamily,
Oid: oid.T_numeric,
Precision: precision,
Width: scale,
Locale: &emptyLocale,
}}
}
// MakeTime constructs a new instance of a TIME type (oid = T_time) that has at
// most the given number of fractional second digits.
func MakeTime(precision int32) *T {
if precision == 0 {
return Time
}
if precision != 6 {
panic(errors.AssertionFailedf("precision %d is not currently supported", precision))
}
return &T{InternalType: InternalType{
Family: TimeFamily, Oid: oid.T_time, Precision: precision, Locale: &emptyLocale}}
}
// MakeTimestamp constructs a new instance of a TIMESTAMP type that has at most
// the given number of fractional second digits.
func MakeTimestamp(precision int32) *T {
if precision == 0 || precision == 6 {
return &T{InternalType: InternalType{
Family: TimestampFamily, Oid: oid.T_timestamp, Precision: precision, Locale: &emptyLocale}}
}
panic(errors.AssertionFailedf("precision %d is not currently supported", precision))
}
// MakeTimestampTZ constructs a new instance of a TIMESTAMPTZ type that has at
// most the given number of fractional second digits.
func MakeTimestampTZ(precision int32) *T {
if precision == 0 || precision == 6 {
return &T{InternalType: InternalType{
Family: TimestampTZFamily, Oid: oid.T_timestamptz, Precision: precision, Locale: &emptyLocale}}
}
panic(errors.AssertionFailedf("precision %d is not currently supported", precision))
}
// MakeArray constructs a new instance of an ArrayFamily type with the given
// element type (which may itself be an ArrayFamily type).
func MakeArray(typ *T) *T {
return &T{InternalType: InternalType{
Family: ArrayFamily,
Oid: calcArrayOid(typ),
ArrayContents: typ,
Locale: &emptyLocale,
}}
}
// MakeTuple constructs a new instance of a TupleFamily type with the given
// field types (some/all of which may be other TupleFamily types).
//
// Warning: the contents slice is used directly; the caller should not modify it
// after calling this function.
func MakeTuple(contents []T) *T {
return &T{InternalType: InternalType{
Family: TupleFamily, Oid: oid.T_record, TupleContents: contents, Locale: &emptyLocale,
}}
}
// MakeLabeledTuple constructs a new instance of a TupleFamily type with the
// given field types and labels.
func MakeLabeledTuple(contents []T, labels []string) *T {
if len(contents) != len(labels) && labels != nil {
panic(errors.AssertionFailedf(
"tuple contents and labels must be of same length: %v, %v", contents, labels))
}
return &T{InternalType: InternalType{
Family: TupleFamily,
Oid: oid.T_record,
TupleContents: contents,
TupleLabels: labels,
Locale: &emptyLocale,
}}
}
// Family specifies a group of types that are compatible with one another. Types
// in the same family can be compared, assigned, etc., but may differ from one
// another in width, precision, locale, and other attributes. For example, it is
// always an error to insert an INT value into a FLOAT column, because they are
// not in the same family. However, values of different types within the same
// family are "insert-compatible" with one another. Insertion may still result
// in an error because of width overflow or other constraints, but it can at
// least be attempted.
//
// Families are convenient for performing type switches on types, because in
// most cases it is the type family that matters, not the specific type. For
// example, when CRDB encodes values, it maintains routines for each family,
// since types in the same family encode in very similar ways.
//
// Most type families have an associated "canonical type" that is the default
// representative of that family, and which is a superset of all other types in
// that family. Values with other types (in the same family) can always be
// trivially converted to the canonical type with no loss of information. For
// example, the canonical type for IntFamily is Int, which is a 64-bit integer.
// Both 32-bit and 16-bit integers can be trivially converted to it.
//
// Execution operators and functions are permissive in terms of input (allow any
// type within a given family), and typically return only values having
// canonical types as output. For example, the IntFamily Plus operator allows
// values having any IntFamily type as input. But then it will always convert
// those values to 64-bit integers, and return a final 64-bit integer value
// (types.Int). Doing this vastly reduces the required number of operator
// overloads.
func (t *T) Family() Family {
return t.InternalType.Family
}
// Oid returns the type's Postgres Object ID. The OID identifies the type more
// specifically than the type family, and is used by the Postgres wire protocol
// various Postgres catalog tables, functions like pg_typeof, etc. Maintaining
// the OID is required for Postgres-compatibility.
func (t *T) Oid() oid.Oid {
return t.InternalType.Oid
}
// Locale identifies a specific geographical, political, or cultural region that
// impacts various character-based operations such as sorting, pattern matching,
// and builtin functions like lower and upper. It is only defined for the
// types in the CollatedStringFamily, and is the empty string for all other
// types.
func (t *T) Locale() string {
return *t.InternalType.Locale
}
// Width is the size or scale of the type, such as number of bits or characters.
//
// INT : # of bits (64, 32, 16)
// FLOAT : # of bits (64, 32)
// DECIMAL : max # of digits after decimal point (must be <= Precision)
// STRING : max # of characters
// COLLATEDSTRING: max # of characters
// BIT : max # of bits
//
// Width is always 0 for other types.
func (t *T) Width() int32 {
return t.InternalType.Width
}
// Precision is the accuracy of the data type.
//
// DECIMAL : max # digits (must be >= Width/Scale)
// TIME : max # fractional second digits
// TIMESTAMP : max # fractional second digits
// TIMESTAMPTZ: max # fractional second digits
//
// For TIMESTAMP and TIMESTAMP TZ, the precision field is -1 for a default precision value of 6.
// Precision is always 0 for other types.
func (t *T) Precision() int32 {
return t.InternalType.Precision
}
// Scale is an alias method for Width, used for clarity for types in
// DecimalFamily.
func (t *T) Scale() int32 {
return t.InternalType.Width
}
// ArrayContents returns the type of array elements. This is nil for types that
// are not in the ArrayFamily.
func (t *T) ArrayContents() *T {
return t.InternalType.ArrayContents
}
// TupleContents returns a slice containing the type of each tuple field. This
// is nil for non-TupleFamily types.
func (t *T) TupleContents() []T {
return t.InternalType.TupleContents
}
// TupleLabels returns a slice containing the labels of each tuple field. This
// is nil for types not in the TupleFamily, or if the tuple type does not
// specify labels.
func (t *T) TupleLabels() []string {
return t.InternalType.TupleLabels
}
// Name returns a single word description of the type that describes it
// succinctly, but without all the details, such as width, locale, etc. The name
// is sometimes the same as the name returned by SQLStandardName, but is more
// CRDB friendly.
//
// TODO(andyk): Should these be changed to be the same as SQLStandardName?
func (t *T) Name() string {
switch t.Family() {
case AnyFamily:
return "anyelement"
case ArrayFamily:
switch t.Oid() {
case oid.T_oidvector:
return "oidvector"
case oid.T_int2vector:
return "int2vector"
}
return t.ArrayContents().Name() + "[]"
case BitFamily:
if t.Oid() == oid.T_varbit {
return "varbit"
}
return "bit"
case BoolFamily:
return "bool"
case BytesFamily:
return "bytes"
case DateFamily:
return "date"
case DecimalFamily:
return "decimal"
case FloatFamily:
switch t.Width() {
case 64:
return "float"
case 32:
return "float4"
default:
panic(errors.AssertionFailedf("programming error: unknown float width: %d", t.Width()))
}
case INetFamily:
return "inet"
case IntFamily:
switch t.Width() {
case 64:
return "int"
case 32:
return "int4"
case 16:
return "int2"
default:
panic(errors.AssertionFailedf("programming error: unknown int width: %d", t.Width()))
}
case IntervalFamily:
return "interval"
case JsonFamily:
return "jsonb"
case OidFamily:
return t.SQLStandardName()
case StringFamily, CollatedStringFamily:
switch t.Oid() {
case oid.T_text:
return "string"
case oid.T_bpchar:
return "char"
case oid.T_char:
// Yes, that's the name. The ways of PostgreSQL are inscrutable.
return `"char"`
case oid.T_varchar:
return "varchar"
case oid.T_name:
return "name"
}
panic(errors.AssertionFailedf("unexpected OID: %d", t.Oid()))
case TimeFamily:
return "time"
case TimestampFamily:
return "timestamp"
case TimestampTZFamily:
return "timestamptz"
case TupleFamily:
// Tuple types are currently anonymous, with no name.
return ""
case UnknownFamily:
return "unknown"
case UuidFamily:
return "uuid"
default:
panic(errors.AssertionFailedf("unexpected Family: %s", t.Family()))
}
}
// PGName returns the Postgres name for the type. This is sometimes different
// than the native CRDB name for it (i.e. the Name function). It is used when
// compatibility with PG is important. Examples of differences:
//
// Name() PGName()
// --------------------------
// char bpchar
// "char" char
// bytes bytea
// int4[] _int4
//
func (t *T) PGName() string {
name, ok := oid.TypeName[t.Oid()]
if ok {
return strings.ToLower(name)
}
// Postgres does not have an UNKNOWN[] type. However, CRDB does, so
// manufacture a name for it.
if t.Family() != ArrayFamily || t.ArrayContents().Family() != UnknownFamily {
panic(errors.AssertionFailedf("unknown PG name for oid %d", t.Oid()))
}
return "_unknown"
}
// SQLStandardName returns the type's name as it is specified in the SQL
// standard (or by Postgres for any non-standard types). This can be looked up
// for any type in Postgres using a query similar to this:
//
// SELECT format_type(pg_typeof(1::int)::regtype, NULL)
//
func (t *T) SQLStandardName() string {
return t.SQLStandardNameWithTypmod(false, 0)
}
// SQLStandardNameWithTypmod is like SQLStandardName but it also accepts a
// typmod argument, and a boolean which indicates whether or not a typmod was
// even specified. The expected results of this function should be, in Postgres:
//
// SELECT format_type('thetype'::regype, typmod)
//
// Generally, what this does with a non-0 typmod is append the scale, precision
// or length of a datatype to the name of the datatype. For example, a
// varchar(20) would appear as character varying(20) when provided the typmod
// value for varchar(20), which happens to be 24.
//
// This function is full of special cases. See backend/utils/adt/format_type.c
// in Postgres.
func (t *T) SQLStandardNameWithTypmod(haveTypmod bool, typmod int) string {
var buf strings.Builder
switch t.Family() {
case AnyFamily:
return "anyelement"
case ArrayFamily:
switch t.Oid() {
case oid.T_oidvector:
return "oidvector"
case oid.T_int2vector:
return "int2vector"
}
return t.ArrayContents().SQLStandardName() + "[]"
case BitFamily:
if t.Oid() == oid.T_varbit {
buf.WriteString("bit varying")
} else {
buf.WriteString("bit")
}
if !haveTypmod || typmod <= 0 {
return buf.String()
}
buf.WriteString(fmt.Sprintf("(%d)", typmod))
return buf.String()
case BoolFamily:
return "boolean"
case BytesFamily:
return "bytea"
case DateFamily:
return "date"
case DecimalFamily:
if !haveTypmod || typmod <= 0 {
return "numeric"
}
// The typmod of a numeric has the precision in the upper bits and the
// scale in the lower bits of a 32-bit int, after subtracting 4 (the var
// header size). See numeric.c.
typmod -= 4
return fmt.Sprintf(
"numeric(%d,%d)",
(typmod>>16)&0xffff,
typmod&0xffff,
)
case FloatFamily:
switch t.Width() {
case 32:
return "real"
case 64:
return "double precision"
default:
panic(errors.AssertionFailedf("programming error: unknown float width: %d", t.Width()))
}
case INetFamily:
return "inet"
case IntFamily:
switch t.Width() {
case 16:
return "smallint"