Edit on GitHub

sqlglot expressions datatypes.

  1"""sqlglot expressions datatypes."""
  2
  3from __future__ import annotations
  4
  5import typing as t
  6from enum import auto
  7
  8from sqlglot.helper import AutoName
  9from sqlglot.errors import ErrorLevel, ParseError
 10from sqlglot.expressions.core import (
 11    Expr,
 12    Expression,
 13    _TimeUnit,
 14    Identifier,
 15    Dot,
 16    maybe_copy,
 17)
 18from builtins import type as Type
 19
 20if t.TYPE_CHECKING:
 21    from sqlglot._typing import DataTypeArgs
 22    from sqlglot.dialects.dialect import DialectType
 23    from typing_extensions import Self, Unpack
 24
 25
 26class DataTypeParam(Expression):
 27    arg_types = {"this": True, "expression": False}
 28
 29    @property
 30    def this(self) -> Expr:
 31        return self.args["this"]
 32
 33    @property
 34    def name(self) -> str:
 35        return self.this.name
 36
 37
 38class DType(AutoName):
 39    ARRAY = auto()
 40    AGGREGATEFUNCTION = auto()
 41    SIMPLEAGGREGATEFUNCTION = auto()
 42    BIGDECIMAL = auto()
 43    BIGINT = auto()
 44    BIGNUM = auto()
 45    BIGSERIAL = auto()
 46    BINARY = auto()
 47    BIT = auto()
 48    BLOB = auto()
 49    BOOLEAN = auto()
 50    BPCHAR = auto()
 51    CHAR = auto()
 52    CHARACTER_SET = auto()
 53    DATE = auto()
 54    DATE32 = auto()
 55    DATEMULTIRANGE = auto()
 56    DATERANGE = auto()
 57    DATETIME = auto()
 58    DATETIME2 = auto()
 59    DATETIME64 = auto()
 60    DECIMAL = auto()
 61    DECIMAL32 = auto()
 62    DECIMAL64 = auto()
 63    DECIMAL128 = auto()
 64    DECIMAL256 = auto()
 65    DECFLOAT = auto()
 66    DOUBLE = auto()
 67    DYNAMIC = auto()
 68    ENUM = auto()
 69    ENUM8 = auto()
 70    ENUM16 = auto()
 71    FILE = auto()
 72    FIXEDSTRING = auto()
 73    FLOAT = auto()
 74    GEOGRAPHY = auto()
 75    GEOGRAPHYPOINT = auto()
 76    GEOMETRY = auto()
 77    HASHTYPE = auto()
 78    POINT = auto()
 79    RING = auto()
 80    LINESTRING = auto()
 81    MULTILINESTRING = auto()
 82    POLYGON = auto()
 83    MULTIPOLYGON = auto()
 84    HLLSKETCH = auto()
 85    HSTORE = auto()
 86    IMAGE = auto()
 87    INET = auto()
 88    INT = auto()
 89    INT128 = auto()
 90    INT256 = auto()
 91    INT4MULTIRANGE = auto()
 92    INT4RANGE = auto()
 93    INT8MULTIRANGE = auto()
 94    INT8RANGE = auto()
 95    INTERVAL = auto()
 96    IPADDRESS = auto()
 97    IPPREFIX = auto()
 98    IPV4 = auto()
 99    IPV6 = auto()
