sqlparser/ast/
data_type.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#[cfg(not(feature = "std"))]
19use alloc::{boxed::Box, format, string::String, vec::Vec};
20use core::fmt;
21
22#[cfg(feature = "serde")]
23use serde::{Deserialize, Serialize};
24
25#[cfg(feature = "visitor")]
26use sqlparser_derive::{Visit, VisitMut};
27
28use crate::ast::{display_comma_separated, Expr, ObjectName, StructField, UnionField};
29
30use super::{value::escape_single_quote_string, ColumnDef};
31
32#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
33#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
34#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
35pub enum EnumMember {
36    Name(String),
37    /// ClickHouse allows to specify an integer value for each enum value.
38    ///
39    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/data-types/enum)
40    NamedValue(String, Expr),
41}
42
43/// SQL data types
44#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
45#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
46#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
47pub enum DataType {
48    /// Table type in [PostgreSQL], e.g. CREATE FUNCTION RETURNS TABLE(...).
49    ///
50    /// [PostgreSQL]: https://www.postgresql.org/docs/15/sql-createfunction.html
51    /// [MsSQL]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql?view=sql-server-ver16#c-create-a-multi-statement-table-valued-function
52    Table(Option<Vec<ColumnDef>>),
53    /// Table type with a name, e.g. CREATE FUNCTION RETURNS @result TABLE(...).
54    ///
55    /// [MsSQl]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql?view=sql-server-ver16#table
56    NamedTable {
57        /// Table name.
58        name: ObjectName,
59        /// Table columns.
60        columns: Vec<ColumnDef>,
61    },
62    /// Fixed-length character type, e.g. CHARACTER(10).
63    Character(Option<CharacterLength>),
64    /// Fixed-length char type, e.g. CHAR(10).
65    Char(Option<CharacterLength>),
66    /// Character varying type, e.g. CHARACTER VARYING(10).
67    CharacterVarying(Option<CharacterLength>),
68    /// Char varying type, e.g. CHAR VARYING(10).
69    CharVarying(Option<CharacterLength>),
70    /// Variable-length character type, e.g. VARCHAR(10).
71    Varchar(Option<CharacterLength>),
72    /// Variable-length character type, e.g. NVARCHAR(10).
73    Nvarchar(Option<CharacterLength>),
74    /// Uuid type.
75    Uuid,
76    /// Large character object with optional length,
77    /// e.g. CHARACTER LARGE OBJECT, CHARACTER LARGE OBJECT(1000), [SQL Standard].
78    ///
79    /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-large-object-type
80    CharacterLargeObject(Option<u64>),
81    /// Large character object with optional length,
82    /// e.g. CHAR LARGE OBJECT, CHAR LARGE OBJECT(1000), [SQL Standard].
83    ///
84    /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-large-object-type
85    CharLargeObject(Option<u64>),
86    /// Large character object with optional length,
87    /// e.g. CLOB, CLOB(1000), [SQL Standard].
88    ///
89    /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-large-object-type
90    /// [Oracle]: https://docs.oracle.com/javadb/10.10.1.2/ref/rrefclob.html
91    Clob(Option<u64>),
92    /// Fixed-length binary type with optional length,
93    /// see [SQL Standard], [MS SQL Server].
94    ///
95    /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#binary-string-type
96    /// [MS SQL Server]: https://learn.microsoft.com/pt-br/sql/t-sql/data-types/binary-and-varbinary-transact-sql?view=sql-server-ver16
97    Binary(Option<u64>),
98    /// Variable-length binary with optional length type,
99    /// see [SQL Standard], [MS SQL Server].
100    ///
101    /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#binary-string-type
102    /// [MS SQL Server]: https://learn.microsoft.com/pt-br/sql/t-sql/data-types/binary-and-varbinary-transact-sql?view=sql-server-ver16
103    Varbinary(Option<BinaryLength>),
104    /// Large binary object with optional length,
105    /// see [SQL Standard], [Oracle].
106    ///
107    /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#binary-large-object-string-type
108    /// [Oracle]: https://docs.oracle.com/javadb/10.8.3.0/ref/rrefblob.html
109    Blob(Option<u64>),
110    /// [MySQL] blob with up to 2**8 bytes.
111    ///
112    /// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/blob.html
113    TinyBlob,
114    /// [MySQL] blob with up to 2**24 bytes.
115    ///
116    /// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/blob.html
117    MediumBlob,
118    /// [MySQL] blob with up to 2**32 bytes.
119    ///
120    /// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/blob.html
121    LongBlob,
122    /// Variable-length binary data with optional length.
123    ///
124    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#bytes_type
125    Bytes(Option<u64>),
126    /// Numeric type with optional precision and scale, e.g. NUMERIC(10,2), [SQL Standard][1].
127    ///
128    /// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#exact-numeric-type
129    Numeric(ExactNumberInfo),
130    /// Decimal type with optional precision and scale, e.g. DECIMAL(10,2), [SQL Standard][1].
131    ///
132    /// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#exact-numeric-type
133    Decimal(ExactNumberInfo),
134    /// [MySQL] unsigned decimal with optional precision and scale, e.g. DECIMAL UNSIGNED or DECIMAL(10,2) UNSIGNED.
135    /// Note: Using UNSIGNED with DECIMAL is deprecated in recent versions of MySQL.
136    ///
137    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/numeric-type-syntax.html
138    DecimalUnsigned(ExactNumberInfo),
139    /// [BigNumeric] type used in BigQuery.
140    ///
141    /// [BigNumeric]: https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#bignumeric_literals
142    BigNumeric(ExactNumberInfo),
143    /// This is alias for `BigNumeric` type used in BigQuery.
144    ///
145    /// [BigDecimal]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#decimal_types
146    BigDecimal(ExactNumberInfo),
147    /// Dec type with optional precision and scale, e.g. DEC(10,2), [SQL Standard][1].
148    ///
149    /// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#exact-numeric-type
150    Dec(ExactNumberInfo),
151    /// [MySQL] unsigned decimal (DEC alias) with optional precision and scale, e.g. DEC UNSIGNED or DEC(10,2) UNSIGNED.
152    /// Note: Using UNSIGNED with DEC is deprecated in recent versions of MySQL.
153    ///
154    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/numeric-type-syntax.html
155    DecUnsigned(ExactNumberInfo),
156    /// Floating point with optional precision and scale, e.g. FLOAT, FLOAT(8), or FLOAT(8,2).
157    Float(ExactNumberInfo),
158    /// [MySQL] unsigned floating point with optional precision and scale, e.g.
159    /// FLOAT UNSIGNED, FLOAT(10) UNSIGNED or FLOAT(10,2) UNSIGNED.
160    /// Note: Using UNSIGNED with FLOAT is deprecated in recent versions of MySQL.
161    ///
162    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/numeric-type-syntax.html
163    FloatUnsigned(ExactNumberInfo),
164    /// Tiny integer with optional display width, e.g. TINYINT or TINYINT(3).
165    TinyInt(Option<u64>),
166    /// Unsigned tiny integer with optional display width,
167    /// e.g. TINYINT UNSIGNED or TINYINT(3) UNSIGNED.
168    TinyIntUnsigned(Option<u64>),
169    /// Unsigned tiny integer, e.g. UTINYINT
170    UTinyInt,
171    /// Int2 is an alias for SmallInt in [PostgreSQL].
172    /// Note: Int2 means 2 bytes in PostgreSQL (not 2 bits).
173    /// Int2 with optional display width, e.g. INT2 or INT2(5).
174    ///
175    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype.html
176    Int2(Option<u64>),
177    /// Unsigned Int2 with optional display width, e.g. INT2 UNSIGNED or INT2(5) UNSIGNED.
178    Int2Unsigned(Option<u64>),
179    /// Small integer with optional display width, e.g. SMALLINT or SMALLINT(5).
180    SmallInt(Option<u64>),
181    /// Unsigned small integer with optional display width,
182    /// e.g. SMALLINT UNSIGNED or SMALLINT(5) UNSIGNED.
183    SmallIntUnsigned(Option<u64>),
184    /// Unsigned small integer, e.g. USMALLINT.
185    USmallInt,
186    /// MySQL medium integer ([1]) with optional display width,
187    /// e.g. MEDIUMINT or MEDIUMINT(5).
188    ///
189    /// [1]: https://dev.mysql.com/doc/refman/8.0/en/integer-types.html
190    MediumInt(Option<u64>),
191    /// Unsigned medium integer ([1]) with optional display width,
192    /// e.g. MEDIUMINT UNSIGNED or MEDIUMINT(5) UNSIGNED.
193    ///
194    /// [1]: https://dev.mysql.com/doc/refman/8.0/en/integer-types.html
195    MediumIntUnsigned(Option<u64>),
196    /// Int with optional display width, e.g. INT or INT(11).
197    Int(Option<u64>),
198    /// Int4 is an alias for Integer in [PostgreSQL].
199    /// Note: Int4 means 4 bytes in PostgreSQL (not 4 bits).
200    /// Int4 with optional display width, e.g. Int4 or Int4(11).
201    ///
202    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype.html
203    Int4(Option<u64>),
204    /// Int8 is an alias for BigInt in [PostgreSQL] and Integer type in [ClickHouse].
205    /// Int8 with optional display width, e.g. INT8 or INT8(11).
206    /// Note: Int8 means 8 bytes in [PostgreSQL], but 8 bits in [ClickHouse].
207    ///
208    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype.html
209    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
210    Int8(Option<u64>),
211    /// Integer type in [ClickHouse].
212    /// Note: Int16 means 16 bits in [ClickHouse].
213    ///
214    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
215    Int16,
216    /// Integer type in [ClickHouse].
217    /// Note: Int32 means 32 bits in [ClickHouse].
218    ///
219    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
220    Int32,
221    /// Integer type in [BigQuery], [ClickHouse].
222    ///
223    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#integer_types
224    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
225    Int64,
226    /// Integer type in [ClickHouse].
227    /// Note: Int128 means 128 bits in [ClickHouse].
228    ///
229    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
230    Int128,
231    /// Integer type in [ClickHouse].
232    /// Note: Int256 means 256 bits in [ClickHouse].
233    ///
234    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
235    Int256,
236    /// Integer with optional display width, e.g. INTEGER or INTEGER(11).
237    Integer(Option<u64>),
238    /// Unsigned int with optional display width, e.g. INT UNSIGNED or INT(11) UNSIGNED.
239    IntUnsigned(Option<u64>),
240    /// Unsigned int4 with optional display width, e.g. INT4 UNSIGNED or INT4(11) UNSIGNED.
241    Int4Unsigned(Option<u64>),
242    /// Unsigned integer with optional display width, e.g. INTEGER UNSIGNED or INTEGER(11) UNSIGNED.
243    IntegerUnsigned(Option<u64>),
244    /// 128-bit integer type, e.g. HUGEINT.
245    HugeInt,
246    /// Unsigned 128-bit integer type, e.g. UHUGEINT.
247    UHugeInt,
248    /// Unsigned integer type in [ClickHouse].
249    /// Note: UInt8 means 8 bits in [ClickHouse].
250    ///
251    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
252    UInt8,
253    /// Unsigned integer type in [ClickHouse].
254    /// Note: UInt16 means 16 bits in [ClickHouse].
255    ///
256    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
257    UInt16,
258    /// Unsigned integer type in [ClickHouse].
259    /// Note: UInt32 means 32 bits in [ClickHouse].
260    ///
261    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
262    UInt32,
263    /// Unsigned integer type in [ClickHouse].
264    /// Note: UInt64 means 64 bits in [ClickHouse].
265    ///
266    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
267    UInt64,
268    /// Unsigned integer type in [ClickHouse].
269    /// Note: UInt128 means 128 bits in [ClickHouse].
270    ///
271    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
272    UInt128,
273    /// Unsigned integer type in [ClickHouse].
274    /// Note: UInt256 means 256 bits in [ClickHouse].
275    ///
276    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/int-uint
277    UInt256,
278    /// Big integer with optional display width, e.g. BIGINT or BIGINT(20).
279    BigInt(Option<u64>),
280    /// Unsigned big integer with optional display width, e.g. BIGINT UNSIGNED or BIGINT(20) UNSIGNED.
281    BigIntUnsigned(Option<u64>),
282    /// Unsigned big integer, e.g. UBIGINT.
283    UBigInt,
284    /// Unsigned Int8 with optional display width, e.g. INT8 UNSIGNED or INT8(11) UNSIGNED.
285    Int8Unsigned(Option<u64>),
286    /// Signed integer as used in [MySQL CAST] target types, without optional `INTEGER` suffix,
287    /// e.g. `SIGNED`
288    ///
289    /// [MySQL CAST]: https://dev.mysql.com/doc/refman/8.4/en/cast-functions.html
290    Signed,
291    /// Signed integer as used in [MySQL CAST] target types, with optional `INTEGER` suffix,
292    /// e.g. `SIGNED INTEGER`
293    ///
294    /// [MySQL CAST]: https://dev.mysql.com/doc/refman/8.4/en/cast-functions.html
295    SignedInteger,
296    /// Signed integer as used in [MySQL CAST] target types, without optional `INTEGER` suffix,
297    /// e.g. `SIGNED`
298    ///
299    /// [MySQL CAST]: https://dev.mysql.com/doc/refman/8.4/en/cast-functions.html
300    Unsigned,
301    /// Unsigned integer as used in [MySQL CAST] target types, with optional `INTEGER` suffix,
302    /// e.g. `UNSIGNED INTEGER`.
303    ///
304    /// [MySQL CAST]: https://dev.mysql.com/doc/refman/8.4/en/cast-functions.html
305    UnsignedInteger,
306    /// Float4 is an alias for Real in [PostgreSQL].
307    ///
308    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype.html
309    Float4,
310    /// Floating point in [ClickHouse].
311    ///
312    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/float
313    Float32,
314    /// Floating point in [BigQuery].
315    ///
316    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#floating_point_types
317    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/float
318    Float64,
319    /// Floating point, e.g. REAL.
320    Real,
321    /// [MySQL] unsigned real, e.g. REAL UNSIGNED.
322    /// Note: Using UNSIGNED with REAL is deprecated in recent versions of MySQL.
323    ///
324    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/numeric-type-syntax.html
325    RealUnsigned,
326    /// Float8 is an alias for Double in [PostgreSQL].
327    ///
328    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype.html
329    Float8,
330    /// Double
331    Double(ExactNumberInfo),
332    /// [MySQL] unsigned double precision with optional precision, e.g. DOUBLE UNSIGNED or DOUBLE(10,2) UNSIGNED.
333    /// Note: Using UNSIGNED with DOUBLE is deprecated in recent versions of MySQL.
334    ///
335    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/numeric-type-syntax.html
336    DoubleUnsigned(ExactNumberInfo),
337    /// Double Precision, see [SQL Standard], [PostgreSQL].
338    ///
339    /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#approximate-numeric-type
340    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype-numeric.html
341    DoublePrecision,
342    /// [MySQL] unsigned double precision, e.g. DOUBLE PRECISION UNSIGNED.
343    /// Note: Using UNSIGNED with DOUBLE PRECISION is deprecated in recent versions of MySQL.
344    ///
345    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/numeric-type-syntax.html
346    DoublePrecisionUnsigned,
347    /// Bool is an alias for Boolean, see [PostgreSQL].
348    ///
349    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype.html
350    Bool,
351    /// Boolean type.
352    Boolean,
353    /// Date type.
354    Date,
355    /// Date32 with the same range as Datetime64.
356    ///
357    /// [1]: https://clickhouse.com/docs/en/sql-reference/data-types/date32
358    Date32,
359    /// Time with optional time precision and time zone information, see [SQL Standard][1].
360    ///
361    /// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#datetime-type
362    Time(Option<u64>, TimezoneInfo),
363    /// Datetime with optional time precision, see [MySQL][1].
364    ///
365    /// [1]: https://dev.mysql.com/doc/refman/8.0/en/datetime.html
366    Datetime(Option<u64>),
367    /// Datetime with time precision and optional timezone, see [ClickHouse][1].
368    ///
369    /// [1]: https://clickhouse.com/docs/en/sql-reference/data-types/datetime64
370    Datetime64(u64, Option<String>),
371    /// Timestamp with optional time precision and time zone information, see [SQL Standard][1].
372    ///
373    /// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#datetime-type
374    Timestamp(Option<u64>, TimezoneInfo),
375    /// Databricks timestamp without time zone. See [1].
376    ///
377    /// [1]: https://docs.databricks.com/aws/en/sql/language-manual/data-types/timestamp-ntz-type
378    TimestampNtz(Option<u64>),
379    /// Interval type.
380    Interval {
381        /// [PostgreSQL] fields specification like `INTERVAL YEAR TO MONTH`.
382        ///
383        /// [PostgreSQL]: https://www.postgresql.org/docs/17/datatype-datetime.html
384        fields: Option<IntervalFields>,
385        /// [PostgreSQL] subsecond precision like `INTERVAL HOUR TO SECOND(3)`
386        ///
387        /// [PostgreSQL]: https://www.postgresql.org/docs/17/datatype-datetime.html
388        precision: Option<u64>,
389    },
390    /// JSON type.
391    JSON,
392    /// Binary JSON type.
393    JSONB,
394    /// Regclass used in [PostgreSQL] serial.
395    ///
396    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype.html
397    Regclass,
398    /// Text type.
399    Text,
400    /// [MySQL] text with up to 2**8 bytes.
401    ///
402    /// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/blob.html
403    TinyText,
404    /// [MySQL] text with up to 2**24 bytes.
405    ///
406    /// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/blob.html
407    MediumText,
408    /// [MySQL] text with up to 2**32 bytes.
409    ///
410    /// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/blob.html
411    LongText,
412    /// String with optional length.
413    String(Option<u64>),
414    /// A fixed-length string e.g [ClickHouse][1].
415    ///
416    /// [1]: https://clickhouse.com/docs/en/sql-reference/data-types/fixedstring
417    FixedString(u64),
418    /// Bytea type, see [PostgreSQL].
419    ///
420    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype-bit.html
421    Bytea,
422    /// Bit string, see [PostgreSQL], [MySQL], or [MSSQL].
423    ///
424    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype-bit.html
425    /// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/bit-type.html
426    /// [MSSQL]: https://learn.microsoft.com/en-us/sql/t-sql/data-types/bit-transact-sql?view=sql-server-ver16
427    Bit(Option<u64>),
428    /// `BIT VARYING(n)`: Variable-length bit string, see [PostgreSQL].
429    ///
430    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype-bit.html
431    BitVarying(Option<u64>),
432    /// `VARBIT(n)`: Variable-length bit string. [PostgreSQL] alias for `BIT VARYING`.
433    ///
434    /// [PostgreSQL]: https://www.postgresql.org/docs/current/datatype.html
435    VarBit(Option<u64>),
436    /// Custom types.
437    Custom(ObjectName, Vec<String>),
438    /// Arrays.
439    Array(ArrayElemTypeDef),
440    /// Map, see [ClickHouse].
441    ///
442    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/map
443    Map(Box<DataType>, Box<DataType>),
444    /// Tuple, see [ClickHouse].
445    ///
446    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/tuple
447    Tuple(Vec<StructField>),
448    /// Nested type, see [ClickHouse].
449    ///
450    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/nested-data-structures/nested
451    Nested(Vec<ColumnDef>),
452    /// Enum type.
453    Enum(Vec<EnumMember>, Option<u8>),
454    /// Set type.
455    Set(Vec<String>),
456    /// Struct type, see [Hive], [BigQuery].
457    ///
458    /// [Hive]: https://docs.cloudera.com/cdw-runtime/cloud/impala-sql-reference/topics/impala-struct.html
459    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#struct_type
460    Struct(Vec<StructField>, StructBracketKind),
461    /// Union type, see [DuckDB].
462    ///
463    /// [DuckDB]: https://duckdb.org/docs/sql/data_types/union.html
464    Union(Vec<UnionField>),
465    /// Nullable - special marker NULL represents in ClickHouse as a data type.
466    ///
467    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/nullable
468    Nullable(Box<DataType>),
469    /// LowCardinality - changes the internal representation of other data types to be dictionary-encoded.
470    ///
471    /// [ClickHouse]: https://clickhouse.com/docs/en/sql-reference/data-types/lowcardinality
472    LowCardinality(Box<DataType>),
473    /// No type specified - only used with
474    /// [`SQLiteDialect`](crate::dialect::SQLiteDialect), from statements such
475    /// as `CREATE TABLE t1 (a)`.
476    Unspecified,
477    /// Trigger data type, returned by functions associated with triggers, see [PostgreSQL].
478    ///
479    /// [PostgreSQL]: https://www.postgresql.org/docs/current/plpgsql-trigger.html
480    Trigger,
481    /// Any data type, used in BigQuery UDF definitions for templated parameters, see [BigQuery].
482    ///
483    /// [BigQuery]: https://cloud.google.com/bigquery/docs/user-defined-functions#templated-sql-udf-parameters
484    AnyType,
485    /// Geometric type, see [PostgreSQL].
486    ///
487    /// [PostgreSQL]: https://www.postgresql.org/docs/9.5/functions-geometry.html
488    GeometricType(GeometricTypeKind),
489    /// PostgreSQL text search vectors, see [PostgreSQL].
490    ///
491    /// [PostgreSQL]: https://www.postgresql.org/docs/17/datatype-textsearch.html
492    TsVector,
493    /// PostgreSQL text search query, see [PostgreSQL].
494    ///
495    /// [PostgreSQL]: https://www.postgresql.org/docs/17/datatype-textsearch.html
496    TsQuery,
497}
498
499impl fmt::Display for DataType {
500    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
501        match self {
502            DataType::Character(size) => format_character_string_type(f, "CHARACTER", size),
503            DataType::Char(size) => format_character_string_type(f, "CHAR", size),
504            DataType::CharacterVarying(size) => {
505                format_character_string_type(f, "CHARACTER VARYING", size)
506            }
507            DataType::CharVarying(size) => format_character_string_type(f, "CHAR VARYING", size),
508            DataType::Varchar(size) => format_character_string_type(f, "VARCHAR", size),
509            DataType::Nvarchar(size) => format_character_string_type(f, "NVARCHAR", size),
510            DataType::Uuid => write!(f, "UUID"),
511            DataType::CharacterLargeObject(size) => {
512                format_type_with_optional_length(f, "CHARACTER LARGE OBJECT", size, false)
513            }
514            DataType::CharLargeObject(size) => {
515                format_type_with_optional_length(f, "CHAR LARGE OBJECT", size, false)
516            }
517            DataType::Clob(size) => format_type_with_optional_length(f, "CLOB", size, false),
518            DataType::Binary(size) => format_type_with_optional_length(f, "BINARY", size, false),
519            DataType::Varbinary(size) => format_varbinary_type(f, "VARBINARY", size),
520            DataType::Blob(size) => format_type_with_optional_length(f, "BLOB", size, false),
521            DataType::TinyBlob => write!(f, "TINYBLOB"),
522            DataType::MediumBlob => write!(f, "MEDIUMBLOB"),
523            DataType::LongBlob => write!(f, "LONGBLOB"),
524            DataType::Bytes(size) => format_type_with_optional_length(f, "BYTES", size, false),
525            DataType::Numeric(info) => {
526                write!(f, "NUMERIC{info}")
527            }
528            DataType::Decimal(info) => {
529                write!(f, "DECIMAL{info}")
530            }
531            DataType::DecimalUnsigned(info) => {
532                write!(f, "DECIMAL{info} UNSIGNED")
533            }
534            DataType::Dec(info) => {
535                write!(f, "DEC{info}")
536            }
537            DataType::DecUnsigned(info) => {
538                write!(f, "DEC{info} UNSIGNED")
539            }
540            DataType::BigNumeric(info) => write!(f, "BIGNUMERIC{info}"),
541            DataType::BigDecimal(info) => write!(f, "BIGDECIMAL{info}"),
542            DataType::Float(info) => write!(f, "FLOAT{info}"),
543            DataType::FloatUnsigned(info) => write!(f, "FLOAT{info} UNSIGNED"),
544            DataType::TinyInt(zerofill) => {
545                format_type_with_optional_length(f, "TINYINT", zerofill, false)
546            }
547            DataType::TinyIntUnsigned(zerofill) => {
548                format_type_with_optional_length(f, "TINYINT", zerofill, true)
549            }
550            DataType::Int2(zerofill) => {
551                format_type_with_optional_length(f, "INT2", zerofill, false)
552            }
553            DataType::Int2Unsigned(zerofill) => {
554                format_type_with_optional_length(f, "INT2", zerofill, true)
555            }
556            DataType::SmallInt(zerofill) => {
557                format_type_with_optional_length(f, "SMALLINT", zerofill, false)
558            }
559            DataType::SmallIntUnsigned(zerofill) => {
560                format_type_with_optional_length(f, "SMALLINT", zerofill, true)
561            }
562            DataType::MediumInt(zerofill) => {
563                format_type_with_optional_length(f, "MEDIUMINT", zerofill, false)
564            }
565            DataType::MediumIntUnsigned(zerofill) => {
566                format_type_with_optional_length(f, "MEDIUMINT", zerofill, true)
567            }
568            DataType::Int(zerofill) => format_type_with_optional_length(f, "INT", zerofill, false),
569            DataType::IntUnsigned(zerofill) => {
570                format_type_with_optional_length(f, "INT", zerofill, true)
571            }
572            DataType::Int4(zerofill) => {
573                format_type_with_optional_length(f, "INT4", zerofill, false)
574            }
575            DataType::Int8(zerofill) => {
576                format_type_with_optional_length(f, "INT8", zerofill, false)
577            }
578            DataType::Int16 => {
579                write!(f, "Int16")
580            }
581            DataType::Int32 => {
582                write!(f, "Int32")
583            }
584            DataType::Int64 => {
585                write!(f, "INT64")
586            }
587            DataType::Int128 => {
588                write!(f, "Int128")
589            }
590            DataType::Int256 => {
591                write!(f, "Int256")
592            }
593            DataType::HugeInt => {
594                write!(f, "HUGEINT")
595            }
596            DataType::Int4Unsigned(zerofill) => {
597                format_type_with_optional_length(f, "INT4", zerofill, true)
598            }
599            DataType::Integer(zerofill) => {
600                format_type_with_optional_length(f, "INTEGER", zerofill, false)
601            }
602            DataType::IntegerUnsigned(zerofill) => {
603                format_type_with_optional_length(f, "INTEGER", zerofill, true)
604            }
605            DataType::BigInt(zerofill) => {
606                format_type_with_optional_length(f, "BIGINT", zerofill, false)
607            }
608            DataType::BigIntUnsigned(zerofill) => {
609                format_type_with_optional_length(f, "BIGINT", zerofill, true)
610            }
611            DataType::Int8Unsigned(zerofill) => {
612                format_type_with_optional_length(f, "INT8", zerofill, true)
613            }
614            DataType::UTinyInt => {
615                write!(f, "UTINYINT")
616            }
617            DataType::USmallInt => {
618                write!(f, "USMALLINT")
619            }
620            DataType::UBigInt => {
621                write!(f, "UBIGINT")
622            }
623            DataType::UHugeInt => {
624                write!(f, "UHUGEINT")
625            }
626            DataType::UInt8 => {
627                write!(f, "UInt8")
628            }
629            DataType::UInt16 => {
630                write!(f, "UInt16")
631            }
632            DataType::UInt32 => {
633                write!(f, "UInt32")
634            }
635            DataType::UInt64 => {
636                write!(f, "UInt64")
637            }
638            DataType::UInt128 => {
639                write!(f, "UInt128")
640            }
641            DataType::UInt256 => {
642                write!(f, "UInt256")
643            }
644            DataType::Signed => {
645                write!(f, "SIGNED")
646            }
647            DataType::SignedInteger => {
648                write!(f, "SIGNED INTEGER")
649            }
650            DataType::Unsigned => {
651                write!(f, "UNSIGNED")
652            }
653            DataType::UnsignedInteger => {
654                write!(f, "UNSIGNED INTEGER")
655            }
656            DataType::Real => write!(f, "REAL"),
657            DataType::RealUnsigned => write!(f, "REAL UNSIGNED"),
658            DataType::Float4 => write!(f, "FLOAT4"),
659            DataType::Float32 => write!(f, "Float32"),
660            DataType::Float64 => write!(f, "FLOAT64"),
661            DataType::Double(info) => write!(f, "DOUBLE{info}"),
662            DataType::DoubleUnsigned(info) => write!(f, "DOUBLE{info} UNSIGNED"),
663            DataType::Float8 => write!(f, "FLOAT8"),
664            DataType::DoublePrecision => write!(f, "DOUBLE PRECISION"),
665            DataType::DoublePrecisionUnsigned => write!(f, "DOUBLE PRECISION UNSIGNED"),
666            DataType::Bool => write!(f, "BOOL"),
667            DataType::Boolean => write!(f, "BOOLEAN"),
668            DataType::Date => write!(f, "DATE"),
669            DataType::Date32 => write!(f, "Date32"),
670            DataType::Time(precision, timezone_info) => {
671                format_datetime_precision_and_tz(f, "TIME", precision, timezone_info)
672            }
673            DataType::Datetime(precision) => {
674                format_type_with_optional_length(f, "DATETIME", precision, false)
675            }
676            DataType::Timestamp(precision, timezone_info) => {
677                format_datetime_precision_and_tz(f, "TIMESTAMP", precision, timezone_info)
678            }
679            DataType::TimestampNtz(precision) => {
680                format_type_with_optional_length(f, "TIMESTAMP_NTZ", precision, false)
681            }
682            DataType::Datetime64(precision, timezone) => {
683                format_clickhouse_datetime_precision_and_timezone(
684                    f,
685                    "DateTime64",
686                    precision,
687                    timezone,
688                )
689            }
690            DataType::Interval { fields, precision } => {
691                write!(f, "INTERVAL")?;
692                if let Some(fields) = fields {
693                    write!(f, " {fields}")?;
694                }
695                if let Some(precision) = precision {
696                    write!(f, "({precision})")?;
697                }
698                Ok(())
699            }
700            DataType::JSON => write!(f, "JSON"),
701            DataType::JSONB => write!(f, "JSONB"),
702            DataType::Regclass => write!(f, "REGCLASS"),
703            DataType::Text => write!(f, "TEXT"),
704            DataType::TinyText => write!(f, "TINYTEXT"),
705            DataType::MediumText => write!(f, "MEDIUMTEXT"),
706            DataType::LongText => write!(f, "LONGTEXT"),
707            DataType::String(size) => format_type_with_optional_length(f, "STRING", size, false),
708            DataType::Bytea => write!(f, "BYTEA"),
709            DataType::Bit(size) => format_type_with_optional_length(f, "BIT", size, false),
710            DataType::BitVarying(size) => {
711                format_type_with_optional_length(f, "BIT VARYING", size, false)
712            }
713            DataType::VarBit(size) => format_type_with_optional_length(f, "VARBIT", size, false),
714            DataType::Array(ty) => match ty {
715                ArrayElemTypeDef::None => write!(f, "ARRAY"),
716                ArrayElemTypeDef::SquareBracket(t, None) => write!(f, "{t}[]"),
717                ArrayElemTypeDef::SquareBracket(t, Some(size)) => write!(f, "{t}[{size}]"),
718                ArrayElemTypeDef::AngleBracket(t) => write!(f, "ARRAY<{t}>"),
719                ArrayElemTypeDef::Parenthesis(t) => write!(f, "Array({t})"),
720            },
721            DataType::Custom(ty, modifiers) => {
722                if modifiers.is_empty() {
723                    write!(f, "{ty}")
724                } else {
725                    write!(f, "{}({})", ty, modifiers.join(", "))
726                }
727            }
728            DataType::Enum(vals, bits) => {
729                match bits {
730                    Some(bits) => write!(f, "ENUM{bits}"),
731                    None => write!(f, "ENUM"),
732                }?;
733                write!(f, "(")?;
734                for (i, v) in vals.iter().enumerate() {
735                    if i != 0 {
736                        write!(f, ", ")?;
737                    }
738                    match v {
739                        EnumMember::Name(name) => {
740                            write!(f, "'{}'", escape_single_quote_string(name))?
741                        }
742                        EnumMember::NamedValue(name, value) => {
743                            write!(f, "'{}' = {}", escape_single_quote_string(name), value)?
744                        }
745                    }
746                }
747                write!(f, ")")
748            }
749            DataType::Set(vals) => {
750                write!(f, "SET(")?;
751                for (i, v) in vals.iter().enumerate() {
752                    if i != 0 {
753                        write!(f, ", ")?;
754                    }
755                    write!(f, "'{}'", escape_single_quote_string(v))?;
756                }
757                write!(f, ")")
758            }
759            DataType::Struct(fields, bracket) => {
760                if !fields.is_empty() {
761                    match bracket {
762                        StructBracketKind::Parentheses => {
763                            write!(f, "STRUCT({})", display_comma_separated(fields))
764                        }
765                        StructBracketKind::AngleBrackets => {
766                            write!(f, "STRUCT<{}>", display_comma_separated(fields))
767                        }
768                    }
769                } else {
770                    write!(f, "STRUCT")
771                }
772            }
773            DataType::Union(fields) => {
774                write!(f, "UNION({})", display_comma_separated(fields))
775            }
776            // ClickHouse
777            DataType::Nullable(data_type) => {
778                write!(f, "Nullable({data_type})")
779            }
780            DataType::FixedString(character_length) => {
781                write!(f, "FixedString({character_length})")
782            }
783            DataType::LowCardinality(data_type) => {
784                write!(f, "LowCardinality({data_type})")
785            }
786            DataType::Map(key_data_type, value_data_type) => {
787                write!(f, "Map({key_data_type}, {value_data_type})")
788            }
789            DataType::Tuple(fields) => {
790                write!(f, "Tuple({})", display_comma_separated(fields))
791            }
792            DataType::Nested(fields) => {
793                write!(f, "Nested({})", display_comma_separated(fields))
794            }
795            DataType::Unspecified => Ok(()),
796            DataType::Trigger => write!(f, "TRIGGER"),
797            DataType::AnyType => write!(f, "ANY TYPE"),
798            DataType::Table(fields) => match fields {
799                Some(fields) => {
800                    write!(f, "TABLE({})", display_comma_separated(fields))
801                }
802                None => {
803                    write!(f, "TABLE")
804                }
805            },
806            DataType::NamedTable { name, columns } => {
807                write!(f, "{} TABLE ({})", name, display_comma_separated(columns))
808            }
809            DataType::GeometricType(kind) => write!(f, "{kind}"),
810            DataType::TsVector => write!(f, "TSVECTOR"),
811            DataType::TsQuery => write!(f, "TSQUERY"),
812        }
813    }
814}
815
816fn format_type_with_optional_length(
817    f: &mut fmt::Formatter,
818    sql_type: &'static str,
819    len: &Option<u64>,
820    unsigned: bool,
821) -> fmt::Result {
822    write!(f, "{sql_type}")?;
823    if let Some(len) = len {
824        write!(f, "({len})")?;
825    }
826    if unsigned {
827        write!(f, " UNSIGNED")?;
828    }
829    Ok(())
830}
831
832fn format_character_string_type(
833    f: &mut fmt::Formatter,
834    sql_type: &str,
835    size: &Option<CharacterLength>,
836) -> fmt::Result {
837    write!(f, "{sql_type}")?;
838    if let Some(size) = size {
839        write!(f, "({size})")?;
840    }
841    Ok(())
842}
843
844fn format_varbinary_type(
845    f: &mut fmt::Formatter,
846    sql_type: &str,
847    size: &Option<BinaryLength>,
848) -> fmt::Result {
849    write!(f, "{sql_type}")?;
850    if let Some(size) = size {
851        write!(f, "({size})")?;
852    }
853    Ok(())
854}
855
856fn format_datetime_precision_and_tz(
857    f: &mut fmt::Formatter,
858    sql_type: &'static str,
859    len: &Option<u64>,
860    time_zone: &TimezoneInfo,
861) -> fmt::Result {
862    write!(f, "{sql_type}")?;
863    let len_fmt = len.as_ref().map(|l| format!("({l})")).unwrap_or_default();
864
865    match time_zone {
866        TimezoneInfo::Tz => {
867            write!(f, "{time_zone}{len_fmt}")?;
868        }
869        _ => {
870            write!(f, "{len_fmt}{time_zone}")?;
871        }
872    }
873
874    Ok(())
875}
876
877fn format_clickhouse_datetime_precision_and_timezone(
878    f: &mut fmt::Formatter,
879    sql_type: &'static str,
880    len: &u64,
881    time_zone: &Option<String>,
882) -> fmt::Result {
883    write!(f, "{sql_type}({len}")?;
884
885    if let Some(time_zone) = time_zone {
886        write!(f, ", '{time_zone}'")?;
887    }
888
889    write!(f, ")")?;
890
891    Ok(())
892}
893
894/// Type of brackets used for `STRUCT` literals.
895#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
896#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
897#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
898pub enum StructBracketKind {
899    /// Example: `STRUCT(a INT, b STRING)`
900    Parentheses,
901    /// Example: `STRUCT<a INT, b STRING>`
902    AngleBrackets,
903}
904
905/// Timestamp and Time data types information about TimeZone formatting.
906///
907/// This is more related to a display information than real differences between each variant. To
908/// guarantee compatibility with the input query we must maintain its exact information.
909#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
910#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
911#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
912pub enum TimezoneInfo {
913    /// No information about time zone, e.g. TIMESTAMP
914    None,
915    /// Temporal type 'WITH TIME ZONE', e.g. TIMESTAMP WITH TIME ZONE, [SQL Standard], [Oracle]
916    ///
917    /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#datetime-type
918    /// [Oracle]: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/nlspg/datetime-data-types-and-time-zone-support.html#GUID-3F1C388E-C651-43D5-ADBC-1A49E5C2CA05
919    WithTimeZone,
920    /// Temporal type 'WITHOUT TIME ZONE', e.g. TIME WITHOUT TIME ZONE, [SQL Standard], [Postgresql]
921    ///
922    /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#datetime-type
923    /// [Postgresql]: https://www.postgresql.org/docs/current/datatype-datetime.html
924    WithoutTimeZone,
925    /// Postgresql specific `WITH TIME ZONE` formatting, for both TIME and TIMESTAMP, e.g. TIMETZ, [Postgresql]
926    ///
927    /// [Postgresql]: https://www.postgresql.org/docs/current/datatype-datetime.html
928    Tz,
929}
930
931impl fmt::Display for TimezoneInfo {
932    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
933        match self {
934            TimezoneInfo::None => {
935                write!(f, "")
936            }
937            TimezoneInfo::WithTimeZone => {
938                write!(f, " WITH TIME ZONE")
939            }
940            TimezoneInfo::WithoutTimeZone => {
941                write!(f, " WITHOUT TIME ZONE")
942            }
943            TimezoneInfo::Tz => {
944                // TZ is the only one that is displayed BEFORE the precision, so the datatype display
945                // must be aware of that. Check <https://www.postgresql.org/docs/14/datatype-datetime.html>
946                // for more information
947                write!(f, "TZ")
948            }
949        }
950    }
951}
952
953/// Fields for [Postgres] `INTERVAL` type.
954///
955/// [Postgres]: https://www.postgresql.org/docs/17/datatype-datetime.html
956#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
957#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
958#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
959pub enum IntervalFields {
960    Year,
961    Month,
962    Day,
963    Hour,
964    Minute,
965    Second,
966    YearToMonth,
967    DayToHour,
968    DayToMinute,
969    DayToSecond,
970    HourToMinute,
971    HourToSecond,
972    MinuteToSecond,
973}
974
975impl fmt::Display for IntervalFields {
976    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
977        match self {
978            IntervalFields::Year => write!(f, "YEAR"),
979            IntervalFields::Month => write!(f, "MONTH"),
980            IntervalFields::Day => write!(f, "DAY"),
981            IntervalFields::Hour => write!(f, "HOUR"),
982            IntervalFields::Minute => write!(f, "MINUTE"),
983            IntervalFields::Second => write!(f, "SECOND"),
984            IntervalFields::YearToMonth => write!(f, "YEAR TO MONTH"),
985            IntervalFields::DayToHour => write!(f, "DAY TO HOUR"),
986            IntervalFields::DayToMinute => write!(f, "DAY TO MINUTE"),
987            IntervalFields::DayToSecond => write!(f, "DAY TO SECOND"),
988            IntervalFields::HourToMinute => write!(f, "HOUR TO MINUTE"),
989            IntervalFields::HourToSecond => write!(f, "HOUR TO SECOND"),
990            IntervalFields::MinuteToSecond => write!(f, "MINUTE TO SECOND"),
991        }
992    }
993}
994
995/// Additional information for `NUMERIC`, `DECIMAL`, and `DEC` data types
996/// following the 2016 [SQL Standard].
997///
998/// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#exact-numeric-type
999#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1000#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1001#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1002pub enum ExactNumberInfo {
1003    /// No additional information, e.g. `DECIMAL`
1004    None,
1005    /// Only precision information, e.g. `DECIMAL(10)`
1006    Precision(u64),
1007    /// Precision and scale information, e.g. `DECIMAL(10,2)`
1008    PrecisionAndScale(u64, i64),
1009}
1010
1011impl fmt::Display for ExactNumberInfo {
1012    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1013        match self {
1014            ExactNumberInfo::None => {
1015                write!(f, "")
1016            }
1017            ExactNumberInfo::Precision(p) => {
1018                write!(f, "({p})")
1019            }
1020            ExactNumberInfo::PrecisionAndScale(p, s) => {
1021                write!(f, "({p},{s})")
1022            }
1023        }
1024    }
1025}
1026
1027/// Information about [character length][1], including length and possibly unit.
1028///
1029/// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-length
1030#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1031#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1032#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1033pub enum CharacterLength {
1034    IntegerLength {
1035        /// Default (if VARYING) or maximum (if not VARYING) length
1036        length: u64,
1037        /// Optional unit. If not informed, the ANSI handles it as CHARACTERS implicitly
1038        unit: Option<CharLengthUnits>,
1039    },
1040    /// VARCHAR(MAX) or NVARCHAR(MAX), used in T-SQL (Microsoft SQL Server)
1041    Max,
1042}
1043
1044impl fmt::Display for CharacterLength {
1045    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1046        match self {
1047            CharacterLength::IntegerLength { length, unit } => {
1048                write!(f, "{length}")?;
1049                if let Some(unit) = unit {
1050                    write!(f, " {unit}")?;
1051                }
1052            }
1053            CharacterLength::Max => {
1054                write!(f, "MAX")?;
1055            }
1056        }
1057        Ok(())
1058    }
1059}
1060
1061/// Possible units for characters, initially based on 2016 ANSI [SQL Standard][1].
1062///
1063/// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#char-length-units
1064#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1065#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1066#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1067pub enum CharLengthUnits {
1068    /// CHARACTERS unit
1069    Characters,
1070    /// OCTETS unit
1071    Octets,
1072}
1073
1074impl fmt::Display for CharLengthUnits {
1075    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1076        match self {
1077            Self::Characters => {
1078                write!(f, "CHARACTERS")
1079            }
1080            Self::Octets => {
1081                write!(f, "OCTETS")
1082            }
1083        }
1084    }
1085}
1086
1087#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1088#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1089#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1090pub enum BinaryLength {
1091    IntegerLength {
1092        /// Default (if VARYING)
1093        length: u64,
1094    },
1095    /// VARBINARY(MAX) used in T-SQL (Microsoft SQL Server)
1096    Max,
1097}
1098
1099impl fmt::Display for BinaryLength {
1100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1101        match self {
1102            BinaryLength::IntegerLength { length } => {
1103                write!(f, "{length}")?;
1104            }
1105            BinaryLength::Max => {
1106                write!(f, "MAX")?;
1107            }
1108        }
1109        Ok(())
1110    }
1111}
1112
1113/// Represents the data type of the elements in an array (if any) as well as
1114/// the syntax used to declare the array.
1115///
1116/// For example: Bigquery/Hive use `ARRAY<INT>` whereas snowflake uses ARRAY.
1117#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1118#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1119#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1120pub enum ArrayElemTypeDef {
1121    /// `ARRAY`
1122    None,
1123    /// `ARRAY<INT>`
1124    AngleBracket(Box<DataType>),
1125    /// `INT[]` or `INT[2]`
1126    SquareBracket(Box<DataType>, Option<u64>),
1127    /// `Array(Int64)`
1128    Parenthesis(Box<DataType>),
1129}
1130
1131/// Represents different types of geometric shapes which are commonly used in
1132/// PostgreSQL/Redshift for spatial operations and geometry-related computations.
1133///
1134/// [PostgreSQL]: https://www.postgresql.org/docs/9.5/functions-geometry.html
1135#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
1136#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1137#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1138pub enum GeometricTypeKind {
1139    Point,
1140    Line,
1141    LineSegment,
1142    GeometricBox,
1143    GeometricPath,
1144    Polygon,
1145    Circle,
1146}
1147
1148impl fmt::Display for GeometricTypeKind {
1149    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1150        match self {
1151            GeometricTypeKind::Point => write!(f, "point"),
1152            GeometricTypeKind::Line => write!(f, "line"),
1153            GeometricTypeKind::LineSegment => write!(f, "lseg"),
1154            GeometricTypeKind::GeometricBox => write!(f, "box"),
1155            GeometricTypeKind::GeometricPath => write!(f, "path"),
1156            GeometricTypeKind::Polygon => write!(f, "polygon"),
1157            GeometricTypeKind::Circle => write!(f, "circle"),
1158        }
1159    }
1160}