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 yachtsql_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,
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 => write!(f, "TIMESTAMP_NTZ"),
680 DataType::Datetime64(precision, timezone) => {
681 format_clickhouse_datetime_precision_and_timezone(
682 f,
683 "DateTime64",
684 precision,
685 timezone,
686 )
687 }
688 DataType::Interval { fields, precision } => {
689 write!(f, "INTERVAL")?;
690 if let Some(fields) = fields {
691 write!(f, " {fields}")?;
692 }
693 if let Some(precision) = precision {
694 write!(f, "({precision})")?;
695 }
696 Ok(())
697 }
698 DataType::JSON => write!(f, "JSON"),
699 DataType::JSONB => write!(f, "JSONB"),
700 DataType::Regclass => write!(f, "REGCLASS"),
701 DataType::Text => write!(f, "TEXT"),
702 DataType::TinyText => write!(f, "TINYTEXT"),
703 DataType::MediumText => write!(f, "MEDIUMTEXT"),
704 DataType::LongText => write!(f, "LONGTEXT"),
705 DataType::String(size) => format_type_with_optional_length(f, "STRING", size, false),
706 DataType::Bytea => write!(f, "BYTEA"),
707 DataType::Bit(size) => format_type_with_optional_length(f, "BIT", size, false),
708 DataType::BitVarying(size) => {
709 format_type_with_optional_length(f, "BIT VARYING", size, false)
710 }
711 DataType::VarBit(size) => format_type_with_optional_length(f, "VARBIT", size, false),
712 DataType::Array(ty) => match ty {
713 ArrayElemTypeDef::None => write!(f, "ARRAY"),
714 ArrayElemTypeDef::SquareBracket(t, None) => write!(f, "{t}[]"),
715 ArrayElemTypeDef::SquareBracket(t, Some(size)) => write!(f, "{t}[{size}]"),
716 ArrayElemTypeDef::AngleBracket(t) => write!(f, "ARRAY<{t}>"),
717 ArrayElemTypeDef::Parenthesis(t) => write!(f, "Array({t})"),
718 },
719 DataType::Custom(ty, modifiers) => {
720 if modifiers.is_empty() {
721 write!(f, "{ty}")
722 } else {
723 write!(f, "{}({})", ty, modifiers.join(", "))
724 }
725 }
726 DataType::Enum(vals, bits) => {
727 match bits {
728 Some(bits) => write!(f, "ENUM{bits}"),
729 None => write!(f, "ENUM"),
730 }?;
731 write!(f, "(")?;
732 for (i, v) in vals.iter().enumerate() {
733 if i != 0 {
734 write!(f, ", ")?;
735 }
736 match v {
737 EnumMember::Name(name) => {
738 write!(f, "'{}'", escape_single_quote_string(name))?
739 }
740 EnumMember::NamedValue(name, value) => {
741 write!(f, "'{}' = {}", escape_single_quote_string(name), value)?
742 }
743 }
744 }
745 write!(f, ")")
746 }
747 DataType::Set(vals) => {
748 write!(f, "SET(")?;
749 for (i, v) in vals.iter().enumerate() {
750 if i != 0 {
751 write!(f, ", ")?;
752 }
753 write!(f, "'{}'", escape_single_quote_string(v))?;
754 }
755 write!(f, ")")
756 }
757 DataType::Struct(fields, bracket) => {
758 if !fields.is_empty() {
759 match bracket {
760 StructBracketKind::Parentheses => {
761 write!(f, "STRUCT({})", display_comma_separated(fields))
762 }
763 StructBracketKind::AngleBrackets => {
764 write!(f, "STRUCT<{}>", display_comma_separated(fields))
765 }
766 }
767 } else {
768 write!(f, "STRUCT")
769 }
770 }
771 DataType::Union(fields) => {
772 write!(f, "UNION({})", display_comma_separated(fields))
773 }
774 // ClickHouse
775 DataType::Nullable(data_type) => {
776 write!(f, "Nullable({data_type})")
777 }
778 DataType::FixedString(character_length) => {
779 write!(f, "FixedString({character_length})")
780 }
781 DataType::LowCardinality(data_type) => {
782 write!(f, "LowCardinality({data_type})")
783 }
784 DataType::Map(key_data_type, value_data_type) => {
785 write!(f, "Map({key_data_type}, {value_data_type})")
786 }
787 DataType::Tuple(fields) => {
788 write!(f, "Tuple({})", display_comma_separated(fields))
789 }
790 DataType::Nested(fields) => {
791 write!(f, "Nested({})", display_comma_separated(fields))
792 }
793 DataType::Unspecified => Ok(()),
794 DataType::Trigger => write!(f, "TRIGGER"),
795 DataType::AnyType => write!(f, "ANY TYPE"),
796 DataType::Table(fields) => match fields {
797 Some(fields) => {
798 write!(f, "TABLE({})", display_comma_separated(fields))
799 }
800 None => {
801 write!(f, "TABLE")
802 }
803 },
804 DataType::NamedTable { name, columns } => {
805 write!(f, "{} TABLE ({})", name, display_comma_separated(columns))
806 }
807 DataType::GeometricType(kind) => write!(f, "{kind}"),
808 DataType::TsVector => write!(f, "TSVECTOR"),
809 DataType::TsQuery => write!(f, "TSQUERY"),
810 }
811 }
812}
813
814fn format_type_with_optional_length(
815 f: &mut fmt::Formatter,
816 sql_type: &'static str,
817 len: &Option<u64>,
818 unsigned: bool,
819) -> fmt::Result {
820 write!(f, "{sql_type}")?;
821 if let Some(len) = len {
822 write!(f, "({len})")?;
823 }
824 if unsigned {
825 write!(f, " UNSIGNED")?;
826 }
827 Ok(())
828}
829
830fn format_character_string_type(
831 f: &mut fmt::Formatter,
832 sql_type: &str,
833 size: &Option<CharacterLength>,
834) -> fmt::Result {
835 write!(f, "{sql_type}")?;
836 if let Some(size) = size {
837 write!(f, "({size})")?;
838 }
839 Ok(())
840}
841
842fn format_varbinary_type(
843 f: &mut fmt::Formatter,
844 sql_type: &str,
845 size: &Option<BinaryLength>,
846) -> fmt::Result {
847 write!(f, "{sql_type}")?;
848 if let Some(size) = size {
849 write!(f, "({size})")?;
850 }
851 Ok(())
852}
853
854fn format_datetime_precision_and_tz(
855 f: &mut fmt::Formatter,
856 sql_type: &'static str,
857 len: &Option<u64>,
858 time_zone: &TimezoneInfo,
859) -> fmt::Result {
860 write!(f, "{sql_type}")?;
861 let len_fmt = len.as_ref().map(|l| format!("({l})")).unwrap_or_default();
862
863 match time_zone {
864 TimezoneInfo::Tz => {
865 write!(f, "{time_zone}{len_fmt}")?;
866 }
867 _ => {
868 write!(f, "{len_fmt}{time_zone}")?;
869 }
870 }
871
872 Ok(())
873}
874
875fn format_clickhouse_datetime_precision_and_timezone(
876 f: &mut fmt::Formatter,
877 sql_type: &'static str,
878 len: &u64,
879 time_zone: &Option<String>,
880) -> fmt::Result {
881 write!(f, "{sql_type}({len}")?;
882
883 if let Some(time_zone) = time_zone {
884 write!(f, ", '{time_zone}'")?;
885 }
886
887 write!(f, ")")?;
888
889 Ok(())
890}
891
892/// Type of brackets used for `STRUCT` literals.
893#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
894#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
895#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
896pub enum StructBracketKind {
897 /// Example: `STRUCT(a INT, b STRING)`
898 Parentheses,
899 /// Example: `STRUCT<a INT, b STRING>`
900 AngleBrackets,
901}
902
903/// Timestamp and Time data types information about TimeZone formatting.
904///
905/// This is more related to a display information than real differences between each variant. To
906/// guarantee compatibility with the input query we must maintain its exact information.
907#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
908#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
909#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
910pub enum TimezoneInfo {
911 /// No information about time zone, e.g. TIMESTAMP
912 None,
913 /// Temporal type 'WITH TIME ZONE', e.g. TIMESTAMP WITH TIME ZONE, [SQL Standard], [Oracle]
914 ///
915 /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#datetime-type
916 /// [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
917 WithTimeZone,
918 /// Temporal type 'WITHOUT TIME ZONE', e.g. TIME WITHOUT TIME ZONE, [SQL Standard], [Postgresql]
919 ///
920 /// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#datetime-type
921 /// [Postgresql]: https://www.postgresql.org/docs/current/datatype-datetime.html
922 WithoutTimeZone,
923 /// Postgresql specific `WITH TIME ZONE` formatting, for both TIME and TIMESTAMP, e.g. TIMETZ, [Postgresql]
924 ///
925 /// [Postgresql]: https://www.postgresql.org/docs/current/datatype-datetime.html
926 Tz,
927}
928
929impl fmt::Display for TimezoneInfo {
930 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
931 match self {
932 TimezoneInfo::None => {
933 write!(f, "")
934 }
935 TimezoneInfo::WithTimeZone => {
936 write!(f, " WITH TIME ZONE")
937 }
938 TimezoneInfo::WithoutTimeZone => {
939 write!(f, " WITHOUT TIME ZONE")
940 }
941 TimezoneInfo::Tz => {
942 // TZ is the only one that is displayed BEFORE the precision, so the datatype display
943 // must be aware of that. Check <https://www.postgresql.org/docs/14/datatype-datetime.html>
944 // for more information
945 write!(f, "TZ")
946 }
947 }
948 }
949}
950
951/// Fields for [Postgres] `INTERVAL` type.
952///
953/// [Postgres]: https://www.postgresql.org/docs/17/datatype-datetime.html
954#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
955#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
956#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
957pub enum IntervalFields {
958 Year,
959 Month,
960 Day,
961 Hour,
962 Minute,
963 Second,
964 YearToMonth,
965 DayToHour,
966 DayToMinute,
967 DayToSecond,
968 HourToMinute,
969 HourToSecond,
970 MinuteToSecond,
971}
972
973impl fmt::Display for IntervalFields {
974 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
975 match self {
976 IntervalFields::Year => write!(f, "YEAR"),
977 IntervalFields::Month => write!(f, "MONTH"),
978 IntervalFields::Day => write!(f, "DAY"),
979 IntervalFields::Hour => write!(f, "HOUR"),
980 IntervalFields::Minute => write!(f, "MINUTE"),
981 IntervalFields::Second => write!(f, "SECOND"),
982 IntervalFields::YearToMonth => write!(f, "YEAR TO MONTH"),
983 IntervalFields::DayToHour => write!(f, "DAY TO HOUR"),
984 IntervalFields::DayToMinute => write!(f, "DAY TO MINUTE"),
985 IntervalFields::DayToSecond => write!(f, "DAY TO SECOND"),
986 IntervalFields::HourToMinute => write!(f, "HOUR TO MINUTE"),
987 IntervalFields::HourToSecond => write!(f, "HOUR TO SECOND"),
988 IntervalFields::MinuteToSecond => write!(f, "MINUTE TO SECOND"),
989 }
990 }
991}
992
993/// Additional information for `NUMERIC`, `DECIMAL`, and `DEC` data types
994/// following the 2016 [SQL Standard].
995///
996/// [SQL Standard]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#exact-numeric-type
997#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
998#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
999#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1000pub enum ExactNumberInfo {
1001 /// No additional information, e.g. `DECIMAL`
1002 None,
1003 /// Only precision information, e.g. `DECIMAL(10)`
1004 Precision(u64),
1005 /// Precision and scale information, e.g. `DECIMAL(10,2)`
1006 PrecisionAndScale(u64, i64),
1007}
1008
1009impl fmt::Display for ExactNumberInfo {
1010 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1011 match self {
1012 ExactNumberInfo::None => {
1013 write!(f, "")
1014 }
1015 ExactNumberInfo::Precision(p) => {
1016 write!(f, "({p})")
1017 }
1018 ExactNumberInfo::PrecisionAndScale(p, s) => {
1019 write!(f, "({p},{s})")
1020 }
1021 }
1022 }
1023}
1024
1025/// Information about [character length][1], including length and possibly unit.
1026///
1027/// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-length
1028#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1029#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1030#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1031pub enum CharacterLength {
1032 IntegerLength {
1033 /// Default (if VARYING) or maximum (if not VARYING) length
1034 length: u64,
1035 /// Optional unit. If not informed, the ANSI handles it as CHARACTERS implicitly
1036 unit: Option<CharLengthUnits>,
1037 },
1038 /// VARCHAR(MAX) or NVARCHAR(MAX), used in T-SQL (Microsoft SQL Server)
1039 Max,
1040}
1041
1042impl fmt::Display for CharacterLength {
1043 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1044 match self {
1045 CharacterLength::IntegerLength { length, unit } => {
1046 write!(f, "{length}")?;
1047 if let Some(unit) = unit {
1048 write!(f, " {unit}")?;
1049 }
1050 }
1051 CharacterLength::Max => {
1052 write!(f, "MAX")?;
1053 }
1054 }
1055 Ok(())
1056 }
1057}
1058
1059/// Possible units for characters, initially based on 2016 ANSI [SQL Standard][1].
1060///
1061/// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#char-length-units
1062#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1063#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1064#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1065pub enum CharLengthUnits {
1066 /// CHARACTERS unit
1067 Characters,
1068 /// OCTETS unit
1069 Octets,
1070}
1071
1072impl fmt::Display for CharLengthUnits {
1073 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1074 match self {
1075 Self::Characters => {
1076 write!(f, "CHARACTERS")
1077 }
1078 Self::Octets => {
1079 write!(f, "OCTETS")
1080 }
1081 }
1082 }
1083}
1084
1085#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1086#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1087#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1088pub enum BinaryLength {
1089 IntegerLength {
1090 /// Default (if VARYING)
1091 length: u64,
1092 },
1093 /// VARBINARY(MAX) used in T-SQL (Microsoft SQL Server)
1094 Max,
1095}
1096
1097impl fmt::Display for BinaryLength {
1098 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1099 match self {
1100 BinaryLength::IntegerLength { length } => {
1101 write!(f, "{length}")?;
1102 }
1103 BinaryLength::Max => {
1104 write!(f, "MAX")?;
1105 }
1106 }
1107 Ok(())
1108 }
1109}
1110
1111/// Represents the data type of the elements in an array (if any) as well as
1112/// the syntax used to declare the array.
1113///
1114/// For example: Bigquery/Hive use `ARRAY<INT>` whereas snowflake uses ARRAY.
1115#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1116#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1117#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1118pub enum ArrayElemTypeDef {
1119 /// `ARRAY`
1120 None,
1121 /// `ARRAY<INT>`
1122 AngleBracket(Box<DataType>),
1123 /// `INT[]` or `INT[2]`
1124 SquareBracket(Box<DataType>, Option<u64>),
1125 /// `Array(Int64)`
1126 Parenthesis(Box<DataType>),
1127}
1128
1129/// Represents different types of geometric shapes which are commonly used in
1130/// PostgreSQL/Redshift for spatial operations and geometry-related computations.
1131///
1132/// [PostgreSQL]: https://www.postgresql.org/docs/9.5/functions-geometry.html
1133#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
1134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1135#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1136pub enum GeometricTypeKind {
1137 Point,
1138 Line,
1139 LineSegment,
1140 GeometricBox,
1141 GeometricPath,
1142 Polygon,
1143 Circle,
1144}
1145
1146impl fmt::Display for GeometricTypeKind {
1147 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1148 match self {
1149 GeometricTypeKind::Point => write!(f, "point"),
1150 GeometricTypeKind::Line => write!(f, "line"),
1151 GeometricTypeKind::LineSegment => write!(f, "lseg"),
1152 GeometricTypeKind::GeometricBox => write!(f, "box"),
1153 GeometricTypeKind::GeometricPath => write!(f, "path"),
1154 GeometricTypeKind::Polygon => write!(f, "polygon"),
1155 GeometricTypeKind::Circle => write!(f, "circle"),
1156 }
1157 }
1158}