100    JSON = auto()
101    JSONB = auto()
102    LIST = auto()
103    LONGBLOB = auto()
104    LONGTEXT = auto()
105    LOWCARDINALITY = auto()
106    MAP = auto()
107    MEDIUMBLOB = auto()
108    MEDIUMINT = auto()
109    MEDIUMTEXT = auto()
110    MONEY = auto()
111    NAME = auto()
112    NCHAR = auto()
113    NESTED = auto()
114    NOTHING = auto()
115    NULL = auto()
116    NUMMULTIRANGE = auto()
117    NUMRANGE = auto()
118    NVARCHAR = auto()
119    OBJECT = auto()
120    RANGE = auto()
121    REF = auto()
122    ROWVERSION = auto()
123    SERIAL = auto()
124    SET = auto()
125    SMALLDATETIME = auto()
126    SMALLINT = auto()
127    SMALLMONEY = auto()
128    SMALLSERIAL = auto()
129    STRUCT = auto()
130    SUPER = auto()
131    TEXT = auto()
132    TINYBLOB = auto()
133    TINYTEXT = auto()
134    TIME = auto()
135    TIMETZ = auto()
136    TIME_NS = auto()
137    TIMESTAMP = auto()
138    TIMESTAMPNTZ = auto()
139    TIMESTAMPLTZ = auto()
140    TIMESTAMPTZ = auto()
141    TIMESTAMP_S = auto()
142    TIMESTAMP_MS = auto()
143    TIMESTAMP_NS = auto()
144    TINYINT = auto()
145    TSMULTIRANGE = auto()
146    TSRANGE = auto()
147    TSTZMULTIRANGE = auto()
148    TSTZRANGE = auto()
149    UBIGINT = auto()
150    UINT = auto()
151    UINT128 = auto()
152    UINT256 = auto()
153    UMEDIUMINT = auto()
154    UDECIMAL = auto()
155    UDOUBLE = auto()
156    UNION = auto()
157    UNKNOWN = auto()  # Sentinel value, useful for type annotation
158    USERDEFINED = "USER-DEFINED"
159    USMALLINT = auto()
160    UTINYINT = auto()
161    UUID = auto()
162    VARBINARY = auto()
163    VARCHAR = auto()
164    VARIANT = auto()
165    VECTOR = auto()
166    XML = auto()
167    YEAR = auto()
168    TDIGEST = auto()
169
170    def into_expr(self, **kwargs: object) -> DataType:
171        """Converts this `DType` into a `DataType` instance.
172
173        Args:
174            **kwargs (object): additional arguments to pass in the constructor of DataType.
175        Returns:
176            DataType: the resulting `DataType` instance.
177        """
178        return DataType(this=self).set_kwargs(kwargs)
179
180
181class DataType(Expression):
182    arg_types = {
183        "this": True,
184        "expressions": False,
185        "nested": False,
186        "values": False,
187        "kind": False,
188        "nullable": False,
189        "collate": False,
190    }
191
192    is_data_type: t.ClassVar[bool] = True
193
194    Type: t.ClassVar[Type[DType]] = DType
195
196    STRUCT_TYPES: t.ClassVar[set[DType]] = {
197        DType.FILE,
198        DType.NESTED,
199        DType.OBJECT,
200        DType.STRUCT,
201        DType.UNION,
202    }
203
204    ARRAY_TYPES: t.ClassVar[set[DType]] = {
205        DType.ARRAY,
206        DType.LIST,
207    }
208
209    NESTED_TYPES: t.ClassVar[set[DType]] = {
210        DType.FILE,
211        DType.NESTED,
212        DType.OBJECT,
213        DType.STRUCT,
214        DType.UNION,
215        DType.ARRAY,
216        DType.LIST,
217        DType.MAP,
218    }
219
220    TEXT_TYPES: t.ClassVar[set[DType]] = {
221        DType.CHAR,
222        DType.NCHAR,
223        DType.NVARCHAR,
224        DType.TEXT,
225        DType.TINYTEXT,
226        DType.MEDIUMTEXT,
227        DType.LONGTEXT,
228        DType.VARCHAR,
229        DType.NAME,
230    }
231
232    BINARY_TYPES: t.ClassVar[set[DType]] = {
233        DType.BINARY,
234        DType.VARBINARY,
235        DType.TINYBLOB,
236        DType.BLOB,
237        DType.MEDIUMBLOB,
238        DType.LONGBLOB,
239    }
240
241    SIGNED_INTEGER_TYPES: t.ClassVar[set[DType]] = {
242        DType.BIGINT,
243        DType.INT,
244        DType.INT128,
245        DType.INT256,
246        DType.MEDIUMINT,
247        DType.SMALLINT,
248        DType.TINYINT,
249    }
250
251    UNSIGNED_INTEGER_TYPES: t.ClassVar[set[DType]] = {
252        DType.UBIGINT,
253        DType.UINT,
254        DType.UINT128,
255        DType.UINT256,
256        DType.UMEDIUMINT,
257        DType.USMALLINT,
258        DType.UTINYINT,
259    }
260
261    INTEGER_TYPES: t.ClassVar[set[DType]] = {
262        DType.BIGINT,
263        DType.BIGNUM,
264        DType.INT,
265        DType.INT128,
266        DType.INT256,
267        DType.MEDIUMINT,
268        DType.SMALLINT,
269        DType.TINYINT,
270        DType.UBIGINT,
271        DType.UINT,
272        DType.UINT128,
273        DType.UINT256,
274        DType.UMEDIUMINT,
275        DType.USMALLINT,
276        DType.UTINYINT,
277        DType.BIT,
278    }
279
280    FLOAT_TYPES: t.ClassVar[set[DType]] = {
281        DType.DOUBLE,
282        DType.FLOAT,
283    }
284
285    REAL_TYPES: t.ClassVar[set[DType]] = {
286        DType.DOUBLE,
287        DType.FLOAT,
288        DType.BIGDECIMAL,
289        DType.DECIMAL,
290        DType.DECIMAL32,
291        DType.DECIMAL64,
292        DType.DECIMAL128,
293        DType.DECIMAL256,
294        DType.DECFLOAT,
295        DType.MONEY,
296        DType.SMALLMONEY,
297        DType.UDECIMAL,
298        DType.UDOUBLE,
299    }
300
301    NUMERIC_TYPES: t.ClassVar[set[DType]] = {
302        DType.BIGINT,
303        DType.BIGNUM,
304        DType.INT,
305        DType.INT128,
306        DType.INT256,
307        DType.MEDIUMINT,
308        DType.SMALLINT,
309        DType.TINYINT,
310        DType.UBIGINT,
311        DType.UINT,
312        DType.UINT128,
313        DType.UINT256,
314        DType.UMEDIUMINT,
315        DType.USMALLINT,
316        DType.UTINYINT,
317        DType.BIT,
318        DType.DOUBLE,
319        DType.FLOAT,
320        DType.BIGDECIMAL,
321        DType.DECIMAL,
322        DType.DECIMAL32,
323        DType.DECIMAL64,
324        DType.DECIMAL128,
325        DType.DECIMAL256,
326        DType.DECFLOAT,
327        DType.MONEY,
328        DType.SMALLMONEY,
329        DType.UDECIMAL,
330        DType.UDOUBLE,
331    }
332
333    TEMPORAL_TYPES: t.ClassVar[set[DType]] = {
334        DType.DATE,
335        DType.DATE32,
336        DType.DATETIME,
337        DType.DATETIME2,
338        DType.DATETIME64,
339        DType.SMALLDATETIME,
340        DType.TIME,
341        DType.TIMESTAMP,
342        DType.TIMESTAMPNTZ,
343        DType.TIMESTAMPLTZ,
344        DType.TIMESTAMPTZ,
345        DType.TIMESTAMP_MS,
346        DType.TIMESTAMP_NS,
347        DType.TIMESTAMP_S,
348        DType.TIMETZ,
349    }
350
351    @classmethod
352    def build(
353        cls,
354        dtype: DATA_TYPE,
355        dialect: DialectType = None,
356        udt: bool = False,
357        copy: bool = True,
358        **kwargs: Unpack[DataTypeArgs],
359    ) -> Self:
360        """
361        Constructs a DataType object.
362
363        Args:
364            dtype: the data type of interest.
365            dialect: the dialect to use for parsing `dtype`, in case it's a string.
366            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
367                DataType, thus creating a user-defined type.
368            copy: whether to copy the data type.
369            kwargs: additional arguments to pass in the constructor of DataType.
370
371        Returns:
372            The constructed DataType object.
373        """
374        if isinstance(dtype, str):
375            return cls.from_str(dtype, dialect, udt, **kwargs)
376        elif isinstance(dtype, DType):
377            data_type_exp = cls(this=dtype)
378            if kwargs:
379                for k, v in kwargs.items():
380                    data_type_exp.set(k, v)
381            return data_type_exp
382        elif isinstance(dtype, (Identifier, Dot)) and udt:
383            return cls(this=DType.USERDEFINED, kind=dtype, **kwargs)
384        elif isinstance(dtype, cls):
385            return maybe_copy(dtype, copy)
386        else:
387            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DType")
388
389    @classmethod
390    def from_str(
391        cls,
392        dtype: str,
393        dialect: DialectType = None,
394        udt: bool = False,
395        **kwargs: Unpack[DataTypeArgs],
396    ) -> Self:
397        """
398        Constructs a `DataType` object from a `str` representation.
399
400        Args:
401            dtype: the data type of interest.
402            dialect: the dialect to use for parsing `dtype`.
403            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
404                `DataType`, thus creating a user-defined type.
405            kwargs: additional arguments to pass in the constructor of `DataType`.
406
407        Returns:
408            The constructed `DataType` object.
409        """
410        from sqlglot import parse_one
411
412        if dtype.upper() == "UNKNOWN":
413            return cls(this=DType.UNKNOWN, **kwargs)
414        try:
415            return parse_one(
416                dtype, read=dialect, into=cls, error_level=ErrorLevel.IGNORE
417            ).set_kwargs(kwargs)
418        except ParseError:
419            if udt:
420                return cls(this=DType.USERDEFINED, kind=dtype, **kwargs)
421            raise
422
423    def is_type(self, *dtypes: DATA_TYPE, check_nullable: bool = False) -> bool:
424        """
425        Checks whether this DataType matches one of the provided data types. Nested types or precision
426        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
427
428        Args:
429            dtypes: the data types to compare this DataType to.
430            check_nullable: whether to take the NULLABLE type constructor into account for the comparison.
431                If false, it means that NULLABLE<INT> is equivalent to INT.
432
433        Returns:
434            True, if and only if there is a type in `dtypes` which is equal to this DataType.
435        """
436        self_is_nullable: bool | None = self.args.get("nullable")
437        for dtype in dtypes:
438            other_type = DataType.build(dtype, copy=False, udt=True)
439            other_is_nullable: bool | None = other_type.args.get("nullable")
440            if (
441                other_type.expressions
442                or (check_nullable and (self_is_nullable or other_is_nullable))
443                or self.this == DType.USERDEFINED
444                or other_type.this == DType.USERDEFINED
445            ):
446                matches = self == other_type
447            else:
448                matches = self.this == other_type.this
449
450            if matches:
451                return True
452        return False
453
454
455class PseudoType(DataType):
456    arg_types = {"this": True}
457
458
459class ObjectIdentifier(DataType):
460    arg_types = {"this": True}
461
462
463class IntervalSpan(DataType):
464    arg_types = {"this": True, "expression": True}
465
466
467class Interval(_TimeUnit):
468    # fraction_in_string: a fractional amount was written with its unit in one string, e.g.
469    # INTERVAL '1.5 DAY', which differs from INTERVAL '1.5' DAY in e.g. DuckDB and Postgres
470    arg_types = {"this": False, "unit": False, "fraction_in_string": False}
471
472
473DATA_TYPE = t.Union[str, Identifier, Dot, DataType, DType]
class DataTypeParam(sqlglot.expressions.core.Expression):
27class DataTypeParam(Expression):
28    arg_types = {"this": True, "expression": False}
29
30    @property
31    def this(self) -> Expr:
32        return self.args["this"]
33
34    @property
35    def name(self) -> str:
36        return self.this.name
arg_types = {'this': True, 'expression': False}
this: sqlglot.expressions.core.Expr
30    @property
31    def this(self) -> Expr:
32        return self.args["this"]

