forked from ruiaylin/pgparser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
2597 lines (2389 loc) · 86.4 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"
"regexp"
"strings"
"github.com/ruiaylin/pgparser/types/geo/geopb"
"github.com/ruiaylin/pgparser/lex"
"github.com/ruiaylin/pgparser/oidext"
"github.com/ruiaylin/pgparser/pgwire/pgcode"
"github.com/ruiaylin/pgparser/pgwire/pgerror"
"github.com/ruiaylin/pgparser/utils/errorutil/unimplemented"
"github.com/ruiaylin/pgparser/utils/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 |
// | TIMETZ | TIMETZ | T_timetz | 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.
//
// User defined types
// ------------------
//
// * Enums
// | Field | Description |
// |---------------|--------------------------------------------|
// | Family | EnumFamily |
// | Oid | A unique OID generated upon enum creation |
//
// See types.proto for the corresponding proto definition. Its automatic
// type declaration is suppressed in the proto so that it is possible to
// add additional fields to T without serializing them.
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
// Fields that are only populated when hydrating from a user defined
// type descriptor. It is assumed that a user defined type is only used
// once its metadata has been hydrated through the process of type resolution.
TypeMeta UserDefinedTypeMetadata
}
// UserDefinedTypeMetadata contains metadata needed for runtime
// operations on user defined types. The metadata must be read only.
type UserDefinedTypeMetadata struct {
// Name is the resolved name of this type.
Name *UserDefinedTypeName
// enumData is non-nil iff the metadata is for an ENUM type.
EnumData *EnumMetadata
}
// EnumMetadata is metadata about an ENUM needed for evaluation.
type EnumMetadata struct {
// PhysicalRepresentations is a slice of the byte array
// physical representations of enum members.
PhysicalRepresentations [][]byte
// LogicalRepresentations is a slice of the string logical
// representations of enum members.
LogicalRepresentations []string
// TODO (rohany): For small enums, having a map would be slower
// than just an array. Investigate at what point the tradeoff
// should occur, if at all.
}
func (e *EnumMetadata) debugString() string {
return fmt.Sprintf(
"PhysicalReps: %v; LogicalReps: %s",
e.PhysicalRepresentations,
e.LogicalRepresentations,
)
}
// UserDefinedTypeName is a struct representing a qualified user defined
// type name. We redefine a common struct from higher level packages. We
// do so because proto will panic if any members of a proto struct are
// private. Rather than expose private members of higher level packages,
// we define a separate type here to be safe.
type UserDefinedTypeName struct {
Catalog string
Schema string
Name string
}
// MakeUserDefinedTypeName creates a user defined type name.
func MakeUserDefinedTypeName(catalog, schema, name string) *UserDefinedTypeName {
return &UserDefinedTypeName{
Catalog: catalog,
Schema: schema,
Name: name,
}
}
// Basename returns the unqualified name.
func (u UserDefinedTypeName) Basename() string {
return u.Name
}
// FQName returns the fully qualified name.
func (u UserDefinedTypeName) FQName() string {
var sb strings.Builder
// Note that cross-database type references are disabled, so we only
// format the qualified name with the schema.
sb.WriteString(u.Schema)
sb.WriteString(".")
sb.WriteString(u.Name)
return sb.String()
}
// 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,
Precision: 0,
TimePrecisionIsSet: false,
Oid: oid.T_time,
Locale: &emptyLocale,
}}
// TimeTZ is the type specifying hour, minute, second and timezone with
// no date component. By default, it has microsecond precision.
// For example:
//
// HH:MM:SS.ssssss+-ZZ:ZZ
TimeTZ = &T{InternalType: InternalType{
Family: TimeTZFamily,
Precision: 0,
TimePrecisionIsSet: false,
Oid: oid.T_timetz,
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: 0,
TimePrecisionIsSet: false,
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: 0,
TimePrecisionIsSet: false,
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,
Precision: 0,
TimePrecisionIsSet: false,
Oid: oid.T_interval,
Locale: &emptyLocale,
IntervalDurationField: &IntervalDurationField{},
}}
// 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}}
// Geometry is the type of a geospatial Geometry object.
Geometry = &T{
InternalType: InternalType{
Family: GeometryFamily,
Oid: oidext.T_geometry,
Locale: &emptyLocale,
GeoMetadata: &GeoMetadata{},
},
}
// Geography is the type of a geospatial Geography object.
Geography = &T{
InternalType: InternalType{
Family: GeographyFamily,
Oid: oidext.T_geography,
Locale: &emptyLocale,
GeoMetadata: &GeoMetadata{},
},
}
// 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,
Geography,
Geometry,
String,
Bytes,
TimestampTZ,
Oid,
Uuid,
INet,
Time,
TimeTZ,
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}}
// AnyEnum is a special type only used during static analysis as a wildcard
// type that matches an possible enum value. Execution-time values should
// never have this type.
AnyEnum = &T{InternalType: InternalType{
Family: EnumFamily, Locale: &emptyLocale, Oid: oid.T_anyenum}}
// 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}}
// FloatArray is the type of an array value having Float-typed elements.
FloatArray = &T{InternalType: InternalType{
Family: ArrayFamily, ArrayContents: Float, Oid: oid.T__float8, 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. Int2vectors are 0-indexed, unlike normal arrays.
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
)
const (
// defaultTimePrecision is the default precision to return for time families
// if time is not set.
defaultTimePrecision = 6
)
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 %d does not match %s", 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))
}
timePrecisionIsSet := false
var intervalDurationField *IntervalDurationField
var geoMetadata *GeoMetadata
switch family {
case IntervalFamily:
intervalDurationField = &IntervalDurationField{}
if precision < 0 || precision > 6 {
panic(errors.AssertionFailedf("precision must be between 0 and 6 inclusive"))
}
timePrecisionIsSet = true
case TimestampFamily, TimestampTZFamily, TimeFamily, TimeTZFamily:
if precision < 0 || precision > 6 {
panic(errors.AssertionFailedf("precision must be between 0 and 6 inclusive"))
}
timePrecisionIsSet = true
case DecimalFamily:
if precision < 0 {
panic(errors.AssertionFailedf("negative precision is not allowed"))
}
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.
case GeometryFamily:
geoMetadata = &GeoMetadata{}
case GeographyFamily:
geoMetadata = &GeoMetadata{}
default:
if width != 0 {
panic(errors.AssertionFailedf("type %s cannot have width", family))
}
}
return &T{InternalType: InternalType{
Family: family,
Oid: o,
Precision: precision,
TimePrecisionIsSet: timePrecisionIsSet,
Width: width,
Locale: &locale,
IntervalDurationField: intervalDurationField,
GeoMetadata: geoMetadata,
}}
}
// 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, oid.T_name:
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.
//
// To use the default precision, use the `Time` variable.
func MakeTime(precision int32) *T {
return &T{InternalType: InternalType{
Family: TimeFamily,
Oid: oid.T_time,
Precision: precision,
TimePrecisionIsSet: true,
Locale: &emptyLocale,
}}
}
// MakeTimeTZ constructs a new instance of a TIMETZ type (oid = T_timetz) that
// has at most the given number of fractional second digits.
//
// To use the default precision, use the `TimeTZ` variable.
func MakeTimeTZ(precision int32) *T {
return &T{InternalType: InternalType{
Family: TimeTZFamily,
Oid: oid.T_timetz,
Precision: precision,
TimePrecisionIsSet: true,
Locale: &emptyLocale,
}}
}
// MakeGeometry constructs a new instance of a GEOMETRY type (oid = T_geometry)
// that has the given shape and SRID.
func MakeGeometry(shape geopb.ShapeType, srid geopb.SRID) *T {
// Negative values are promoted to 0.
if srid < 0 {
srid = 0
}
return &T{InternalType: InternalType{
Family: GeometryFamily,
Oid: oidext.T_geometry,
Locale: &emptyLocale,
GeoMetadata: &GeoMetadata{
ShapeType: shape,
SRID: srid,
},
}}
}
// MakeGeography constructs a new instance of a geography-related type.
func MakeGeography(shape geopb.ShapeType, srid geopb.SRID) *T {
// Negative values are promoted to 0.
if srid < 0 {
srid = 0
}
return &T{InternalType: InternalType{
Family: GeographyFamily,
Oid: oidext.T_geography,
Locale: &emptyLocale,
GeoMetadata: &GeoMetadata{
ShapeType: shape,
SRID: srid,
},
}}
}
// GeoMetadata returns the GeoMetadata of the type object if it exists.
// This should only exist on Geometry and Geography types.
func (t *T) GeoMetadata() (*GeoMetadata, error) {
if t.InternalType.GeoMetadata == nil {
return nil, errors.Newf("GeoMetadata does not exist on type")
}
return t.InternalType.GeoMetadata, nil
}
// GeoSRIDOrZero returns the geo SRID of the type object if it exists.
// This should only exist on a subset of Geometry and Geography types.
func (t *T) GeoSRIDOrZero() geopb.SRID {
if t.InternalType.GeoMetadata != nil {
return t.InternalType.GeoMetadata.SRID
}
return 0
}
var (
// DefaultIntervalTypeMetadata returns a duration field that is unset,
// using INTERVAL or INTERVAL ( iconst32 ) syntax instead of INTERVAL
// with a qualifier afterwards.
DefaultIntervalTypeMetadata = IntervalTypeMetadata{}
)
// IntervalTypeMetadata is metadata pertinent for intervals.
type IntervalTypeMetadata struct {
// DurationField represents the duration field definition.
DurationField IntervalDurationField
// Precision is the precision to use - note this matches InternalType rules.
Precision int32
// PrecisionIsSet indicates whether Precision is explicitly set.
PrecisionIsSet bool
}
// IsMinuteToSecond returns whether the IntervalDurationField represents
// the MINUTE TO SECOND interval qualifier.
func (m *IntervalDurationField) IsMinuteToSecond() bool {
return m.FromDurationType == IntervalDurationType_MINUTE &&
m.DurationType == IntervalDurationType_SECOND
}
// IsDayToHour returns whether the IntervalDurationField represents
// the DAY TO HOUR interval qualifier.
func (m *IntervalDurationField) IsDayToHour() bool {
return m.FromDurationType == IntervalDurationType_DAY &&
m.DurationType == IntervalDurationType_HOUR
}
// IntervalTypeMetadata returns the IntervalTypeMetadata for interval types.
func (t *T) IntervalTypeMetadata() (IntervalTypeMetadata, error) {
if t.Family() != IntervalFamily {
return IntervalTypeMetadata{}, errors.Newf("cannot call IntervalTypeMetadata on non-intervals")
}
return IntervalTypeMetadata{
DurationField: *t.InternalType.IntervalDurationField,
Precision: t.InternalType.Precision,
PrecisionIsSet: t.InternalType.TimePrecisionIsSet,
}, nil
}
// MakeInterval constructs a new instance of a
// INTERVAL type (oid = T_interval) with a duration field.
//
// To use the default precision and field, use the `Interval` variable.
func MakeInterval(itm IntervalTypeMetadata) *T {
switch itm.DurationField.DurationType {
case IntervalDurationType_SECOND, IntervalDurationType_UNSET:
default:
if itm.PrecisionIsSet {
panic(errors.Errorf("cannot set precision for duration type %s", itm.DurationField.DurationType))
}
}
if itm.Precision > 0 && !itm.PrecisionIsSet {
panic(errors.Errorf("precision must be set if Precision > 0"))
}
return &T{InternalType: InternalType{
Family: IntervalFamily,
Oid: oid.T_interval,
Locale: &emptyLocale,
Precision: itm.Precision,
TimePrecisionIsSet: itm.PrecisionIsSet,
IntervalDurationField: &itm.DurationField,
}}
}
// MakeTimestamp constructs a new instance of a TIMESTAMP type that has at most
// the given number of fractional second digits.
//
// To use the default precision, use the `Timestamp` variable.
func MakeTimestamp(precision int32) *T {
return &T{InternalType: InternalType{
Family: TimestampFamily,
Oid: oid.T_timestamp,
Precision: precision,
TimePrecisionIsSet: true,
Locale: &emptyLocale,
}}
}
// MakeTimestampTZ constructs a new instance of a TIMESTAMPTZ type that has at
// most the given number of fractional second digits.
//
// To use the default precision, use the `TimestampTZ` variable.
func MakeTimestampTZ(precision int32) *T {
return &T{InternalType: InternalType{
Family: TimestampTZFamily,
Oid: oid.T_timestamptz,
Precision: precision,
TimePrecisionIsSet: true,
Locale: &emptyLocale,
}}
}
// MakeEnum constructs a new instance of an EnumFamily type with the given
// stable type ID. Note that it does not hydrate cached fields on the type.
func MakeEnum(typeID, arrayTypeID uint32) *T {
return &T{InternalType: InternalType{
Family: EnumFamily,
Oid: StableTypeIDToOID(typeID),
Locale: &emptyLocale,
UDTMetadata: &PersistentUserDefinedTypeMetadata{
StableTypeID: typeID,