Skip to main content

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