Retrieves the argument with key "this".

name: str
34    @property
35    def name(self) -> str:
36        return self.this.name
key: ClassVar[str] = 'datatypeparam'
required_args: 't.ClassVar[set[str]]' = {'this'}
class DType(sqlglot.helper.AutoName):
 39class DType(AutoName):
 40    ARRAY = auto()
 41    AGGREGATEFUNCTION = auto()
 42    SIMPLEAGGREGATEFUNCTION = auto()
 43    BIGDECIMAL = auto()
 44    BIGINT = auto()
 45    BIGNUM = auto()
 46    BIGSERIAL = auto()
 47    BINARY = auto()
 48    BIT = auto()
 49    BLOB = auto()
 50    BOOLEAN = auto()
 51    BPCHAR = auto()
 52    CHAR = auto()
 53    CHARACTER_SET = auto()
 54    DATE = auto()
 55    DATE32 = auto()
 56    DATEMULTIRANGE = auto()
 57    DATERANGE = auto()
 58    DATETIME = auto()
 59    DATETIME2 = auto()
 60    DATETIME64 = auto()
 61    DECIMAL = auto()
 62    DECIMAL32 = auto()
 63    DECIMAL64 = auto()
 64    DECIMAL128 = auto()
 65    DECIMAL256 = auto()
 66    DECFLOAT = auto()
 67    DOUBLE = auto()
 68    DYNAMIC = auto()
 69    ENUM = auto()
 70    ENUM8 = auto()
 71    ENUM16 = auto()
 72    FILE = auto()
 73    FIXEDSTRING = auto()
 74    FLOAT = auto()
 75    GEOGRAPHY = auto()
 76    GEOGRAPHYPOINT = auto()
 77    GEOMETRY = auto()
 78    HASHTYPE = auto()
 79    POINT = auto()
 80    RING = auto()
 81    LINESTRING = auto()
 82    MULTILINESTRING = auto()
 83    POLYGON = auto()
 84    MULTIPOLYGON = auto()
 85    HLLSKETCH = auto()
 86    HSTORE = auto()
 87    IMAGE = auto()
 88    INET = auto()
 89    INT = auto()
 90    INT128 = auto()
 91    INT256 = auto()
 92    INT4MULTIRANGE = auto()
 93    INT4RANGE = auto()
 94    INT8MULTIRANGE = auto()
 95    INT8RANGE = auto()
 96    INTERVAL = auto()
 97    IPADDRESS = auto()
 98    IPPREFIX = auto()
 99    IPV4 = auto()
100    IPV6 = auto()
101    JSON = auto()
102    JSONB = auto()
103    LIST = auto()
104    LONGBLOB = auto()
105    LONGTEXT = auto()
106    LOWCARDINALITY = auto()
107    MAP = auto()
108    MEDIUMBLOB = auto()
109    MEDIUMINT = auto()
110    MEDIUMTEXT = auto()
111    MONEY = auto()
112    NAME = auto()
113    NCHAR = auto()
114    NESTED = auto()
115    NOTHING = auto()
116    NULL = auto()
117    NUMMULTIRANGE = auto()
118    NUMRANGE = auto()
119    NVARCHAR = auto()
120    OBJECT = auto()
121    RANGE = auto()
122    REF = auto()
123    ROWVERSION = auto()
124    SERIAL = auto()
125    SET = auto()
126    SMALLDATETIME = auto()
127    SMALLINT = auto()
128    SMALLMONEY = auto()
129    SMALLSERIAL = auto()
130    STRUCT = auto()
131    SUPER = auto()
132    TEXT = auto()
133    TINYBLOB = auto()
134    TINYTEXT = auto()
135    TIME = auto()
136    TIMETZ = auto()
137    TIME_NS = auto()
138    TIMESTAMP = auto()
139    TIMESTAMPNTZ = auto()
140    TIMESTAMPLTZ = auto()
141    TIMESTAMPTZ = auto()
142    TIMESTAMP_S = auto()
143    TIMESTAMP_MS = auto()
144    TIMESTAMP_NS = auto()
145    TINYINT = auto()
146    TSMULTIRANGE = auto()
147    TSRANGE = auto()
148    TSTZMULTIRANGE = auto()
149    TSTZRANGE = auto()
150    UBIGINT = auto()
151    UINT = auto()
152    UINT128 = auto()
153    UINT256 = auto()
154    UMEDIUMINT = auto()
155    UDECIMAL = auto()
156    UDOUBLE = auto()
157    UNION = auto()
158    UNKNOWN = auto()  # Sentinel value, useful for type annotation
159    USERDEFINED = "USER-DEFINED"
160    USMALLINT = auto()
161    UTINYINT = auto()
162    UUID = auto()
163    VARBINARY = auto()
164    VARCHAR = auto()
165    VARIANT = auto()
166    VECTOR = auto()
167    XML = auto()
168    YEAR = auto()
169    TDIGEST = auto()
170
171    def into_expr(self, **kwargs: object) -> DataType:
172        """Converts this `DType` into a `DataType` instance.
173
174        Args:
175            **kwargs (object): additional arguments to pass in the constructor of DataType.
176        Returns:
177            DataType: the resulting `DataType` instance.
178        """
179        return DataType(this=self).set_kwargs(kwargs)

An enumeration.

ARRAY = <DType.ARRAY: 'ARRAY'>
AGGREGATEFUNCTION = <DType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>
SIMPLEAGGREGATEFUNCTION = <DType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>
BIGDECIMAL = <DType.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <DType.BIGINT: 'BIGINT'>
BIGNUM = <DType.BIGNUM: 'BIGNUM'>
BIGSERIAL = <DType.BIGSERIAL: 'BIGSERIAL'>
BINARY = <DType.BINARY: 'BINARY'>
BIT = <DType.BIT: 'BIT'>
BLOB = <DType.BLOB: 'BLOB'>
BOOLEAN = <DType.BOOLEAN: 'BOOLEAN'>
BPCHAR = <DType.BPCHAR: 'BPCHAR'>
CHAR = <DType.CHAR: 'CHAR'>
CHARACTER_SET = <DType.CHARACTER_SET: 'CHARACTER_SET'>
DATE = <DType.DATE: 'DATE'>
DATE32 = <DType.DATE32: 'DATE32'>
DATEMULTIRANGE = <DType.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DATERANGE = <DType.DATERANGE: 'DATERANGE'>
DATETIME = <DType.DATETIME: 'DATETIME'>
DATETIME2 = <DType.DATETIME2: 'DATETIME2'>
DATETIME64 = <DType.DATETIME64: 'DATETIME64'>
DECIMAL = <DType.DECIMAL: 'DECIMAL'>
DECIMAL32 = <DType.DECIMAL32: 'DECIMAL32'>
DECIMAL64 = <DType.DECIMAL64: 'DECIMAL64'>
DECIMAL128 = <DType.DECIMAL128: 'DECIMAL128'>
DECIMAL256 = <DType.DECIMAL256: 'DECIMAL256'>
DECFLOAT = <DType.DECFLOAT: 'DECFLOAT'>
DOUBLE = <DType.DOUBLE: 'DOUBLE'>
DYNAMIC = <DType.DYNAMIC: 'DYNAMIC'>
ENUM = <DType.ENUM: 'ENUM'>
ENUM8 = <DType.ENUM8: 'ENUM8'>
ENUM16 = <DType.ENUM16: 'ENUM16'>
FILE = <DType.FILE: 'FILE'>
FIXEDSTRING = <DType.FIXEDSTRING: 'FIXEDSTRING'>
FLOAT = <DType.FLOAT: 'FLOAT'>
GEOGRAPHY = <DType.GEOGRAPHY: 'GEOGRAPHY'>
GEOGRAPHYPOINT = <DType.GEOGRAPHYPOINT: 'GEOGRAPHYPOINT'>
GEOMETRY = <DType.GEOMETRY: 'GEOMETRY'>
HASHTYPE = <DType.HASHTYPE: 'HASHTYPE'>
POINT = <DType.POINT: 'POINT'>
RING = <DType.RING: 'RING'>
LINESTRING = <DType.LINESTRING: 'LINESTRING'>
MULTILINESTRING = <DType.MULTILINESTRING: 'MULTILINESTRING'>
POLYGON = <DType.POLYGON: 'POLYGON'>
MULTIPOLYGON = <DType.MULTIPOLYGON: 'MULTIPOLYGON'>
HLLSKETCH = <DType.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <DType.HSTORE: 'HSTORE'>
IMAGE = <DType.IMAGE: 'IMAGE'>
INET = <DType.INET: 'INET'>
INT = <DType.INT: 'INT'>
INT128 = <DType.INT128: 'INT128'>
INT256 = <DType.INT256: 'INT256'>
INT4MULTIRANGE = <DType.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT4RANGE = <DType.INT4RANGE: 'INT4RANGE'>
INT8MULTIRANGE = <DType.INT8MULTIRANGE: 'INT8MULTIRANGE'>
INT8RANGE = <DType.INT8RANGE: 'INT8RANGE'>
INTERVAL = <DType.INTERVAL: 'INTERVAL'>
IPADDRESS = <DType.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <DType.IPPREFIX: 'IPPREFIX'>
IPV4 = <DType.IPV4: 'IPV4'>
IPV6 = <DType.IPV6: 'IPV6'>
JSON = <DType.JSON: 'JSON'>
JSONB = <DType.JSONB: 'JSONB'>
LIST = <DType.LIST: 'LIST'>
LONGBLOB = <DType.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <DType.LONGTEXT: 'LONGTEXT'>
LOWCARDINALITY = <DType.LOWCARDINALITY: 'LOWCARDINALITY'>
MAP = <DType.MAP: 'MAP'>
MEDIUMBLOB = <DType.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMINT = <DType.MEDIUMINT: 'MEDIUMINT'>
MEDIUMTEXT = <DType.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <DType.MONEY: 'MONEY'>
NAME = <DType.NAME: 'NAME'>
NCHAR = <DType.NCHAR: 'NCHAR'>
NESTED = <DType.NESTED: 'NESTED'>
NOTHING = <DType.NOTHING: 'NOTHING'>
NULL = <DType.NULL: 'NULL'>
NUMMULTIRANGE = <DType.NUMMULTIRANGE: 'NUMMULTIRANGE'>
NUMRANGE = <DType.NUMRANGE: 'NUMRANGE'>
NVARCHAR = <DType.NVARCHAR: 'NVARCHAR'>
OBJECT = <DType.OBJECT: 'OBJECT'>
RANGE = <DType.RANGE: 'RANGE'>
REF = <DType.REF: 'REF'>
ROWVERSION = <DType.ROWVERSION: 'ROWVERSION'>
SERIAL = <DType.SERIAL: 'SERIAL'>
SET = <DType.SET: 'SET'>
SMALLDATETIME = <DType.SMALLDATETIME: 'SMALLDATETIME'>
SMALLINT = <DType.SMALLINT: 'SMALLINT'>
SMALLMONEY = <DType.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <DType.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <DType.STRUCT: 'STRUCT'>
SUPER = <DType.SUPER: 'SUPER'>
TEXT = <DType.TEXT: 'TEXT'>
TINYBLOB = <DType.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <DType.TINYTEXT: 'TINYTEXT'>
TIME = <DType.TIME: 'TIME'>
TIMETZ = <DType.TIMETZ: 'TIMETZ'>
TIME_NS = <DType.TIME_NS: 'TIME_NS'>
TIMESTAMP = <DType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPNTZ = <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>
TIMESTAMPLTZ = <DType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPTZ = <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMP_S = <DType.TIMESTAMP_S: 'TIMESTAMP_S'>
TIMESTAMP_MS = <DType.TIMESTAMP_MS: 'TIMESTAMP_MS'>
TIMESTAMP_NS = <DType.TIMESTAMP_NS: 'TIMESTAMP_NS'>
TINYINT = <DType.TINYINT: 'TINYINT'>
TSMULTIRANGE = <DType.TSMULTIRANGE: 'TSMULTIRANGE'>
TSRANGE = <DType.TSRANGE: 'TSRANGE'>
TSTZMULTIRANGE = <DType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
TSTZRANGE = <DType.TSTZRANGE: 'TSTZRANGE'>
UBIGINT = <DType.UBIGINT: 'UBIGINT'>
UINT = <DType.UINT: 'UINT'>
UINT128 = <DType.UINT128: 'UINT128'>
UINT256 = <DType.UINT256: 'UINT256'>
UMEDIUMINT = <DType.UMEDIUMINT: 'UMEDIUMINT'>
UDECIMAL = <DType.UDECIMAL: 'UDECIMAL'>
UDOUBLE = <DType.UDOUBLE: 'UDOUBLE'>
UNION = <DType.UNION: 'UNION'>
UNKNOWN = <DType.UNKNOWN: 'UNKNOWN'>
USERDEFINED = <DType.USERDEFINED: 'USER-DEFINED'>
USMALLINT = <DType.USMALLINT: 'USMALLINT'>
UTINYINT = <DType.UTINYINT: 'UTINYINT'>
UUID = <DType.UUID: 'UUID'>
VARBINARY = <DType.VARBINARY: 'VARBINARY'>
VARCHAR = <DType.VARCHAR: 'VARCHAR'>
VARIANT = <DType.VARIANT: 'VARIANT'>
VECTOR = <DType.VECTOR: 'VECTOR'>
XML = <DType.XML: 'XML'>
YEAR = <DType.YEAR: 'YEAR'>
TDIGEST = <DType.TDIGEST: 'TDIGEST'>
def into_expr(self, **kwargs: object) -> DataType:
171    def into_expr(self, **kwargs: object) -> DataType:
172        """Converts this `DType` into a `DataType` instance.
173
174        Args:
175            **kwargs (object): additional arguments to pass in the constructor of DataType.
176        Returns:
177            DataType: the resulting `DataType` instance.
178        """
179        return DataType(this=self).set_kwargs(kwargs)

Converts this DType into a DataType instance.

Arguments:
  • **kwargs (object): additional arguments to pass in the constructor of DataType.
Returns:

DataType: the resulting DataType instance.

class DataType(sqlglot.expressions.core.Expression):
182class DataType(Expression):
183    arg_types = {
184        "this": True,
185        "expressions": False,
186        "nested": False,
187        "values": False,
188        "kind": False,
189        "nullable": False,
190        "collate": False,
191    }
192
193    is_data_type: t.ClassVar[bool] = True
194
195    Type: t.ClassVar[Type[DType]] = DType
196
197    STRUCT_TYPES: t.ClassVar[set[DType]] = {
198        DType.FILE,
199        DType.NESTED,
200        DType.OBJECT,
201        DType.STRUCT,
202        DType.UNION,
203    }
204
205    ARRAY_TYPES: t.ClassVar[set[DType]] = {
206        DType.ARRAY,
207        DType.LIST,
208    }
209
210    NESTED_TYPES: t.ClassVar[set[DType]] = {
211        DType.FILE,
212        DType.NESTED,
213        DType.OBJECT,
214        DType.STRUCT,
215        DType.UNION,
216        DType.ARRAY,
217        DType.LIST,
218        DType.MAP,
219    }
220
221    TEXT_TYPES: t.ClassVar[set[DType]] = {
222        DType.CHAR,
223        DType.NCHAR,
224        DType.NVARCHAR,
225        DType.TEXT,
226        DType.TINYTEXT,
227        DType.MEDIUMTEXT,
228        DType.LONGTEXT,
229        DType.VARCHAR,
230        DType.NAME,
231    }
232
233    BINARY_TYPES: t.ClassVar[set[DType]] = {
234        DType.BINARY,
235        DType.VARBINARY,
236        DType.TINYBLOB,
237        DType.BLOB,
238        DType.MEDIUMBLOB,
239        DType.LONGBLOB,
240    }
241
242    SIGNED_INTEGER_TYPES: t.ClassVar[set[DType]] = {
243        DType.BIGINT,
244        DType.INT,
245        DType.INT128,
246        DType.INT256,
247        DType.MEDIUMINT,
248        DType.SMALLINT,
249        DType.TINYINT,
250    }
251
252    UNSIGNED_INTEGER_TYPES: t.ClassVar[set[DType]] = {
253        DType.UBIGINT,
254        DType.UINT,
255        DType.UINT128,
256        DType.UINT256,
257        DType.UMEDIUMINT,
258        DType.USMALLINT,
259        DType.UTINYINT,
260    }
261
262    INTEGER_TYPES: t.ClassVar[set[DType]] = {
263        DType.BIGINT,
264        DType.BIGNUM,
265        DType.INT,
266        DType.INT128,
267        DType.INT256,
268        DType.MEDIUMINT,
269        DType.SMALLINT,
270        DType.TINYINT,
271        DType.UBIGINT,
272        DType.UINT,
273        DType.UINT128,
274        DType.UINT256,
275        DType.UMEDIUMINT,
276        DType.USMALLINT,
277        DType.UTINYINT,
278        DType.BIT,
279    }
280
281    FLOAT_TYPES: t.ClassVar[set[DType]] = {
282        DType.DOUBLE,
283        DType.FLOAT,
284    }
285
286    REAL_TYPES: t.ClassVar[set[DType]] = {
287        DType.DOUBLE,
288        DType.FLOAT,
289        DType.BIGDECIMAL,
290        DType.DECIMAL,
291        DType.DECIMAL32,
292        DType.DECIMAL64,
293        DType.DECIMAL128,
294        DType.DECIMAL256,
295        DType.DECFLOAT,
296        DType.MONEY,
297        DType.SMALLMONEY,
298        DType.UDECIMAL,
299        DType.UDOUBLE,
300    }
301
302    NUMERIC_TYPES: t.ClassVar[set[DType]] = {
303        DType.BIGINT,
304        DType.BIGNUM,
305        DType.INT,
306        DType.INT128,
307        DType.INT256,
308        DType.MEDIUMINT,
309        DType.SMALLINT,
310        DType.TINYINT,
311        DType.UBIGINT,
312        DType.UINT,
313        DType.UINT128,
314        DType.UINT256,
315        DType.UMEDIUMINT,
316        DType.USMALLINT,
317        DType.UTINYINT,
318        DType.BIT,
319        DType.DOUBLE,
320        DType.FLOAT,
321        DType.BIGDECIMAL,
322        DType.DECIMAL,
323        DType.DECIMAL32,
324        DType.DECIMAL64,
325        DType.DECIMAL128,
326        DType.DECIMAL256,
327        DType.DECFLOAT,
328        DType.MONEY,
329        DType.SMALLMONEY,
330        DType.UDECIMAL,
331        DType.UDOUBLE,
332    }
333
334    TEMPORAL_TYPES: t.ClassVar[set[DType]] = {
335        DType.DATE,
336        DType.DATE32,
337        DType.DATETIME,
338        DType.DATETIME2,
339        DType.DATETIME64,
340        DType.SMALLDATETIME,
341        DType.TIME,
342        DType.TIMESTAMP,
343        DType.TIMESTAMPNTZ,
344        DType.TIMESTAMPLTZ,
345        DType.TIMESTAMPTZ,
346        DType.TIMESTAMP_MS,
347        DType.TIMESTAMP_NS,
348        DType.TIMESTAMP_S,
349        DType.TIMETZ,
350    }
351
352    @classmethod
353    def build(
354        cls,
355        dtype: DATA_TYPE,
356        dialect: DialectType = None,
357        udt: bool = False,
358        copy: bool = True,
359        **kwargs: Unpack[DataTypeArgs],
360    ) -> Self:
361        """
362        Constructs a DataType object.
363
364        Args:
365            dtype: the data type of interest.
366            dialect: the dialect to use for parsing `dtype`, in case it's a string.
367            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
368                DataType, thus creating a user-defined type.
369            copy: whether to copy the data type.
370            kwargs: additional arguments to pass in the constructor of DataType.
371
372        Returns:
373            The constructed DataType object.
374        """
375        if isinstance(dtype, str):
376            return cls.from_str(dtype, dialect, udt, **kwargs)
377        elif isinstance(dtype, DType):
378            data_type_exp = cls(this=dtype)
379            if kwargs:
380                for k, v in kwargs.items():
381                    data_type_exp.set(k, v)
382            return data_type_exp
383        elif isinstance(dtype, (Identifier, Dot)) and udt:
384            return cls(this=DType.USERDEFINED, kind=dtype, **kwargs)
385        elif isinstance(dtype, cls):
386            return maybe_copy(dtype, copy)
387        else:
388            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DType")
389
390    @classmethod
391    def from_str(
392        cls,
393        dtype: str,
394        dialect: DialectType = None,
395        udt: bool = False,
396        **kwargs: Unpack[DataTypeArgs],
397    ) -> Self:
398        """
399        Constructs a `DataType` object from a `str` representation.
400
401        Args:
402            dtype: the data type of interest.
403            dialect: the dialect to use for parsing `dtype`.
404            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
405                `DataType`, thus creating a user-defined type.
406            kwargs: additional arguments to pass in the constructor of `DataType`.
407
408        Returns:
409            The constructed `DataType` object.
410        """
411        from sqlglot import parse_one
412
413        if dtype.upper() == "UNKNOWN":
414            return cls(this=DType.UNKNOWN, **kwargs)
415        try:
416            return parse_one(
417                dtype, read=dialect, into=cls, error_level=ErrorLevel.IGNORE
418            ).set_kwargs(kwargs)
419        except ParseError:
420            if udt:
421                return cls(this=DType.USERDEFINED, kind=dtype, **kwargs)
422            raise
423
424    def is_type(self, *dtypes: DATA_TYPE, check_nullable: bool = False) -> bool:
425        """
426        Checks whether this DataType matches one of the provided data types. Nested types or precision
427        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
428
429        Args:
430            dtypes: the data types to compare this DataType to.
431            check_nullable: whether to take the NULLABLE type constructor into account for the comparison.
432                If false, it means that NULLABLE<INT> is equivalent to INT.
433
434        Returns:
435            True, if and only if there is a type in `dtypes` which is equal to this DataType.
436        """
437        self_is_nullable: bool | None = self.args.get("nullable")
438        for dtype in dtypes:
439            other_type = DataType.build(dtype, copy=False, udt=True)
440            other_is_nullable: bool | None = other_type.args.get("nullable")
441            if (
442                other_type.expressions
443                or (check_nullable and (self_is_nullable or other_is_nullable))
444                or self.this == DType.USERDEFINED
445                or other_type.this == DType.USERDEFINED
446            ):
447                matches = self == other_type
448            else:
449                matches = self.this == other_type.this
450
451            if matches:
452                return True
453        return False
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'kind': False, 'nullable': False, 'collate': False}
is_data_type: ClassVar[bool] = True
Type: 't.ClassVar[Type[DType]]' = <enum 'DType'>
STRUCT_TYPES: ClassVar[set[DType]] = {<DType.UNION: 'UNION'>, <DType.OBJECT: 'OBJECT'>, <DType.STRUCT: 'STRUCT'>, <DType.FILE: 'FILE'>, <DType.NESTED: 'NESTED'>}
ARRAY_TYPES: ClassVar[set[DType]] = {<DType.LIST: 'LIST'>, <DType.ARRAY: 'ARRAY'>}
NESTED_TYPES: ClassVar[set[DType]] = {<DType.UNION: 'UNION'>, <DType.MAP: 'MAP'>, <DType.LIST: 'LIST'>, <DType.ARRAY: 'ARRAY'>, <DType.OBJECT: 'OBJECT'>, <DType.STRUCT: 'STRUCT'>, <DType.FILE: 'FILE'>, <DType.NESTED: 'NESTED'>}
TEXT_TYPES: ClassVar[set[DType]] = {<DType.TEXT: 'TEXT'>, <DType.NCHAR: 'NCHAR'>, <DType.VARCHAR: 'VARCHAR'>, <DType.NVARCHAR: 'NVARCHAR'>, <DType.TINYTEXT: 'TINYTEXT'>, <DType.LONGTEXT: 'LONGTEXT'>, <DType.MEDIUMTEXT: 'MEDIUMTEXT'>, <DType.CHAR: 'CHAR'>, <DType.NAME: 'NAME'>}
BINARY_TYPES: ClassVar[set[DType]] = {<DType.MEDIUMBLOB: 'MEDIUMBLOB'>, <DType.TINYBLOB: 'TINYBLOB'>, <DType.BLOB: 'BLOB'>, <DType.LONGBLOB: 'LONGBLOB'>, <DType.VARBINARY: 'VARBINARY'>, <DType.BINARY: 'BINARY'>}
SIGNED_INTEGER_TYPES: ClassVar[set[DType]] = {<DType.INT256: 'INT256'>, <DType.INT128: 'INT128'>, <DType.MEDIUMINT: 'MEDIUMINT'>, <DType.INT: 'INT'>, <DType.SMALLINT: 'SMALLINT'>, <DType.BIGINT: 'BIGINT'>, <DType.TINYINT: 'TINYINT'>}
UNSIGNED_INTEGER_TYPES: ClassVar[set[DType]] = {<DType.UINT128: 'UINT128'>, <DType.UBIGINT: 'UBIGINT'>, <DType.UINT256: 'UINT256'>, <DType.UTINYINT: 'UTINYINT'>, <DType.UINT: 'UINT'>, <DType.UMEDIUMINT: 'UMEDIUMINT'>, <DType.USMALLINT: 'USMALLINT'>}
INTEGER_TYPES: ClassVar[set[DType]] = {<DType.INT256: 'INT256'>, <DType.INT128: 'INT128'>, <DType.MEDIUMINT: 'MEDIUMINT'>, <DType.UINT128: 'UINT128'>, <DType.UBIGINT: 'UBIGINT'>, <DType.INT: 'INT'>, <DType.UINT256: 'UINT256'>, <DType.UTINYINT: 'UTINYINT'>, <DType.UINT: 'UINT'>, <DType.SMALLINT: 'SMALLINT'>, <DType.UMEDIUMINT: 'UMEDIUMINT'>, <DType.BIGNUM: 'BIGNUM'>, <DType.USMALLINT: 'USMALLINT'>, <DType.BIGINT: 'BIGINT'>, <DType.BIT: 'BIT'>, <DType.TINYINT: 'TINYINT'>}
FLOAT_TYPES: ClassVar[set[DType]] = {<DType.DOUBLE: 'DOUBLE'>, <DType.FLOAT: 'FLOAT'>}
REAL_TYPES: ClassVar[set[DType]] = {<DType.DECIMAL32: 'DECIMAL32'>, <DType.DECIMAL256: 'DECIMAL256'>, <DType.DOUBLE: 'DOUBLE'>, <DType.FLOAT: 'FLOAT'>, <DType.DECIMAL128: 'DECIMAL128'>, <DType.UDECIMAL: 'UDECIMAL'>, <DType.DECIMAL: 'DECIMAL'>, <DType.DECFLOAT: 'DECFLOAT'>, <DType.DECIMAL64: 'DECIMAL64'>, <DType.UDOUBLE: 'UDOUBLE'>, <DType.BIGDECIMAL: 'BIGDECIMAL'>, <DType.MONEY: 'MONEY'>, <DType.SMALLMONEY: 'SMALLMONEY'>}
NUMERIC_TYPES: ClassVar[set[DType]] = {<DType.DECIMAL32: 'DECIMAL32'>, <DType.DECIMAL256: 'DECIMAL256'>, <DType.INT: 'INT'>, <DType.SMALLINT: 'SMALLINT'>, <DType.BIT: 'BIT'>, <DType.MONEY: 'MONEY'>, <DType.FLOAT: 'FLOAT'>, <DType.UTINYINT: 'UTINYINT'>, <DType.UINT: 'UINT'>, <DType.UDECIMAL: 'UDECIMAL'>, <DType.UMEDIUMINT: 'UMEDIUMINT'>, <DType.TINYINT: 'TINYINT'>, <DType.SMALLMONEY: 'SMALLMONEY'>, <DType.INT256: 'INT256'>, <DType.UDOUBLE: 'UDOUBLE'>, <DType.MEDIUMINT: 'MEDIUMINT'>, <DType.UINT128: 'UINT128'>, <DType.UBIGINT: 'UBIGINT'>, <DType.DOUBLE: 'DOUBLE'>, <DType.DECIMAL: 'DECIMAL'>, <DType.DECFLOAT: 'DECFLOAT'>, <DType.BIGNUM: 'BIGNUM'>, <DType.USMALLINT: 'USMALLINT'>, <DType.BIGDECIMAL: 'BIGDECIMAL'>, <DType.INT128: 'INT128'>, <DType.UINT256: 'UINT256'>, <DType.DECIMAL128: 'DECIMAL128'>, <DType.DECIMAL64: 'DECIMAL64'>, <DType.BIGINT: 'BIGINT'>}
TEMPORAL_TYPES: ClassVar[set[DType]] = {<DType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <DType.TIMESTAMP_S: 'TIMESTAMP_S'>, <DType.TIMESTAMP: 'TIMESTAMP'>, <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <DType.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <DType.DATETIME2: 'DATETIME2'>, <DType.DATETIME64: 'DATETIME64'>, <DType.TIME: 'TIME'>, <DType.TIMETZ: 'TIMETZ'>, <DType.DATETIME: 'DATETIME'>, <DType.SMALLDATETIME: 'SMALLDATETIME'>, <DType.DATE: 'DATE'>, <DType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <DType.DATE32: 'DATE32'>}
@classmethod
def build( cls, dtype: Union[str, sqlglot.expressions.core.Identifier, sqlglot.expressions.core.Dot, DataType, DType], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, udt: bool = False, copy: bool = True, **kwargs: typing_extensions.Unpack[sqlglot._typing.DataTypeArgs]) -> typing_extensions.Self:
352    @classmethod
353    def build(
354        cls,
355        dtype: DATA_TYPE,
356        dialect: DialectType = None,
357        udt: bool = False,
358        copy: bool = True,
359        **kwargs: Unpack[DataTypeArgs],
360    ) -> Self:
361        """
362        Constructs a DataType object.
363
364        Args:
365            dtype: the data type of interest.
366            dialect: the dialect to use for parsing `dtype`, in case it's a string.
367            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
368                DataType, thus creating a user-defined type.
369            copy: whether to copy the data type.
370            kwargs: additional arguments to pass in the constructor of DataType.
371
372        Returns:
373            The constructed DataType object.
374        """
375        if isinstance(dtype, str):
376            return cls.from_str(dtype, dialect, udt, **kwargs)
377        elif isinstance(dtype, DType):
378            data_type_exp = cls(this=dtype)
379            if kwargs:
380                for k, v in kwargs.items():
381                    data_type_exp.set(k, v)
382            return data_type_exp
383        elif isinstance(dtype, (Identifier, Dot)) and udt:
384            return cls(this=DType.USERDEFINED, kind=dtype, **kwargs)
385        elif isinstance(dtype, cls):
386            return maybe_copy(dtype, copy)
387        else:
388            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DType")

Constructs a DataType object.

Arguments:
  • dtype: the data type of interest.
  • dialect: the dialect to use for parsing dtype, in case it's a string.
  • udt: when set to True, dtype will be used as-is if it can't be parsed into a DataType, thus creating a user-defined type.
  • copy: whether to copy the data type.
  • kwargs: additional arguments to pass in the constructor of DataType.
Returns:

The constructed DataType object.

@classmethod
def from_str( cls, dtype: str, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, udt: bool = False, **kwargs: typing_extensions.Unpack[sqlglot._typing.DataTypeArgs]) -> typing_extensions.Self:
390    @classmethod
391    def from_str(
392        cls,
393        dtype: str,
394        dialect: DialectType = None,
395        udt: bool = False,
396        **kwargs: Unpack[DataTypeArgs],
397    ) -> Self:
398        """
399        Constructs a `DataType` object from a `str` representation.
400
401        Args:
402            dtype: the data type of interest.
403            dialect: the dialect to use for parsing `dtype`.
404            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
405                `DataType`, thus creating a user-defined type.
406            kwargs: additional arguments to pass in the constructor of `DataType`.
407
408        Returns:
409            The constructed `DataType` object.
410        """
411        from sqlglot import parse_one
412
413        if dtype.upper() == "UNKNOWN":
414            return cls(this=DType.UNKNOWN, **kwargs)
415        try:
416            return parse_one(
417                dtype, read=dialect, into=cls, error_level=ErrorLevel.IGNORE
418            ).set_kwargs(kwargs)
419        except ParseError:
420            if udt:
421                return cls(this=DType.USERDEFINED, kind=dtype, **kwargs)
422            raise

Constructs a DataType object from a str representation.

Arguments:
  • dtype: the data type of interest.
  • dialect: the dialect to use for parsing dtype.
  • udt: when set to True, dtype will be used as-is if it can't be parsed into a DataType, thus creating a user-defined type.
  • kwargs: additional arguments to pass in the constructor of DataType.
Returns:

The constructed DataType object.

def is_type( self, *dtypes: Union[str, sqlglot.expressions.core.Identifier, sqlglot.expressions.core.Dot, DataType, DType], check_nullable: bool = False) -> bool:
424    def is_type(self, *dtypes: DATA_TYPE, check_nullable: bool = False) -> bool:
425        """
426        Checks whether this DataType matches one of the provided data types. Nested types or precision
427        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
428
429        Args:
430            dtypes: the data types to compare this DataType to.
431            check_nullable: whether to take the NULLABLE type constructor into account for the comparison.
432                If false, it means that NULLABLE<INT> is equivalent to INT.
433
434        Returns:
435            True, if and only if there is a type in `dtypes` which is equal to this DataType.
436        """
437        self_is_nullable: bool | None = self.args.get("nullable")
438        for dtype in dtypes:
439            other_type = DataType.build(dtype, copy=False, udt=True)
440            other_is_nullable: bool | None = other_type.args.get("nullable")
441            if (
442                other_type.expressions
443                or (check_nullable and (self_is_nullable or other_is_nullable))
444                or self.this == DType.USERDEFINED
445                or other_type.this == DType.USERDEFINED
446            ):
447                matches = self == other_type
448            else:
449                matches = self.this == other_type.this
450
451            if matches:
452                return True
453        return False

Checks whether this DataType matches one of the provided data types. Nested types or precision will be compared using "structural equivalence" semantics, so e.g. array != array.

Arguments:
  • dtypes: the data types to compare this DataType to.
  • check_nullable: whether to take the NULLABLE type constructor into account for the comparison. If false, it means that NULLABLE is equivalent to INT.
Returns:

True, if and only if there is a type in dtypes which is equal to this DataType.

key: ClassVar[str] = 'datatype'
required_args: 't.ClassVar[set[str]]' = {'this'}
class PseudoType(DataType):
456class PseudoType(DataType):
457    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'pseudotype'
required_args: 't.ClassVar[set[str]]' = {'this'}
class ObjectIdentifier(DataType):
460class ObjectIdentifier(DataType):
461    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'objectidentifier'
required_args: 't.ClassVar[set[str]]' = {'this'}
class IntervalSpan(DataType):
464class IntervalSpan(DataType):
465    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key: ClassVar[str] = 'intervalspan'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Interval(sqlglot.expressions.core._TimeUnit):
468class Interval(_TimeUnit):
469    # fraction_in_string: a fractional amount was written with its unit in one string, e.g.
470    # INTERVAL '1.5 DAY', which differs from INTERVAL '1.5' DAY in e.g. DuckDB and Postgres
471    arg_types = {"this": False, "unit": False, "fraction_in_string": False}
arg_types = {'this': False, 'unit': False, 'fraction_in_string': False}
key: ClassVar[str] = 'interval'
required_args: 't.ClassVar[set[str]]' = set()