Harbor format: 871 coding_baseline tasks (part 59)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot.pngAdded
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/hive.pyAdded+139
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/materialize.pyAdded+18
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/mysql.pyAdded+175
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/oracle.pyAdded+120
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/postgres.pyAdded+160
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/presto.pyAdded+73
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/prql.pyAdded+32
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/redshift.pyAdded+67
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/risingwave.pyAdded+26
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/singlestore.pyAdded+64
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/snowflake.pyAdded+202
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/solr.pyAdded+20
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/spark.pyAdded+47
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/spark2.pyAdded+41
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/sqlite.pyAdded+46
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/starrocks.pyAdded+51
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/tableau.pyAdded+18
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/teradata.pyAdded+81
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/trino.pyAdded+26
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/tsql.pyAdded+196
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/diff.pyAdded+447
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/errors.pyAdded+176
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/__init__.pyAdded+90
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/context.pyAdded+112
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/env.pyAdded+335
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/python.pyAdded+557
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/table.pyAdded+157
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/__init__.pyAdded+54
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/aggregate.pyAdded+329
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/array.pyAdded+394
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/builders.pyAdded+1197
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/constraints.pyAdded+247
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/core.pyAdded+3138
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/datatypes.pyAdded+467
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/ddl.pyAdded+447
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/dml.pyAdded+528
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/functions.pyAdded+555
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/json.pyAdded+252
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/math.pyAdded+286
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/properties.pyAdded+673
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/query.pyAdded+2329
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/string.pyAdded+608
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/temporal.pyAdded+567
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generator.pyAdded
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/__init__.pyAdded
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/athena.pyAdded+184
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/bigquery.pyAdded+881
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/clickhouse.pyAdded+782
- tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/databricks.pyAdded+127
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139from __future__ import annotations
from copy import deepcopyfrom collections import defaultdict
from sqlglot import exp, jsonpath, tokensfrom sqlglot.dialects.dialect import ( Dialect, NormalizationStrategy,)from sqlglot.generators.hive import HiveGeneratorfrom sqlglot.parsers.hive import HiveParserfrom sqlglot.tokens import TokenTypefrom sqlglot.optimizer.annotate_types import TypeAnnotatorfrom sqlglot.typing.hive import EXPRESSION_METADATA
class Hive(Dialect): ALIAS_POST_TABLESAMPLE = True IDENTIFIERS_CAN_START_WITH_DIGIT = True SUPPORTS_USER_DEFINED_TYPES = False SAFE_DIVISION = True CONCAT_WS_COALESCE = True ARRAY_AGG_INCLUDES_NULLS = None REGEXP_EXTRACT_DEFAULT_GROUP = 1 ALTER_TABLE_SUPPORTS_CASCADE = True
# https://spark.apache.org/docs/latest/sql-ref-identifier.html#description NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
# https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362046#LanguageManualUDF-StringFunctions # https://github.com/apache/hive/blob/master/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java#L266-L269 INITCAP_DEFAULT_DELIMITER_CHARS = " \t\n\r\f\u000b\u001c\u001d\u001e\u001f"
# Support only the non-ANSI mode (default for Hive, Spark2, Spark) COERCES_TO = defaultdict(set, deepcopy(TypeAnnotator.COERCES_TO)) for target_type in { *exp.DataType.NUMERIC_TYPES, *exp.DataType.TEMPORAL_TYPES, exp.DType.INTERVAL, }: COERCES_TO[target_type] |= exp.DataType.TEXT_TYPES
TIME_MAPPING = { "y": "%Y", "Y": "%Y", "YYYY": "%Y", "yyyy": "%Y", "YY": "%y", "yy": "%y", "MMMM": "%B", "MMM": "%b", # Hive 4.0+ parses MM/dd/HH/hh/mm/ss strictly (java.time.DateTimeFormatter, see # HIVE-25458/HIVE-25576) "MM": "%mstrict", "M": "%-m", "dd": "%dstrict", "d": "%-d", "HH": "%Hstrict", "H": "%-H", "hh": "%Istrict", "h": "%-I", "mm": "%Mstrict", "m": "%-M", "ss": "%Sstrict", "s": "%-S", "SSSSSS": "%f", "a": "%p", "DD": "%j", "D": "%-j", "E": "%a", "EE": "%a", "EEE": "%a", "EEEE": "%A", "z": "%Z", "Z": "%z", }
DATE_FORMAT = "'yyyy-MM-dd'" DATEINT_FORMAT = "'yyyyMMdd'" TIME_FORMAT = "'yyyy-MM-dd HH:mm:ss'"
class JSONPathTokenizer(jsonpath.JSONPathTokenizer): VAR_TOKENS = { *jsonpath.JSONPathTokenizer.VAR_TOKENS, TokenType.DASH, }
UNESCAPED_SEQUENCES = { "\\0": "\0", "\\Z": "\x1a", "\\%": "\\%", "\\_": "\\_", "\\a": "a", "\\f": "f", "\\v": "v", }
class Tokenizer(tokens.Tokenizer): NUMERIC_ESCAPES = {"u": (16, 4, 4, 0xFFFF), "0": (8, 3, 3, 0x7F)} DROP_UNKNOWN_ESCAPES = True LONE_SURROGATE_REPLACEMENT = "?" QUOTES = ["'", '"'] IDENTIFIERS = ["`"] STRING_ESCAPES = ["\\"]
SINGLE_TOKENS = { **tokens.Tokenizer.SINGLE_TOKENS, "$": TokenType.PARAMETER, }
KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "ADD ARCHIVE": TokenType.COMMAND, "ADD ARCHIVES": TokenType.COMMAND, "ADD FILE": TokenType.COMMAND, "ADD FILES": TokenType.COMMAND, "ADD JAR": TokenType.COMMAND, "ADD JARS": TokenType.COMMAND, "MINUS": TokenType.EXCEPT, "MSCK REPAIR": TokenType.COMMAND, "REFRESH": TokenType.REFRESH, "SERDEPROPERTIES": TokenType.SERDE_PROPERTIES, }
NUMERIC_LITERALS = { "L": "BIGINT", "S": "SMALLINT", "Y": "TINYINT", "D": "DOUBLE", "F": "FLOAT", "BD": "DECIMAL", }
Parser = HiveParser
Generator = HiveGenerator123456789101112131415161718from __future__ import annotations
from sqlglot.dialects.postgres import Postgresfrom sqlglot.generators.materialize import MaterializeGeneratorfrom sqlglot.parsers.materialize import MaterializeParser
class Materialize(Postgres): NORMALIZE_NOT_NULL = True
UNESCAPED_SEQUENCES = {"\\a": "a", "\\v": "v"}
class Tokenizer(Postgres.Tokenizer): NUMERIC_ESCAPES = {"u": (16, 4, 4, 0xFFFF), "U": (16, 8, 8, 0x10FFFF)}
Parser = MaterializeParser
Generator = MaterializeGenerator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175from __future__ import annotations
from sqlglot import tokensfrom sqlglot.dialects.dialect import ( Dialect, NormalizationStrategy, UsingColumnOrder,)from sqlglot.generators.mysql import MySQLGeneratorfrom sqlglot.parsers.mysql import MySQLParserfrom sqlglot.tokens import TokenTypefrom sqlglot.typing.mysql import EXPRESSION_METADATA
class MySQL(Dialect): PROMOTE_TO_INFERRED_DATETIME_TYPE = True USING_COLUMN_ORDER = UsingColumnOrder.LEFT_TABLE
# https://dev.mysql.com/doc/refman/8.0/en/identifiers.html IDENTIFIERS_CAN_START_WITH_DIGIT = True
# We default to treating all identifiers as case-sensitive, since it matches MySQL's # behavior on Linux systems. For MacOS and Windows systems, one can override this # setting by specifying `dialect="mysql, normalization_strategy = lowercase"`. # # See also https://dev.mysql.com/doc/refman/8.2/en/identifier-case-sensitivity.html NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_SENSITIVE
TIME_FORMAT = "'%Y-%m-%d %T'" DPIPE_IS_STRING_CONCAT = False CONCAT_WS_COALESCE = True SUPPORTS_USER_DEFINED_TYPES = False SAFE_DIVISION = True SAFE_TO_ELIMINATE_DOUBLE_NEGATION = False LEAST_GREATEST_IGNORES_NULLS = False
EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
# https://prestodb.io/docs/current/functions/datetime.html#mysql-date-functions TIME_MAPPING = { "%M": "%B", "%c": "%-m", "%e": "%-d", "%h": "%I", "%i": "%M", "%s": "%S", "%u": "%W", "%k": "%-H", "%l": "%-I", "%r": "%I:%M:%S %p", "%T": "%H:%M:%S", "%W": "%A", "%x": "%G", # %v (ISO week) is unmapped due to collision with %V (roundtrip issue) }
VALID_INTERVAL_UNITS = { *Dialect.VALID_INTERVAL_UNITS, "SECOND_MICROSECOND", "MINUTE_MICROSECOND", "MINUTE_SECOND", "HOUR_MICROSECOND", "HOUR_SECOND", "HOUR_MINUTE", "DAY_MICROSECOND", "DAY_SECOND", "DAY_MINUTE", "DAY_HOUR", "YEAR_MONTH", }
UNESCAPED_SEQUENCES = { "\\0": "\0", "\\Z": "\x1a", "\\%": "\\%", "\\_": "\\_", "\\a": "a", "\\f": "f", "\\v": "v", }
class Tokenizer(tokens.Tokenizer): QUOTES = ["'", '"'] COMMENTS = ["--", "#", ("/*", "*/")] IDENTIFIERS = ["`"] STRING_ESCAPES = ["'", '"', "\\"] BIT_STRINGS = [("b'", "'"), ("B'", "'"), ("0b", "")] HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", "")] # https://dev.mysql.com/doc/refman/8.4/en/string-literals.html DROP_UNKNOWN_ESCAPES = True
NESTED_COMMENTS = False DASH_COMMENT_REQUIRES_BOUNDARY = True COMMENTS_TERMINATE_AT_NEWLINE_ONLY = True
KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "BLOB": TokenType.BLOB, "CHARSET": TokenType.CHARACTER_SET, "DISTINCTROW": TokenType.DISTINCT, "EXPLAIN": TokenType.DESCRIBE, "FORCE": TokenType.FORCE, "IGNORE": TokenType.IGNORE, "KEY": TokenType.KEY, "LOCK TABLES": TokenType.COMMAND, "LONGBLOB": TokenType.LONGBLOB, "LONGTEXT": TokenType.LONGTEXT, "MEDIUMBLOB": TokenType.MEDIUMBLOB, "MEDIUMINT": TokenType.MEDIUMINT, "MEDIUMTEXT": TokenType.MEDIUMTEXT, "MEMBER OF": TokenType.MEMBER_OF, "MOD": TokenType.MOD, "SEPARATOR": TokenType.SEPARATOR, "SERIAL": TokenType.SERIAL, "SIGNED": TokenType.BIGINT, "SIGNED INTEGER": TokenType.BIGINT, "START": TokenType.BEGIN, "TIMESTAMP": TokenType.TIMESTAMPTZ, "TINYBLOB": TokenType.TINYBLOB, "TINYTEXT": TokenType.TINYTEXT, "UNLOCK TABLES": TokenType.COMMAND, "UNSIGNED": TokenType.UBIGINT, "UNSIGNED INTEGER": TokenType.UBIGINT, "YEAR": TokenType.YEAR, "_ARMSCII8": TokenType.INTRODUCER, "_ASCII": TokenType.INTRODUCER, "_BIG5": TokenType.INTRODUCER, "_BINARY": TokenType.INTRODUCER, "_CP1250": TokenType.INTRODUCER, "_CP1251": TokenType.INTRODUCER, "_CP1256": TokenType.INTRODUCER, "_CP1257": TokenType.INTRODUCER, "_CP850": TokenType.INTRODUCER, "_CP852": TokenType.INTRODUCER, "_CP866": TokenType.INTRODUCER, "_CP932": TokenType.INTRODUCER, "_DEC8": TokenType.INTRODUCER, "_EUCJPMS": TokenType.INTRODUCER, "_EUCKR": TokenType.INTRODUCER, "_GB18030": TokenType.INTRODUCER, "_GB2312": TokenType.INTRODUCER, "_GBK": TokenType.INTRODUCER, "_GEOSTD8": TokenType.INTRODUCER, "_GREEK": TokenType.INTRODUCER, "_HEBREW": TokenType.INTRODUCER, "_HP8": TokenType.INTRODUCER, "_KEYBCS2": TokenType.INTRODUCER, "_KOI8R": TokenType.INTRODUCER, "_KOI8U": TokenType.INTRODUCER, "_LATIN1": TokenType.INTRODUCER, "_LATIN2": TokenType.INTRODUCER, "_LATIN5": TokenType.INTRODUCER, "_LATIN7": TokenType.INTRODUCER, "_MACCE": TokenType.INTRODUCER, "_MACROMAN": TokenType.INTRODUCER, "_SJIS": TokenType.INTRODUCER, "_SWE7": TokenType.INTRODUCER, "_TIS620": TokenType.INTRODUCER, "_UCS2": TokenType.INTRODUCER, "_UJIS": TokenType.INTRODUCER, # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html "_UTF8": TokenType.INTRODUCER, "_UTF16": TokenType.INTRODUCER, "_UTF16LE": TokenType.INTRODUCER, "_UTF32": TokenType.INTRODUCER, "_UTF8MB3": TokenType.INTRODUCER, "_UTF8MB4": TokenType.INTRODUCER, "@@": TokenType.SESSION_PARAMETER, }
COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.REPLACE} - {TokenType.SHOW}
Parser = MySQLParser
Generator = MySQLGenerator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120from __future__ import annotations
import stringimport typing as t
from sqlglot import exp, tokensfrom sqlglot.dialects.dialect import ( Dialect, NormalizationStrategy,)from sqlglot.generators.oracle import OracleGeneratorfrom sqlglot.parsers.oracle import OracleParserfrom sqlglot.tokens import TokenType
class Oracle(Dialect): ALIAS_POST_TABLESAMPLE = True LOCKING_READS_SUPPORTED = True TABLESAMPLE_SIZE_IS_PERCENT = True NULL_ORDERING = "nulls_are_large" ON_CONDITION_EMPTY_BEFORE_ERROR = False ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False DISABLES_ALIAS_REF_EXPANSION = True
# See section 8: https://docs.oracle.com/cd/A97630_01/server.920/a96540/sql_elements9a.htm NORMALIZATION_STRATEGY = NormalizationStrategy.UPPERCASE
# https://docs.oracle.com/database/121/SQLRF/sql_elements004.htm#SQLRF00212 # https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes TIME_MAPPING = { "D": "%u", # Day of week (1-7) "DAY": "%A", # name of day "DD": "%d", # day of month (1-31) "DDD": "%j", # day of year (1-366) "DY": "%a", # abbreviated name of day "HH": "%I", # Hour of day (1-12) "HH12": "%I", # alias for HH "HH24": "%H", # Hour of day (0-23) "IW": "%V", # Calendar week of year (1-52 or 1-53), as defined by the ISO 8601 standard "IYYY": "%G", # 4-digit year of the ISO 8601 week-numbering calendar "MI": "%M", # Minute (0-59) "MM": "%m", # Month (01-12; January = 01) "MON": "%b", # Abbreviated name of month "MONTH": "%B", # Name of month "SS": "%S", # Second (0-59) "WW": "%W", # Week of year (1-53) "YY": "%y", # 15 "YYYY": "%Y", # 2015 "FF6": "%f", # only 6 digits are supported in python formats }
PSEUDOCOLUMNS = {"ROWNUM", "ROWID", "OBJECT_ID", "OBJECT_VALUE", "LEVEL"}
def can_quote(self, identifier: exp.Identifier, identify: str | bool = "safe") -> bool: # Disable quoting for pseudocolumns as it may break queries e.g # `WHERE "ROWNUM" = ...` does not work but `WHERE ROWNUM = ...` does return ( identifier.quoted or not isinstance(identifier.parent, exp.Pseudocolumn) ) and super().can_quote(identifier, identify=identify)
class Tokenizer(tokens.Tokenizer): VAR_SINGLE_TOKENS = {"@", "$", "#"}
UNICODE_STRINGS = [ (prefix + q, q) for q in t.cast(list[str], tokens.Tokenizer.QUOTES) for prefix in ("U", "u") ]
# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Literals.html # Alternative quoting, e.g. q'[it's]': the delimiters are part of the quote, so the # text in between is taken as is, without escapes RAW_STRINGS = [ (f"{prefix}'{start}", f"{end}'") for prefix in ("q", "Q") for start, end in ( ("[", "]"), ("{", "}"), ("(", ")"), ("<", ">"), *( (c, c) for c in string.ascii_letters + string.digits + string.punctuation if c not in "[{(<" ), ) ] NATIONAL_RAW_STRINGS = [ (prefix + start, end) for start, end in t.cast(list[tuple[str, str]], RAW_STRINGS) for prefix in ("n", "N") ] STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = False
NESTED_COMMENTS = False
KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "(+)": TokenType.JOIN_MARKER, # https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Comparison-Conditions.html "^=": TokenType.NEQ, "BINARY_DOUBLE": TokenType.DOUBLE, "BINARY_FLOAT": TokenType.FLOAT, "BULK COLLECT INTO": TokenType.BULK_COLLECT_INTO, "COLUMNS": TokenType.COLUMN, "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, "MINUS": TokenType.EXCEPT, "NVARCHAR2": TokenType.NVARCHAR, "ORDER SIBLINGS BY": TokenType.ORDER_SIBLINGS_BY, "SAMPLE": TokenType.TABLE_SAMPLE, "START": TokenType.BEGIN, "SUBPARTITION": TokenType.PARTITION, "TOP": TokenType.TOP, "VARCHAR2": TokenType.VARCHAR, "SYSTIMESTAMP": TokenType.SYSTIMESTAMP, }
Parser = OracleParser
Generator = OracleGenerator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160from __future__ import annotations
from sqlglot import exp, tokensfrom sqlglot.dialects.dialect import Dialectfrom sqlglot.generators.postgres import PostgresGeneratorfrom sqlglot.parsers.postgres import PostgresParserfrom sqlglot.tokens import TokenTypefrom sqlglot.typing.postgres import EXPRESSION_METADATA
class Postgres(Dialect): EXPRESSION_METADATA = EXPRESSION_METADATA.copy() INDEX_OFFSET = 1 ASCII_ONLY_NORMALIZATION = True # Normalizing `x IS NOT NULL` to `NOT x IS NULL` is unsafe due to row values, # e.g. `ROW(1, NULL) IS NOT NULL` is false whereas `NOT ROW(1, NULL) IS NULL` is true NORMALIZE_NOT_NULL = False TYPED_DIVISION = True CONCAT_COALESCE = True CONCAT_WS_COALESCE = True NULL_ORDERING = "nulls_are_large" SUPPORTS_LIMIT_ALL = True TIME_FORMAT = "'YYYY-MM-DD HH24:MI:SS'" TABLESAMPLE_SIZE_IS_PERCENT = True TABLES_REFERENCEABLE_AS_COLUMNS = True
DEFAULT_FUNCTIONS_COLUMN_NAMES = { exp.ExplodingGenerateSeries: "generate_series", }
TIME_MAPPING = { "d": "%u", # 1-based day of week "D": "%u", # 1-based day of week "dd": "%d", # day of month "DD": "%d", # day of month "ddd": "%j", # zero padded day of year "DDD": "%j", # zero padded day of year "FMDD": "%-d", # - is no leading zero for Python; same for FM in postgres "FMDDD": "%-j", # day of year "FMHH12": "%-I", # 9 "FMHH24": "%-H", # 9 "FMMI": "%-M", # Minute "FMMM": "%-m", # 1 "FMSS": "%-S", # Second "HH12": "%I", # 09 "HH24": "%H", # 09 "iw": "%V", # ISO 8601 week of year "IW": "%V", # ISO 8601 week of year "iyyy": "%G", # ISO 8601 week-numbering year "IYYY": "%G", # ISO 8601 week-numbering year "mi": "%M", # zero padded minute "MI": "%M", # zero padded minute "mm": "%m", # 01 "MM": "%m", # 01 "OF": "%z", # utc offset "ss": "%S", # zero padded second "SS": "%S", # zero padded second "TMDay": "%A", # TM is locale dependent "TMDy": "%a", "TMMon": "%b", # Sep "TMMonth": "%B", # September "day": "%Aenlower", # tuesday "dy": "%aenlower", # tue "TZ": "%Z", # uppercase timezone name "US": "%f", # zero padded microsecond "ww": "%U", # 1-based week of year "WW": "%U", # 1-based week of year "yy": "%y", # 15 "YY": "%y", # 15 "yyy": "%Ythree", # 015 "YYY": "%Ythree", # 015 "yyyy": "%Y", # 2015 "YYYY": "%Y", # 2015 }
UNESCAPED_SEQUENCES = {"\\a": "a"}
class Tokenizer(tokens.Tokenizer): NUMERIC_ESCAPES = { "x": (16, 1, 2, 0xFF), "u": (16, 4, 4, 0xFFFF), "U": (16, 8, 8, 0x10FFFF), "0": (8, 1, 3, 0o777), } NUMERIC_ESCAPES_ARE_BYTES = True DROP_UNKNOWN_ESCAPES = True BIT_STRINGS = [("b'", "'"), ("B'", "'")] HEX_STRINGS = [("x'", "'"), ("X'", "'")] BYTE_STRINGS = [("e'", "'"), ("E'", "'")] UNICODE_STRINGS = [("U&'", "'"), ("u&'", "'")] BYTE_STRING_ESCAPES = ["'", "\\"] HEREDOC_STRINGS = ["$"]
HEREDOC_TAG_IS_IDENTIFIER = True HEREDOC_STRING_ALTERNATIVE = TokenType.PARAMETER
COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.LOCK}
KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "~": TokenType.RLIKE, "@@": TokenType.DAT, "@?": TokenType.AT_QMARK, "@>": TokenType.AT_GT, "<@": TokenType.LT_AT, "?&": TokenType.QMARK_AMP, "?|": TokenType.QMARK_PIPE, "#-": TokenType.HASH_DASH, "|/": TokenType.PIPE_SLASH, "||/": TokenType.DPIPE_SLASH, "^@": TokenType.CARET_AT, "BEGIN": TokenType.BEGIN, "BIGSERIAL": TokenType.BIGSERIAL, "CSTRING": TokenType.PSEUDO_TYPE, "DECLARE": TokenType.COMMAND, "DO": TokenType.COMMAND, "EXEC": TokenType.COMMAND, "HSTORE": TokenType.HSTORE, "INT8": TokenType.BIGINT, "MONEY": TokenType.MONEY, "NAME": TokenType.NAME, "OID": TokenType.OBJECT_IDENTIFIER, "ONLY": TokenType.ONLY, "POINT": TokenType.POINT, "REFRESH": TokenType.COMMAND, "REINDEX": TokenType.COMMAND, "RESET": TokenType.COMMAND, "SERIAL": TokenType.SERIAL, "SMALLSERIAL": TokenType.SMALLSERIAL, "TEMP": TokenType.TEMPORARY, "TYPE": TokenType.TYPE, "REGCLASS": TokenType.OBJECT_IDENTIFIER, "REGCOLLATION": TokenType.OBJECT_IDENTIFIER, "REGCONFIG": TokenType.OBJECT_IDENTIFIER, "REGDICTIONARY": TokenType.OBJECT_IDENTIFIER, "REGNAMESPACE": TokenType.OBJECT_IDENTIFIER, "REGOPER": TokenType.OBJECT_IDENTIFIER, "REGOPERATOR": TokenType.OBJECT_IDENTIFIER, "REGPROC": TokenType.OBJECT_IDENTIFIER, "REGPROCEDURE": TokenType.OBJECT_IDENTIFIER, "REGROLE": TokenType.OBJECT_IDENTIFIER, "REGTYPE": TokenType.OBJECT_IDENTIFIER, "FLOAT": TokenType.DOUBLE, "XML": TokenType.XML, "VARIADIC": TokenType.VARIADIC, "INOUT": TokenType.INOUT, } KEYWORDS.pop("/*+") KEYWORDS.pop("DIV")
SINGLE_TOKENS = { **tokens.Tokenizer.SINGLE_TOKENS, "$": TokenType.HEREDOC_STRING, }
VAR_SINGLE_TOKENS = {"$"}
Parser = PostgresParser
Generator = PostgresGenerator12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273from __future__ import annotations
import typing as t
from sqlglot import tokensfrom sqlglot.dialects.dialect import ( Dialect, NormalizationStrategy,)from sqlglot.dialects.mysql import MySQLfrom sqlglot.generators.presto import PrestoGeneratorfrom sqlglot.parsers.presto import PrestoParserfrom sqlglot.tokens import TokenTypefrom sqlglot.typing.presto import EXPRESSION_METADATA
class Presto(Dialect): INDEX_OFFSET = 1 NULL_ORDERING = "nulls_are_last" TIME_FORMAT = MySQL.TIME_FORMAT STRICT_STRING_CONCAT = True TYPED_DIVISION = True TABLESAMPLE_SIZE_IS_PERCENT = True LOG_BASE_FIRST: bool | None = None SUPPORTS_LIMIT_ALL = True SUPPORTS_VALUES_DEFAULT = False LEAST_GREATEST_IGNORES_NULLS = False UUID_IS_STRING_TYPE = False
TIME_MAPPING = MySQL.TIME_MAPPING
# https://github.com/trinodb/trino/issues/17 # https://github.com/trinodb/trino/issues/12289 # https://github.com/prestodb/presto/issues/2863 NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
SUPPORTED_SETTINGS = { *Dialect.SUPPORTED_SETTINGS, "variant_extract_is_json_extract", }
class Tokenizer(tokens.Tokenizer): HEX_STRINGS = [("x'", "'"), ("X'", "'")] UNICODE_STRINGS = [ (prefix + q, q) for q in t.cast(list[str], tokens.Tokenizer.QUOTES) for prefix in ("U&", "u&") ]
NESTED_COMMENTS = False
KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "DEALLOCATE PREPARE": TokenType.COMMAND, "DESCRIBE INPUT": TokenType.COMMAND, "DESCRIBE OUTPUT": TokenType.COMMAND, "RESET SESSION": TokenType.COMMAND, "START": TokenType.BEGIN, "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, "ROW": TokenType.STRUCT, "IPADDRESS": TokenType.IPADDRESS, "IPPREFIX": TokenType.IPPREFIX, "TDIGEST": TokenType.TDIGEST, "HYPERLOGLOG": TokenType.HLLSKETCH, } KEYWORDS.pop("/*+") KEYWORDS.pop("QUALIFY")
Parser = PrestoParser
Generator = PrestoGenerator1234567891011121314151617181920212223242526272829303132from __future__ import annotations
from sqlglot import tokensfrom sqlglot.dialects.dialect import Dialectfrom sqlglot.generators.prql import PRQLGeneratorfrom sqlglot.parsers.prql import PRQLParserfrom sqlglot.tokens import TokenType
class PRQL(Dialect): DPIPE_IS_STRING_CONCAT = False
Generator = PRQLGenerator
class Tokenizer(tokens.Tokenizer): IDENTIFIERS = ["`"] QUOTES = ["'", '"']
SINGLE_TOKENS = { **tokens.Tokenizer.SINGLE_TOKENS, "=": TokenType.ALIAS, "'": TokenType.QUOTE, '"': TokenType.QUOTE, "`": TokenType.IDENTIFIER, "#": TokenType.COMMENT, }
KEYWORDS = { **tokens.Tokenizer.KEYWORDS, }
Parser = PRQLParser12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667from __future__ import annotations
from sqlglot.typing.redshift import EXPRESSION_METADATAfrom sqlglot.dialects.dialect import NormalizationStrategyfrom sqlglot.dialects.postgres import Postgresfrom sqlglot.generators.redshift import RedshiftGeneratorfrom sqlglot.parsers.redshift import RedshiftParserfrom sqlglot.tokens import TokenType
class Redshift(Postgres): # https://docs.aws.amazon.com/redshift/latest/dg/r_names.html NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
NORMALIZE_NOT_NULL = True
EXPRESSION_METADATA = EXPRESSION_METADATA.copy() SUPPORTS_USER_DEFINED_TYPES = False INDEX_OFFSET = 0 COPY_PARAMS_ARE_CSV = False HEX_LOWERCASE = True HAS_DISTINCT_ARRAY_CONSTRUCTORS = True COALESCE_COMPARISON_NON_STANDARD = True REGEXP_EXTRACT_POSITION_OVERFLOW_RETURNS_NULL = False ARRAY_FUNCS_PROPAGATES_NULLS = True
# ref: https://docs.aws.amazon.com/redshift/latest/dg/r_FORMAT_strings.html TIME_FORMAT = "'YYYY-MM-DD HH24:MI:SS'"
TIME_MAPPING = { **Postgres.TIME_MAPPING, "MON": "%b", "MONTH": "%B", }
Parser = RedshiftParser
UNESCAPED_SEQUENCES = {"\\a": "a", "\\v": "v"}
class Tokenizer(Postgres.Tokenizer): NUMERIC_ESCAPES = {"0": (8, 1, 3, 0o777)} NUMERIC_ESCAPES_ARE_BYTES = True DROP_UNKNOWN_ESCAPES = True BIT_STRINGS = [] HEX_STRINGS = [] STRING_ESCAPES = ["\\", "'"]
KEYWORDS = { **Postgres.Tokenizer.KEYWORDS, "(+)": TokenType.JOIN_MARKER, "BINARY VARYING": TokenType.VARBINARY, "CURRENT_USER_ID": TokenType.CURRENT_USER_ID, "HLLSKETCH": TokenType.HLLSKETCH, "MINUS": TokenType.EXCEPT, "SUPER": TokenType.SUPER, "TOP": TokenType.TOP, "UNLOAD": TokenType.COMMAND, "USER": TokenType.CURRENT_USER, "VARBYTE": TokenType.VARBINARY, } KEYWORDS.pop("VALUES")
# Redshift allows # to appear as a table identifier prefix SINGLE_TOKENS = Postgres.Tokenizer.SINGLE_TOKENS.copy() SINGLE_TOKENS.pop("#")
Generator = RedshiftGenerator1234567891011121314151617181920212223242526from __future__ import annotations
from sqlglot.dialects.postgres import Postgresfrom sqlglot.generators.risingwave import RisingWaveGeneratorfrom sqlglot.parsers.risingwave import RisingWaveParserfrom sqlglot.tokens import TokenType
class RisingWave(Postgres): NORMALIZE_NOT_NULL = True
REQUIRES_PARENTHESIZED_STRUCT_ACCESS = True SUPPORTS_STRUCT_STAR_EXPANSION = True
UNESCAPED_SEQUENCES = {"\\a": "a", "\\v": "v"}
class Tokenizer(Postgres.Tokenizer): KEYWORDS = { **Postgres.Tokenizer.KEYWORDS, "SINK": TokenType.SINK, "SOURCE": TokenType.SOURCE, }
Parser = RisingWaveParser
Generator = RisingWaveGenerator12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364from sqlglot import TokenTypefrom sqlglot.dialects.mysql import MySQLfrom sqlglot.generators.singlestore import SingleStoreGeneratorfrom sqlglot.parsers.singlestore import SingleStoreParser, cast_to_time6
class SingleStore(MySQL): SUPPORTS_ORDER_BY_ALL = True
MYSQL_INVERSE_TIME_MAPPING = MySQL.INVERSE_TIME_MAPPING MYSQL_INVERSE_TIME_TRIE = MySQL.INVERSE_TIME_TRIE CAST_TO_TIME6 = staticmethod(cast_to_time6)
TIME_MAPPING: dict[str, str] = { "D": "%u", # Day of week (1-7) "DD": "%d", # day of month (01-31) "DY": "%a", # abbreviated name of day "HH": "%I", # Hour of day (01-12) "HH12": "%I", # alias for HH "HH24": "%H", # Hour of day (00-23) "MI": "%M", # Minute (00-59) "MM": "%m", # Month (01-12; January = 01) "MON": "%b", # Abbreviated name of month "MONTH": "%B", # Name of month "SS": "%S", # Second (00-59) "RR": "%y", # 15 "YY": "%y", # 15 "YYYY": "%Y", # 2015 "FF6": "%f", # only 6 digits are supported in python formats }
VECTOR_TYPE_ALIASES = { "I8": "TINYINT", "I16": "SMALLINT", "I32": "INT", "I64": "BIGINT", "F32": "FLOAT", "F64": "DOUBLE", }
INVERSE_VECTOR_TYPE_ALIASES = {v: k for k, v in VECTOR_TYPE_ALIASES.items()}
class Tokenizer(MySQL.Tokenizer): BYTE_STRINGS = [("e'", "'"), ("E'", "'")]
KEYWORDS = { **MySQL.Tokenizer.KEYWORDS, "BSON": TokenType.JSONB, "GEOGRAPHYPOINT": TokenType.GEOGRAPHYPOINT, "TIMESTAMP": TokenType.TIMESTAMP, "UTC_DATE": TokenType.UTC_DATE, "UTC_TIME": TokenType.UTC_TIME, "UTC_TIMESTAMP": TokenType.UTC_TIMESTAMP, ":>": TokenType.COLON_GT, "!:>": TokenType.NCOLON_GT, "::$": TokenType.DCOLONDOLLAR, "::%": TokenType.DCOLONPERCENT, "::?": TokenType.DCOLONQMARK, "RECORD": TokenType.STRUCT, }
Parser = SingleStoreParser
Generator = SingleStoreGenerator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202from __future__ import annotations
from sqlglot import exp, jsonpath, tokensfrom sqlglot.dialects.dialect import ( Dialect, NormalizationStrategy,)from sqlglot.generators.snowflake import SnowflakeGeneratorfrom sqlglot.parsers.snowflake import ( SnowflakeParser,)from sqlglot.tokens import TokenTypefrom sqlglot.typing.snowflake import EXPRESSION_METADATA
class Snowflake(Dialect): # https://docs.snowflake.com/en/sql-reference/identifiers-syntax NORMALIZATION_STRATEGY = NormalizationStrategy.UPPERCASE # https://docs.snowflake.com/en/sql-reference/data-types-text#escape-sequences UNESCAPED_SEQUENCES = {"\\a": "a", "\\v": "v"} NULL_ORDERING = "nulls_are_large" TIME_FORMAT = "'YYYY-MM-DD HH24:MI:SS'" SUPPORTS_USER_DEFINED_TYPES = False PREFER_CTE_ALIAS_COLUMN = True SUPPORTS_POSITIONAL_COLUMN_REFS = True TABLESAMPLE_SIZE_IS_PERCENT = True COPY_PARAMS_ARE_CSV = False ARRAY_AGG_INCLUDES_NULLS = None ARRAY_FUNCS_PROPAGATES_NULLS = True ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False ALTER_TABLE_DROP_REQUIRED_FOR_EACH_COLUMN = False TRY_CAST_REQUIRES_STRING = True SUPPORTS_ALIAS_REFS_IN_JOIN_CONDITIONS = True LEAST_GREATEST_IGNORES_NULLS = False UUID_IS_STRING_TYPE = True STAR_ILIKE_BACKSLASH_ESCAPE = True
# https://docs.snowflake.com/en/sql-reference/functions/split_to_table DEFAULT_FUNCTIONS_COLUMN_NAMES = { exp.SplitToTable: ("seq", "index", "value"), }
EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
# https://docs.snowflake.com/en/en/sql-reference/functions/initcap INITCAP_DEFAULT_DELIMITER_CHARS = ' \t\n\r\f\v!?@"^#$&~_,.:;+\\-*%/|\\[\\](){}<>'
INVERSE_TIME_MAPPING = { "T": "T", # in TIME_MAPPING we map '"T"' with the double quotes to 'T', and we want to prevent 'T' from being mapped back to '"T"' so that 'AUTO' doesn't become 'AU"T"O' }
TIME_MAPPING = { "YYYY": "%Y", "yyyy": "%Y", "YY": "%y", "yy": "%y", "MMMM": "%B", "mmmm": "%B", "MON": "%b", "mon": "%b", "MM": "%m", "mm": "%m", "DD": "%d", "dd": "%-d", "DY": "%a", "dy": "%w", "HH24": "%H", "hh24": "%H", "HH12": "%I", "hh12": "%I", "MI": "%M", "mi": "%M", "SS": "%S", "ss": "%S", "FF": "%f_nine", # %f_ internal representation with precision specified "ff": "%f_nine", "FF0": "%f_zero", "ff0": "%f_zero", "FF1": "%f_one", "ff1": "%f_one", "FF2": "%f_two", "ff2": "%f_two", "FF3": "%f_three", "ff3": "%f_three", "FF4": "%f_four", "ff4": "%f_four", "FF5": "%f_five", "ff5": "%f_five", "FF6": "%f", "ff6": "%f", "FF7": "%f_seven", "ff7": "%f_seven", "FF8": "%f_eight", "ff8": "%f_eight", "FF9": "%f_nine", "ff9": "%f_nine", "TZHTZM": "%z", "tzhtzm": "%z", "TZH:TZM": "%:z", # internal representation for ±HH:MM "tzh:tzm": "%:z", "TZH": "%-z", # internal representation ±HH "tzh": "%-z", '"T"': "T", # remove the optional double quotes around the separator between the date and time # Seems like Snowflake treats AM/PM in the format string as equivalent, # only the time (stamp) value's AM/PM affects the output "AM": "%p", "am": "%p", "PM": "%p", "pm": "%p", }
DATE_PART_MAPPING = { **Dialect.DATE_PART_MAPPING, "ISOWEEK": "WEEKISO", # The base Dialect maps EPOCH_SECOND -> EPOCH, but we need to preserve # EPOCH_SECOND as a distinct value for two reasons: # 1. Type annotation: EPOCH_SECOND returns BIGINT, while EPOCH returns DOUBLE # 2. Transpilation: DuckDB's EPOCH() returns float, so we cast EPOCH_SECOND # to BIGINT to match Snowflake's integer behavior # Without this override, EXTRACT(EPOCH_SECOND FROM ts) would be normalized # to EXTRACT(EPOCH FROM ts) and lose the integer semantics. "EPOCH_SECOND": "EPOCH_SECOND", "EPOCH_SECONDS": "EPOCH_SECOND", }
PSEUDOCOLUMNS = {"LEVEL"}
def can_quote(self, identifier: exp.Identifier, identify: str | bool = "safe") -> bool: # This disables quoting DUAL in SELECT ... FROM DUAL, because Snowflake treats an # unquoted DUAL keyword in a special way and does not map it to a user-defined table return super().can_quote(identifier, identify) and not ( isinstance(identifier.parent, exp.Table) and not identifier.quoted and identifier.name.lower() == "dual" )
class JSONPathTokenizer(jsonpath.JSONPathTokenizer): SINGLE_TOKENS = jsonpath.JSONPathTokenizer.SINGLE_TOKENS.copy() SINGLE_TOKENS.pop("$")
Parser = SnowflakeParser
class Tokenizer(tokens.Tokenizer): STRING_ESCAPES = ["\\", "'"] NUMERIC_ESCAPES = {"x": (16, 2, 2, 0xFF), "u": (16, 4, 4, 0xFFFF), "0": (8, 1, 3, 0xFF)} DROP_UNKNOWN_ESCAPES = True HEX_STRINGS = [("x'", "'"), ("X'", "'")] RAW_STRINGS = ["$$"] COMMENTS = ["--", "//", ("/*", "*/")] NESTED_COMMENTS = False
KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "(+)": TokenType.JOIN_MARKER, "BYTEINT": TokenType.INT, "FILE://": TokenType.URI_START, "FILE FORMAT": TokenType.FILE_FORMAT, "GET": TokenType.GET, "INTEGRATION": TokenType.INTEGRATION, "LS": TokenType.LIST, "MATCH_CONDITION": TokenType.MATCH_CONDITION, "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, "MINUS": TokenType.EXCEPT, "NCHAR VARYING": TokenType.VARCHAR, "PACKAGE": TokenType.PACKAGE, "POLICY": TokenType.POLICY, "POOL": TokenType.POOL, "PUT": TokenType.PUT, "UNDROP": TokenType.UNDROP, "REMOVE": TokenType.COMMAND, "RM": TokenType.COMMAND, "ROLE": TokenType.ROLE, "RULE": TokenType.RULE, "SAMPLE": TokenType.TABLE_SAMPLE, "SEMANTIC VIEW": TokenType.SEMANTIC_VIEW, "SQL_DOUBLE": TokenType.DOUBLE, "SQL_VARCHAR": TokenType.VARCHAR, "STAGE": TokenType.STAGE, "STORAGE INTEGRATION": TokenType.STORAGE_INTEGRATION, "STREAMLIT": TokenType.STREAMLIT, "TAG": TokenType.TAG, "TIMESTAMP_TZ": TokenType.TIMESTAMPTZ, "TOP": TokenType.TOP, "VOLUME": TokenType.VOLUME, "WAREHOUSE": TokenType.WAREHOUSE, # https://docs.snowflake.com/en/sql-reference/data-types-numeric#float # FLOAT is a synonym for DOUBLE in Snowflake "FLOAT": TokenType.DOUBLE, } KEYWORDS.pop("/*+")
SINGLE_TOKENS = { **tokens.Tokenizer.SINGLE_TOKENS, "$": TokenType.PARAMETER, "!": TokenType.EXCLAMATION, }
VAR_SINGLE_TOKENS = {"$"}
COMMANDS = tokens.Tokenizer.COMMANDS - {TokenType.SHOW}
Generator = SnowflakeGenerator1234567891011121314151617181920from sqlglot import tokensfrom sqlglot.dialects.dialect import Dialect, NormalizationStrategyfrom sqlglot.generators.solr import SolrGeneratorfrom sqlglot.parsers.solr import SolrParser
# https://solr.apache.org/guide/solr/latest/query-guide/sql-query.html
class Solr(Dialect): NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE DPIPE_IS_STRING_CONCAT = False
Generator = SolrGenerator
Parser = SolrParser
class Tokenizer(tokens.Tokenizer): QUOTES = ["'"] IDENTIFIERS = ["`"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647from __future__ import annotations
import typing as t
from sqlglot.dialects.spark2 import Spark2from sqlglot.generators.spark import SparkGeneratorfrom sqlglot.parsers.spark import SparkParserfrom sqlglot.tokens import TokenTypefrom sqlglot.typing.spark import EXPRESSION_METADATA
class Spark(Spark2): SUPPORTS_ORDER_BY_ALL = True SUPPORTS_LIMIT_ALL = True SUPPORTS_NULL_TYPE = True ARRAY_FUNCS_PROPAGATES_NULLS = True EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
# Spark 3+ parses MM/dd/HH/hh/mm/ss strictly, unlike Spark 2 (SimpleDateFormat) TIME_MAPPING = { **Spark2.TIME_MAPPING, "MM": "%mstrict", "dd": "%dstrict", "HH": "%Hstrict", "hh": "%Istrict", "mm": "%Mstrict", "ss": "%Sstrict", }
class Tokenizer(Spark2.Tokenizer): NUMERIC_ESCAPES = {"u": (16, 4, 4, 0xFFFF), "U": (16, 8, 8, 0x10FFFF), "0": (8, 3, 3, 0x7F)} STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = False
RAW_STRINGS = [ (prefix + q, q) for q in t.cast(list[str], Spark2.Tokenizer.QUOTES) for prefix in ("r", "R") ]
KEYWORDS = { **Spark2.Tokenizer.KEYWORDS, "DECLARE": TokenType.DECLARE, }
Parser = SparkParser
Generator = SparkGenerator1234567891011121314151617181920212223242526272829303132333435363738394041from __future__ import annotations
from sqlglot.dialects.hive import Hivefrom sqlglot.generators.spark2 import Spark2Generatorfrom sqlglot.parsers.spark2 import Spark2Parserfrom sqlglot.tokens import TokenTypefrom sqlglot.typing.spark2 import EXPRESSION_METADATA
class Spark2(Hive): ALTER_TABLE_SUPPORTS_CASCADE = False
EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
# Spark 2.x parses MM/dd/HH/hh/mm/ss leniently (SimpleDateFormat), unlike strict Hive/Spark 3+ TIME_MAPPING = { **Hive.TIME_MAPPING, "MM": "%m", "dd": "%d", "HH": "%H", "hh": "%I", "mm": "%M", "ss": "%S", }
# https://spark.apache.org/docs/latest/api/sql/index.html#initcap # https://docs.databricks.com/aws/en/sql/language-manual/functions/initcap # https://github.com/apache/spark/blob/master/common/unsafe/src/main/java/org/apache/spark/unsafe/types/UTF8String.java#L859-L905 INITCAP_DEFAULT_DELIMITER_CHARS = " "
class Tokenizer(Hive.Tokenizer): HEX_STRINGS = [("X'", "'"), ("x'", "'")]
KEYWORDS = { **Hive.Tokenizer.KEYWORDS, "TIMESTAMP": TokenType.TIMESTAMPTZ, }
Parser = Spark2Parser
Generator = Spark2Generator12345678910111213141516171819202122232425262728293031323334353637383940414243444546from __future__ import annotations
from sqlglot import tokensfrom sqlglot.dialects.dialect import ( Dialect, NormalizationStrategy, UsingColumnOrder,)from sqlglot.generators.sqlite import SQLiteGeneratorfrom sqlglot.parsers.sqlite import SQLiteParserfrom sqlglot.tokens import TokenType
class SQLite(Dialect): # https://sqlite.org/forum/forumpost/5e575586ac5c711b?raw NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE ASCII_ONLY_NORMALIZATION = True TYPED_DIVISION = True SAFE_DIVISION = True SAFE_TO_ELIMINATE_DOUBLE_NEGATION = False USING_COLUMN_ORDER = UsingColumnOrder.IN_PLACE CONCAT_COALESCE = True CONCAT_WS_COALESCE = True
class Tokenizer(tokens.Tokenizer): IDENTIFIERS = ['"', ("[", "]"), "`"] HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", ""), ("0X", "")]
NESTED_COMMENTS = False COMMENTS_TERMINATE_AT_NEWLINE_ONLY = True
KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "ATTACH": TokenType.ATTACH, "DETACH": TokenType.DETACH, "INDEXED BY": TokenType.INDEXED_BY, "MATCH": TokenType.MATCH, }
KEYWORDS.pop("/*+")
COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.REPLACE}
Parser = SQLiteParser
Generator = SQLiteGenerator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051from __future__ import annotations
from sqlglot import expfrom sqlglot.dialects.dialect import UsingColumnOrderfrom sqlglot.dialects.mysql import MySQLfrom sqlglot.generators.starrocks import StarRocksGeneratorfrom sqlglot.parsers.starrocks import StarRocksParserfrom sqlglot.tokens import TokenType
class StarRocks(MySQL): STRICT_JSON_PATH_SYNTAX = False INDEX_OFFSET = 1 USING_COLUMN_ORDER = UsingColumnOrder.USING_LIST
DEFAULT_FUNCTIONS_COLUMN_NAMES = { exp.GenerateSeries: "generate_series", }
class Tokenizer(MySQL.Tokenizer): # Unlike MySQL, "#" doesn't start a comment COMMENTS = ["--", ("/*", "*/")] DASH_COMMENT_REQUIRES_BOUNDARY = False COMMENTS_TERMINATE_AT_NEWLINE_ONLY = False
KEYWORDS = { **MySQL.Tokenizer.KEYWORDS, "ADMIN": TokenType.COMMAND, "BACKUP": TokenType.COMMAND, "CANCEL": TokenType.COMMAND, "DEALLOCATE": TokenType.COMMAND, "EXPORT": TokenType.COMMAND, "HLL": TokenType.HLLSKETCH, "INSTALL": TokenType.COMMAND, "LARGEINT": TokenType.INT128, "PAUSE": TokenType.COMMAND, "RECOVER": TokenType.COMMAND, "REFRESH": TokenType.REFRESH, "RESTORE": TokenType.COMMAND, "RESUME": TokenType.COMMAND, "STOP": TokenType.COMMAND, "SUBMIT": TokenType.COMMAND, "UNINSTALL": TokenType.COMMAND, } KEYWORDS.pop("IGNORE") KEYWORDS.pop("#>") KEYWORDS.pop("#>>")
Parser = StarRocksParser
Generator = StarRocksGenerator123456789101112131415161718from __future__ import annotations
from sqlglot import tokensfrom sqlglot.dialects.dialect import Dialectfrom sqlglot.generators.tableau import TableauGeneratorfrom sqlglot.parsers.tableau import TableauParser
class Tableau(Dialect): LOG_BASE_FIRST = False
class Tokenizer(tokens.Tokenizer): IDENTIFIERS = [("[", "]")] QUOTES = ["'", '"']
Generator = TableauGenerator
Parser = TableauParser123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081from __future__ import annotations
from sqlglot import tokensfrom sqlglot.dialects.dialect import Dialectfrom sqlglot.generators.teradata import TeradataGeneratorfrom sqlglot.parsers.teradata import TeradataParserfrom sqlglot.tokens import TokenType
class Teradata(Dialect): TYPED_DIVISION = True
TIME_MAPPING = { "YY": "%y", "Y4": "%Y", "YYYY": "%Y", "M4": "%B", "M3": "%b", "M": "%-M", "MI": "%M", "MM": "%m", "MMM": "%b", "MMMM": "%B", "D": "%-d", "DD": "%d", "D3": "%j", "DDD": "%j", "H": "%-H", "HH": "%H", "HH24": "%H", "S": "%-S", "SS": "%S", "SSSSSS": "%f", "E": "%a", "EE": "%a", "E3": "%a", "E4": "%A", "EEE": "%a", "EEEE": "%A", }
class Tokenizer(tokens.Tokenizer): # Tested each of these and they work, although there is no # Teradata documentation explicitly mentioning them. HEX_STRINGS = [("X'", "'"), ("x'", "'"), ("0x", "")] # https://docs.teradata.com/r/Teradata-Database-SQL-Functions-Operators-Exprs-and-Predicates/March-2017/Comparison-Operators-and-Functions/Comparison-Operators/ANSI-Compliance # https://docs.teradata.com/r/SQL-Functions-Operators-Exprs-and-Predicates/June-2017/Arithmetic-Trigonometric-Hyperbolic-Operators/Functions KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "**": TokenType.DSTAR, "^=": TokenType.NEQ, "BYTEINT": TokenType.SMALLINT, "COLLECT": TokenType.COMMAND, "DEL": TokenType.DELETE, "EQ": TokenType.EQ, "GE": TokenType.GTE, "GT": TokenType.GT, "HELP": TokenType.COMMAND, "INS": TokenType.INSERT, "LE": TokenType.LTE, "LOCKING": TokenType.LOCK, "LT": TokenType.LT, "MINUS": TokenType.EXCEPT, "MOD": TokenType.MOD, "NE": TokenType.NEQ, "NOT=": TokenType.NEQ, "SAMPLE": TokenType.TABLE_SAMPLE, "SEL": TokenType.SELECT, "ST_GEOMETRY": TokenType.GEOMETRY, "TOP": TokenType.TOP, "UPD": TokenType.UPDATE, } KEYWORDS.pop("/*+")
# Teradata does not support % as a modulo operator SINGLE_TOKENS = {**tokens.Tokenizer.SINGLE_TOKENS} SINGLE_TOKENS.pop("%")
Parser = TeradataParser
Generator = TeradataGenerator1234567891011121314151617181920212223242526from __future__ import annotations
from sqlglot.dialects.presto import Prestofrom sqlglot.generators.trino import TrinoGeneratorfrom sqlglot.parsers.trino import TrinoParserfrom sqlglot.tokens import TokenType
class Trino(Presto): SUPPORTS_USER_DEFINED_TYPES = False LOG_BASE_FIRST = True CONCAT_WS_COALESCE = True
class Tokenizer(Presto.Tokenizer): KEYWORDS = { **Presto.Tokenizer.KEYWORDS, "REFRESH": TokenType.REFRESH, "DECLARE": TokenType.DECLARE, } # Trino has no `SQL SECURITY` clause, only bare `SECURITY DEFINER`/`INVOKER`; # the merged base keyword otherwise eats the `SQL` in `LANGUAGE SQL SECURITY DEFINER`. KEYWORDS.pop("SQL SECURITY")
Parser = TrinoParser
Generator = TrinoGenerator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196from __future__ import annotations
from sqlglot import tokensfrom sqlglot.dialects.dialect import ( Dialect, NormalizationStrategy,)from sqlglot.generators.tsql import TSQLGeneratorfrom sqlglot.parsers.tsql import TSQLParserfrom sqlglot.tokens import TokenTypefrom sqlglot.typing.tsql import EXPRESSION_METADATA
class TSQL(Dialect): # Week truncation follows @@DATEFIRST, which defaults to 7 (Sunday) WEEK_OFFSET = -1
LOG_BASE_FIRST = False TYPED_DIVISION = True CONCAT_COALESCE = True CONCAT_WS_COALESCE = True JSON_EXTRACT_SCALAR_SCALAR_ONLY = True NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False ALTER_TABLE_DROP_REQUIRED_FOR_EACH_COLUMN = False
TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
DATE_PART_MAPPING = { **Dialect.DATE_PART_MAPPING, "QQ": "QUARTER", "M": "MONTH", "Y": "DAYOFYEAR", "WW": "WEEK", "N": "MINUTE", "SS": "SECOND", "MCS": "MICROSECOND", "TZOFFSET": "TIMEZONE_MINUTE", "TZ": "TIMEZONE_MINUTE", "ISO_WEEK": "WEEKISO", "ISOWK": "WEEKISO", "ISOWW": "WEEKISO", }
TIME_MAPPING = { "year": "%Y", "dayofyear": "%j", "day": "%d", "dy": "%d", "y": "%Y", "week": "%W", "ww": "%W", "wk": "%W", "isowk": "%V", "isoww": "%V", "iso_week": "%V", "hour": "%h", "hh": "%I", "minute": "%M", "mi": "%M", "n": "%M", "second": "%S", "ss": "%S", "s": "%-S", "millisecond": "%f", "ms": "%f", "weekday": "%w", "dw": "%w", "month": "%m", "mm": "%M", "m": "%-M", "Y": "%Y", "YYYY": "%Y", "YY": "%y", "MMMM": "%B", "MMM": "%b", "MM": "%m", "M": "%-m", "dddd": "%A", "dd": "%d", "d": "%-d", "HH": "%H", "H": "%-H", "h": "%-I", "ffffff": "%f", "yyyy": "%Y", "yy": "%y", }
CONVERT_FORMAT_MAPPING = { "0": "%b %d %Y %-I:%M%p", "1": "%m/%d/%y", "2": "%y.%m.%d", "3": "%d/%m/%y", "4": "%d.%m.%y", "5": "%d-%m-%y", "6": "%d %b %y", "7": "%b %d, %y", "8": "%H:%M:%S", "9": "%b %d %Y %-I:%M:%S:%f%p", "10": "mm-dd-yy", "11": "yy/mm/dd", "12": "yymmdd", "13": "%d %b %Y %H:%M:ss:%f", "14": "%H:%M:%S:%f", "20": "%Y-%m-%d %H:%M:%S", "21": "%Y-%m-%d %H:%M:%S.%f", "22": "%m/%d/%y %-I:%M:%S %p", "23": "%Y-%m-%d", "24": "%H:%M:%S", "25": "%Y-%m-%d %H:%M:%S.%f", "100": "%b %d %Y %-I:%M%p", "101": "%m/%d/%Y", "102": "%Y.%m.%d", "103": "%d/%m/%Y", "104": "%d.%m.%Y", "105": "%d-%m-%Y", "106": "%d %b %Y", "107": "%b %d, %Y", "108": "%H:%M:%S", "109": "%b %d %Y %-I:%M:%S:%f%p", "110": "%m-%d-%Y", "111": "%Y/%m/%d", "112": "%Y%m%d", "113": "%d %b %Y %H:%M:%S:%f", "114": "%H:%M:%S:%f", "120": "%Y-%m-%d %H:%M:%S", "121": "%Y-%m-%d %H:%M:%S.%f", "126": "%Y-%m-%dT%H:%M:%S.%f", }
FORMAT_TIME_MAPPING = { "y": "%B %Y", "d": "%m/%d/%Y", "H": "%-H", "h": "%-I", "s": "%Y-%m-%d %H:%M:%S", "D": "%A,%B,%Y", "f": "%A,%B,%Y %-I:%M %p", "F": "%A,%B,%Y %-I:%M:%S %p", "g": "%m/%d/%Y %-I:%M %p", "G": "%m/%d/%Y %-I:%M:%S %p", "M": "%B %-d", "m": "%B %-d", "O": "%Y-%m-%dT%H:%M:%S", "u": "%Y-%M-%D %H:%M:%S%z", "U": "%A, %B %D, %Y %H:%M:%S%z", "T": "%-I:%M:%S %p", "t": "%-I:%M", "Y": "%a %Y", }
class Tokenizer(tokens.Tokenizer): IDENTIFIERS = [("[", "]"), '"'] QUOTES = ["'", '"'] HEX_STRINGS = [("0x", ""), ("0X", "")] VAR_SINGLE_TOKENS = {"@", "$", "#"}
KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "CLUSTERED INDEX": TokenType.INDEX, "DATETIME2": TokenType.DATETIME2, "DATETIMEOFFSET": TokenType.TIMESTAMPTZ, "DECLARE": TokenType.DECLARE, "EXEC": TokenType.EXECUTE, "GO": TokenType.COMMAND, "IMAGE": TokenType.IMAGE, "MONEY": TokenType.MONEY, "NONCLUSTERED INDEX": TokenType.INDEX, "NTEXT": TokenType.TEXT, "OPTION": TokenType.OPTION, "OUTPUT": TokenType.RETURNING, "PRINT": TokenType.COMMAND, "PROC": TokenType.PROCEDURE, "REAL": TokenType.FLOAT, "ROWVERSION": TokenType.ROWVERSION, "SMALLDATETIME": TokenType.SMALLDATETIME, "SMALLMONEY": TokenType.SMALLMONEY, "SQL_VARIANT": TokenType.VARIANT, "SYSTEM_USER": TokenType.CURRENT_USER, "TOP": TokenType.TOP, "TIMESTAMP": TokenType.ROWVERSION, "TINYINT": TokenType.UTINYINT, "UNIQUEIDENTIFIER": TokenType.UUID, "UPDATE STATISTICS": TokenType.COMMAND, "XML": TokenType.XML, } KEYWORDS.pop("/*+")
COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.END} - {TokenType.EXECUTE}
Parser = TSQLParser
Generator = TSQLGenerator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447""".. include:: ../posts/sql_diff.md
----"""
from __future__ import annotations
import typing as tfrom collections import defaultdictfrom dataclasses import dataclassfrom heapq import heappop, heappushfrom itertools import chain
from sqlglot import Dialect, expressions as expfrom sqlglot.helper import seq_get
if t.TYPE_CHECKING: from collections.abc import Iterator, Sequence from sqlglot.dialects.dialect import DialectType
@dataclass(frozen=True)class Insert: """Indicates that a new node has been inserted"""
expression: exp.Expr
@dataclass(frozen=True)class Remove: """Indicates that an existing node has been removed"""
expression: exp.Expr
@dataclass(frozen=True)class Move: """Indicates that an existing node's position within the tree has changed"""
source: exp.Expr target: exp.Expr
@dataclass(frozen=True)class Update: """Indicates that an existing node has been updated"""
source: exp.Expr target: exp.Expr
@dataclass(frozen=True)class Keep: """Indicates that an existing node hasn't been changed"""
source: exp.Expr target: exp.Expr
if t.TYPE_CHECKING: from sqlglot._typing import T
Edit = t.Union[Insert, Remove, Move, Update, Keep]
def diff( source: exp.Expr, target: exp.Expr, matchings: list[tuple[exp.Expr, exp.Expr]] | None = None, delta_only: bool = False, **kwargs: t.Any,) -> list[Edit]: """ Returns the list of changes between the source and the target expressions.
Examples: >>> from sqlglot import parse_one >>> diff(parse_one("a + b"), parse_one("a + c")) # doctest: +SKIP [...]
Args: source: the source expression. target: the target expression against which the diff should be calculated. matchings: the list of pre-matched node pairs which is used to help the algorithm's heuristics produce better results for subtrees that are known by a caller to be matching. Note: expression references in this list must refer to the same node objects that are referenced in the source / target trees. delta_only: excludes all `Keep` nodes from the diff. kwargs: additional arguments to pass to the ChangeDistiller instance.
Returns: the list of Insert, Remove, Move, Update and Keep objects for each node in the source and the target expression trees. This list represents a sequence of steps needed to transform the source expression tree into the target one. """ matchings = matchings or []
def compute_node_mappings( old_nodes: tuple[exp.Expr, ...], new_nodes: tuple[exp.Expr, ...] ) -> dict[int, exp.Expr]: node_mapping = {} for old_node, new_node in zip(reversed(old_nodes), reversed(new_nodes)): new_node._hash = hash(new_node) node_mapping[id(old_node)] = new_node
return node_mapping
# if the source and target have any shared objects, that means there's an issue with the ast # the algorithm won't work because the parent / hierarchies will be inaccurate source_nodes = tuple(source.walk()) target_nodes = tuple(target.walk()) source_ids = {id(n) for n in source_nodes} target_ids = {id(n) for n in target_nodes}
copy = ( len(source_nodes) != len(source_ids) or len(target_nodes) != len(target_ids) or source_ids & target_ids )
source_copy = source.copy() if copy else source target_copy = target.copy() if copy else target
try: # We cache the hash of each new node here to speed up equality comparisons. If the input # trees aren't copied, these hashes will be evicted before returning the edit script. if copy and matchings: source_mapping = compute_node_mappings(source_nodes, tuple(source_copy.walk())) target_mapping = compute_node_mappings(target_nodes, tuple(target_copy.walk())) matchings = [(source_mapping[id(s)], target_mapping[id(t)]) for s, t in matchings] else: for node in chain(reversed(source_nodes), reversed(target_nodes)): node._hash = hash(node)
edit_script = ChangeDistiller(**kwargs).diff( source_copy, target_copy, matchings=matchings, delta_only=delta_only, ) finally: if not copy: for node in chain(source_nodes, target_nodes): node._hash = None
return edit_script
# The expression types for which Update edits are allowed.UPDATABLE_EXPRESSION_TYPES = ( exp.Alias, exp.Boolean, exp.Column, exp.DataType, exp.Lambda, exp.Literal, exp.Table, exp.Window,)
IGNORED_LEAF_EXPRESSION_TYPES = (exp.Identifier,)
class ChangeDistiller: """ The implementation of the Change Distiller algorithm described by Beat Fluri and Martin Pinzger in their paper https://ieeexplore.ieee.org/document/4339230, which in turn is based on the algorithm by Chawathe et al. described in http://ilpubs.stanford.edu:8090/115/1/1995-46.pdf. """
def __init__(self, f: float = 0.6, t: float = 0.6, dialect: DialectType = None) -> None: self.f = f self.t = t self._sql_generator = Dialect.get_or_raise(dialect).generator(comments=False)
def diff( self, source: exp.Expr, target: exp.Expr, matchings: list[tuple[exp.Expr, exp.Expr]] | None = None, delta_only: bool = False, ) -> list[Edit]: matchings = matchings or [] pre_matched_nodes = {id(s): id(t) for s, t in matchings}
self._source = source self._target = target self._source_index = { id(n): n for n in self._source.bfs() if not isinstance(n, IGNORED_LEAF_EXPRESSION_TYPES) } self._target_index = { id(n): n for n in self._target.bfs() if not isinstance(n, IGNORED_LEAF_EXPRESSION_TYPES) } self._unmatched_source_nodes = set(self._source_index) - set(pre_matched_nodes) self._unmatched_target_nodes = set(self._target_index) - set(pre_matched_nodes.values()) self._bigram_histo_cache: dict[int, defaultdict[str, int]] = {}
matching_set = self._compute_matching_set() | set(pre_matched_nodes.items()) return self._generate_edit_script(dict(matching_set), delta_only)
def _generate_edit_script(self, matchings: dict[int, int], delta_only: bool) -> list[Edit]: edit_script: list[Edit] = [] for removed_node_id in self._unmatched_source_nodes: edit_script.append(Remove(self._source_index[removed_node_id])) for inserted_node_id in self._unmatched_target_nodes: edit_script.append(Insert(self._target_index[inserted_node_id])) for kept_source_node_id, kept_target_node_id in matchings.items(): source_node = self._source_index[kept_source_node_id] target_node = self._target_index[kept_target_node_id]
identical_nodes = source_node == target_node
if not isinstance(source_node, UPDATABLE_EXPRESSION_TYPES) or identical_nodes: if identical_nodes: source_parent = source_node.parent target_parent = target_node.parent
if ( (source_parent and not target_parent) or (not source_parent and target_parent) or ( source_parent and target_parent and matchings.get(id(source_parent)) != id(target_parent) ) ): edit_script.append(Move(source=source_node, target=target_node)) else: edit_script.extend( self._generate_move_edits(source_node, target_node, matchings) )
source_non_expression_leaves = dict(_get_non_expression_leaves(source_node)) target_non_expression_leaves = dict(_get_non_expression_leaves(target_node))
if source_non_expression_leaves != target_non_expression_leaves: edit_script.append(Update(source_node, target_node)) elif not delta_only: edit_script.append(Keep(source_node, target_node)) else: edit_script.append(Update(source_node, target_node))
return edit_script
def _generate_move_edits( self, source: exp.Expr, target: exp.Expr, matchings: dict[int, int] ) -> list[Move]: source_args = [id(e) for e in _expression_only_args(source)] target_args = [id(e) for e in _expression_only_args(target)]
args_lcs = set( _lcs(source_args, target_args, lambda l, r: matchings.get(t.cast(int, l)) == r) )
move_edits = [] for a in source_args: if a not in args_lcs and a not in self._unmatched_source_nodes: move_edits.append( Move(source=self._source_index[a], target=self._target_index[matchings[a]]) )
return move_edits
def _compute_matching_set(self) -> set[tuple[int, int]]: leaves_matching_set = self._compute_leaf_matching_set() matching_set = leaves_matching_set.copy()
ordered_unmatched_source_nodes = { id(n): None for n in self._source.bfs() if id(n) in self._unmatched_source_nodes } ordered_unmatched_target_nodes = { id(n): None for n in self._target.bfs() if id(n) in self._unmatched_target_nodes }
for source_node_id in ordered_unmatched_source_nodes: for target_node_id in ordered_unmatched_target_nodes: source_node = self._source_index[source_node_id] target_node = self._target_index[target_node_id] if _is_same_type(source_node, target_node): source_leaf_ids = {id(l) for l in _get_expression_leaves(source_node)} target_leaf_ids = {id(l) for l in _get_expression_leaves(target_node)}
max_leaves_num = max(len(source_leaf_ids), len(target_leaf_ids)) if max_leaves_num: common_leaves_num = sum( 1 if s in source_leaf_ids and t in target_leaf_ids else 0 for s, t in leaves_matching_set ) leaf_similarity_score = common_leaves_num / max_leaves_num else: leaf_similarity_score = 0.0
adjusted_t = ( self.t if min(len(source_leaf_ids), len(target_leaf_ids)) > 4 else 0.4 )
if leaf_similarity_score >= 0.8 or ( leaf_similarity_score >= adjusted_t and self._dice_coefficient(source_node, target_node) >= self.f ): matching_set.add((source_node_id, target_node_id)) self._unmatched_source_nodes.remove(source_node_id) self._unmatched_target_nodes.remove(target_node_id) ordered_unmatched_target_nodes.pop(target_node_id, None) break
return matching_set
def _compute_leaf_matching_set(self) -> set[tuple[int, int]]: candidate_matchings: list[tuple[float, int, int, exp.Expr, exp.Expr]] = [] source_expression_leaves = list(_get_expression_leaves(self._source)) target_expression_leaves = list(_get_expression_leaves(self._target)) for source_leaf in source_expression_leaves: for target_leaf in target_expression_leaves: if _is_same_type(source_leaf, target_leaf): similarity_score = self._dice_coefficient(source_leaf, target_leaf) if similarity_score >= self.f: heappush( candidate_matchings, ( -similarity_score, -_parent_similarity_score(source_leaf, target_leaf), len(candidate_matchings), source_leaf, target_leaf, ), )
# Pick best matchings based on the highest score matching_set = set() while candidate_matchings: _, _, _, source_leaf, target_leaf = heappop(candidate_matchings) if ( id(source_leaf) in self._unmatched_source_nodes and id(target_leaf) in self._unmatched_target_nodes ): matching_set.add((id(source_leaf), id(target_leaf))) self._unmatched_source_nodes.remove(id(source_leaf)) self._unmatched_target_nodes.remove(id(target_leaf))
return matching_set
def _dice_coefficient(self, source: exp.Expr, target: exp.Expr) -> float: source_histo = self._bigram_histo(source) target_histo = self._bigram_histo(target)
total_grams = sum(source_histo.values()) + sum(target_histo.values()) if not total_grams: return 1.0 if source == target else 0.0
overlap_len = 0 overlapping_grams = set(source_histo) & set(target_histo) for g in overlapping_grams: overlap_len += min(source_histo[g], target_histo[g])
return 2 * overlap_len / total_grams
def _bigram_histo(self, expression: exp.Expr) -> defaultdict[str, int]: if id(expression) in self._bigram_histo_cache: return self._bigram_histo_cache[id(expression)]
expression_str = self._sql_generator.generate(expression) count = max(0, len(expression_str) - 1) bigram_histo: defaultdict[str, int] = defaultdict(int) for i in range(count): bigram_histo[expression_str[i : i + 2]] += 1
self._bigram_histo_cache[id(expression)] = bigram_histo return bigram_histo
def _get_expression_leaves(expression: exp.Expr) -> Iterator[exp.Expr]: has_child_exprs = False
for node in expression.iter_expressions(): if not isinstance(node, IGNORED_LEAF_EXPRESSION_TYPES): has_child_exprs = True yield from _get_expression_leaves(node)
if not has_child_exprs: yield expression
def _get_non_expression_leaves(expression: exp.Expr) -> Iterator[tuple[str, t.Any]]: for arg, value in expression.args.items(): if ( value is None or isinstance(value, exp.Expr) or (isinstance(value, list) and isinstance(seq_get(value, 0), exp.Expr)) ): continue
yield (arg, value)
def _is_same_type(source: exp.Expr, target: exp.Expr) -> bool: if type(source) is type(target): if isinstance(source, exp.Join): return source.args.get("side") == target.args.get("side")
if isinstance(source, exp.Anonymous): return source.this == target.this
return True
return False
def _parent_similarity_score(source: exp.Expr | None, target: exp.Expr | None) -> int: if source is None or target is None or type(source) is not type(target): return 0
return 1 + _parent_similarity_score(source.parent, target.parent)
def _expression_only_args(expression: exp.Expr) -> Iterator[exp.Expr]: yield from ( arg for arg in expression.iter_expressions() if not isinstance(arg, IGNORED_LEAF_EXPRESSION_TYPES) )
def _lcs( seq_a: Sequence[T], seq_b: Sequence[T], equal: t.Callable[[T, T], bool]) -> Sequence[T | None]: """Calculates the longest common subsequence"""
len_a = len(seq_a) len_b = len(seq_b) lcs_result = [[None] * (len_b + 1) for i in range(len_a + 1)]
for i in range(len_a + 1): for j in range(len_b + 1): if i == 0 or j == 0: lcs_result[i][j] = [] # type: ignore elif equal(seq_a[i - 1], seq_b[j - 1]): lcs_result[i][j] = lcs_result[i - 1][j - 1] + [seq_a[i - 1]] # type: ignore else: lcs_result[i][j] = ( lcs_result[i - 1][j] if len(lcs_result[i - 1][j]) > len(lcs_result[i][j - 1]) # type: ignore else lcs_result[i][j - 1] )
return lcs_result[len_a][len_b] # type: ignore123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176from __future__ import annotations
import typing as tfrom enum import autofrom collections.abc import Sequencefrom sqlglot.helper import AutoName
# ANSI escape codes for error formattingANSI_UNDERLINE = "\033[4m"ANSI_RESET = "\033[0m"ERROR_MESSAGE_CONTEXT_DEFAULT = 100
class ErrorLevel(AutoName): IGNORE = auto() """Ignore all errors."""
WARN = auto() """Log all errors."""
RAISE = auto() """Collect all errors and raise a single exception."""
IMMEDIATE = auto() """Immediately raise an exception on the first error found."""
class SqlglotError(Exception): pass
class UnsupportedError(SqlglotError): pass
class ParseError(SqlglotError): def __init__( self, message: str, errors: list[dict[str, t.Any]] | None = None, ): super().__init__(message) self.errors = errors or []
@classmethod def new( cls, message: str, description: str | None = None, line: int | None = None, col: int | None = None, start_context: str | None = None, highlight: str | None = None, end_context: str | None = None, into_expression: str | None = None, ) -> ParseError: return cls( message, [ { "description": description, "line": line, "col": col, "start_context": start_context, "highlight": highlight, "end_context": end_context, "into_expression": into_expression, } ], )
class TokenError(SqlglotError): """Error raised when tokenizing fails.
When available, `start` and `end` are the offsets in the source SQL of the context snippet quoted in the message, i.e. the snippet is `sql[start:end]`. """
def __init__( self, message: str, start: int | None = None, end: int | None = None, ): super().__init__(message) self.start = start self.end = end
class OptimizeError(SqlglotError): pass
class SchemaError(SqlglotError): pass
class ExecuteError(SqlglotError): pass
def highlight_sql( sql: str, positions: list[tuple[int, int]], context_length: int = ERROR_MESSAGE_CONTEXT_DEFAULT,) -> tuple[str, str, str, str]: """ Highlight a SQL string using ANSI codes at the given positions.
Args: sql: The complete SQL string. positions: List of (start, end) tuples where both start and end are inclusive 0-based indexes. For example, to highlight "foo" in "SELECT foo", use (7, 9). The positions will be sorted and de-duplicated if they overlap. context_length: Number of characters to show before the first highlight and after the last highlight.
Returns: A tuple of (formatted_sql, start_context, highlight, end_context) where: - formatted_sql: The SQL with ANSI underline codes applied to highlighted sections - start_context: Plain text before the first highlight - highlight: Plain text from the first highlight start to the last highlight end, including any non-highlighted text in between (no ANSI) - end_context: Plain text after the last highlight
Note: If positions is empty, raises a ValueError. """ if not positions: raise ValueError("positions must contain at least one (start, end) tuple")
start_context = "" end_context = "" first_highlight_start = 0 formatted_parts = [] previous_part_end = 0 sorted_positions = sorted(positions, key=lambda pos: pos[0])
if sorted_positions[0][0] > 0: first_highlight_start = sorted_positions[0][0] start_context = sql[max(0, first_highlight_start - context_length) : first_highlight_start] formatted_parts.append(start_context) previous_part_end = first_highlight_start
for start, end in sorted_positions: highlight_start = max(start, previous_part_end) highlight_end = end + 1 if highlight_start >= highlight_end: continue # Skip invalid or overlapping highlights if highlight_start > previous_part_end: formatted_parts.append(sql[previous_part_end:highlight_start]) formatted_parts.append(f"{ANSI_UNDERLINE}{sql[highlight_start:highlight_end]}{ANSI_RESET}") previous_part_end = highlight_end
if previous_part_end < len(sql): end_context = sql[previous_part_end : previous_part_end + context_length] formatted_parts.append(end_context)
formatted_sql = "".join(formatted_parts) highlight = sql[first_highlight_start:previous_part_end]
return formatted_sql, start_context, highlight, end_context
def concat_messages(errors: Sequence[t.Any], maximum: int) -> str: msg = [str(e) for e in errors[:maximum]] remaining = len(errors) - maximum if remaining > 0: msg.append(f"... and {remaining} more") return "\n\n".join(msg)
def merge_errors(errors: Sequence[ParseError]) -> list[dict[str, t.Any]]: return [e_dict for error in errors for e_dict in error.errors]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990""".. include:: ../../posts/python_sql_engine.md
----"""
from __future__ import annotations
import loggingimport timeimport typing as t
from sqlglot import expfrom sqlglot.errors import ExecuteErrorfrom sqlglot.executor.python import PythonExecutorfrom sqlglot.executor.table import Table, ensure_tablesfrom sqlglot.helper import dict_depthfrom sqlglot.optimizer import optimizefrom sqlglot.optimizer.annotate_types import annotate_typesfrom sqlglot.planner import Planfrom sqlglot.schema import ensure_schema, flatten_schema, nested_get, nested_set
logger = logging.getLogger("sqlglot")
if t.TYPE_CHECKING: from sqlglot.dialects.dialect import DialectType from sqlglot.expressions import Expr from sqlglot.schema import Schema
def execute( sql: str | Expr, schema: dict | Schema | None = None, dialect: DialectType = None, tables: dict | None = None,) -> Table: """ Run a sql query against data.
Args: sql: a sql statement. schema: database schema. This can either be an instance of `Schema` or a mapping in one of the following forms: 1. {table: {col: type}} 2. {db: {table: {col: type}}} 3. {catalog: {db: {table: {col: type}}}} dialect: the SQL dialect to apply during parsing (eg. "spark", "hive", "presto", "mysql"). tables: additional tables to register.
Returns: Simple columnar data structure. """ tables_ = ensure_tables(tables, dialect=dialect)
if not schema: schema = {} flattened_tables = flatten_schema(tables_.mapping, depth=dict_depth(tables_.mapping))
for keys in flattened_tables: table = nested_get(tables_.mapping, *zip(keys, keys)) assert table is not None
for column in table.columns: value = table[0][column] column_type = ( annotate_types(exp.convert(value), dialect=dialect).type or type(value).__name__ ) nested_set(schema, [*keys, column], column_type)
schema = ensure_schema(schema, dialect=dialect)
if tables_.supported_table_args and tables_.supported_table_args != schema.supported_table_args: raise ExecuteError("Tables must support the same table args as schema")
now = time.time() expression = optimize(sql, schema, leave_tables_isolated=True, dialect=dialect)
logger.debug("Optimization finished: %f", time.time() - now) logger.debug("Optimized SQL: %s", expression.sql(pretty=True))
plan = Plan(expression)
logger.debug("Logical Plan: %s", plan)
now = time.time() result = PythonExecutor(tables=tables_).execute(plan)
logger.debug("Query finished: %f", time.time() - now)
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112from __future__ import annotations
import typing as t
from sqlglot.executor.env import ENV
if t.TYPE_CHECKING: from sqlglot.executor.table import Table, TableIter
class Context: """ Execution context for sql expressions.
Context is used to hold relevant data tables which can then be queried on with eval.
References to columns can either be scalar or vectors. When set_row is used, column references evaluate to scalars while set_range evaluates to vectors. This allows convenient and efficient evaluation of aggregation functions. """
def __init__( self, tables: dict[str, Table], env: dict | None = None, outer: dict | None = None ) -> None: """ Args tables: representing the scope of the current execution context. env: dictionary of functions within the execution context. outer: readers of an enclosing query, for a subquery run once per outer row. Own tables shadow them, as an inner alias shadows an outer one in SQL. """ self.tables = tables self._table: Table | None = None range_readers = {name: table.range_reader for name, table in self.tables.items()} row_readers = {name: table.reader for name, table in tables.items()}
if outer: range_readers = {**outer, **range_readers} row_readers = {**outer, **row_readers}
self.range_readers = range_readers self.row_readers = row_readers self.env = {**ENV, **(env or {}), "scope": self.row_readers}
def eval(self, code): return eval(code, self.env)
def eval_tuple(self, codes): return tuple(self.eval(code) for code in codes)
@property def table(self) -> Table: if self._table is None: self._table = list(self.tables.values())[0]
for other in self.tables.values(): if self._table.columns != other.columns: raise Exception("Columns are different.") if len(self._table.rows) != len(other.rows): raise Exception("Rows are different.")
return self._table
def add_columns(self, *columns: str) -> None: for table in self.tables.values(): table.add_columns(*columns)
@property def columns(self) -> tuple: return self.table.columns if self.tables else ()
def __iter__(self): self.env["scope"] = self.row_readers for i in range(len(self.table.rows)): for table in self.tables.values(): reader = table[i] yield reader, self
def table_iter(self, table: str) -> TableIter: self.env["scope"] = self.row_readers return iter(self.tables[table])
def filter(self, condition) -> None: rows = [reader.row for reader, _ in self if self.eval(condition)]
for table in self.tables.values(): table.rows = rows
def sort(self, key) -> None: def sort_key(row: tuple) -> tuple: self.set_row(row) return tuple((t is None, t) for t in self.eval_tuple(key))
self.table.rows.sort(key=sort_key)
def set_row(self, row: tuple) -> None: for table in self.tables.values(): table.reader.row = row self.env["scope"] = self.row_readers
def set_index(self, index: int) -> None: for table in self.tables.values(): table[index] self.env["scope"] = self.row_readers
def set_range(self, start: int, end: int) -> None: for name in self.tables: self.range_readers[name].range = range(start, end) self.env["scope"] = self.range_readers
def __contains__(self, table: str) -> bool: return table in self.tables123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335import datetimeimport inspectimport reimport statisticsfrom functools import wraps
from sqlglot import expfrom sqlglot.generator import Generatorfrom sqlglot.helper import PYTHON_VERSION, is_int, seq_get
def sql_not(value): return None if value is None else not bool(value)
def sql_and(left, right): left = left() left = None if left is None else bool(left)
if left is False: return False
right = right() right = None if right is None else bool(right) if right is False: return False
return None if left is None or right is None else True
def sql_or(left, right): left = left() left = None if left is None else bool(left)
if left is True: return True
right = right() right = None if right is None else bool(right) if right is True: return True
return None if left is None or right is None else False
def sql_in(value, *candidates): if value is None: return None
has_null = False for candidate in candidates: if candidate is None: has_null = True elif value == candidate: return True
return None if has_null else False
class reverse_key: def __init__(self, obj): self.obj = obj
def __eq__(self, other): return other.obj == self.obj
def __lt__(self, other): return other.obj < self.obj
def filter_nulls(func, empty_null=True): @wraps(func) def _func(values): filtered = tuple(v for v in values if v is not None) if not filtered and empty_null: return None return func(filtered)
return _func
def null_if_any(*required): """ Decorator that makes a function return `None` if any of the `required` arguments are `None`.
This also supports decoration with no arguments, e.g.:
@null_if_any def foo(a, b): ...
In which case all arguments are required. """ f = None if len(required) == 1 and callable(required[0]): f = required[0] required = ()
def decorator(func): if required: required_indices = [ i for i, param in enumerate(inspect.signature(func).parameters) if param in required ]
def predicate(*args): return any(args[i] is None for i in required_indices)
else:
def predicate(*args): return any(a is None for a in args)
@wraps(func) def _func(*args): if predicate(*args): return None return func(*args)
return _func
if f: return decorator(f)
return decorator
@null_if_any("this", "substr")def str_position(this, substr, position=None): position = position - 1 if position is not None else position return this.find(substr, position) + 1
@null_if_any("this")def substring(this, start=None, length=None): if start is None: return this elif start == 0: return "" elif start < 0: start = len(this) + start else: start -= 1
end = None if length is None else start + length
return this[start:end]
@null_if_anydef cast(this, to): if to == exp.DType.DATE: if isinstance(this, datetime.datetime): return this.date() if isinstance(this, datetime.date): return this if isinstance(this, str): return datetime.date.fromisoformat(this) if to == exp.DType.TIME: if isinstance(this, datetime.datetime): return this.time() if isinstance(this, datetime.time): return this if isinstance(this, str): return datetime.time.fromisoformat(this) if to in (exp.DType.DATETIME, exp.DType.TIMESTAMP): if isinstance(this, datetime.datetime): return this if isinstance(this, datetime.date): return datetime.datetime(this.year, this.month, this.day) if isinstance(this, str): return datetime.datetime.fromisoformat(this) if to == exp.DType.BOOLEAN: return bool(this) if to in exp.DataType.TEXT_TYPES: return str(this) if to in {exp.DType.FLOAT, exp.DType.DOUBLE}: return float(this) if to in exp.DataType.NUMERIC_TYPES: return int(this) raise NotImplementedError(f"Casting {this} to '{to}' not implemented.")
FIRST = 0LAST = 1NULL_PLACEHOLDER = 0
def ordered(this, desc, nulls_first): if this is None: return (FIRST if nulls_first else LAST, NULL_PLACEHOLDER) return (LAST if nulls_first else FIRST, reverse_key(this) if desc else this)
def _like(this, e, flags=0): return bool( re.fullmatch(re.escape(e).replace("_", ".").replace("%", ".*"), this, re.DOTALL | flags) )
@null_if_anydef intdiv(this, e): if not isinstance(this, int) or not isinstance(e, int): return int(this / e)
quotient = abs(this) // abs(e) return quotient if (this < 0) == (e < 0) else -quotient
@null_if_anydef interval(this, unit): plural = unit + "S" if plural in Generator.TIME_PART_SINGULARS: unit = plural return datetime.timedelta(**{unit.lower(): float(this)})
def zip_not_null(*args): return (row for row in zip(*args) if all(v is not None for v in row))
@null_if_anydef arrayconcat(*args): result = [] for arg in args: result.extend(arg if isinstance(arg, list) else [arg]) return result
@null_if_any("this", "expression")def arraytostring(this, expression, null=None): return expression.join(x for x in (x if x is not None else null for x in this) if x is not None)
@null_if_any("this", "expression")def jsonextract(this, expression): for path_segment in expression: if isinstance(this, dict): this = this.get(path_segment) elif isinstance(this, list) and is_int(path_segment): this = seq_get(this, int(path_segment)) else: raise NotImplementedError(f"Unable to extract value for {this} at {path_segment}.")
if this is None: break
return this
ENV = { "exp": exp, "AND": sql_and, # aggs "ARRAYAGG": list, "ARRAYUNIQUEAGG": filter_nulls(lambda acc: list(set(acc))), "AVG": filter_nulls(statistics.fmean if PYTHON_VERSION >= (3, 8) else statistics.mean), # type: ignore "COUNT": filter_nulls(lambda acc: sum(1 for _ in acc), False), "FIRST": lambda acc: next(iter(acc), None), "MAX": filter_nulls(max), "MIN": filter_nulls(min), "SUM": filter_nulls(sum), # scalar functions "ABS": null_if_any(lambda this: abs(this)), "ADD": null_if_any(lambda e, this: e + this), "ARRAYANY": null_if_any(lambda arr, func: any(func(e) for e in arr)), "ARRAYCONCAT": arrayconcat, "ARRAYTOSTRING": arraytostring, "BETWEEN": null_if_any(lambda this, low, high: low <= this and this <= high), "BITWISEAND": null_if_any(lambda this, e: this & e), "BITWISELEFTSHIFT": null_if_any(lambda this, e: this << e), "BITWISEOR": null_if_any(lambda this, e: this | e), "BITWISERIGHTSHIFT": null_if_any(lambda this, e: this >> e), "BITWISEXOR": null_if_any(lambda this, e: this ^ e), "CAST": cast, "COALESCE": lambda *args: next((a for a in args if a is not None), None), "CONCAT": null_if_any(lambda *args: "".join(args)), "SAFECONCAT": null_if_any(lambda *args: "".join(str(arg) for arg in args)), "CONCATWS": null_if_any(lambda this, *args: this.join(args)), "DATEDIFF": null_if_any(lambda this, expression, *_: (this - expression).days), "DATESTRTODATE": null_if_any(lambda arg: datetime.date.fromisoformat(arg)), "DIV": null_if_any(lambda e, this: e / this), "DOT": null_if_any(lambda e, this: e[this]), "EQ": null_if_any(lambda this, e: this == e), "EXTRACT": null_if_any(lambda this, e: getattr(e, this)), "GT": null_if_any(lambda this, e: this > e), "GTE": null_if_any(lambda this, e: this >= e), "IF": lambda predicate, true, false: true if predicate else false, "IN": sql_in, "INT": null_if_any(int), "INTDIV": intdiv, "INTERVAL": interval, "JSONEXTRACT": jsonextract, "LEFT": null_if_any(lambda this, e: this[:e]), "LENGTH": null_if_any(len), "LIKE": null_if_any(lambda this, e: _like(this, e)), "ILIKE": null_if_any(lambda this, e: _like(this, e, re.IGNORECASE)), "LOWER": null_if_any(lambda arg: arg.lower()), "LT": null_if_any(lambda this, e: this < e), "LTE": null_if_any(lambda this, e: this <= e), "MAP": null_if_any(lambda *args: dict(zip(*args))), # type: ignore "MOD": null_if_any(lambda e, this: e % this), "MUL": null_if_any(lambda e, this: e * this), "NEQ": null_if_any(lambda this, e: this != e), "ORD": null_if_any(ord), "NOT": sql_not, "OR": sql_or, "ORDERED": ordered, "POW": null_if_any(pow), "REVERSE": null_if_any(lambda this: this[::-1]), "RIGHT": null_if_any(lambda this, e: this[-e:]), "ROUND": null_if_any(lambda this, decimals=None, truncate=None: round(this, ndigits=decimals)), "STRPOSITION": str_position, "SUB": null_if_any(lambda e, this: e - this), "SUBSTRING": substring, "TIMESTRTOTIME": null_if_any(lambda arg: datetime.datetime.fromisoformat(arg)), "UPPER": null_if_any(lambda arg: arg.upper()), "ZIPNOTNULL": zip_not_null, "YEAR": null_if_any(lambda arg: arg.year), "MONTH": null_if_any(lambda arg: arg.month), "DAY": null_if_any(lambda arg: arg.day), "CURRENTDATETIME": datetime.datetime.now, "CURRENTTIMESTAMP": datetime.datetime.now, "CURRENTTIME": datetime.datetime.now, "CURRENTDATE": datetime.date.today, "STRFTIME": null_if_any(lambda fmt, arg: datetime.datetime.fromisoformat(arg).strftime(fmt)), "STRTOTIME": null_if_any(lambda arg, format: datetime.datetime.strptime(arg, format)), "TRIM": null_if_any(lambda this, e=None: this.strip(e)), "STRUCT": lambda *args: { args[x]: args[x + 1] for x in range(0, len(args), 2) if (args[x + 1] is not None and args[x] is not None) }, "UNIXTOTIME": null_if_any( lambda arg: datetime.datetime.fromtimestamp(arg, datetime.timezone.utc) ),}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557import collectionsimport itertoolsimport math
from sqlglot import exp, planner, tokensfrom sqlglot.dialects.dialect import Dialectfrom sqlglot.errors import ExecuteErrorfrom sqlglot.executor.context import Contextfrom sqlglot.executor.env import ENVfrom sqlglot.executor.table import RowReader, Tablefrom sqlglot.generators.python import PythonGeneratorfrom sqlglot.optimizer.scope import build_scope
SUBQUERY_NODES = (exp.Subquery, exp.Exists, exp.All, exp.Any)
class PythonExecutor: def __init__(self, env=None, tables=None): self.generator = Python().generator(identify=True, comments=False) self.env = {**ENV, **(env or {})} self.tables = tables or {} self._subquery_plans = {} self._plan_names_by_sql = {} self._ctes = None self._outer_scope = None self.env.update( SUBQUERY_COMPARISON=self._subquery_comparison, SUBQUERY_EXISTS=self._subquery_exists, SUBQUERY_SCALAR=self._subquery_scalar, )
def execute(self, plan, outer_scope=None): ctes, scope = self._ctes, self._outer_scope self._ctes, self._outer_scope = plan.ctes, outer_scope try: return self._execute(plan) finally: self._ctes, self._outer_scope = ctes, scope
def _execute(self, plan): finished = set() queue = set(plan.leaves) contexts = {}
while queue: node = queue.pop() try: context = self.context( { name: table for dep in node.dependencies for name, table in contexts[dep].tables.items() } )
if isinstance(node, planner.Scan): contexts[node] = self.scan(node, context) elif isinstance(node, planner.Aggregate): contexts[node] = self.aggregate(node, context) elif isinstance(node, planner.Join): contexts[node] = self.join(node, context) elif isinstance(node, planner.Sort): contexts[node] = self.sort(node, context) elif isinstance(node, planner.SetOperation): contexts[node] = self.set_operation(node, context) else: raise NotImplementedError
if node.offset: table = contexts[node].tables[node.name] table.rows = table.rows[node.offset :]
finished.add(node)
for dep in node.dependents: if all(d in contexts for d in dep.dependencies): queue.add(dep)
for dep in node.dependencies: if all(d in finished for d in dep.dependents): contexts.pop(dep) except Exception as e: raise ExecuteError(f"Step '{node.id}' failed: {e}") from e
root = plan.root return contexts[root].tables[root.name]
def generate(self, expression): """Convert a SQL expression into literal Python code and compile it into bytecode.""" if not expression: return None
expression = self._replace_subqueries(expression) sql = self.generator.generate(expression) return compile(sql, sql, "eval", optimize=2)
def _replace_subqueries(self, expression): if not expression.find(*SUBQUERY_NODES): return expression
expression = expression.copy()
while True: subquery = expression.find(*SUBQUERY_NODES)
if subquery is None: return expression
target, replacement = self._compile_subquery(subquery)
if target is expression: expression = replacement else: target.replace(replacement)
def _compile_subquery(self, subquery): query = subquery.this.unnest() scope = build_scope(query)
outer_columns = list(scope.external_columns if scope else [])
plan = self._register_subquery(query) parent = subquery.parent
if isinstance(subquery, exp.Exists): return subquery, exp.func( "SUBQUERY_EXISTS", plan, exp.var("scope"), *outer_columns, copy=False )
if len(query.selects) != 1: raise ExecuteError( f"Subquery used as an expression returned {len(query.selects)} columns" )
if isinstance(subquery, (exp.All, exp.Any)): return self._compile_quantified(parent, subquery.key.upper(), plan, outer_columns)
if isinstance(parent, exp.In) and subquery is parent.args.get("query"): return self._compile_quantified(parent, "ANY", plan, outer_columns, op="EQ")
return subquery, exp.func( "SUBQUERY_SCALAR", plan, exp.var("scope"), *outer_columns, copy=False )
def _compile_quantified(self, comparison, quantifier, plan, outer_columns, op=None): if not isinstance(comparison, (exp.Binary, exp.In)): raise ExecuteError(f"Unsupported {quantifier} subquery: expected a comparison")
return comparison, exp.func( "SUBQUERY_COMPARISON", comparison.this, plan, exp.var("scope"), exp.Literal.string(op or comparison.key.upper()), exp.Literal.string(quantifier), *outer_columns, copy=False, )
def _register_subquery(self, query): if self._ctes is not None and not query.args.get("with_"): query.set("with_", self._ctes)
sql = query.sql() name = self._plan_names_by_sql.get(sql)
if name is None: name = self._plan_names_by_sql[sql] = f"_sq_{len(self._subquery_plans)}" self._subquery_plans[name] = (planner.Plan(query), {})
return exp.Literal.string(name)
def _subquery_table(self, plan_name, scope, args): plan, cache = self._subquery_plans[plan_name]
try: return cache[args] except KeyError: pass except TypeError: # an unhashable correlated value can't be memoized cache = None
table = self.execute(plan, scope)
if cache is not None: cache[args] = table
return table
def _subquery_exists(self, plan_name, scope, *args): return bool(self._subquery_table(plan_name, scope, args).rows)
def _subquery_scalar(self, plan_name, scope, *args): rows = self._subquery_table(plan_name, scope, args).rows
if len(rows) > 1: raise ExecuteError("More than one row returned by a subquery used as an expression")
return rows[0][0] if rows else None
def _subquery_comparison(self, value, plan_name, scope, op, quantifier, *args): compare = self.env[op] is_any = quantifier == "ANY" saw_null = False
for row in self._subquery_table(plan_name, scope, args).rows: result = compare(value, row[0])
if result is None: saw_null = True elif bool(result) is is_any: return is_any
return None if saw_null else not is_any
def generate_tuple(self, expressions): """Convert an array of SQL expressions into tuple of Python byte code.""" if not expressions: return tuple() return tuple(self.generate(expression) for expression in expressions)
def context(self, tables): return Context(tables, env=self.env, outer=self._outer_scope)
def table(self, expressions): return Table( expression.alias_or_name if isinstance(expression, exp.Expr) else expression for expression in expressions )
def scan(self, step, context): source = step.source
if source and isinstance(source, exp.Expr): source = source.name or source.alias
if source is None: context, table_iter = self.static() elif source in context: if not step.projections and not step.condition: return self.context({step.name: context.tables[source]}) table_iter = context.table_iter(source) else: context, table_iter = self.scan_table(step)
return self.context({step.name: self._project_and_filter(context, step, table_iter)})
def _project_and_filter(self, context, step, table_iter): sink = self.table(step.projections if step.projections else context.columns) condition = self.generate(step.condition) projections = self.generate_tuple(step.projections)
for reader in table_iter: if len(sink) >= step.offset + step.limit: break
if condition and not context.eval(condition): continue
if projections: sink.append(context.eval_tuple(projections)) else: sink.append(reader.row)
return sink
def static(self): return self.context({}), [RowReader(())]
def scan_table(self, step): table = self.tables.find(step.source) context = self.context({step.source.alias_or_name: table}) return context, iter(table)
def join(self, step, context): source = step.source_name
source_table = context.tables[source] source_context = self.context({source: source_table}) column_ranges = {source: range(0, len(source_table.columns))}
for name, join in step.joins.items(): table = context.tables[name] start = max(r.stop for r in column_ranges.values()) column_ranges[name] = range(start, len(table.columns) + start) join_context = self.context({name: table}) condition = self.generate(join["condition"]) condition_context = ( self.context( { name: Table( source_context.columns + join_context.columns, column_range=column_range, ) for name, column_range in column_ranges.items() } ) if condition else None )
if join.get("source_key"): table = self.hash_join( join, source_context, join_context, condition, condition_context ) else: table = self.nested_loop_join( join, source_context, join_context, condition, condition_context )
source_context = self.context( { name: Table(table.columns, table.rows, column_range) for name, column_range in column_ranges.items() } ) if not step.condition and not step.projections: return source_context
sink = self._project_and_filter( source_context, step, (reader for reader, _ in iter(source_context)), )
if step.projections: return self.context({step.name: sink}) else: return self.context( { name: Table(table.columns, sink.rows, table.column_range) for name, table in source_context.tables.items() } )
@staticmethod def _join_matches(row, condition, condition_context): if not condition: return True
condition_context.set_row(row) return condition_context.eval(condition) is True
def nested_loop_join(self, join, source_context, join_context, condition, condition_context): table = Table(source_context.columns + join_context.columns) source_rows = source_context.table.rows join_rows = join_context.table.rows matched_source = set() matched_join = set()
for source_index, source_row in enumerate(source_rows): for join_index, join_row in enumerate(join_rows): row = source_row + join_row if self._join_matches(row, condition, condition_context): table.append(row) matched_source.add(source_index) matched_join.add(join_index)
self._append_unmatched_join_rows( table, join, source_rows, join_rows, matched_source, matched_join )
return table
def hash_join(self, join, source_context, join_context, condition, condition_context): source_key = self.generate_tuple(join["source_key"]) join_key = self.generate_tuple(join["join_key"]) results = collections.defaultdict(lambda: ([], []))
for index, (reader, ctx) in enumerate(source_context): key = ctx.eval_tuple(source_key) if all(value is not None for value in key): results[key][0].append((index, reader.row)) for index, (reader, ctx) in enumerate(join_context): key = ctx.eval_tuple(join_key) if all(value is not None for value in key): results[key][1].append((index, reader.row))
table = Table(source_context.columns + join_context.columns) matched_source = set() matched_join = set()
for source_group, join_group in results.values(): for (source_index, source_row), (join_index, join_row) in itertools.product( source_group, join_group ): row = source_row + join_row if self._join_matches(row, condition, condition_context): table.append(row) matched_source.add(source_index) matched_join.add(join_index)
self._append_unmatched_join_rows( table, join, source_context.table.rows, join_context.table.rows, matched_source, matched_join, )
return table
@staticmethod def _append_unmatched_join_rows( table, join, source_rows, join_rows, matched_source, matched_join ): side = join.get("side") if side in ("LEFT", "FULL"): join_nulls = (None,) * (len(table.columns) - len(source_rows[0]) if source_rows else 0) for index, row in enumerate(source_rows): if index not in matched_source: table.append(row + join_nulls)
if side in ("RIGHT", "FULL"): source_width = len(table.columns) - (len(join_rows[0]) if join_rows else 0) source_nulls = (None,) * source_width for index, row in enumerate(join_rows): if index not in matched_join: table.append(source_nulls + row)
def aggregate(self, step, context): group_by = self.generate_tuple(step.group.values()) aggregations = self.generate_tuple(step.aggregations) operands = self.generate_tuple(step.operands)
if operands: operand_table = Table(self.table(step.operands).columns)
for reader, ctx in context: operand_table.append(ctx.eval_tuple(operands))
for i, (a, b) in enumerate(zip(context.table.rows, operand_table.rows)): context.table.rows[i] = a + b
width = len(context.columns) context.add_columns(*operand_table.columns)
operand_table = Table( context.columns, context.table.rows, range(width, width + len(operand_table.columns)), )
context = self.context( { None: operand_table, **context.tables, } )
context.sort(group_by)
group = None start = 0 end = 1 length = len(context.table) table = self.table(list(step.group) + step.aggregations)
def add_row(): table.append(group + context.eval_tuple(aggregations))
if length: for i in range(length): context.set_index(i) key = context.eval_tuple(group_by) group = key if group is None else group end += 1 if key != group: context.set_range(start, end - 2) add_row() group = key start = end - 2 if not step.condition and len(table.rows) >= step.offset + step.limit: break if i == length - 1: context.set_range(start, end - 1) add_row() elif step.limit > 0 and not group_by: context.set_range(0, 0) table.append(context.eval_tuple(aggregations))
context = self.context({step.name: table, **{name: table for name in context.tables}})
if step.projections or step.condition: return self.context( {step.name: self._project_and_filter(context, step, context.table_iter(step.name))} ) return context
def sort(self, step, context): projections = self.generate_tuple(step.projections) projection_columns = [p.alias_or_name for p in step.projections] all_columns = list(context.columns) + projection_columns sink = self.table(all_columns) for reader, ctx in context: sink.append(reader.row + ctx.eval_tuple(projections))
sort_ctx = self.context( { None: sink, **{table: sink for table in context.tables}, } ) sort_ctx.sort(self.generate_tuple(step.key))
if not math.isinf(step.limit): sort_ctx.table.rows = sort_ctx.table.rows[0 : step.offset + step.limit]
rows = sort_ctx.table.rows
if projection_columns: rows = [row[len(context.columns) : len(all_columns)] for row in rows]
output = Table(projection_columns or context.columns, rows=rows) return self.context({step.name: output})
def set_operation(self, step, context): left = context.tables[step.left] right = context.tables[step.right]
sink = self.table(left.columns)
if issubclass(step.op, exp.Intersect): right_counts = collections.Counter(right.rows) seen = set() for row in left.rows: if right_counts[row] and (not step.distinct or row not in seen): sink.append(row) seen.add(row) if not step.distinct: right_counts[row] -= 1 elif issubclass(step.op, exp.Except): right_counts = collections.Counter(right.rows) seen = set() for row in left.rows: if right_counts[row] and not step.distinct: right_counts[row] -= 1 elif not right_counts[row] and (not step.distinct or row not in seen): sink.append(row) seen.add(row) elif issubclass(step.op, exp.Union) and step.distinct: sink.rows = list(set(left.rows).union(set(right.rows))) else: sink.rows = left.rows + right.rows
if not math.isinf(step.limit): sink.rows = sink.rows[0 : step.offset + step.limit]
return self.context({step.name: sink})
class Python(Dialect): class Tokenizer(tokens.Tokenizer): STRING_ESCAPES = ["\\"]
Generator = PythonGenerator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157from __future__ import annotations
import typing as t
from sqlglot.dialects.dialect import DialectTypefrom sqlglot.helper import dict_depthfrom sqlglot.schema import AbstractMappingSchema, normalize_name
class Table: def __init__( self, columns: t.Any = None, rows: t.Any = None, column_range: range | None = None, ) -> None: self.columns: t.Any = tuple(columns) if columns is not None else () self.column_range = column_range self.reader: t.Any = RowReader(self.columns, self.column_range) self.rows: t.Any = rows or [] if rows: assert len(rows[0]) == len(self.columns) self.range_reader = RangeReader(self)
def add_columns(self, *columns: str) -> None: self.columns += columns if self.column_range: self.column_range = range( self.column_range.start, self.column_range.stop + len(columns) ) self.reader = RowReader(self.columns, self.column_range)
def append(self, row: t.Any) -> None: assert len(row) == len(self.columns) self.rows.append(row)
def pop(self) -> None: self.rows.pop()
def to_pylist(self) -> list: return [dict(zip(self.columns, row)) for row in self.rows]
@property def width(self) -> int: return len(self.columns)
def __len__(self) -> int: return len(self.rows)
def __iter__(self) -> TableIter: return TableIter(self)
def __getitem__(self, index: int) -> RowReader: self.reader.row = self.rows[index] return self.reader
def __repr__(self) -> str: columns = tuple( column for i, column in enumerate(self.columns) if not self.column_range or i in self.column_range ) widths = {column: len(column) for column in columns} lines = [" ".join(column for column in columns)]
for i, row in enumerate(self): if i > 10: break
lines.append( " ".join( str(row[column]).rjust(widths[column])[0 : widths[column]] for column in columns ) ) return "\n".join(lines)
class TableIter: def __init__(self, table: Table) -> None: self.table = table self.index = -1
def __iter__(self) -> TableIter: return self
def __next__(self) -> RowReader: self.index += 1 if self.index < len(self.table): return self.table[self.index] raise StopIteration
class RangeReader: def __init__(self, table: t.Any = None) -> None: self.table: t.Any = table self.range = range(0)
def __len__(self) -> int: return len(self.range)
def __getitem__(self, column: str): return (self.table[i][column] for i in self.range)
class RowReader: def __init__(self, columns=None, column_range=None): self.columns = ( {column: i for i, column in enumerate(columns) if not column_range or i in column_range} if columns is not None else {} ) self.row = ()
def __getitem__(self, column): return self.row[self.columns[column]]
class Tables(AbstractMappingSchema): pass
def ensure_tables(d: dict | None, dialect: DialectType = None) -> Tables: return Tables(_ensure_tables(d, dialect=dialect))
def _ensure_tables(d: dict | None, dialect: DialectType = None) -> dict: if not d: return {}
depth = dict_depth(d) if depth > 1: return { normalize_name(k, dialect=dialect, is_table=True).name: _ensure_tables( v, dialect=dialect ) for k, v in d.items() }
result = {} for table_name, table in d.items(): table_name = normalize_name(table_name, dialect=dialect).name
if isinstance(table, Table): result[table_name] = table else: table = [ { normalize_name(column_name, dialect=dialect).name: value for column_name, value in row.items() } for row in table ] column_names = tuple(column_name for column_name in table[0]) if table else () rows = [tuple(row[name] for name in column_names) for row in table] result[table_name] = Table(columns=column_names, rows=rows)
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# ruff: noqa: F405"""## Exprs
Every AST node in SQLGlot is represented by a subclass of `Expr`.
This module contains the implementation of all supported `Expr` types. Additionally,it exposes a number of helper functions, which are mainly used to programmatically buildSQL expressions, such as `sqlglot.expressions.select`.
----"""
from sqlglot.expressions.core import * # noqa: F401,F403from sqlglot.expressions.datatypes import * # noqa: F401,F403from sqlglot.expressions.constraints import * # noqa: F401,F403from sqlglot.expressions.properties import * # noqa: F401,F403from sqlglot.expressions.query import * # noqa: F401,F403from sqlglot.expressions.ddl import * # noqa: F401,F403from sqlglot.expressions.dml import * # noqa: F401,F403from sqlglot.expressions.math import * # noqa: F401,F403from sqlglot.expressions.string import * # noqa: F401,F403from sqlglot.expressions.temporal import * # noqa: F401,F403from sqlglot.expressions.aggregate import * # noqa: F401,F403from sqlglot.expressions.array import * # noqa: F401,F403from sqlglot.expressions.json import * # noqa: F401,F403from sqlglot.expressions.functions import * # noqa: F401,F403from sqlglot.expressions.builders import * # noqa: F401,F403
# Explicitly import private helpers (not exported by star imports)from sqlglot.expressions.core import ( # noqa: F401,E402 Expression, _apply_builder, _apply_child_list_builder, _apply_list_builder, _apply_conjunction_builder, _apply_set_operation, _combine, _wrap, _is_wrong_expression, _to_s,)from sqlglot.expressions.query import _apply_cte_builder # noqa: F401,E402from sqlglot.expressions.dml import DML # noqa: F401,E402from sqlglot.expressions.array import _ExplodeOuter # noqa: F401,E402
from sqlglot.helper import subclasses
ALL_FUNCTIONS = subclasses(__name__, Func, {AggFunc, Anonymous, Func})FUNCTION_BY_NAME = {name: func for func in ALL_FUNCTIONS for name in func.sql_names()}EXPR_CLASSES: dict[str, type[Expr]] = {cls.key: cls for cls in subclasses(__name__, Expr)}
# Functions that can return multiple rows. We include anonymous functions conservatively.SET_RETURNING_FUNCTIONS = (Anonymous, UDTF, ExplodingGenerateSeries)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329"""sqlglot expressions - aggregate, window, and statistical functions."""
from __future__ import annotations
from sqlglot.expressions.core import Expression, Func, AggFunc, Binary
class Agg(Expression, AggFunc): @property def output_name(self) -> str: return self.this.name
class AIAgg(Expression, AggFunc): arg_types = {"this": True, "expression": True} _sql_names = ["AI_AGG"]
class AISummarizeAgg(Expression, AggFunc): _sql_names = ["AI_SUMMARIZE_AGG"]
class AnyValue(Expression, AggFunc): pass
class ApproximateSimilarity(Expression, AggFunc): _sql_names = ["APPROXIMATE_SIMILARITY", "APPROXIMATE_JACCARD_INDEX"]
class ApproxPercentileAccumulate(Expression, AggFunc): pass
class ApproxPercentileCombine(Expression, AggFunc): pass
class ApproxPercentileEstimate(Expression, Func): arg_types = {"this": True, "percentile": True}
class ApproxQuantiles(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class ApproxTopK(Expression, AggFunc): arg_types = {"this": True, "expression": False, "counters": False}
class ApproxTopKAccumulate(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class ApproxTopKCombine(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class ApproxTopKEstimate(Expression, Func): arg_types = {"this": True, "expression": False}
class ApproxTopSum(Expression, AggFunc): arg_types = {"this": True, "expression": True, "count": True}
class ArgMax(Expression, AggFunc): arg_types = {"this": True, "expression": True, "count": False} _sql_names = ["ARG_MAX", "ARGMAX", "MAX_BY"]
class ArgMin(Expression, AggFunc): arg_types = {"this": True, "expression": True, "count": False} _sql_names = ["ARG_MIN", "ARGMIN", "MIN_BY"]
class ArrayAgg(Expression, AggFunc): arg_types = {"this": True, "nulls_excluded": False}
class ArrayConcatAgg(Expression, AggFunc): pass
class ArrayUnionAgg(Expression, AggFunc): pass
class ArrayUniqueAgg(Expression, AggFunc): pass
class Avg(Expression, AggFunc): pass
class Corr(Expression, AggFunc, Binary): # Correlation divides by variance(column). If a column has 0 variance, the denominator # is 0 - some dialects return NaN (DuckDB) while others return NULL (Snowflake). # `null_on_zero_variance` is set to True at parse time for dialects that return NULL. arg_types = {"this": True, "expression": True, "null_on_zero_variance": False}
class Count(Expression, AggFunc): arg_types = {"this": False, "expressions": False, "big_int": False} is_var_len_args = True
class CountIf(Expression, AggFunc): _sql_names = ["COUNT_IF", "COUNTIF"] arg_types = {"this": True, "zero_on_all_null": False}
class CovarPop(Expression, AggFunc): arg_types = {"this": True, "expression": True}
class CovarSamp(Expression, AggFunc): arg_types = {"this": True, "expression": True}
class CumeDist(Expression, AggFunc): arg_types = {"expressions": False} is_var_len_args = True
class DenseRank(Expression, AggFunc): arg_types = {"expressions": False} is_var_len_args = True
class First(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class FirstValue(Expression, AggFunc): pass
class GroupConcat(Expression, AggFunc): arg_types = {"this": True, "separator": False, "on_overflow": False}
class Grouping(Expression, AggFunc): arg_types = {"expressions": True} is_var_len_args = True
class GroupingId(Expression, AggFunc): arg_types = {"expressions": False} is_var_len_args = True
class Kurtosis(Expression, AggFunc): pass
class Lag(Expression, AggFunc): arg_types = {"this": True, "offset": False, "default": False}
class Last(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class LastValue(Expression, AggFunc): pass
class Lead(Expression, AggFunc): arg_types = {"this": True, "offset": False, "default": False}
class LogicalAnd(Expression, AggFunc): _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class LogicalOr(Expression, AggFunc): _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class Max(Expression, AggFunc): arg_types = {"this": True, "expressions": False} is_var_len_args = True
class Median(Expression, AggFunc): pass
class Min(Expression, AggFunc): arg_types = {"this": True, "expressions": False} is_var_len_args = True
class Minhash(Expression, AggFunc): arg_types = {"this": True, "expressions": True} is_var_len_args = True
class MinhashCombine(Expression, AggFunc): pass
class Mode(Expression, AggFunc): arg_types = {"this": False, "deterministic": False}
class Ntile(Expression, AggFunc): arg_types = {"this": False}
class NthValue(Expression, AggFunc): arg_types = {"this": True, "offset": True, "from_first": False}
class ObjectAgg(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class PercentileCont(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class PercentileDisc(Expression, AggFunc): arg_types = {"this": True, "expression": False}
PERCENTILES = (PercentileCont, PercentileDisc)
class PercentRank(Expression, AggFunc): arg_types = {"expressions": False} is_var_len_args = True
class Quantile(Expression, AggFunc): arg_types = {"this": True, "quantile": True}
class ApproxQuantile(Quantile): arg_types = { "this": True, "quantile": True, "accuracy": False, "weight": False, "error_tolerance": False, }
class Rank(Expression, AggFunc): arg_types = {"expressions": False} is_var_len_args = True
class RegrAvgx(Expression, AggFunc): arg_types = {"this": True, "expression": True}
class RegrAvgy(Expression, AggFunc): arg_types = {"this": True, "expression": True}
class RegrCount(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class RegrIntercept(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class RegrR2(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class RegrSlope(Expression, AggFunc): arg_types = {"this": True, "expression": False}
class RegrSxx(Expression, AggFunc): arg_types = {"this": True, "expression": True}
class RegrSxy(Expression, AggFunc): arg_types = {"this": True, "expression": True}
class RegrSyy(Expression, AggFunc): arg_types = {"this": True, "expression": True}
class RegrValx(Expression, AggFunc): arg_types = {"this": True, "expression": True}
class RegrValy(Expression, AggFunc): arg_types = {"this": True, "expression": True}
class RowNumber(Expression, Func): arg_types = {"this": False}
class Skewness(Expression, AggFunc): pass
class Stddev(Expression, AggFunc): _sql_names = ["STDDEV", "STDEV"]
class StddevPop(Expression, AggFunc): pass
class StddevSamp(Expression, AggFunc): pass
class Sum(Expression, AggFunc): pass
class Variance(Expression, AggFunc): _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(Expression, AggFunc): _sql_names = ["VARIANCE_POP", "VAR_POP"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394"""sqlglot expressions - array, map, struct, and table-valued functions."""
from __future__ import annotations
from sqlglot.expressions.core import ( Expression, Expr, Func, Binary, Predicate, to_identifier,)from sqlglot.helper import traitfrom sqlglot.expressions.query import UDTF
# Array creation / construction
class Array(Expression, Func): arg_types = { "expressions": False, "bracket_notation": False, "struct_name_inheritance": False, "value_constructor": False, } is_var_len_args = True
class ArrayConstructCompact(Expression, Func): arg_types = {"expressions": False} is_var_len_args = True
class List(Expression, Func): arg_types = {"expressions": False} is_var_len_args = True
class ToArray(Expression, Func): pass
# Array manipulation
class ArrayAppend(Expression, Func): arg_types = {"this": True, "expression": True, "null_propagation": False}
class ArrayCompact(Expression, Func): pass
class ArrayConcat(Expression, Func): _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"] arg_types = {"this": True, "expressions": False, "null_propagation": False} is_var_len_args = True
class ArrayFilter(Expression, Func): arg_types = {"this": True, "expression": True} _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayInsert(Expression, Func): arg_types = {"this": True, "position": True, "expression": True, "offset": False}
class ArrayPrepend(Expression, Func): arg_types = {"this": True, "expression": True, "null_propagation": False}
class ArrayRemove(Expression, Func): arg_types = {"this": True, "expression": True, "null_propagation": False}
class ArrayRemoveAt(Expression, Func): arg_types = {"this": True, "position": True}
class ArrayReverse(Expression, Func): pass
class ArraySlice(Expression, Func): """Slice by end index, or by length when is_length is set."""
arg_types = { "this": True, "start": True, "end": False, "step": False, "zero_based": False, "is_length": False, }
class ArraySort(Expression, Func): arg_types = {"this": True, "expression": False, "asc": False, "nulls_first": False}
class Shuffle(Expression, Func): pass
# Array predicates / search
class ArrayAll(Expression, Func): arg_types = {"this": True, "expression": True}
class ArrayAny(Expression, Func): arg_types = {"this": True, "expression": True}
class ArrayContains(Expression, Binary, Predicate, Func): arg_types = {"this": True, "expression": True, "ensure_variant": False, "check_null": False} _sql_names = ["ARRAY_CONTAINS", "ARRAY_HAS"]
class ArrayContainsAll(Expression, Binary, Predicate, Func): _sql_names = ["ARRAY_CONTAINS_ALL", "ARRAY_HAS_ALL"]
class ArrayContainedBy(Expression, Binary, Predicate, Func): pass
class ArrayExcept(Expression, Func): arg_types = {"this": True, "expression": True, "is_multiset": False}
class ArrayIntersect(Expression, Func): arg_types = {"expressions": True, "is_multiset": False} is_var_len_args = True _sql_names = ["ARRAY_INTERSECT", "ARRAY_INTERSECTION"]
class ArrayOverlaps(Expression, Binary, Predicate, Func): arg_types = {"this": True, "expression": True, "null_safe": False}
class ArrayPosition(Expression, Binary, Func): arg_types = {"this": True, "expression": True, "zero_based": False}
# Array properties
class ArrayDistinct(Expression, Func): arg_types = {"this": True, "check_null": False}
class ArrayFirst(Expression, Func): arg_types = {"this": True, "expression": False}
class ArrayLast(Expression, Func): pass
class ArrayMax(Expression, Func): pass
class ArrayMin(Expression, Func): pass
class ArraySize(Expression, Func): arg_types = {"this": True, "expression": False} _sql_names = ["ARRAY_SIZE", "ARRAY_LENGTH"]
class ArraySum(Expression, Func): arg_types = {"this": True, "expression": False}
# Array conversion / utility
class ArraysZip(Expression, Func): arg_types = {"expressions": False} is_var_len_args = True
class ArrayToString(Expression, Func): arg_types = { "this": True, "expression": True, "null": False, "null_is_empty": False, "null_delim_is_null": False, } _sql_names = ["ARRAY_TO_STRING", "ARRAY_JOIN"]
class Flatten(Expression, Func): pass
class StringToArray(Expression, Func): arg_types = {"this": True, "expression": False, "null": False} _sql_names = ["STRING_TO_ARRAY", "SPLIT_BY_STRING"]
class StrtokToArray(Expression, Func): arg_types = {"this": True, "expression": False}
# Higher-order / lambda
class Apply(Expression, Func): arg_types = {"this": True, "expression": True}
class Reduce(Expression, Func): arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class Transform(Expression, Func): arg_types = {"this": True, "expression": True}
# Table-valued / UDTF
class GenerateSeries(Expression, Func): arg_types = {"start": True, "end": True, "step": False, "is_end_exclusive": False}
class ExplodingGenerateSeries(GenerateSeries): pass
class Generator(Expression, Func, UDTF): arg_types = {"rowcount": False, "timelimit": False}
class Explode(Expression, Func, UDTF): arg_types = {"this": True, "expressions": False} is_var_len_args = True
class Inline(Expression, Func, UDTF): pass
class SplitToTable(Expression, Func, UDTF): arg_types = {"this": True, "expression": True}
class Stack(Expression, Func, UDTF): arg_types = {"this": True, "expressions": True} is_var_len_args = True
@traitclass ExplodeOuter(Expr): pass
class _ExplodeOuter(Explode, ExplodeOuter): _sql_names = ["EXPLODE_OUTER"]
class Posexplode(Explode): pass
class PosexplodeOuter(Posexplode, ExplodeOuter): pass
class PositionalColumn(Expression): pass
class Unnest(Expression, Func, UDTF): arg_types = { "expressions": True, "alias": False, "offset": False, "explode_array": False, }
@property def selects(self) -> list[Expr]: columns = super().selects offset = self.args.get("offset") if offset: columns = columns + [to_identifier("offset") if offset is True else offset] return columns
# Map
class Map(Expression, Func): arg_types = {"keys": False, "values": False}
@property def keys(self) -> list[Expr]: keys = self.args.get("keys") return keys.expressions if keys else []
@property def values(self) -> list[Expr]: values = self.args.get("values") return values.expressions if values else []
class MapCat(Expression, Func): arg_types = {"this": True, "expression": True}
class MapContainsKey(Expression, Func): arg_types = {"this": True, "key": True}
class MapDelete(Expression, Func): arg_types = {"this": True, "expressions": True} is_var_len_args = True
class MapFromEntries(Expression, Func): pass
class MapInsert(Expression, Func): arg_types = {"this": True, "key": False, "value": True, "update_flag": False}
class MapKeys(Expression, Func): pass
class MapPick(Expression, Func): arg_types = {"this": True, "expressions": True} is_var_len_args = True
class MapSize(Expression, Func): pass
class StarMap(Expression, Func): pass
class ToMap(Expression, Func): pass
class VarMap(Expression, Func): arg_types = {"keys": True, "values": True} is_var_len_args = True var_len_arg_key = "values"
@property def keys(self) -> list[Expr]: return self.args["keys"].expressions
@property def values(self) -> list[Expr]: return self.args["values"].expressions
# Struct
class Struct(Expression, Func): arg_types = {"expressions": False} is_var_len_args = True
class StructExtract(Expression, Func): arg_types = {"this": True, "expression": True}
# Geospatial
class StDistance(Expression, Func): arg_types = {"this": True, "expression": True, "use_spheroid": False}
class StPoint(Expression, Func): arg_types = {"this": True, "expression": True, "z": False, "m": False} _sql_names = ["ST_POINT", "ST_MAKEPOINT"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197"""sqlglot expressions builders."""
from __future__ import annotations
import reimport typing as t
from sqlglot.helper import seq_get, ensure_collection, split_num_wordsfrom sqlglot.errors import ParseError, TokenErrorfrom sqlglot.expressions.core import ( Alias, Anonymous, AtTimeZone, Between, Binary, BitwiseNot, Boolean, Bracket, Column, Condition, Dot, EQ, Expr, Func, Identifier, In, Literal, Neg, Not, Null, Paren, Placeholder, TABLE_PARTS, Var, logger, SAFE_IDENTIFIER_RE, maybe_parse, maybe_copy, to_identifier, convert, alias_, column,)from sqlglot.expressions.datatypes import DataType, DType, Intervalfrom sqlglot.expressions.query import ( CTE, From, Schema, Select, SetOperation, Subquery, Table, TableAlias, Tuple, Values, Where, With, Query,)from sqlglot.expressions.ddl import Alter, AlterRename, Create, RenameColumnfrom sqlglot.expressions.dml import Delete, Insert, Merge, Update, When, Whensfrom sqlglot.expressions.functions import Case, Castfrom sqlglot.expressions.array import Array
if t.TYPE_CHECKING: from collections.abc import Sequence, Iterable, Iterator from sqlglot.dialects.dialect import DialectType from sqlglot.expressions.core import ExpOrStr from sqlglot.expressions.datatypes import DATA_TYPE from sqlglot._typing import ParserArgs, ParserNoDialectArgs, E, P from typing_extensions import Unpack, Concatenate
def select( *expressions: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Select: """ Initializes a syntax tree from one or multiple SELECT expressions.
Example: >>> select("col1", "col2").from_("tbl").sql() 'SELECT col1, col2 FROM tbl'
Args: *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expr instance is passed, this is used as-is. dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string). **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns: Select: the syntax tree for the SELECT statement. """ return Select().select(*expressions, dialect=dialect, copy=copy, **opts)
def from_( expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Select: """ Initializes a syntax tree from a FROM expression.
Example: >>> from_("tbl").select("col1", "col2").sql() 'SELECT col1, col2 FROM tbl'
Args: *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expr instance is passed, this is used as-is. dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string). **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns: Select: the syntax tree for the SELECT statement. """ return Select().from_(expression, dialect=dialect, copy=copy, **opts)
def update( table: str | Table, properties: dict[str, object] | None = None, where: ExpOrStr | None = None, from_: ExpOrStr | None = None, with_: dict[str, ExpOrStr] | None = None, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Update: """ Creates an update statement.
Example: >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz_cte", where="baz_cte.id > 1 and my_table.id = baz_cte.id", with_={"baz_cte": "SELECT id FROM foo"}).sql() "WITH baz_cte AS (SELECT id FROM foo) UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz_cte WHERE baz_cte.id > 1 AND my_table.id = baz_cte.id"
Args: properties: dictionary of properties to SET which are auto converted to sql objects eg None -> NULL where: sql conditional parsed into a WHERE statement from_: sql statement parsed into a FROM statement with_: dictionary of CTE aliases / select statements to include in a WITH clause. dialect: the dialect used to parse the input expressions. copy: whether to copy the input expressions. **opts: other options to use to parse the input expressions.
Returns: Update: the syntax tree for the UPDATE statement. """ update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect, copy=copy)) if properties: update_expr.set( "expressions", [ EQ(this=maybe_parse(k, dialect=dialect, copy=copy, **opts), expression=convert(v)) for k, v in properties.items() ], ) if from_: update_expr.set( "from_", maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", copy=copy, **opts), ) if isinstance(where, Condition): where = Where(this=where) if where: update_expr.set( "where", maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", copy=copy, **opts), ) if with_: cte_list = [ alias_( CTE(this=maybe_parse(qry, dialect=dialect, copy=copy, **opts)), alias, table=True ) for alias, qry in with_.items() ] update_expr.set( "with_", With(expressions=cte_list), ) return update_expr
def delete( table: ExpOrStr, where: ExpOrStr | None = None, returning: ExpOrStr | None = None, dialect: DialectType = None, **opts: Unpack[ParserNoDialectArgs],) -> Delete: """ Builds a delete statement.
Example: >>> delete("my_table", where="id > 1").sql() 'DELETE FROM my_table WHERE id > 1'
Args: where: sql conditional parsed into a WHERE statement returning: sql conditional parsed into a RETURNING statement dialect: the dialect used to parse the input expressions. **opts: other options to use to parse the input expressions.
Returns: Delete: the syntax tree for the DELETE statement. """ delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) if where: delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) if returning: delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) return delete_expr
def insert( expression: ExpOrStr, into: str | Table, columns: Sequence[str | Identifier] | None = None, overwrite: bool | None = None, returning: ExpOrStr | None = None, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Insert: """ Builds an INSERT statement.
Example: >>> insert("VALUES (1, 2, 3)", "tbl").sql() 'INSERT INTO tbl VALUES (1, 2, 3)'
Args: expression: the sql string or expression of the INSERT statement into: the tbl to insert data to. columns: optionally the table's column names. overwrite: whether to INSERT OVERWRITE or not. returning: sql conditional parsed into a RETURNING statement dialect: the dialect used to parse the input expressions. copy: whether to copy the expression. **opts: other options to use to parse the input expressions.
Returns: Insert: the syntax tree for the INSERT statement. """ expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts) this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
if columns: this = Schema(this=this, expressions=[to_identifier(c, copy=copy) for c in columns])
insert = Insert(this=this, expression=expr, overwrite=overwrite)
if returning: insert = insert.returning(returning, dialect=dialect, copy=False, **opts)
return insert
def merge( *when_exprs: ExpOrStr, into: ExpOrStr, using: ExpOrStr, on: ExpOrStr, returning: ExpOrStr | None = None, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Merge: """ Builds a MERGE statement.
Example: >>> merge("WHEN MATCHED THEN UPDATE SET col1 = source_table.col1", ... "WHEN NOT MATCHED THEN INSERT (col1) VALUES (source_table.col1)", ... into="my_table", ... using="source_table", ... on="my_table.id = source_table.id").sql() 'MERGE INTO my_table USING source_table ON my_table.id = source_table.id WHEN MATCHED THEN UPDATE SET col1 = source_table.col1 WHEN NOT MATCHED THEN INSERT (col1) VALUES (source_table.col1)'
Args: *when_exprs: The WHEN clauses specifying actions for matched and unmatched rows. into: The target table to merge data into. using: The source table to merge data from. on: The join condition for the merge. returning: The columns to return from the merge. dialect: The dialect used to parse the input expressions. copy: Whether to copy the expression. **opts: Other options to use to parse the input expressions.
Returns: Merge: The syntax tree for the MERGE statement. """ expressions: list[Expr] = [] for when_expr in when_exprs: expression = maybe_parse(when_expr, dialect=dialect, copy=copy, into=Whens, **opts) expressions.extend([expression] if isinstance(expression, When) else expression.expressions)
merge = Merge( this=maybe_parse(into, dialect=dialect, copy=copy, **opts), using=maybe_parse(using, dialect=dialect, copy=copy, **opts), on=maybe_parse(on, dialect=dialect, copy=copy, **opts), whens=Whens(expressions=expressions), ) if returning: merge = merge.returning(returning, dialect=dialect, copy=False, **opts)
if isinstance(using_clause := merge.args.get("using"), Alias): using_clause.replace(alias_(using_clause.this, using_clause.args["alias"], table=True))
return merge
def parse_identifier(name: str | Identifier, dialect: DialectType = None) -> Identifier: """ Parses a given string into an identifier.
Args: name: The name to parse into an identifier. dialect: The dialect to parse against.
Returns: The identifier ast node. """ if isinstance(name, str) and SAFE_IDENTIFIER_RE.match(name): # Simple names parse to a single unquoted identifier in all dialects, so we can # avoid the tokenizer/parser round-trip for them. return Identifier(this=name, quoted=False)
try: expression = maybe_parse(name, dialect=dialect, into=Identifier) except (ParseError, TokenError): expression = to_identifier(name)
return expression
INTERVAL_STRING_RE = re.compile(r"\s*(-?[0-9]+(?:\.[0-9]+)?)\s*([a-zA-Z]+)\s*")
INTERVAL_DAY_TIME_RE = re.compile( r"\s*-?\s*\d+(?:\.\d+)?\s+(?:-?(?:\d+:)?\d+:\d+(?:\.\d+)?|-?(?:\d+:){1,2}|:)\s*")
def to_interval(interval: str | Expr) -> Interval: """Builds an interval expression from a string like '1 day' or '5 months'.""" if isinstance(interval, Literal): if not interval.is_string: raise ValueError("Invalid interval string.")
interval = interval.this
interval = maybe_parse(f"INTERVAL {interval}") assert isinstance(interval, Interval) return interval
def to_table( sql_path: str | Table, dialect: DialectType = None, copy: bool = True, **kwargs: object) -> Table: """ Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. If a table is passed in then that table is returned.
Args: sql_path: a `[catalog].[schema].[table]` string. dialect: the source dialect according to which the table name will be parsed. copy: Whether to copy a table if it is passed in. kwargs: the kwargs to instantiate the resulting `Table` expression with.
Returns: A table expression. """ if isinstance(sql_path, Table): return maybe_copy(sql_path, copy=copy)
try: table = maybe_parse(sql_path, into=Table, dialect=dialect) except ParseError: catalog, db, this = split_num_words(sql_path, ".", 3)
if not this: raise
table = table_(this, db=db, catalog=catalog)
return table.set_kwargs(kwargs)
def to_column( sql_path: str | Column, quoted: bool | None = None, dialect: DialectType = None, copy: bool = True, **kwargs: t.Any,) -> Column | Dot: """ Create a column from a `[table].[column]` sql path. Table is optional. If a column is passed in then that column is returned.
Args: sql_path: a `[table].[column]` string. quoted: Whether or not to force quote identifiers. dialect: the source dialect according to which the column name will be parsed. copy: Whether to copy a column if it is passed in. kwargs: the kwargs to instantiate the resulting `Column` expression with.
Returns: A column expression. """ if isinstance(sql_path, Column): return maybe_copy(sql_path, copy=copy)
try: col = maybe_parse(sql_path, into=Column, dialect=dialect) except ParseError: return column(*reversed(sql_path.split(".")), quoted=quoted, **kwargs)
for k, v in kwargs.items(): col.set(k, v)
if quoted: for i in col.find_all(Identifier): i.set("quoted", True)
return col
def subquery( expression: ExpOrStr, alias: Identifier | str | None = None, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Select: """ Build a subquery expression that's selected from.
Example: >>> subquery('select x from tbl', 'bar').select('x').sql() 'SELECT x FROM (SELECT x FROM tbl) AS bar'
Args: expression: the SQL code strings to parse. If an Expr instance is passed, this is used as-is. alias: the alias name to use. dialect: the dialect used to parse the input expression. **opts: other options to use to parse the input expressions.
Returns: A new Select instance with the subquery expression included. """ expr = ( maybe_parse(expression, dialect=dialect, **opts).assert_is(Query).subquery(alias, copy=copy) ) return Select().from_(expr, dialect=dialect, **opts)
def cast( expression: ExpOrStr, to: DATA_TYPE, copy: bool = True, dialect: DialectType = None, **opts: Unpack[ParserNoDialectArgs],) -> Cast: """Cast an expression to a data type.
Example: >>> cast('x + 1', 'int').sql() 'CAST(x + 1 AS INT)'
Args: expression: The expression to cast. to: The datatype to cast to. copy: Whether to copy the supplied expressions. dialect: The target dialect. This is used to prevent a re-cast in the following scenario: - The expression to be cast is already a exp.Cast expression - The existing cast is to a type that is logically equivalent to new type
For example, if :expression='CAST(x as DATETIME)' and :to=Type.TIMESTAMP, but in the target dialect DATETIME is mapped to TIMESTAMP, then we will NOT return `CAST(x (as DATETIME) as TIMESTAMP)` and instead just return the original expression `CAST(x as DATETIME)`.
This is to prevent it being output as a double cast `CAST(x (as TIMESTAMP) as TIMESTAMP)` once the DATETIME -> TIMESTAMP mapping is applied in the target dialect generator.
Returns: The new Cast instance. """ expr = maybe_parse(expression, copy=copy, dialect=dialect, **opts) data_type = DataType.build(to, copy=copy, dialect=dialect, **opts)
# dont re-cast if the expression is already a cast to the correct type if isinstance(expr, Cast): from sqlglot.dialects.dialect import Dialect
target_dialect = Dialect.get_or_raise(dialect) type_mapping = target_dialect.generator_class.TYPE_MAPPING
existing_cast_type = expr.to.this new_cast_type: DType = data_type.this # `this` is only a plain type enum for simple types; complex ones such as # INTERVAL nest another expression there, so the equivalence check is skipped. types_are_equivalent = ( isinstance(existing_cast_type, DType) and isinstance(new_cast_type, DType) and type_mapping.get(existing_cast_type, existing_cast_type.value) == type_mapping.get(new_cast_type, new_cast_type.value) )
if expr.is_type(data_type) or types_are_equivalent: return expr
expr = Cast(this=expr, to=data_type) expr.type = data_type
return expr
def table_( table: Identifier | str | None, db: Identifier | str | None = None, catalog: Identifier | str | None = None, quoted: bool | None = None, alias: Identifier | str | None = None,) -> Table: """Build a Table.
Args: table: Table name. db: Database name. catalog: Catalog name. quote: Whether to force quotes on the table's identifiers. alias: Table's alias.
Returns: The new Table instance. """ return Table( this=to_identifier(table, quoted=quoted) if table else None, db=to_identifier(db, quoted=quoted) if db else None, catalog=to_identifier(catalog, quoted=quoted) if catalog else None, alias=TableAlias(this=to_identifier(alias)) if alias else None, )
def values( values: Iterable[tuple[object, ...] | Tuple], alias: str | None = None, columns: Iterable[str] | dict[str, DataType] | None = None,) -> Values: """Build VALUES statement.
Example: >>> values([(1, '2')]).sql() "VALUES (1, '2')"
Args: values: values statements that will be converted to SQL alias: optional alias columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns: Values: the Values expression object """ if columns and not alias: raise ValueError("Alias is required when providing columns")
return Values( expressions=[convert(tup) for tup in values], alias=( TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) if columns else (TableAlias(this=to_identifier(alias)) if alias else None) ), )
def var(name: ExpOrStr | None) -> Var: """Build a SQL variable.
Example: >>> repr(var('x')) 'Var(this=x)'
>>> repr(var(column('x', table='y'))) 'Var(this=x)'
Args: name: The name of the var or an expression who's name will become the var.
Returns: The new variable node. """ if not name: raise ValueError("Cannot convert empty name into var.")
if isinstance(name, Expr): name = name.name return Var(this=name)
def rename_table( old_name: str | Table, new_name: str | Table, dialect: DialectType = None,) -> Alter: """Build ALTER TABLE... RENAME... expression
Args: old_name: The old name of the table new_name: The new name of the table dialect: The dialect to parse the table.
Returns: Alter table expression """ old_table = to_table(old_name, dialect=dialect) new_table = to_table(new_name, dialect=dialect) return Alter( this=old_table, kind="TABLE", actions=[ AlterRename(this=new_table), ], )
def rename_column( table_name: str | Table, old_column_name: str | Column, new_column_name: str | Column, exists: bool | None = None, dialect: DialectType = None,) -> Alter: """Build ALTER TABLE... RENAME COLUMN... expression
Args: table_name: Name of the table old_column: The old name of the column new_column: The new name of the column exists: Whether to add the `IF EXISTS` clause dialect: The dialect to parse the table/column.
Returns: Alter table expression """ table = to_table(table_name, dialect=dialect) old_column = to_column(old_column_name, dialect=dialect) new_column = to_column(new_column_name, dialect=dialect) return Alter( this=table, kind="TABLE", actions=[ RenameColumn(this=old_column, to=new_column, exists=exists), ], )
def replace_children( expression: Expr, fun: t.Callable[Concatenate[Expr, P], object], *args: P.args, **kwargs: P.kwargs,) -> None: """ Replace children of an expression with the result of a lambda fun(child) -> exp. """ for k, v in tuple(expression.args.items()): is_list_arg = type(v) is list
child_nodes = v if is_list_arg else [v] new_child_nodes = []
for cn in child_nodes: if isinstance(cn, Expr): for child_node in ensure_collection(fun(cn, *args, **kwargs)): new_child_nodes.append(child_node) else: new_child_nodes.append(cn)
if is_list_arg: expression.set(k, new_child_nodes) else: expression.set(k, seq_get(new_child_nodes, 0))
def replace_tree( expression: Expr, fun: t.Callable[[Expr], Expr], prune: t.Callable[[Expr], bool] | None = None,) -> Expr: """ Replace an entire tree with the result of function calls on each node.
This will be traversed in reverse dfs, so leaves first. If new nodes are created as a result of function calls, they will also be traversed. """ stack = list(expression.dfs(prune=prune))
while stack: node = stack.pop() new_node = fun(node)
if new_node is not node: node.replace(new_node)
if isinstance(new_node, Expr): stack.append(new_node)
return new_node
def find_tables(expression: Expr) -> set[Table]: """ Find all tables referenced in a query.
Args: expressions: The query to find the tables in.
Returns: A set of all the tables. """ from sqlglot.optimizer.scope import traverse_scope
return { table for scope in traverse_scope(expression) for table in scope.tables if isinstance(table, Table) and table.name and table.name not in scope.cte_sources }
def column_table_names(expression: Expr, exclude: str = "") -> set[str]: """ Return all table names referenced through columns in an expression.
Example: >>> import sqlglot >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))) ['a', 'c']
Args: expression: expression to find table names. exclude: a table name to exclude
Returns: A list of unique names. """ return { table for table in (column.table for column in expression.find_all(Column)) if table and table != exclude }
def table_name(table: Table | str, dialect: DialectType = None, identify: bool = False) -> str: """Get the full name of a table as a string.
Args: table: Table expression node or string. dialect: The dialect to generate the table name for. identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True: Always quote.
Examples: >>> from sqlglot import exp, parse_one >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 'a.b.c'
Returns: The table name. """
expr = maybe_parse(table, into=Table, dialect=dialect)
if not expr: raise ValueError(f"Cannot parse {table}")
return ".".join( ( part.sql(dialect=dialect, identify=True, copy=False, comments=False) if identify or not SAFE_IDENTIFIER_RE.match(part.name) else part.name ) for part in expr.parts )
def normalize_table_name(table: str | Table, dialect: DialectType = None, copy: bool = True) -> str: """Returns a case normalized table name without quotes.
Args: table: the table to normalize dialect: the dialect to use for normalization rules copy: whether to copy the expression.
Examples: >>> normalize_table_name("`A-B`.c", dialect="bigquery") 'A-B.c' """ from sqlglot.optimizer.normalize_identifiers import normalize_identifiers
return ".".join( p.name for p in normalize_identifiers( to_table(table, dialect=dialect, copy=copy), dialect=dialect ).parts )
def replace_tables( expression: E, mapping: dict[str, str], dialect: DialectType = None, copy: bool = True) -> E: """Replace all tables in expression according to the mapping.
Args: expression: expression node to be transformed and replaced. mapping: mapping of table names. dialect: the dialect of the mapping table copy: whether to copy the expression.
Examples: >>> from sqlglot import exp, parse_one >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 'SELECT * FROM c /* a.b */'
Returns: The mapped expression. """
mapping = {normalize_table_name(k, dialect=dialect): v for k, v in mapping.items()}
def _replace_tables(node: Expr) -> Expr: if isinstance(node, Table) and node.meta_get("replace") is not False: original = normalize_table_name(node, dialect=dialect) new_name = mapping.get(original)
if new_name: table = to_table( new_name, **{k: v for k, v in node.args.items() if k not in TABLE_PARTS}, dialect=dialect, ) table.add_comments([original]) return table return node
return expression.transform(_replace_tables, copy=copy) # type: ignore
OPERATORS = (AtTimeZone, Between, Binary, BitwiseNot, In, Neg, Not)
def _is_operand(placeholder: Placeholder) -> bool: parent = placeholder.parent if isinstance(parent, (Bracket, In)): return placeholder.arg_key == "this" return isinstance(parent, OPERATORS)
def _takes_query(placeholder: Placeholder) -> bool: parent = placeholder.parent if isinstance(parent, In): return placeholder.arg_key == "expressions" and len(parent.expressions) == 1 if isinstance(parent, Func): return len(list(parent.iter_expressions())) == 1 if isinstance(parent, Table): return isinstance(parent.parent, (Create, Subquery)) return not parent or isinstance(parent, (CTE, Paren, SetOperation))
def _replace_placeholder(placeholder: Placeholder, expression: Expr) -> Expr: if ( isinstance(expression, Query) and not isinstance(expression, Subquery) and not _takes_query(placeholder) ): return expression.subquery(copy=False) if ( _is_operand(placeholder) and isinstance(expression, OPERATORS) and not isinstance(expression, Dot) ): return Paren(this=expression) return expression
def replace_placeholders(expression: Expr, *args: object, **kwargs: t.Any) -> Expr: """Replace placeholders in an expression.
Args: expression: expression node to be transformed and replaced. args: positional names that will substitute unnamed placeholders in the given order. kwargs: keyword arguments that will substitute named placeholders.
Examples: >>> from sqlglot import exp, parse_one >>> replace_placeholders( ... parse_one("select * from :tbl where ? = ?"), ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") ... ).sql() "SELECT * FROM foo WHERE str_col = 'b'"
Returns: The mapped expression. """
def _replace_placeholders(node: Expr, args: Iterator[object], **kwargs: object) -> Expr: if isinstance(node, Placeholder): if node.this: new_name = kwargs.get(node.this) if new_name is not None: return _replace_placeholder(node, convert(new_name)) else: try: return _replace_placeholder(node, convert(next(args))) except StopIteration: pass return node
return expression.transform(_replace_placeholders, iter(args), **kwargs)
def expand( expression: Expr, sources: dict[str, Query | t.Callable[[], Query]], dialect: DialectType = None, copy: bool = True,) -> Expr: """Transforms an expression by expanding all referenced sources into subqueries.
Examples: >>> from sqlglot import parse_one >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Args: expression: The expression to expand. sources: A dict of name to query or a callable that provides a query on demand. dialect: The dialect of the sources dict or the callable. copy: Whether to copy the expression during transformation. Defaults to True.
Returns: The transformed expression. """ normalized_sources = {normalize_table_name(k, dialect=dialect): v for k, v in sources.items()}
def _expand(node: Expr): if isinstance(node, Table): name = normalize_table_name(node, dialect=dialect) source = normalized_sources.get(name)
if source: # Create a subquery with the same alias (or table name if no alias) parsed_source = source() if callable(source) else source subquery = parsed_source.subquery(node.alias or name) subquery.comments = [f"source: {name}"]
# Continue expanding within the subquery return subquery.transform(_expand, copy=False)
return node
return expression.transform(_expand, copy=copy)
def func( name: str, *args: t.Any, copy: bool = True, dialect: DialectType = None, **kwargs: t.Any) -> Func: """ Returns a Func expression.
Examples: >>> func("abs", 5).sql() 'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 'CAST(5 AS DOUBLE)'
Args: name: the name of the function to build. args: the args used to instantiate the function of interest. copy: whether to copy the argument expressions. dialect: the source dialect. kwargs: the kwargs used to instantiate the function of interest.
Note: The arguments `args` and `kwargs` are mutually exclusive.
Returns: An instance of the function of interest, or an anonymous function, if `name` doesn't correspond to an existing `sqlglot.expressions.Func` class. """ if args and kwargs: raise ValueError("Can't use both args and kwargs to instantiate a function.")
from sqlglot.dialects.dialect import Dialect
dialect = Dialect.get_or_raise(dialect)
converted: list[Expr] = [maybe_parse(arg, dialect=dialect, copy=copy) for arg in args] kwargs = {key: maybe_parse(value, dialect=dialect, copy=copy) for key, value in kwargs.items()}
constructor = dialect.parser_class.FUNCTIONS.get(name.upper()) if constructor: if converted: try: function = constructor(converted) except TypeError: function = constructor(converted, dialect=dialect) elif constructor.__name__ == "from_arg_list": function = constructor.__self__(**kwargs) # type: ignore else: from sqlglot.expressions import FUNCTION_BY_NAME as _FUNCTION_BY_NAME
constructor = _FUNCTION_BY_NAME.get(name.upper()) if constructor: function = constructor(**kwargs) else: raise ValueError( f"Unable to convert '{name}' into a Func. Either manually construct " "the Func expression of interest or parse the function call." ) else: kwargs = kwargs or {"expressions": converted} function = Anonymous(this=name, **kwargs)
for error_message in function.error_messages(converted): raise ValueError(error_message)
return function
def case( expression: ExpOrStr | None = None, copy: bool = True, **opts: Unpack[ParserArgs],) -> Case: """ Initialize a CASE statement.
Example: case().when("a = 1", "foo").else_("bar")
Args: expression: Optionally, the input expression (not all dialects support this) copy: whether to copy the argument expressions. **opts: Extra keyword arguments for parsing `expression` """ if expression is not None: this = maybe_parse(expression, copy=copy, **opts) else: this = None return Case(this=this, ifs=[])
def array( *expressions: ExpOrStr, copy: bool = True, dialect: DialectType = None, **kwargs: Unpack[ParserNoDialectArgs],) -> Array: """ Returns an array.
Examples: >>> array(1, 'x').sql() 'ARRAY(1, x)'
Args: expressions: the expressions to add to the array. copy: whether to copy the argument expressions. dialect: the source dialect. kwargs: the kwargs used to instantiate the function of interest.
Returns: An array expression. """ return Array( expressions=[ maybe_parse(expression, copy=copy, dialect=dialect, **kwargs) for expression in expressions ] )
def tuple_( *expressions: ExpOrStr, copy: bool = True, dialect: DialectType = None, **kwargs: Unpack[ParserNoDialectArgs],) -> Tuple: """ Returns an tuple.
Examples: >>> tuple_(1, 'x').sql() '(1, x)'
Args: expressions: the expressions to add to the tuple. copy: whether to copy the argument expressions. dialect: the source dialect. kwargs: the kwargs used to instantiate the function of interest.
Returns: A tuple expression. """ return Tuple( expressions=[ maybe_parse(expression, copy=copy, dialect=dialect, **kwargs) for expression in expressions ] )
def true() -> Boolean: """ Returns a true Boolean expression. """ return Boolean(this=True)
def false() -> Boolean: """ Returns a false Boolean expression. """ return Boolean(this=False)
def null() -> Null: """ Returns a Null expression. """ return Null()
def apply_index_offset( this: Expr, expressions: list[E], offset: int, dialect: DialectType = None,) -> list[E]: if not offset or len(expressions) != 1: return expressions
expression = expressions[0]
from sqlglot.optimizer.annotate_types import annotate_types from sqlglot.optimizer.simplify import simplify
if not this.type: annotate_types(this, dialect=dialect)
if t.cast(DataType, this.type).this not in ( DType.UNKNOWN, DType.ARRAY, ): return expressions
if not expression.type: annotate_types(expression, dialect=dialect)
if t.cast(DataType, expression.type).this in DataType.INTEGER_TYPES: logger.info("Applying array index offset (%s)", offset) expression = simplify(expression + offset) return [expression]
return expressions
NONNULL_CONSTANTS = ( Literal, Boolean,)
CONSTANTS = ( Literal, Boolean, Null,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"""sqlglot expressions constraints."""
from __future__ import annotations
from sqlglot.expressions.core import Expression, ColumnConstraintKind
class IndexConstraintOption(Expression): arg_types = { "key_block_size": False, "using": False, "parser": False, "comment": False, "visible": False, "engine_attr": False, "secondary_engine_attr": False, }
class Reference(Expression): arg_types = {"this": True, "expressions": False, "options": False}
class ColumnConstraint(Expression): arg_types = {"this": False, "kind": True}
@property def kind(self) -> ColumnConstraintKind | Reference: return self.args["kind"]
class AutoIncrementColumnConstraint(Expression, ColumnConstraintKind): pass
class InvisibleColumnConstraint(Expression, ColumnConstraintKind): arg_types = {}
class ZeroFillColumnConstraint(ColumnConstraint): arg_types = {}
class BinaryColumnConstraint(ColumnConstraint): arg_types = {}
class PeriodForSystemTimeConstraint(Expression, ColumnConstraintKind): arg_types = {"this": True, "expression": True}
class CaseSpecificColumnConstraint(Expression, ColumnConstraintKind): arg_types = {"not_": True}
class CharacterSetColumnConstraint(Expression, ColumnConstraintKind): pass
class CheckColumnConstraint(Expression, ColumnConstraintKind): arg_types = {"this": True, "enforced": False}
class AssumeColumnConstraint(Expression, ColumnConstraintKind): pass
class ClusteredColumnConstraint(Expression, ColumnConstraintKind): pass
class CollateColumnConstraint(Expression, ColumnConstraintKind): pass
class CommentColumnConstraint(Expression, ColumnConstraintKind): pass
class CompressColumnConstraint(Expression, ColumnConstraintKind): arg_types = {"this": False}
class DateFormatColumnConstraint(Expression, ColumnConstraintKind): pass
class DefaultColumnConstraint(Expression, ColumnConstraintKind): pass
class EncodeColumnConstraint(Expression, ColumnConstraintKind): pass
class ExcludeColumnConstraint(Expression, ColumnConstraintKind): pass
class EphemeralColumnConstraint(Expression, ColumnConstraintKind): arg_types = {"this": False}
class WithOperator(Expression): arg_types = {"this": True, "op": True}
class GeneratedAsIdentityColumnConstraint(Expression, ColumnConstraintKind): # this: True -> ALWAYS, this: False -> BY DEFAULT arg_types = { "this": False, "expression": False, "on_null": False, "start": False, "increment": False, "minvalue": False, "maxvalue": False, "cycle": False, "order": False, }
class GeneratedAsRowColumnConstraint(Expression, ColumnConstraintKind): arg_types = {"start": False, "hidden": False}
class IndexColumnConstraint(Expression, ColumnConstraintKind): arg_types = { "this": False, "expressions": False, "kind": False, "index_type": False, "options": False, "expression": False, # Clickhouse "granularity": False, }
class InlineLengthColumnConstraint(Expression, ColumnConstraintKind): pass
class NonClusteredColumnConstraint(Expression, ColumnConstraintKind): pass
class NotForReplicationColumnConstraint(Expression, ColumnConstraintKind): arg_types = {}
class MaskingPolicyColumnConstraint(Expression, ColumnConstraintKind): arg_types = {"this": True, "expressions": False}
class NotNullColumnConstraint(Expression, ColumnConstraintKind): arg_types = {"allow_null": False}
class OnUpdateColumnConstraint(Expression, ColumnConstraintKind): pass
class PrimaryKeyColumnConstraint(Expression, ColumnConstraintKind): arg_types = {"desc": False, "options": False}
class TitleColumnConstraint(Expression, ColumnConstraintKind): pass
class UniqueColumnConstraint(Expression, ColumnConstraintKind): arg_types = { "this": False, "index_type": False, "on_conflict": False, "nulls": False, "options": False, }
class UppercaseColumnConstraint(Expression, ColumnConstraintKind): arg_types = {}
class WatermarkColumnConstraint(Expression): arg_types = {"this": True, "expression": True}
class PathColumnConstraint(Expression, ColumnConstraintKind): pass
class ProjectionPolicyColumnConstraint(Expression, ColumnConstraintKind): pass
class ComputedColumnConstraint(Expression, ColumnConstraintKind): arg_types = {"this": True, "persisted": False, "not_null": False, "data_type": False}
class InOutColumnConstraint(Expression, ColumnConstraintKind): arg_types = {"input_": False, "output": False, "variadic": False}
class Constraint(Expression): arg_types = {"this": True, "expressions": True}
class ForeignKey(Expression): arg_types = { "this": False, "expressions": False, "reference": False, "delete": False, "update": False, "options": False, }
class ColumnPrefix(Expression): arg_types = {"this": True, "expression": True}
class PrimaryKey(Expression): arg_types = {"this": False, "expressions": True, "options": False, "include": False}
# https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-ddl-create-table-constraintclass TimeseriesKey(Expression): pass
class IndexParameters(Expression): arg_types = { "using": False, "include": False, "columns": False, "with_storage": False, "partition_by": False, "tablespace": False, "where": False, "on": False, }
class AddConstraint(Expression): arg_types = {"expressions": True}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138"""sqlglot expressions core - base classes, traits, operators, and helpers."""
from __future__ import annotations
import datetimeimport loggingimport mathimport numbersimport reimport sysimport textwrapimport typing as tfrom builtins import type as Typefrom collections import dequefrom collections.abc import Collection, Iterator, Mapping, MutableMapping, Sequencefrom copy import deepcopyfrom decimal import Decimal, InvalidOperationfrom functools import reduce
from sqlglot._typing import E, GeneratorNoDialectArgs, ParserNoDialectArgs, Tfrom sqlglot.errors import ParseErrorfrom sqlglot.helper import ( camel_to_snake_case, ensure_list, seq_get, to_bool, trait,)from sqlglot.tokenizer_core import Token
if t.TYPE_CHECKING: from typing_extensions import Concatenate, Self, Unpack
from sqlglot._typing import P from sqlglot.dialects.dialect import DialectType from sqlglot.expressions.datatypes import DATA_TYPE, DataType, DType, Interval from sqlglot.expressions.query import Select
R = t.TypeVar("R")
logger = logging.getLogger("sqlglot")
SQLGLOT_META: str = "sqlglot.meta"SQLGLOT_ANONYMOUS = "sqlglot.anonymous"TABLE_PARTS = ("this", "db", "catalog")COLUMN_PARTS = ("this", "table", "db", "catalog")POSITION_META_KEYS: tuple[str, ...] = ("line", "col", "start", "end")UNITTEST: bool = "unittest" in sys.modules or "pytest" in sys.modules
@traitclass Expr: """ The base class for all expressions in a syntax tree. Each Expr encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.
Attributes: key: a unique key for each class in the Expr hierarchy. This is useful for hashing and representing expressions as strings. arg_types: determines the arguments (child nodes) supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional. parent: a reference to the parent expression (or None, in case of root expressions). arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it. index: the index of an expression if it is inside of a list argument in its parent. comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code. type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information. meta: a dictionary that can be used to store useful metadata for a given expression.
Example: >>> class Foo(Expr): ... arg_types = {"this": True, "expression": False}
The above definition informs us that Foo is an Expr that requires an argument called "this" and may also optionally receive an argument called "expression".
Args: args: a mapping used for retrieving the arguments of an expression, given their arg keys. """
key: t.ClassVar[str] = "expression" arg_types: t.ClassVar[dict[str, bool]] = {"this": True} required_args: t.ClassVar[set[str]] = {"this"} is_var_len_args: t.ClassVar[bool] = False var_len_arg_key: t.ClassVar[str] = "expressions" _hash_raw_args: t.ClassVar[bool] = False is_subquery: t.ClassVar[bool] = False is_cast: t.ClassVar[bool] = False is_data_type: t.ClassVar[bool] = False
args: dict[str, t.Any] parent: Expr | None arg_key: str | None index: int | None comments: list[str] | None _type: DataType | None _meta: dict[str, t.Any] | None _hash: int | None
@classmethod def __init_subclass__(cls, **kwargs: t.Any) -> None: super().__init_subclass__(**kwargs) # When an Expr class is created, its key is automatically set # to be the lowercase version of the class' name. cls.key = cls.__name__.lower() cls.required_args = {k for k, v in cls.arg_types.items() if v} # This is so that docstrings are not inherited in pdoc setattr(cls, "__doc__", getattr(cls, "__doc__", None) or "")
is_primitive: t.ClassVar[bool] = False
def __init__(self, **args: object) -> None: self.args: dict[str, t.Any] = args self.parent: Expr | None = None self.arg_key: str | None = None self.index: int | None = None self.comments: list[str] | None = None self._type: DataType | None = None self._meta: dict[str, t.Any] | None = None self._hash: int | None = None
if not self.is_primitive: for arg_key, value in self.args.items(): self._set_parent(arg_key, value)
@property def this(self) -> t.Any: """ Retrieves the argument with key "this". """ raise NotImplementedError
@property def expression(self) -> t.Any: """ Retrieves the argument with key "expression". """ raise NotImplementedError
@property def expressions(self) -> list[t.Any]: """ Retrieves the argument with key "expressions". """ raise NotImplementedError
def text(self, key: str) -> str: """ Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expr instances, such as identifiers and literals. """ raise NotImplementedError
@property def is_string(self) -> bool: """ Checks whether a Literal expression is a string. """ raise NotImplementedError
@property def is_number(self) -> bool: """ Checks whether a Literal expression is a number. """ raise NotImplementedError
def to_py(self) -> t.Any: """ Returns a Python object equivalent of the SQL node. """ raise NotImplementedError
@property def is_int(self) -> bool: """ Checks whether an expression is an integer. """ raise NotImplementedError
@property def is_star(self) -> bool: """Checks whether an expression is a star.""" raise NotImplementedError
@property def alias(self) -> str: """ Returns the alias of the expression, or an empty string if it's not aliased. """ raise NotImplementedError
@property def alias_column_names(self) -> list[str]: raise NotImplementedError
@property def name(self) -> str: raise NotImplementedError
@property def alias_or_name(self) -> str: raise NotImplementedError
@property def output_name(self) -> str: """ Name of the output column if this expression is a selection.
If the Expr has no output name, an empty string is returned.
Example: >>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name '' """ raise NotImplementedError
@property def type(self) -> DataType | None: raise NotImplementedError
@type.setter def type(self, dtype: DataType | DType | str | None) -> None: raise NotImplementedError
def is_type(self, *dtypes: DATA_TYPE) -> bool: raise NotImplementedError
def is_leaf(self) -> bool: raise NotImplementedError
@property def meta(self) -> dict[str, t.Any]: raise NotImplementedError
def meta_get(self, key: str, default: t.Any = None) -> t.Any: raise NotImplementedError
def __deepcopy__(self, memo: t.Any) -> Expr: raise NotImplementedError
def copy(self: E) -> E: """ Returns a deep copy of the expression. """ raise NotImplementedError
def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None: raise NotImplementedError
def pop_comments(self) -> list[str]: raise NotImplementedError
def append(self, arg_key: str, value: t.Any) -> None: """ Appends value to arg_key if it's a list or sets it as a new list.
Args: arg_key (str): name of the list expression arg value (Any): value to append to the list """ raise NotImplementedError
def set( self, arg_key: str, value: object, index: int | None = None, overwrite: bool = True, ) -> None: """ Sets arg_key to value.
Args: arg_key: name of the expression arg. value: value to set the arg to. index: if the arg is a list, this specifies what position to add the value in it. overwrite: assuming an index is given, this determines whether to overwrite the list entry instead of only inserting a new value (i.e., like list.insert). """ raise NotImplementedError
def _set_parent(self, arg_key: str, value: object, index: int | None = None) -> None: raise NotImplementedError
@property def depth(self) -> int: """ Returns the depth of this tree. """ raise NotImplementedError
def iter_expressions(self: E, reverse: bool = False) -> Iterator[E]: """Yields the key and expression for all arguments, exploding list args.""" raise NotImplementedError
def find(self, *expression_types: Type[E], bfs: bool = True) -> E | None: """ Returns the first node in this tree which matches at least one of the specified types.
Args: expression_types: the expression type(s) to match. bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns: The node which matches the criteria or None if no such node was found. """ raise NotImplementedError
def find_all(self, *expression_types: Type[E], bfs: bool = True) -> Iterator[E]: """ Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.
Args: expression_types: the expression type(s) to match. bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns: The generator object. """ raise NotImplementedError
def find_ancestor(self, *expression_types: Type[E]) -> E | None: """ Returns a nearest parent matching expression_types.
Args: expression_types: the expression type(s) to match.
Returns: The parent node. """ raise NotImplementedError
@property def parent_select(self) -> Select | None: """ Returns the parent select statement. """ raise NotImplementedError
@property def same_parent(self) -> bool: """Returns if the parent is the same class as itself.""" raise NotImplementedError
def root(self) -> Expr: """ Returns the root expression of this tree. """ raise NotImplementedError
def walk( self, bfs: bool = True, prune: t.Callable[[Expr], bool] | None = None ) -> Iterator[Expr]: """ Returns a generator object which visits all nodes in this tree.
Args: bfs: if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead. prune: callable that returns True if the generator should stop traversing this branch of the tree.
Returns: the generator object. """ raise NotImplementedError
def dfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]: """ Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.
Returns: The generator object. """ raise NotImplementedError
def bfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]: """ Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.
Returns: The generator object. """ raise NotImplementedError
def unnest(self) -> Expr: """ Returns the first non parenthesis child or self. """ raise NotImplementedError
def unalias(self) -> Expr: """ Returns the inner expression if this is an Alias. """ raise NotImplementedError
def unnest_operands(self) -> tuple[Expr, ...]: """ Returns unnested operands as a tuple. """ raise NotImplementedError
def flatten(self, unnest: bool = True) -> Iterator[Expr]: """ Returns a generator which yields child nodes whose parents are the same class.
A AND B AND C -> [A, B, C] """ raise NotImplementedError
def to_s(self) -> str: """ Same as __repr__, but includes additional information which can be useful for debugging, like empty or missing args and the AST nodes' object IDs. """ raise NotImplementedError
def sql( self, dialect: DialectType = None, copy: bool = True, **opts: Unpack[GeneratorNoDialectArgs] ) -> str: """ Returns SQL string representation of this tree.
Args: dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). opts: other `sqlglot.generator.Generator` options.
Returns: The SQL string. """ raise NotImplementedError
def transform( self, fun: t.Callable[..., T], *args: object, copy: bool = True, **kwargs: object ) -> T: """ Visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.
Args: fun: a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree. copy: if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns: The transformed tree. """ raise NotImplementedError
def replace(self, expression: T) -> T: """ Swap out this expression with a new expression.
For example::
>>> import sqlglot >>> tree = sqlglot.parse_one("SELECT x FROM tbl") >>> tree.find(sqlglot.exp.Column).replace(sqlglot.exp.column("y")) Column( this=Identifier(this=y, quoted=False)) >>> tree.sql() 'SELECT y FROM tbl'
Args: expression (T): new node
Returns: T: The new expression or expressions. """ raise NotImplementedError
def pop(self: E) -> E: """ Remove this expression from its AST.
Returns: The popped expression. """ raise NotImplementedError
def assert_is(self, type_: Type[E]) -> E: """ Assert that this `Expr` is an instance of `type_`.
If it is NOT an instance of `type_`, this raises an assertion error. Otherwise, this returns this expression.
Examples: This is useful for type security in chained expressions:
>>> import sqlglot >>> sqlglot.parse_one("SELECT x from y").assert_is(sqlglot.exp.Select).select("z").sql() 'SELECT x, z FROM y' """ raise NotImplementedError
def error_messages(self, args: Sequence[object] | None = None) -> list[str]: """ Checks if this expression is valid (e.g. all mandatory args are set).
Args: args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns: A list of error messages for all possible errors that were found. """ raise NotImplementedError
def dump(self) -> list[dict[str, t.Any]]: """ Dump this Expr to a JSON-serializable dict. """ from sqlglot.serde import dump
return dump(self)
@classmethod def load(cls, obj: list[dict[str, Any]] | None) -> Expr: """ Load a dict (as returned by `Expr.dump`) into an Expr instance. """ from sqlglot.serde import load
result = load(obj) assert isinstance(result, Expr) return result
def and_( self, *expressions: ExpOrStr | None, dialect: DialectType = None, copy: bool = True, wrap: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Condition: """ AND this condition with one or multiple expressions.
Example: >>> condition("x=1").and_("y=1").sql() 'x = 1 AND y = 1'
Args: *expressions: the SQL code strings to parse. If an `Expr` instance is passed, it will be used as-is. dialect: the dialect used to parse the input expression. copy: whether to copy the involved expressions (only applies to Exprs). wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues. opts: other options to use to parse the input expressions.
Returns: The new And condition. """ raise NotImplementedError
def or_( self, *expressions: ExpOrStr | None, dialect: DialectType = None, copy: bool = True, wrap: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Condition: """ OR this condition with one or multiple expressions.
Example: >>> condition("x=1").or_("y=1").sql() 'x = 1 OR y = 1'
Args: *expressions: the SQL code strings to parse. If an `Expr` instance is passed, it will be used as-is. dialect: the dialect used to parse the input expression. copy: whether to copy the involved expressions (only applies to Exprs). wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues. opts: other options to use to parse the input expressions.
Returns: The new Or condition. """ raise NotImplementedError
def not_(self, copy: bool = True) -> Not: """ Wrap this condition with NOT.
Example: >>> condition("x=1").not_().sql() 'NOT x = 1'
Args: copy: whether to copy this object.
Returns: The new Not instance. """ raise NotImplementedError
def update_positions( self: E, other: Token | Expr | None = None, line: int | None = None, col: int | None = None, start: int | None = None, end: int | None = None, ) -> E: """ Update this expression with positions from a token or other expression.
Args: other: a token or expression to update this expression with. line: the line number to use if other is None col: column number start: start char index end: end char index
Returns: The updated expression. """ raise NotImplementedError
def as_( self, alias: str | Identifier, quoted: bool | None = None, dialect: DialectType = None, copy: bool = True, table: bool | Sequence[str | Identifier] = False, **opts: Unpack[ParserNoDialectArgs], ) -> Expr: raise NotImplementedError
def _binop(self, klass: Type[E], other: t.Any, reverse: bool = False) -> E: raise NotImplementedError
def __getitem__(self, other: ExpOrStr | tuple[ExpOrStr, ...]) -> Bracket: raise NotImplementedError
def __iter__(self) -> Iterator: raise NotImplementedError
def isin( self, *expressions: t.Any, query: ExpOrStr | None = None, unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> In: raise NotImplementedError
def between( self, low: t.Any, high: t.Any, copy: bool = True, symmetric: bool | None = None ) -> Between: raise NotImplementedError
def is_(self, other: ExpOrStr) -> Is: raise NotImplementedError
def like(self, other: ExpOrStr) -> Like: raise NotImplementedError
def ilike(self, other: ExpOrStr) -> ILike: raise NotImplementedError
def eq(self, other: t.Any) -> EQ: raise NotImplementedError
def neq(self, other: t.Any) -> NEQ: raise NotImplementedError
def rlike(self, other: ExpOrStr) -> RegexpLike: raise NotImplementedError
def div(self, other: ExpOrStr, typed: bool = False, safe: bool = False) -> Div: raise NotImplementedError
def asc(self, nulls_first: bool = True) -> Ordered: raise NotImplementedError
def desc(self, nulls_first: bool = False) -> Ordered: raise NotImplementedError
def __lt__(self, other: t.Any) -> LT: raise NotImplementedError
def __le__(self, other: t.Any) -> LTE: raise NotImplementedError
def __gt__(self, other: t.Any) -> GT: raise NotImplementedError
def __ge__(self, other: t.Any) -> GTE: raise NotImplementedError
def __add__(self, other: t.Any) -> Add: raise NotImplementedError
def __radd__(self, other: t.Any) -> Add: raise NotImplementedError
def __sub__(self, other: t.Any) -> Sub: raise NotImplementedError
def __rsub__(self, other: t.Any) -> Sub: raise NotImplementedError
def __mul__(self, other: t.Any) -> Mul: raise NotImplementedError
def __rmul__(self, other: t.Any) -> Mul: raise NotImplementedError
def __truediv__(self, other: t.Any) -> Div: raise NotImplementedError
def __rtruediv__(self, other: t.Any) -> Div: raise NotImplementedError
def __floordiv__(self, other: t.Any) -> IntDiv: raise NotImplementedError
def __rfloordiv__(self, other: t.Any) -> IntDiv: raise NotImplementedError
def __mod__(self, other: t.Any) -> Mod: raise NotImplementedError
def __rmod__(self, other: t.Any) -> Mod: raise NotImplementedError
def __pow__(self, other: t.Any) -> Pow: raise NotImplementedError
def __rpow__(self, other: t.Any) -> Pow: raise NotImplementedError
def __and__(self, other: t.Any) -> And: raise NotImplementedError
def __rand__(self, other: t.Any) -> And: raise NotImplementedError
def __or__(self, other: t.Any) -> Or: raise NotImplementedError
def __ror__(self, other: t.Any) -> Or: raise NotImplementedError
def __neg__(self) -> Neg: raise NotImplementedError
def __invert__(self) -> Not: raise NotImplementedError
def pipe( self, func: t.Callable[Concatenate[Self, P], R], *args: P.args, **kwargs: P.kwargs ) -> R: """Apply a function to `Self` (the current instance) and return the result.
Doing `expr.pipe(func, *args, **kwargs)` is equivalent to `func(expr, *args, **kwargs)`.
It allows you to chain operations in a fluent way on any given function that takes `Self` as its first argument.
Tip: If `func` doesn't take `Self` as it's first argument, you can use a lambda to work around it.
Args: func: The function to apply. It should take `Self` as its first argument, followed by any additional arguments specified in `*args` and `**kwargs`. *args: Additional positional arguments to pass to `func` after `Self`. **kwargs: Additional keyword arguments to pass to `func`.
Returns: The result of applying `func` to `Self` with the given arguments. """ return func(self, *args, **kwargs)
def apply( self, func: t.Callable[Concatenate[Self, P], t.Any], *args: P.args, **kwargs: P.kwargs ) -> Self: """Apply a function to `Self` (the current instance) for side effects, and return `Self`.
Useful for inspecting intermediate expressions in a method chain by simply adding/removing `apply` calls, especially when combined with `pipe`.
Tip: If `func` doesn't take `Self` as it's first argument, you can use a lambda to work around it.
Args: func: The function to apply. It should take `Self` as its first argument, followed by any additional arguments specified in `*args` and `**kwargs`. *args: Additional positional arguments to pass to `func` after `Self`. **kwargs: Additional keyword arguments to pass to `func`.
Returns: The same instance. """ func(self, *args, **kwargs) return self
class Expression(Expr): __slots__ = ( "args", "parent", "arg_key", "index", "comments", "_type", "_meta", "_hash", )
def __eq__(self, other: object) -> bool: return self is other or (type(self) is type(other) and hash(self) == hash(other))
def __ne__(self, other: object) -> bool: return not self.__eq__(other)
def __hash__(self) -> int: if self._hash is None: nodes: list[Expr] = [] stack: list[Expr] = [self]
# Collect nodes, finding child expressions inline instead of via the # iter_expressions generator (whose per-node generator object dominates the # hash's cost). reversed(nodes) is a valid post-order regardless of DFS/BFS. while stack: node = stack.pop() nodes.append(node)
for v in node.args.values(): if isinstance(v, Expr): if v._hash is None: stack.append(v) elif type(v) is list: for x in v: if isinstance(x, Expr) and x._hash is None: stack.append(x)
for node in reversed(nodes): hash_ = hash(node.key)
if node._hash_raw_args: for k in sorted(node.args): v = node.args[k] if v: hash_ = hash((hash_, k, tuple(v) if type(v) is list else v)) else: for k in sorted(node.args): v = node.args[k] vt = type(v)
if vt is list: for x in v: if x is not None and x is not False: hash_ = hash((hash_, k, x.lower() if type(x) is str else x)) else: hash_ = hash((hash_, k)) elif v is not None and v is not False: hash_ = hash((hash_, k, v.lower() if vt is str else v))
node._hash = hash_ assert self._hash return self._hash
def __reduce__( self, ) -> tuple[ t.Callable[[list[dict[str, t.Any]] | None], Expr | DType | None], tuple[list[dict[str, t.Any]]], ]: from sqlglot.serde import dump, load
return (load, (dump(self),))
@property def this(self) -> t.Any: return self.args.get("this")
@property def expression(self) -> t.Any: return self.args.get("expression")
@property def expressions(self) -> list[t.Any]: return self.args.get("expressions") or []
def text(self, key: str) -> str: field = self.args.get(key) if isinstance(field, str): return field if isinstance(field, (Identifier, Literal, Var)): return field.this if isinstance(field, (Star, Null)): return field.name return ""
@property def is_string(self) -> bool: return isinstance(self, Literal) and self.args["is_string"]
@property def is_number(self) -> bool: return (isinstance(self, Literal) and not self.args["is_string"]) or ( isinstance(self, Neg) and self.this.is_number )
def to_py(self) -> t.Any: raise ValueError(f"{self} cannot be converted to a Python object.")
@property def is_int(self) -> bool: return self.is_number and isinstance(self.to_py(), int)
@property def is_star(self) -> bool: return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
@property def alias(self) -> str: alias = self.args.get("alias") if isinstance(alias, Expression): return alias.name return self.text("alias")
@property def alias_column_names(self) -> list[str]: table_alias = self.args.get("alias") if not table_alias: return [] return [c.name for c in table_alias.args.get("columns") or []]
@property def name(self) -> str: return self.text("this")
@property def alias_or_name(self) -> str: return self.alias or self.name
@property def output_name(self) -> str: return ""
@property def type(self) -> DataType | None: if self.is_data_type: return self # type: ignore[return-value] if self.is_cast: return self._type or self.to # type: ignore[attr-defined] return self._type
@type.setter def type(self, dtype: DataType | DType | str | None) -> None: if dtype and type(dtype).__name__ != "DataType": from sqlglot.expressions.datatypes import DataType as _DataType
dtype = _DataType.build(dtype) self._type = dtype # type: ignore[assignment]
def is_type(self, *dtypes: DATA_TYPE) -> bool: t = self._type return t is not None and t.is_type(*dtypes)
def is_leaf(self) -> bool: return not any((isinstance(v, Expr) or type(v) is list) and v for v in self.args.values())
@property def meta(self) -> dict[str, t.Any]: if self._meta is None: self._meta = {} return self._meta
def meta_get(self, key: str, default: t.Any = None) -> t.Any: """Reads a meta value without allocating the meta dict (unlike the `meta` property).""" meta = self._meta return meta.get(key, default) if meta is not None else default
def __deepcopy__(self, memo: t.Any) -> Expr: root = self.__class__() stack: list[tuple[Expr, Expr]] = [(self, root)]
while stack: node, copy = stack.pop()
if node.comments is not None: copy.comments = deepcopy(node.comments) if node._type is not None: copy._type = deepcopy(node._type) if node._meta is not None: copy._meta = deepcopy(node._meta) if node._hash is not None: copy._hash = node._hash
for k, vs in node.args.items(): if isinstance(vs, Expr): stack.append((vs, vs.__class__())) copy.set(k, stack[-1][-1]) elif type(vs) is list: copy.args[k] = []
for v in vs: if isinstance(v, Expr): stack.append((v, v.__class__())) copy.append(k, stack[-1][-1]) else: copy.append(k, v) else: copy.args[k] = vs
return root
def copy(self: E) -> E: return deepcopy(self)
def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None: if self.comments is None: self.comments = []
if comments: for comment in comments: _, *meta = comment.split(SQLGLOT_META) if meta: for kv in "".join(meta).split(","): k, *v = kv.split("=") self.meta[k.strip()] = to_bool(v[0].strip() if v else True)
if not prepend: self.comments.append(comment)
if prepend: self.comments = comments + self.comments
def pop_comments(self) -> list[str]: comments = self.comments or [] self.comments = None return comments
def append(self, arg_key: str, value: t.Any) -> None: node: Expr | None = self while node and node._hash is not None: node._hash = None node = node.parent
if type(self.args.get(arg_key)) is not list: self.args[arg_key] = [] self._set_parent(arg_key, value) values = self.args[arg_key] if isinstance(value, Expr): value.index = len(values) values.append(value)
def set( self, arg_key: str, value: object, index: int | None = None, overwrite: bool = True, ) -> None: node: Expr | None = self
while node and node._hash is not None: node._hash = None node = node.parent
if index is not None: expressions = self.args.get(arg_key) or []
if seq_get(expressions, index) is None: return
if value is None: expressions.pop(index) for v in expressions[index:]: v.index = v.index - 1 return
if isinstance(value, list): expressions.pop(index) expressions[index:index] = value elif overwrite: expressions[index] = value else: expressions.insert(index, value)
value = expressions elif value is None: self.args.pop(arg_key, None) return
self.args[arg_key] = value self._set_parent(arg_key, value, index)
def _set_parent(self, arg_key: str, value: object, index: int | None = None) -> None: if isinstance(value, Expr): value.parent = self value.arg_key = arg_key value.index = index elif isinstance(value, list): for i, v in enumerate(value): if isinstance(v, Expr): v.parent = self v.arg_key = arg_key v.index = i
def set_kwargs(self, kwargs: Mapping[str, object]) -> Self: """Set multiples keyword arguments at once, using `.set()` method.
Args: kwargs (Mapping[str, object]): a `Mapping` of arg keys to values to set. Returns: Self: The same `Expression` with the updated arguments. """ if kwargs: for k, v in kwargs.items(): self.set(k, v) return self
@property def depth(self) -> int: if self.parent: return self.parent.depth + 1 return 0
def iter_expressions(self: E, reverse: bool = False) -> Iterator[E]: for vs in reversed(self.args.values()) if reverse else self.args.values(): if isinstance(vs, list): for v in reversed(vs) if reverse else vs: if isinstance(v, Expr): yield t.cast(E, v) elif isinstance(vs, Expr): yield t.cast(E, vs)
def find(self, *expression_types: Type[E], bfs: bool = True) -> E | None: return next(self.find_all(*expression_types, bfs=bfs), None)
def find_all(self, *expression_types: Type[E], bfs: bool = True) -> Iterator[E]: for expression in self.walk(bfs=bfs): if isinstance(expression, expression_types): yield expression
def find_ancestor(self, *expression_types: Type[E]) -> E | None: ancestor = self.parent while ancestor and not isinstance(ancestor, expression_types): ancestor = ancestor.parent return ancestor # type: ignore[return-value]
@property def parent_select(self) -> Select | None: from sqlglot.expressions.query import Select as _Select
return self.find_ancestor(_Select)
@property def same_parent(self) -> bool: return type(self.parent) is self.__class__
def root(self) -> Expr: expression: Expr = self while expression.parent: expression = expression.parent return expression
def walk( self, bfs: bool = True, prune: t.Callable[[Expr], bool] | None = None ) -> Iterator[Expr]: if bfs: yield from self.bfs(prune=prune) else: yield from self.dfs(prune=prune)
def dfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]: stack = [self]
while stack: node = stack.pop() yield node if prune and prune(node): continue for v in node.iter_expressions(reverse=True): stack.append(v)
def bfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]: queue: deque[Expr] = deque() queue.append(self)
while queue: node = queue.popleft() yield node if prune and prune(node): continue for v in node.iter_expressions(): queue.append(v)
def unnest(self) -> Expr: expression = self while type(expression) is Paren: expression = expression.this return expression
def unalias(self) -> Expr: if isinstance(self, Alias): return self.this return self
def unnest_operands(self) -> tuple[Expr, ...]: return tuple(arg.unnest() for arg in self.iter_expressions())
def flatten(self, unnest: bool = True) -> Iterator[Expr]: for node in self.dfs(prune=lambda n: bool(n.parent and type(n) is not self.__class__)): if type(node) is not self.__class__: yield node.unnest() if unnest and not node.is_subquery else node
def __str__(self) -> str: return self.sql()
def __repr__(self) -> str: return _to_s(self)
def to_s(self) -> str: return _to_s(self, verbose=True)
def sql( self, dialect: DialectType = None, copy: bool = True, **opts: Unpack[GeneratorNoDialectArgs] ) -> str: from sqlglot.dialects.dialect import Dialect
return Dialect.get_or_raise(dialect).generate(self, copy=copy, **opts)
def transform( self, fun: t.Callable[..., T], *args: object, copy: bool = True, **kwargs: object ) -> T: root: t.Any = None new_node: t.Any = None
for node in (self.copy() if copy else self).dfs(prune=lambda n: n is not new_node): parent, arg_key, index = node.parent, node.arg_key, node.index new_node = fun(node, *args, **kwargs)
if not root: root = new_node elif parent and arg_key and new_node is not node: parent.set(arg_key, new_node, index)
assert root return root
def replace(self, expression: T) -> T: parent = self.parent
if not parent or parent is expression: return expression
key = self.arg_key
if key: value = parent.args.get(key)
if type(expression) is list and isinstance(value, Expr): # We are trying to replace an Expr with a list, so it's assumed that # the intention was to really replace the parent of this expression. if value.parent: value.parent.replace(expression) else: parent.set(key, expression, self.index)
if expression is not self: self.parent = None self.arg_key = None self.index = None
return expression
def pop(self: E) -> E: self.replace(None) return self
def assert_is(self, type_: Type[E]) -> E: if not isinstance(self, type_): raise AssertionError(f"{self} is not {type_}.") return self
def error_messages(self, args: Sequence[object] | None = None) -> list[str]: if UNITTEST: for k in self.args: if k not in self.arg_types: raise TypeError(f"Unexpected keyword: '{k}' for {self.__class__}")
errors: list[str] | None = None
for k in self.required_args: v = self.args.get(k) if v is None or (isinstance(v, list) and not v): if errors is None: errors = [] errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
if ( args and isinstance(self, Func) and len(args) > len(self.arg_types) and not self.is_var_len_args ): if errors is None: errors = [] errors.append( f"The number of provided arguments ({len(args)}) is greater than " f"the maximum number of supported arguments ({len(self.arg_types)})" )
return errors or []
def and_( self, *expressions: ExpOrStr | None, dialect: DialectType = None, copy: bool = True, wrap: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Condition: return and_(self, *expressions, dialect=dialect, copy=copy, wrap=wrap, **opts)
def or_( self, *expressions: ExpOrStr | None, dialect: DialectType = None, copy: bool = True, wrap: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Condition: return or_(self, *expressions, dialect=dialect, copy=copy, wrap=wrap, **opts)
def not_(self, copy: bool = True) -> Not: return not_(self, copy=copy)
def update_positions( self: E, other: Token | Expr | None = None, line: int | None = None, col: int | None = None, start: int | None = None, end: int | None = None, ) -> E: if isinstance(other, Token): meta = self.meta meta["line"] = other.line meta["col"] = other.col meta["start"] = other.start meta["end"] = other.end elif other is not None: other_meta = other._meta if other_meta: meta = self.meta for k in POSITION_META_KEYS: if k in other_meta: meta[k] = other_meta[k] else: meta = self.meta meta["line"] = line meta["col"] = col meta["start"] = start meta["end"] = end return self
def as_( self, alias: str | Identifier, quoted: bool | None = None, dialect: DialectType = None, copy: bool = True, table: bool | Sequence[str | Identifier] = False, **opts: Unpack[ParserNoDialectArgs], ) -> Expr: return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, table=table, **opts)
def _binop(self, klass: Type[E], other: t.Any, reverse: bool = False) -> E: this = self.copy() other = convert(other, copy=True) if not isinstance(this, klass) and not isinstance(other, klass): this = _wrap(this, Binary) other = _wrap(other, Binary) if reverse: return klass(this=other, expression=this) return klass(this=this, expression=other)
def __getitem__(self, other: ExpOrStr | tuple[ExpOrStr, ...]) -> Bracket: return Bracket( this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)] )
def __iter__(self) -> Iterator: if "expressions" in self.arg_types: return iter(self.args.get("expressions") or []) # We define this because __getitem__ converts Expr into an iterable, which is # problematic because one can hit infinite loops if they do "for x in some_expr: ..." # See: https://peps.python.org/pep-0234/ raise TypeError(f"'{self.__class__.__name__}' object is not iterable")
def isin( self, *expressions: t.Any, query: ExpOrStr | None = None, unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> In: from sqlglot.expressions.query import Query
subquery: Expr | None = None if query: subquery = maybe_parse(query, dialect=dialect, copy=copy, **opts) if isinstance(subquery, Query): subquery = subquery.subquery(copy=False) unnest_list: list[ExpOrStr] = ensure_list(unnest) return In( this=maybe_copy(self, copy), expressions=[convert(e, copy=copy) for e in expressions], query=subquery, unnest=( _lazy_unnest( expressions=[ maybe_parse(e, dialect=dialect, copy=copy, **opts) for e in unnest_list ] ) if unnest else None ), )
def between( self, low: t.Any, high: t.Any, copy: bool = True, symmetric: bool | None = None ) -> Between: between = Between( this=maybe_copy(self, copy), low=convert(low, copy=copy), high=convert(high, copy=copy), ) if symmetric is not None: between.set("symmetric", symmetric)
return between
def is_(self, other: ExpOrStr) -> Is: return self._binop(Is, other)
def like(self, other: ExpOrStr) -> Like: return self._binop(Like, other)
def ilike(self, other: ExpOrStr) -> ILike: return self._binop(ILike, other)
def eq(self, other: t.Any) -> EQ: return self._binop(EQ, other)
def neq(self, other: t.Any) -> NEQ: return self._binop(NEQ, other)
def rlike(self, other: ExpOrStr) -> RegexpLike: return self._binop(RegexpLike, other)
def div(self, other: ExpOrStr, typed: bool = False, safe: bool = False) -> Div: div = self._binop(Div, other) div.set("typed", typed) div.set("safe", safe) return div
def asc(self, nulls_first: bool = True) -> Ordered: return Ordered(this=self.copy(), nulls_first=nulls_first)
def desc(self, nulls_first: bool = False) -> Ordered: return Ordered(this=self.copy(), desc=True, nulls_first=nulls_first)
def __lt__(self, other: t.Any) -> LT: return self._binop(LT, other)
def __le__(self, other: t.Any) -> LTE: return self._binop(LTE, other)
def __gt__(self, other: t.Any) -> GT: return self._binop(GT, other)
def __ge__(self, other: t.Any) -> GTE: return self._binop(GTE, other)
def __add__(self, other: t.Any) -> Add: return self._binop(Add, other)
def __radd__(self, other: t.Any) -> Add: return self._binop(Add, other, reverse=True)
def __sub__(self, other: t.Any) -> Sub: return self._binop(Sub, other)
def __rsub__(self, other: t.Any) -> Sub: return self._binop(Sub, other, reverse=True)
def __mul__(self, other: t.Any) -> Mul: return self._binop(Mul, other)
def __rmul__(self, other: t.Any) -> Mul: return self._binop(Mul, other, reverse=True)
def __truediv__(self, other: t.Any) -> Div: return self._binop(Div, other)
def __rtruediv__(self, other: t.Any) -> Div: return self._binop(Div, other, reverse=True)
def __floordiv__(self, other: t.Any) -> IntDiv: return self._binop(IntDiv, other)
def __rfloordiv__(self, other: t.Any) -> IntDiv: return self._binop(IntDiv, other, reverse=True)
def __mod__(self, other: t.Any) -> Mod: return self._binop(Mod, other)
def __rmod__(self, other: t.Any) -> Mod: return self._binop(Mod, other, reverse=True)
def __pow__(self, other: t.Any) -> Pow: return self._binop(Pow, other)
def __rpow__(self, other: t.Any) -> Pow: return self._binop(Pow, other, reverse=True)
def __and__(self, other: t.Any) -> And: return self._binop(And, other)
def __rand__(self, other: t.Any) -> And: return self._binop(And, other, reverse=True)
def __or__(self, other: t.Any) -> Or: return self._binop(Or, other)
def __ror__(self, other: t.Any) -> Or: return self._binop(Or, other, reverse=True)
def __neg__(self) -> Neg: return Neg(this=_wrap(self.copy(), Binary))
def __invert__(self) -> Not: return not_(self.copy())
IntoType = t.Union[Type[Expr], Collection[Type[Expr]]]ExpOrStr = t.Union[int, str, Expr]
@traitclass Condition(Expr): """Logical conditions like x AND y, or simply x"""
@traitclass Predicate(Condition): """Any condition that evaluates to a boolean, e.g. x = y, x LIKE 'a%', a @> b."""
class Cache(Expression): arg_types = { "this": True, "lazy": False, "options": False, "expression": False, }
class Uncache(Expression): arg_types = {"this": True, "exists": False}
class Refresh(Expression): arg_types = { "this": True, "kind": True, "partition_start": False, "partition_end": False, "force": False, "mode": False, }
class LockingStatement(Expression): arg_types = {"this": True, "expression": True}
@traitclass ColumnConstraintKind(Expr): pass
@traitclass SubqueryPredicate(Predicate): pass
class All(Expression, SubqueryPredicate): pass
class Any(Expression, SubqueryPredicate): pass
@traitclass Binary(Condition): arg_types: t.ClassVar[dict[str, bool]] = {"this": True, "expression": True}
@property def left(self) -> Expr: return self.args["this"]
@property def right(self) -> Expr: return self.args["expression"]
@traitclass Connector(Binary): pass
@traitclass Func(Condition): """ The base class for all function expressions.
Attributes: is_var_len_args (bool): if set to True the argument identified by var_len_arg_key will be treated as a variable length argument and the argument's value will be stored as a list. var_len_arg_key (str): the arg_types key that collects the variable length arguments. Arguments preceding it in arg_types are filled positionally; those following it (e.g. dialect flags) are never populated by from_arg_list. _sql_names (list): the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case. """
is_var_len_args: t.ClassVar[bool] = False var_len_arg_key: t.ClassVar[str] = "expressions" _sql_names: t.ClassVar[list[str]] = []
@classmethod def from_arg_list(cls, args: Sequence[object]) -> Self: if cls.is_var_len_args: all_arg_keys = tuple(cls.arg_types) var_len_index = all_arg_keys.index(cls.var_len_arg_key)
args_dict = {arg_key: arg for arg, arg_key in zip(args, all_arg_keys[:var_len_index])} args_dict[cls.var_len_arg_key] = args[var_len_index:] else: args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
return cls(**args_dict)
@classmethod def sql_names(cls) -> list[str]: if cls is Func: raise NotImplementedError( "SQL name is only supported by concrete function implementations" ) if not cls._sql_names: return [camel_to_snake_case(cls.__name__)] return cls._sql_names
@classmethod def sql_name(cls) -> str: sql_names = cls.sql_names() assert sql_names, f"Expected non-empty 'sql_names' for Func: {cls.__name__}." return sql_names[0]
@classmethod def default_parser_mappings(cls) -> dict[str, t.Callable[[Sequence[object]], Self]]: return {name: cls.from_arg_list for name in cls.sql_names()}
@traitclass AggFunc(Func): pass
class Column(Expression, Condition): # "shadow" marks a column whose qualifier is shadowed by a projection alias, so it must be # rendered unqualified in dialects where PROJECTION_ALIASES_SHADOW_SOURCE_NAMES is set arg_types = { "this": True, "table": False, "db": False, "catalog": False, "join_mark": False, "shadow": False, }
@property def table(self) -> str: return self.text("table")
@property def db(self) -> str: return self.text("db")
@property def catalog(self) -> str: return self.text("catalog")
@property def output_name(self) -> str: return self.name
@property def parts(self) -> list[Expr]: """Return the parts of a column in order catalog, db, table, name.""" return [ self.args[part] for part in ("catalog", "db", "table", "this") if self.args.get(part) ]
def to_dot(self, include_dots: bool = True) -> Expr: """Converts the column into a dot expression.""" parts = self.parts parent = self.parent
if include_dots: while isinstance(parent, Dot): parts.append(parent.expression) parent = parent.parent
return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]
class Literal(Expression, Condition): arg_types = {"this": True, "is_string": True} _hash_raw_args = True is_primitive = True
@classmethod def number(cls, number: object) -> Literal | Neg: lit = cls(this=str(number), is_string=False) try: to_py = lit.to_py() if not isinstance(to_py, str) and to_py < 0: lit.set("this", str(abs(to_py))) return Neg(this=lit) except Exception: pass return lit
@classmethod def string(cls, string: object) -> Literal: return cls(this=str(string), is_string=True)
@property def output_name(self) -> str: return self.name
def to_py(self) -> int | str | Decimal: if self.is_number: try: return int(self.this) except ValueError: try: return Decimal(self.this) except InvalidOperation as e: raise ValueError(f"Invalid numeric literal: {self.this!r}") from e return self.this
class Var(Expression): is_primitive = True
class WithinGroup(Expression): arg_types = {"this": True, "expression": False}
class Pseudocolumn(Column): pass
class Hint(Expression): arg_types = {"expressions": True}
class JoinHint(Expression): arg_types = {"this": True, "expressions": True}
class Identifier(Expression): arg_types = { "this": True, "quoted": False, "global_": False, "temporary": False, } is_primitive = True _hash_raw_args = True
@property def quoted(self) -> bool: return bool(self.args.get("quoted"))
@property def output_name(self) -> str: return self.name
# https://docs.snowflake.com/en/sql-reference/identifier-literal# "expressions" holds the arguments when the resolved identifier is invoked as a# function, e.g. `IDENTIFIER('my_func')(1, 2)`class DynamicIdentifier(Expression, Func): arg_types = {"this": True, "expressions": False}
@property def name(self) -> str: return self.this.name if self.this else ""
class Opclass(Expression): arg_types = {"this": True, "expression": True}
class Star(Expression): arg_types = {"except_": False, "replace": False, "rename": False, "ilike": False}
@property def name(self) -> str: return "*"
@property def output_name(self) -> str: return self.name
class Parameter(Expression, Condition): arg_types = {"this": True, "expression": False}
class SessionParameter(Expression, Condition): arg_types = {"this": True, "kind": False}
class Placeholder(Expression, Condition): arg_types = {"this": False, "kind": False, "widget": False, "jdbc": False} _hash_raw_args = True
@property def name(self) -> str: return self.text("this") or "?"
class Null(Expression, Condition): arg_types = {}
@property def name(self) -> str: return "NULL"
def to_py(self) -> t.Literal[None]: return None
class Boolean(Expression, Condition): is_primitive = True
def to_py(self) -> bool: return self.this
class Dot(Expression, Binary): @property def is_star(self) -> bool: return self.expression.is_star
@property def name(self) -> str: return self.expression.name
@property def output_name(self) -> str: return self.name
@classmethod def build(cls, expressions: Sequence[Expr]) -> Dot: """Build a Dot object with a sequence of expressions.""" if len(expressions) < 2: raise ValueError("Dot requires >= 2 expressions.")
return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))
@property def parts(self) -> list[Expr]: """Return the parts of a table / column in order catalog, db, table.""" this, *parts = self.flatten()
parts.reverse()
for arg in COLUMN_PARTS: part = this.args.get(arg)
if isinstance(part, Expr): parts.append(part)
parts.reverse() return parts
class Kwarg(Expression, Binary): """Kwarg in special functions like func(kwarg => y)."""
class Alias(Expression): arg_types = {"this": True, "alias": False}
@property def output_name(self) -> str: return self.alias
class PivotAlias(Alias): pass
class PivotAny(Expression): arg_types = {"this": False}
class Aliases(Expression): arg_types = {"this": True, "expressions": True}
@property def aliases(self) -> list[Expr]: return self.expressions
class Bracket(Expression, Condition): # https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#array_subscript_operator arg_types = { "this": True, "expressions": True, "offset": False, "safe": False, "returns_list_for_maps": False, "json_access": False, }
@property def output_name(self) -> str: if len(self.expressions) == 1: return self.expressions[0].output_name
return super().output_name
class ForIn(Expression): arg_types = {"this": True, "expression": True}
class IgnoreNulls(Expression): pass
class RespectNulls(Expression): pass
class HavingMax(Expression): arg_types = {"this": True, "expression": True, "max": True}
class SafeFunc(Expression, Func): pass
class Typeof(Expression, Func): pass
class ParameterizedAgg(Expression, AggFunc): arg_types = {"this": True, "expressions": True, "params": True} _hash_raw_args = True
class Anonymous(Expression, Func): arg_types = {"this": True, "expressions": False} is_var_len_args = True
@property def name(self) -> str: return self.this if isinstance(self.this, str) else self.this.name
class AnonymousAggFunc(Expression, AggFunc): arg_types = {"this": True, "expressions": False} is_var_len_args = True _hash_raw_args = True
class CombinedAggFunc(AnonymousAggFunc): arg_types = {"this": True, "expressions": False}
class CombinedParameterizedAgg(ParameterizedAgg): arg_types = {"this": True, "expressions": True, "params": True}
class HashAgg(Expression, AggFunc): arg_types = {"this": True, "expressions": False} is_var_len_args = True
class Hll(Expression, AggFunc): arg_types = {"this": True, "expressions": False} is_var_len_args = True
class ApproxDistinct(Expression, AggFunc): arg_types = {"this": True, "accuracy": False} _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
class Slice(Expression): arg_types = {"this": False, "expression": False, "step": False}
@traitclass TimeUnit(Expr): """Automatically converts unit arg into a var."""
UNABBREVIATED_UNIT_NAME: t.ClassVar[dict[str, str]] = { "D": "DAY", "H": "HOUR", "M": "MINUTE", "MS": "MILLISECOND", "NS": "NANOSECOND", "Q": "QUARTER", "S": "SECOND", "US": "MICROSECOND", "W": "WEEK", "Y": "YEAR", }
VAR_LIKE: t.ClassVar[tuple[Type[Expr], ...]] = (Column, Literal, Var)
def __init__(self, **args: object) -> None: super().__init__(**args)
unit = self.args.get("unit") if ( unit and type(unit) in TimeUnit.VAR_LIKE and not (isinstance(unit, Column) and len(unit.parts) != 1) ): unit = Var(this=(self.UNABBREVIATED_UNIT_NAME.get(unit.name) or unit.name).upper()) self.args["unit"] = unit self._set_parent("unit", unit) elif type(unit).__name__ == "Week": unit.set("this", Var(this=unit.this.name.upper())) # type: ignore[union-attr]
@property def unit(self) -> Expr | None: return self.args.get("unit")
class _TimeUnit(Expression, TimeUnit): """Automatically converts unit arg into a var."""
arg_types = {"unit": False}
@traitclass IntervalOp(TimeUnit): def interval(self) -> Interval: from sqlglot.expressions.datatypes import Interval
expr = self.expression return Interval( this=expr.copy() if expr is not None else None, unit=self.unit.copy() if self.unit else None, )
class Filter(Expression): arg_types = {"this": True, "expression": True}
class Check(Expression): pass
class Ordered(Expression): arg_types = {"this": True, "desc": False, "nulls_first": True, "with_fill": False}
@property def name(self) -> str: return self.this.name
class Add(Expression, Binary): pass
class BitwiseAnd(Expression, Binary): arg_types = {"this": True, "expression": True, "padside": False}
class BitwiseLeftShift(Expression, Binary): arg_types = {"this": True, "expression": True, "requires_int128": False}
class BitwiseOr(Expression, Binary): arg_types = {"this": True, "expression": True, "padside": False}
class BitwiseRightShift(Expression, Binary): arg_types = {"this": True, "expression": True, "requires_int128": False}
class BitwiseXor(Expression, Binary): arg_types = {"this": True, "expression": True, "padside": False}
class Div(Expression, Binary): arg_types = {"this": True, "expression": True, "typed": False, "safe": False}
class Overlaps(Expression, Binary, Predicate): pass
class ExtendsLeft(Expression, Binary, Predicate): pass
class ExtendsRight(Expression, Binary, Predicate): pass
class DPipe(Expression, Binary): arg_types = {"this": True, "expression": True, "safe": False}
class EQ(Expression, Binary, Predicate): pass
class NullSafeEQ(Expression, Binary, Predicate): pass
class NullSafeNEQ(Expression, Binary, Predicate): pass
class PropertyEQ(Expression, Binary): pass
class Distance(Expression, Binary): pass
class DistanceNd(Expression, Binary): pass
class Escape(Expression, Binary): pass
class Glob(Expression, Binary, Predicate): pass
class GT(Expression, Binary, Predicate): pass
class GTE(Expression, Binary, Predicate): pass
class ILike(Expression, Binary, Predicate): arg_types = {"this": True, "expression": True, "negate": False}
class IntDiv(Expression, Binary): pass
class Is(Expression, Binary, Predicate): arg_types = {"this": True, "expression": True, "negate": False}
class Like(Expression, Binary, Predicate): arg_types = {"this": True, "expression": True, "negate": False}
class Match(Expression, Binary, Predicate): arg_types = {"this": True, "expression": True, "kind": False, "analyzer": False}
class LT(Expression, Binary, Predicate): pass
class LTE(Expression, Binary, Predicate): pass
class Mod(Expression, Binary): pass
class Mul(Expression, Binary): pass
class NEQ(Expression, Binary, Predicate): pass
class NestedJSONSelect(Expression, Binary): pass
class Operator(Expression, Binary): arg_types = {"this": True, "operator": True, "expression": True}
class SimilarTo(Expression, Binary, Predicate): pass
class Sub(Expression, Binary): pass
class Adjacent(Expression, Binary, Predicate): pass
class Unary(Expression, Condition): pass
class BitwiseNot(Unary): pass
class Not(Unary): pass
class Paren(Unary): @property def output_name(self) -> str: return self.this.name
class Neg(Unary): def to_py(self) -> int | Decimal: if self.is_number: return self.this.to_py() * -1 return super().to_py()
class AtIndex(Expression): arg_types = {"this": True, "expression": True}
class AtTimeZone(Expression): arg_types = {"this": True, "zone": True}
class FromTimeZone(Expression): arg_types = {"this": True, "zone": True}
class FormatPhrase(Expression): """Format override for a column in Teradata. Can be expanded to additional dialects as needed
https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Types-and-Literals/Data-Type-Formats-and-Format-Phrases/FORMAT """
arg_types = {"this": True, "format": True}
class Between(Expression, Predicate): arg_types = {"this": True, "low": True, "high": True, "symmetric": False}
class Distinct(Expression): arg_types = {"expressions": False, "on": False}
class In(Expression, Predicate): arg_types = { "this": True, "expressions": False, "query": False, "unnest": False, "field": False, "is_global": False, }
class And(Expression, Connector, Func): pass
class Or(Expression, Connector, Func): pass
class Xor(Expression, Connector, Func): arg_types = {"this": True, "expression": True, "round_input": False}
class Pow(Expression, Binary, Func): _sql_names = ["POWER", "POW"]
class RegexpLike(Expression, Binary, Predicate, Func): arg_types = {"this": True, "expression": True, "flag": False, "full_match": False}
def not_( expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Not: """ Wrap a condition with a NOT operator.
Example: >>> not_("this_suit='black'").sql() "NOT this_suit = 'black'"
Args: expression: the SQL code string to parse. If an Expr instance is passed, this is used as-is. dialect: the dialect used to parse the input expression. copy: whether to copy the expression or not. **opts: other options to use to parse the input expressions.
Returns: The new condition. """ this = condition( expression, dialect=dialect, copy=copy, **opts, ) return Not(this=_wrap(this, Connector))
def _lazy_unnest(**kwargs: object) -> Expr: from sqlglot.expressions.array import Unnest
return Unnest(**kwargs)
def convert(value: t.Any, copy: bool = False) -> Expr: """Convert a python value into an expression object.
Raises an error if a conversion is not possible.
Args: value: A python object. copy: Whether to copy `value` (only applies to Exprs and collections).
Returns: The equivalent expression object. """ if isinstance(value, Expr): return maybe_copy(value, copy) if isinstance(value, str): return Literal.string(value) if isinstance(value, bool): return Boolean(this=value) if value is None or (isinstance(value, float) and math.isnan(value)): return Null() if isinstance(value, numbers.Number): return Literal.number(value) if isinstance(value, bytes): from sqlglot.expressions.query import HexString as _HexString
return _HexString(this=value.hex()) if isinstance(value, datetime.datetime): datetime_literal = Literal.string(value.isoformat(sep=" "))
tz = None if value.tzinfo: # this works for zoneinfo.ZoneInfo, pytz.timezone and datetime.datetime.utc to return IANA timezone names like "America/Los_Angeles" # instead of abbreviations like "PDT". This is for consistency with other timezone handling functions in SQLGlot tz = Literal.string(str(value.tzinfo))
from sqlglot.expressions.temporal import TimeStrToTime as _TimeStrToTime
return _TimeStrToTime(this=datetime_literal, zone=tz) if isinstance(value, datetime.date): date_literal = Literal.string(value.strftime("%Y-%m-%d")) from sqlglot.expressions.temporal import DateStrToDate as _DateStrToDate
return _DateStrToDate(this=date_literal) if isinstance(value, datetime.time): time_literal = Literal.string(value.isoformat()) from sqlglot.expressions.temporal import TsOrDsToTime as _TsOrDsToTime
return _TsOrDsToTime(this=time_literal) if isinstance(value, tuple): if hasattr(value, "_fields"): from sqlglot.expressions.array import Struct as _Struct
return _Struct( expressions=[ PropertyEQ( this=to_identifier(k), expression=convert(getattr(value, k), copy=copy) ) for k in value._fields ] ) from sqlglot.expressions.query import Tuple as _Tuple
return _Tuple(expressions=[convert(v, copy=copy) for v in value]) if isinstance(value, list): from sqlglot.expressions.array import Array as _Array
return _Array(expressions=[convert(v, copy=copy) for v in value]) if isinstance(value, dict): from sqlglot.expressions.array import Array as _Array from sqlglot.expressions.array import Map as _Map
return _Map( keys=_Array(expressions=[convert(k, copy=copy) for k in value]), values=_Array(expressions=[convert(v, copy=copy) for v in value.values()]), ) if hasattr(value, "__dict__"): from sqlglot.expressions.array import Struct as _Struct
return _Struct( expressions=[ PropertyEQ(this=to_identifier(k), expression=convert(v, copy=copy)) for k, v in value.__dict__.items() ] ) raise ValueError(f"Cannot convert {value}")
QUERY_MODIFIERS = { "match": False, "laterals": False, "joins": False, "connect": False, "pivots": False, "prewhere": False, "where": False, "group": False, "having": False, "qualify": False, "windows": False, "distribute": False, "sort": False, "cluster": False, "order": False, "limit": False, "offset": False, "locks": False, "sample": False, "settings": False, "format": False, "options": False, "for_": False,}
TIMESTAMP_PARTS = { "year": False, "month": False, "day": False, "hour": False, "min": False, "sec": False, "nano": False,}
@t.overloaddef maybe_parse( sql_or_expression: int | str, *, into: Type[E], dialect: DialectType = None, prefix: str | None = None, copy: bool = False, **opts: Unpack[ParserNoDialectArgs],) -> E: ...
@t.overloaddef maybe_parse( sql_or_expression: int | str | E, *, into: IntoType | None = None, dialect: DialectType = None, prefix: str | None = None, copy: bool = False, **opts: Unpack[ParserNoDialectArgs],) -> E: ...
def maybe_parse( sql_or_expression: ExpOrStr, *, into: IntoType | None = None, dialect: DialectType = None, prefix: str | None = None, copy: bool = False, **opts: Unpack[ParserNoDialectArgs],) -> Expr: """Gracefully handle a possible string or expression.
Example: >>> maybe_parse("1") Literal(this=1, is_string=False) >>> maybe_parse(to_identifier("x")) Identifier(this=x, quoted=False)
Args: sql_or_expression: the SQL code string or an expression into: the SQLGlot Expr to parse into dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string). prefix: a string to prefix the sql with before it gets parsed (automatically includes a space) copy: whether to copy the expression. **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns: Expr: the parsed or given expression. """ if isinstance(sql_or_expression, Expr): if copy: return sql_or_expression.copy() return sql_or_expression
if sql_or_expression is None: raise ParseError("SQL cannot be None")
import sqlglot
sql = str(sql_or_expression) if prefix: sql = f"{prefix} {sql}"
return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
@t.overloaddef maybe_copy(instance: None, copy: bool = True) -> None: ...
@t.overloaddef maybe_copy(instance: E, copy: bool = True) -> E: ...
def maybe_copy(instance, copy=True): return instance.copy() if copy and instance else instance
def _to_s(node: t.Any, verbose: bool = False, level: int = 0, repr_str: bool = False) -> str: """Generate a textual representation of an Expr tree""" indent = "\n" + (" " * (level + 1)) delim = f",{indent}"
if isinstance(node, Expr): args = {k: v for k, v in node.args.items() if (v is not None and v != []) or verbose}
if (node.type or verbose) and not node.is_data_type: args["_type"] = node.type if node.comments or verbose: args["_comments"] = node.comments
if verbose: args["_id"] = id(node)
# Inline leaves for a more compact representation if node.is_leaf(): indent = "" delim = ", "
repr_str = node.is_string or (isinstance(node, Identifier) and node.quoted) items = delim.join( [f"{k}={_to_s(v, verbose, level + 1, repr_str=repr_str)}" for k, v in args.items()] ) return f"{node.__class__.__name__}({indent}{items})"
if isinstance(node, list): items = delim.join(_to_s(i, verbose, level + 1) for i in node) items = f"{indent}{items}" if items else "" return f"[{items}]"
# We use the representation of the string to avoid stripping out important whitespace if repr_str and isinstance(node, str): node = repr(node)
# Indent multiline strings to match the current level return indent.join(textwrap.dedent(str(node).strip("\n")).splitlines())
def _is_wrong_expression(expression, into): return isinstance(expression, Expr) and not isinstance(expression, into)
def _apply_builder( expression: ExpOrStr, instance: E, arg: str, copy: bool = True, prefix: str | None = None, into: Type[Expr] | None = None, dialect: DialectType = None, into_arg="this", **opts: Unpack[ParserNoDialectArgs],) -> E: if _is_wrong_expression(expression, into) and into is not None: expression = into(**{into_arg: expression}) instance = maybe_copy(instance, copy) expression = maybe_parse( sql_or_expression=expression, prefix=prefix, into=into, dialect=dialect, **opts, ) instance.set(arg, expression) return instance
def _apply_child_list_builder( *expressions: ExpOrStr | None, instance: E, arg: str, append: bool = True, copy: bool = True, prefix: str | None = None, into: Type[Expr] | None = None, dialect: DialectType = None, properties: MutableMapping[str, object] | None = None, **opts: Unpack[ParserNoDialectArgs],) -> E: instance = maybe_copy(instance, copy) parsed = [] properties = {} if properties is None else properties
for expression in expressions: if expression is not None: if _is_wrong_expression(expression, into) and into is not None: expression = into(expressions=[expression])
expression = maybe_parse( expression, into=into, dialect=dialect, prefix=prefix, **opts, ) for k, v in expression.args.items(): if k == "expressions": parsed.extend(v) else: properties[k] = v
existing = instance.args.get(arg) if append and existing: parsed = existing.expressions + parsed if into is None: raise ValueError("`into` is required to use `_apply_child_list_builder`") child = into(expressions=parsed) for k, v in properties.items(): child.set(k, v) instance.set(arg, child)
return instance
def _apply_list_builder( *expressions: ExpOrStr | None, instance: E, arg: str, append: bool = True, copy: bool = True, prefix: str | None = None, into: Type[Expr] | None = None, dialect: DialectType = None, **opts: Unpack[ParserNoDialectArgs],) -> E: inst = maybe_copy(instance, copy)
parsed = [ maybe_parse( sql_or_expression=expression, into=into, prefix=prefix, dialect=dialect, **opts, ) for expression in expressions if expression is not None ]
existing_expressions = inst.args.get(arg) if append and existing_expressions: parsed = existing_expressions + parsed
inst.set(arg, parsed) return inst
def _apply_conjunction_builder( *expressions: ExpOrStr | None, instance: E, arg: str, into: Type[Expr] | None = None, append: bool = True, copy: bool = True, dialect: DialectType = None, **opts: Unpack[ParserNoDialectArgs],) -> E: filtered = [exp for exp in expressions if exp is not None and exp != ""] if not filtered: return instance
inst = maybe_copy(instance, copy)
existing = inst.args.get(arg) if append and existing is not None: filtered = [existing.this if into else existing] + filtered
node = and_(*filtered, dialect=dialect, copy=copy, **opts)
inst.set(arg, into(this=node) if into else node) return inst
def _combine( expressions: Sequence[ExpOrStr | None], operator: Type[Expr], dialect: DialectType = None, copy: bool = True, wrap: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Expr: conditions = [ condition(expression, dialect=dialect, copy=copy, **opts) for expression in expressions if expression is not None ]
this, *rest = conditions if rest and wrap: this = _wrap(this, Connector) for expression in rest: this = operator(this=this, expression=_wrap(expression, Connector) if wrap else expression)
return this
@t.overloaddef _wrap(expression: None, kind: Type[Expr]) -> None: ...
@t.overloaddef _wrap(expression: E, kind: Type[Expr]) -> E | Paren: ...
def _wrap(expression: E | None, kind: Type[Expr]) -> E | None | Paren: return Paren(this=expression) if isinstance(expression, kind) else expression
def _apply_set_operation( *expressions: ExpOrStr, set_operation: Type, distinct: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> t.Any: return reduce( lambda x, y: set_operation(this=x, expression=y, distinct=distinct, **opts), (maybe_parse(e, dialect=dialect, copy=copy, **opts) for e in expressions), )
SAFE_IDENTIFIER_RE: t.Pattern[str] = re.compile(r"^[_a-zA-Z][\w]*$")
@t.overloaddef to_identifier(name: None, quoted: bool | None = None, copy: bool = True) -> None: ...
@t.overloaddef to_identifier( name: int | str | Identifier, quoted: bool | None = None, copy: bool = True) -> Identifier: ...
def to_identifier(name, quoted=None, copy=True): """Builds an identifier.
Args: name: The name to turn into an identifier. quoted: Whether to force quote the identifier. copy: Whether to copy name if it's an Identifier.
Returns: The identifier ast node. """
if name is None: return None
if isinstance(name, Identifier): identifier = maybe_copy(name, copy) elif isinstance(name, str): identifier = Identifier( this=name, quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, ) else: raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") return identifier
def condition( expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Expr: """ Initialize a logical condition expression.
Example: >>> condition("x=1").sql() 'x = 1'
This is helpful for composing larger logical syntax trees: >>> where = condition("x=1") >>> where = where.and_("y=1") >>> where.sql() 'x = 1 AND y = 1'
Args: *expression: the SQL code string to parse. If an Expr instance is passed, this is used as-is. dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string). copy: Whether to copy `expression` (only applies to expressions). **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns: The new Condition instance """ return maybe_parse( expression, into=Condition, dialect=dialect, copy=copy, **opts, )
def and_( *expressions: ExpOrStr | None, dialect: DialectType = None, copy: bool = True, wrap: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Condition: """ Combine multiple conditions with an AND logical operator.
Example: >>> and_("x=1", and_("y=1", "z=1")).sql() 'x = 1 AND (y = 1 AND z = 1)'
Args: *expressions: the SQL code strings to parse. If an Expr instance is passed, this is used as-is. dialect: the dialect used to parse the input expression. copy: whether to copy `expressions` (only applies to Exprs). wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues. **opts: other options to use to parse the input expressions.
Returns: The new condition """ return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, wrap=wrap, **opts))
def or_( *expressions: ExpOrStr | None, dialect: DialectType = None, copy: bool = True, wrap: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Condition: """ Combine multiple conditions with an OR logical operator.
Example: >>> or_("x=1", or_("y=1", "z=1")).sql() 'x = 1 OR (y = 1 OR z = 1)'
Args: *expressions: the SQL code strings to parse. If an Expr instance is passed, this is used as-is. dialect: the dialect used to parse the input expression. copy: whether to copy `expressions` (only applies to Exprs). wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues. **opts: other options to use to parse the input expressions.
Returns: The new condition """ return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, wrap=wrap, **opts))
def xor( *expressions: ExpOrStr | None, dialect: DialectType = None, copy: bool = True, wrap: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Condition: """ Combine multiple conditions with an XOR logical operator.
Example: >>> xor("x=1", xor("y=1", "z=1")).sql() 'x = 1 XOR (y = 1 XOR z = 1)'
Args: *expressions: the SQL code strings to parse. If an Expr instance is passed, this is used as-is. dialect: the dialect used to parse the input expression. copy: whether to copy `expressions` (only applies to Exprs). wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues. **opts: other options to use to parse the input expressions.
Returns: The new condition """ return t.cast(Condition, _combine(expressions, Xor, dialect, copy=copy, wrap=wrap, **opts))
def paren(expression: ExpOrStr, copy: bool = True) -> Paren: """ Wrap an expression in parentheses.
Example: >>> paren("5 + 3").sql() '(5 + 3)'
Args: expression: the SQL code string to parse. If an Expr instance is passed, this is used as-is. copy: whether to copy the expression or not.
Returns: The wrapped expression. """ return Paren(this=maybe_parse(expression, copy=copy))
def alias_( expression: ExpOrStr, alias: str | Identifier | None, table: bool | Sequence[str | Identifier] = False, quoted: bool | None = None, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Expr: """Create an Alias expression.
Example: >>> alias_('foo', 'bar').sql() 'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() '(SELECT 1, 2) AS bar(a, b)'
Args: expression: the SQL code strings to parse. If an Expr instance is passed, this is used as-is. alias: the alias name to use. If the name has special characters it is quoted. table: Whether to create a table alias, can also be a list of columns. quoted: whether to quote the alias dialect: the dialect used to parse the input expression. copy: Whether to copy the expression. **opts: other options to use to parse the input expressions.
Returns: Alias: the aliased expression """ exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts) alias = to_identifier(alias, quoted=quoted)
if table: from sqlglot.expressions.query import TableAlias as _TableAlias
table_alias = _TableAlias(this=alias) exp.set("alias", table_alias)
if not isinstance(table, bool): for column in table: table_alias.append("columns", to_identifier(column, quoted=quoted))
return exp
# We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node # for the complete Window expression. # # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
if "alias" in exp.arg_types and type(exp).__name__ != "Window": exp.set("alias", alias) return exp return Alias(this=exp, alias=alias)
@t.overloaddef column( col: str | Expr, table: str | Identifier | None = None, db: str | Identifier | None = None, catalog: str | Identifier | None = None, *, fields: Collection[str | Identifier], quoted: bool | None = None, copy: bool = True,) -> Dot: pass
@t.overloaddef column( col: str | Expr, table: str | Identifier | None = None, db: str | Identifier | None = None, catalog: str | Identifier | None = None, *, fields: t.Literal[None] = None, quoted: bool | None = None, copy: bool = True,) -> Column: pass
def column( col, table=None, db=None, catalog=None, *, fields=None, quoted=None, copy: bool = True,): """ Build a Column.
Args: col: Column name or expression. table: Table name. db: Database name. catalog: Catalog name. fields: Additional fields using dots. quoted: Whether to force quotes on the column's identifiers. copy: Whether to copy expressions if passed in.
Returns: The new Column instance. """ col = maybe_copy(col, copy) if isinstance(col, Expr) else to_identifier(col, quoted=quoted)
this: Column | Dot = Column( this=col, table=to_identifier(table, quoted=quoted, copy=copy), db=to_identifier(db, quoted=quoted, copy=copy), catalog=to_identifier(catalog, quoted=quoted, copy=copy), )
if fields: this = Dot.build( (this, *(to_identifier(field, quoted=quoted, copy=copy) for field in fields)) ) return this123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467"""sqlglot expressions datatypes."""
from __future__ import annotations
import typing as tfrom enum import auto
from sqlglot.helper import AutoNamefrom sqlglot.errors import ErrorLevel, ParseErrorfrom sqlglot.expressions.core import ( Expr, Expression, _TimeUnit, Identifier, Dot, maybe_copy,)from builtins import type as Type
if t.TYPE_CHECKING: from sqlglot._typing import DataTypeArgs from sqlglot.dialects.dialect import DialectType from typing_extensions import Self, Unpack
class DataTypeParam(Expression): arg_types = {"this": True, "expression": False}
@property def this(self) -> Expr: return self.args["this"]
@property def name(self) -> str: return self.this.name
class DType(AutoName): ARRAY = auto() AGGREGATEFUNCTION = auto() SIMPLEAGGREGATEFUNCTION = auto() BIGDECIMAL = auto() BIGINT = auto() BIGNUM = auto() BIGSERIAL = auto() BINARY = auto() BIT = auto() BLOB = auto() BOOLEAN = auto() BPCHAR = auto() CHAR = auto() CHARACTER_SET = auto() DATE = auto() DATE32 = auto() DATEMULTIRANGE = auto() DATERANGE = auto() DATETIME = auto() DATETIME2 = auto() DATETIME64 = auto() DECIMAL = auto() DECIMAL32 = auto() DECIMAL64 = auto() DECIMAL128 = auto() DECIMAL256 = auto() DECFLOAT = auto() DOUBLE = auto() DYNAMIC = auto() ENUM = auto() ENUM8 = auto() ENUM16 = auto() FILE = auto() FIXEDSTRING = auto() FLOAT = auto() GEOGRAPHY = auto() GEOGRAPHYPOINT = auto() GEOMETRY = auto() POINT = auto() RING = auto() LINESTRING = auto() MULTILINESTRING = auto() POLYGON = auto() MULTIPOLYGON = auto() HLLSKETCH = auto() HSTORE = auto() IMAGE = auto() INET = auto() INT = auto() INT128 = auto() INT256 = auto() INT4MULTIRANGE = auto() INT4RANGE = auto() INT8MULTIRANGE = auto() INT8RANGE = auto() INTERVAL = auto() IPADDRESS = auto() IPPREFIX = auto() IPV4 = auto() IPV6 = auto() JSON = auto() JSONB = auto() LIST = auto() LONGBLOB = auto() LONGTEXT = auto() LOWCARDINALITY = auto() MAP = auto() MEDIUMBLOB = auto() MEDIUMINT = auto() MEDIUMTEXT = auto() MONEY = auto() NAME = auto() NCHAR = auto() NESTED = auto() NOTHING = auto() NULL = auto() NUMMULTIRANGE = auto() NUMRANGE = auto() NVARCHAR = auto() OBJECT = auto() RANGE = auto() ROWVERSION = auto() SERIAL = auto() SET = auto() SMALLDATETIME = auto() SMALLINT = auto() SMALLMONEY = auto() SMALLSERIAL = auto() STRUCT = auto() SUPER = auto() TEXT = auto() TINYBLOB = auto() TINYTEXT = auto() TIME = auto() TIMETZ = auto() TIME_NS = auto() TIMESTAMP = auto() TIMESTAMPNTZ = auto() TIMESTAMPLTZ = auto() TIMESTAMPTZ = auto() TIMESTAMP_S = auto() TIMESTAMP_MS = auto() TIMESTAMP_NS = auto() TINYINT = auto() TSMULTIRANGE = auto() TSRANGE = auto() TSTZMULTIRANGE = auto() TSTZRANGE = auto() UBIGINT = auto() UINT = auto() UINT128 = auto() UINT256 = auto() UMEDIUMINT = auto() UDECIMAL = auto() UDOUBLE = auto() UNION = auto() UNKNOWN = auto() # Sentinel value, useful for type annotation USERDEFINED = "USER-DEFINED" USMALLINT = auto() UTINYINT = auto() UUID = auto() VARBINARY = auto() VARCHAR = auto() VARIANT = auto() VECTOR = auto() XML = auto() YEAR = auto() TDIGEST = auto()
def into_expr(self, **kwargs: object) -> DataType: """Converts this `DType` into a `DataType` instance.
Args: **kwargs (object): additional arguments to pass in the constructor of DataType. Returns: DataType: the resulting `DataType` instance. """ return DataType(this=self).set_kwargs(kwargs)
class DataType(Expression): arg_types = { "this": True, "expressions": False, "nested": False, "values": False, "kind": False, "nullable": False, "collate": False, }
is_data_type: t.ClassVar[bool] = True
Type: t.ClassVar[Type[DType]] = DType
STRUCT_TYPES: t.ClassVar[set[DType]] = { DType.FILE, DType.NESTED, DType.OBJECT, DType.STRUCT, DType.UNION, }
ARRAY_TYPES: t.ClassVar[set[DType]] = { DType.ARRAY, DType.LIST, }
NESTED_TYPES: t.ClassVar[set[DType]] = { DType.FILE, DType.NESTED, DType.OBJECT, DType.STRUCT, DType.UNION, DType.ARRAY, DType.LIST, DType.MAP, }
TEXT_TYPES: t.ClassVar[set[DType]] = { DType.CHAR, DType.NCHAR, DType.NVARCHAR, DType.TEXT, DType.TINYTEXT, DType.MEDIUMTEXT, DType.LONGTEXT, DType.VARCHAR, DType.NAME, }
BINARY_TYPES: t.ClassVar[set[DType]] = { DType.BINARY, DType.VARBINARY, DType.TINYBLOB, DType.BLOB, DType.MEDIUMBLOB, DType.LONGBLOB, }
SIGNED_INTEGER_TYPES: t.ClassVar[set[DType]] = { DType.BIGINT, DType.INT, DType.INT128, DType.INT256, DType.MEDIUMINT, DType.SMALLINT, DType.TINYINT, }
UNSIGNED_INTEGER_TYPES: t.ClassVar[set[DType]] = { DType.UBIGINT, DType.UINT, DType.UINT128, DType.UINT256, DType.UMEDIUMINT, DType.USMALLINT, DType.UTINYINT, }
INTEGER_TYPES: t.ClassVar[set[DType]] = { DType.BIGINT, DType.INT, DType.INT128, DType.INT256, DType.MEDIUMINT, DType.SMALLINT, DType.TINYINT, DType.UBIGINT, DType.UINT, DType.UINT128, DType.UINT256, DType.UMEDIUMINT, DType.USMALLINT, DType.UTINYINT, DType.BIT, }
FLOAT_TYPES: t.ClassVar[set[DType]] = { DType.DOUBLE, DType.FLOAT, }
REAL_TYPES: t.ClassVar[set[DType]] = { DType.DOUBLE, DType.FLOAT, DType.BIGDECIMAL, DType.DECIMAL, DType.DECIMAL32, DType.DECIMAL64, DType.DECIMAL128, DType.DECIMAL256, DType.DECFLOAT, DType.MONEY, DType.SMALLMONEY, DType.UDECIMAL, DType.UDOUBLE, }
NUMERIC_TYPES: t.ClassVar[set[DType]] = { DType.BIGINT, DType.INT, DType.INT128, DType.INT256, DType.MEDIUMINT, DType.SMALLINT, DType.TINYINT, DType.UBIGINT, DType.UINT, DType.UINT128, DType.UINT256, DType.UMEDIUMINT, DType.USMALLINT, DType.UTINYINT, DType.BIT, DType.DOUBLE, DType.FLOAT, DType.BIGDECIMAL, DType.DECIMAL, DType.DECIMAL32, DType.DECIMAL64, DType.DECIMAL128, DType.DECIMAL256, DType.DECFLOAT, DType.MONEY, DType.SMALLMONEY, DType.UDECIMAL, DType.UDOUBLE, }
TEMPORAL_TYPES: t.ClassVar[set[DType]] = { DType.DATE, DType.DATE32, DType.DATETIME, DType.DATETIME2, DType.DATETIME64, DType.SMALLDATETIME, DType.TIME, DType.TIMESTAMP, DType.TIMESTAMPNTZ, DType.TIMESTAMPLTZ, DType.TIMESTAMPTZ, DType.TIMESTAMP_MS, DType.TIMESTAMP_NS, DType.TIMESTAMP_S, DType.TIMETZ, }
@classmethod def build( cls, dtype: DATA_TYPE, dialect: DialectType = None, udt: bool = False, copy: bool = True, **kwargs: Unpack[DataTypeArgs], ) -> Self: """ Constructs a DataType object.
Args: 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. """ if isinstance(dtype, str): return cls.from_str(dtype, dialect, udt, **kwargs) elif isinstance(dtype, DType): data_type_exp = cls(this=dtype) if kwargs: for k, v in kwargs.items(): data_type_exp.set(k, v) return data_type_exp elif isinstance(dtype, (Identifier, Dot)) and udt: return cls(this=DType.USERDEFINED, kind=dtype, **kwargs) elif isinstance(dtype, cls): return maybe_copy(dtype, copy) else: raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DType")
@classmethod def from_str( cls, dtype: str, dialect: DialectType = None, udt: bool = False, **kwargs: Unpack[DataTypeArgs], ) -> Self: """ Constructs a `DataType` object from a `str` representation.
Args: 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. """ from sqlglot import parse_one
if dtype.upper() == "UNKNOWN": return cls(this=DType.UNKNOWN, **kwargs) try: return parse_one( dtype, read=dialect, into=cls, error_level=ErrorLevel.IGNORE ).set_kwargs(kwargs) except ParseError: if udt: return cls(this=DType.USERDEFINED, kind=dtype, **kwargs) raise
def is_type(self, *dtypes: DATA_TYPE, check_nullable: bool = False) -> bool: """ 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<int> != array<float>.
Args: 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<INT> is equivalent to INT.
Returns: True, if and only if there is a type in `dtypes` which is equal to this DataType. """ self_is_nullable: bool | None = self.args.get("nullable") for dtype in dtypes: other_type = DataType.build(dtype, copy=False, udt=True) other_is_nullable: bool | None = other_type.args.get("nullable") if ( other_type.expressions or (check_nullable and (self_is_nullable or other_is_nullable)) or self.this == DType.USERDEFINED or other_type.this == DType.USERDEFINED ): matches = self == other_type else: matches = self.this == other_type.this
if matches: return True return False
class PseudoType(DataType): arg_types = {"this": True}
class ObjectIdentifier(DataType): arg_types = {"this": True}
class IntervalSpan(DataType): arg_types = {"this": True, "expression": True}
class Interval(_TimeUnit): arg_types = {"this": False, "unit": False}
DATA_TYPE = t.Union[str, Identifier, Dot, DataType, DType]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447"""sqlglot expressions DDL."""
from __future__ import annotations
import typing as t
from sqlglot.helper import traitfrom sqlglot.expressions.core import Expression, Expr, Funcfrom sqlglot.expressions.query import Query, Selectable
if t.TYPE_CHECKING: from sqlglot.expressions.query import CTE
@traitclass DDL(Selectable): @property def ctes(self) -> list[CTE]: """Returns a list of all the CTEs attached to this statement.""" with_ = self.args.get("with_") return with_.expressions if with_ else []
@property def selects(self) -> list[Expr]: """If this statement contains a query (e.g. a CTAS), this returns the query's projections.""" expression = self.expression return expression.selects if isinstance(expression, Query) else []
@property def named_selects(self) -> list[str]: """ If this statement contains a query (e.g. a CTAS), this returns the output names of the query's projections. """ expression = self.expression return expression.named_selects if isinstance(expression, Query) else []
class Create(Expression, DDL): arg_types = { "with_": False, "this": True, "kind": True, "expression": False, "exists": False, "properties": False, "replace": False, "refresh": False, "unique": False, "indexes": False, "no_schema_binding": False, "begin": False, "clone": False, "concurrently": False, "clustered": False, }
@property def kind(self) -> str | None: kind = self.args.get("kind") return kind and kind.upper()
class SequenceProperties(Expression): arg_types = { "increment": False, "minvalue": False, "maxvalue": False, "cache": False, "start": False, "owned": False, "options": False, }
class TriggerProperties(Expression): arg_types = { "table": True, "timing": True, "events": True, "execute": True, "constraint": False, "referenced_table": False, "deferrable": False, "initially": False, "referencing": False, "for_each": False, "when": False, }
class TriggerExecute(Expression): pass
class TriggerEvent(Expression): arg_types = {"this": True, "columns": False}
class TriggerReferencing(Expression): arg_types = {"old": False, "new": False}
class TruncateTable(Expression): arg_types = { "expressions": True, "is_database": False, "exists": False, "only": False, "cluster": False, "identity": False, "option": False, "partition": False, }
class Clone(Expression): arg_types = {"this": True, "shallow": False, "copy": False}
class Describe(Expression): arg_types = { "this": True, "style": False, "kind": False, "properties": False, "expressions": False, "partition": False, "format": False, "as_json": False, }
class Attach(Expression): arg_types = {"this": True, "exists": False, "expressions": False}
class Detach(Expression): arg_types = { "this": True, "kind": False, "exists": False, "cluster": False, "permanent": False, "sync": False, }
class Install(Expression): arg_types = {"this": True, "from_": False, "force": False}
class Summarize(Expression): arg_types = {"this": True, "table": False}
class Kill(Expression): arg_types = {"this": True, "kind": False}
class Pragma(Expression): pass
class Declare(Expression): arg_types = {"expressions": True, "replace": False}
class DeclareItem(Expression): arg_types = {"this": True, "kind": False, "default": False}
class Set(Expression): arg_types = {"expressions": False, "unset": False, "tag": False}
class Heredoc(Expression): arg_types = {"this": True, "tag": False} _hash_raw_args = True
class SetItem(Expression): arg_types = { "this": False, "expressions": False, "kind": False, "collate": False, # MySQL SET NAMES statement "global_": False, }
class Show(Expression): arg_types = { "this": True, "history": False, "terse": False, "target": False, "offset": False, "starts_with": False, "limit": False, "from_": False, "like": False, "where": False, "db": False, "scope": False, "scope_kind": False, "full": False, "mutex": False, "query": False, "channel": False, "global_": False, "log": False, "position": False, "types": False, "privileges": False, "for_table": False, "for_group": False, "for_user": False, "for_role": False, "into_outfile": False, "json": False, "iceberg": False, }
class UserDefinedFunction(Expression): arg_types = {"this": True, "expressions": False, "wrapped": False}
class MacroOverloads(Expression): arg_types = {"expressions": True}
class MacroOverload(Expression): arg_types = {"this": True, "expressions": False, "is_table": False}
class CharacterSet(Expression): arg_types = {"this": True, "default": False}
class AlterColumn(Expression): arg_types = { "this": True, "dtype": False, "collate": False, "using": False, "default": False, "drop": False, "comment": False, "allow_null": False, "visible": False, "rename_to": False, "exists": False, }
class ModifyColumn(Expression): arg_types = {"this": True, "rename_from": False}
class AlterIndex(Expression): arg_types = {"this": True, "visible": True}
class AlterDistStyle(Expression): pass
class AlterSortKey(Expression): arg_types = {"this": False, "expressions": False, "compound": False}
class AlterSet(Expression): arg_types = { "expressions": False, "option": False, "tablespace": False, "access_method": False, "file_format": False, "copy_options": False, "tag": False, "location": False, "serde": False, }
class RenameColumn(Expression): arg_types = {"this": True, "to": True, "exists": False}
class AlterRename(Expression): pass
class RenameIndex(Expression): arg_types = {"this": True, "to": True}
class AlterModifySqlSecurity(Expression): arg_types = {"expressions": True}
class SwapTable(Expression): pass
class Comment(Expression): arg_types = { "this": True, "kind": True, "expression": True, "exists": False, "materialized": False, }
class Comprehension(Expression): arg_types = { "this": True, "expression": True, "position": False, "iterator": True, "condition": False, }
class MergeTreeTTLAction(Expression): arg_types = { "this": True, "delete": False, "recompress": False, "to_disk": False, "to_volume": False, }
class MergeTreeTTL(Expression): arg_types = { "expressions": True, "where": False, "group": False, "aggregates": False, }
class Drop(Expression): arg_types = { "kind": False, "tables": False, "expressions": False, "exists": False, "temporary": False, "materialized": False, "cascade": False, "restrict": False, "constraints": False, "purge": False, "cluster": False, "concurrently": False, "sync": False, "iceberg": False, "force": False, }
@property def kind(self) -> str | None: kind = self.args.get("kind") return kind and kind.upper()
class DropPrimaryKey(Expression): arg_types = {}
class Undrop(Expression): arg_types = {"this": True, "kind": True, "rename": False}
@property def kind(self) -> str: return self.args["kind"].upper()
class Command(Expression): arg_types = {"this": True, "expression": False} _hash_raw_args = True
class Transaction(Expression): arg_types = {"this": False, "modes": False, "mark": False}
class Commit(Expression): arg_types = {"chain": False, "this": False, "durability": False}
class Rollback(Expression): arg_types = {"savepoint": False, "this": False}
class Alter(Expression): arg_types = { "this": False, "kind": True, "actions": False, "exists": False, "only": False, "options": False, "cluster": False, "not_valid": False, "check": False, "cascade": False, "iceberg": False, }
@property def kind(self) -> str | None: kind = self.args.get("kind") return kind and kind.upper()
@property def actions(self) -> list[Expr]: return self.args.get("actions") or []
class AlterSession(Expression): arg_types = {"expressions": True, "unset": False}
class Use(Expression): arg_types = {"this": False, "expressions": False, "kind": False}
class NextValueFor(Expression, Func): arg_types = {"this": True, "order": False}
class Execute(Expression): arg_types = {"this": True, "expressions": False, "return_status": False}
@property def name(self) -> str: return self.this.name
class ExecuteSql(Execute): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528"""sqlglot expressions DML."""
from __future__ import annotations
import typing as t
from sqlglot.helper import traitfrom sqlglot.expressions.core import ( Expr, Expression, _apply_builder, _apply_list_builder, maybe_copy, _apply_conjunction_builder,)from sqlglot.expressions.ddl import DDLfrom sqlglot.expressions.query import ( Table, Where, From, _apply_cte_builder,)
if t.TYPE_CHECKING: from typing_extensions import Self, Unpack from sqlglot.dialects.dialect import DialectType from sqlglot.expressions.core import ExpOrStr from sqlglot._typing import ParserNoDialectArgs
@traitclass DML(Expr): """Trait for data manipulation language statements."""
def returning( self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Self: """ Set the RETURNING expression. Not supported by all dialects.
Example: >>> Delete().delete("tbl").returning("*", dialect="postgres").sql() 'DELETE FROM tbl RETURNING *'
Args: expression: the SQL code strings to parse. If an `Expr` instance is passed, it will be used as-is. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: Delete: the modified expression. """ return _apply_builder( expression=expression, instance=self, arg="returning", prefix="RETURNING", dialect=dialect, copy=copy, into=Returning, **opts, )
class Delete(Expression, DML): arg_types = { "with_": False, "this": False, "using": False, "where": False, "returning": False, "order": False, "limit": False, "tables": False, # Multiple-Table Syntax (MySQL) "cluster": False, # Clickhouse "hint": False, }
def delete( self, table: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Delete: """ Create a DELETE expression or replace the table on an existing DELETE expression.
Example: >>> Delete().delete("tbl").sql() 'DELETE FROM tbl'
Args: table: the table from which to delete. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: Delete: the modified expression. """ return _apply_builder( expression=table, instance=self, arg="this", dialect=dialect, into=Table, copy=copy, **opts, )
def where( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Delete: """ Append to or set the WHERE expressions.
Example: >>> Delete().delete("tbl").where("x = 'a' OR x < 'b'").sql() "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Args: *expressions: the SQL code strings to parse. If an `Expr` instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. append: if `True`, AND the new expressions to any existing expression. Otherwise, this resets the expression. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: Delete: the modified expression. """ return _apply_conjunction_builder( *expressions, instance=self, arg="where", append=append, into=Where, dialect=dialect, copy=copy, **opts, )
class Export(Expression): arg_types = {"this": True, "connection": False, "options": True}
class CopyParameter(Expression): arg_types = {"this": True, "expression": False, "expressions": False}
class Copy(Expression, DML): arg_types = { "this": True, "kind": True, "files": False, "credentials": False, "format": False, "params": False, }
class Credentials(Expression): arg_types = { "credentials": False, "encryption": False, "storage": False, "iam_role": False, "region": False, }
class Directory(Expression): arg_types = {"this": True, "local": False, "row_format": False}
class DirectoryStage(Expression): pass
class Insert(Expression, DDL, DML): arg_types = { "hint": False, "with_": False, "is_function": False, "this": False, "expression": False, "conflict": False, "returning": False, "overwrite": False, "exists": False, "alternative": False, "where": False, "ignore": False, "by_name": False, "stored": False, "partition": False, "settings": False, "source": False, "default": False, "using": False, }
def with_( self, alias: ExpOrStr, as_: ExpOrStr, recursive: bool | None = None, materialized: bool | None = None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Insert: """ Append to or set the common table expressions.
Example: >>> import sqlglot >>> sqlglot.parse_one("INSERT INTO t SELECT x FROM cte").with_("cte", as_="SELECT * FROM tbl").sql() 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Args: alias: the SQL code string to parse as the table name. If an `Expr` instance is passed, this is used as-is. as_: the SQL code string to parse as the table expression. If an `Expr` instance is passed, it will be used as-is. recursive: set the RECURSIVE part of the expression. Defaults to `False`. materialized: set the MATERIALIZED part of the expression. append: if `True`, add to any existing expressions. Otherwise, this resets the expressions. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified expression. """ return _apply_cte_builder( self, alias, as_, recursive=recursive, materialized=materialized, append=append, dialect=dialect, copy=copy, **opts, )
class OnConflict(Expression): arg_types = { "duplicate": False, "expressions": False, "action": False, "conflict_keys": False, "index_predicate": False, "constraint": False, "where": False, }
class Returning(Expression): arg_types = {"expressions": True, "into": False}
class LoadData(Expression): arg_types = { "this": True, "local": False, "overwrite": False, "temp": False, "inpath": False, "files": False, "partition": False, "input_format": False, "serde": False, }
class Update(Expression, DML): arg_types = { "with_": False, "this": False, "expressions": False, "from_": False, "where": False, "returning": False, "order": False, "limit": False, "options": False, "hint": False, }
def table( self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Update: """ Set the table to update.
Example: >>> Update().table("my_table").set_("x = 1").sql() 'UPDATE my_table SET x = 1'
Args: expression : the SQL code strings to parse. If a `Table` instance is passed, this is used as-is. If another `Expr` instance is passed, it will be wrapped in a `Table`. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Update expression. """ return _apply_builder( expression=expression, instance=self, arg="this", into=Table, prefix=None, dialect=dialect, copy=copy, **opts, )
def set_( self, *expressions: ExpOrStr, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Update: """ Append to or set the SET expressions.
Example: >>> Update().table("my_table").set_("x = 1").sql() 'UPDATE my_table SET x = 1'
Args: *expressions: the SQL code strings to parse. If `Expr` instance(s) are passed, they will be used as-is. Multiple expressions are combined with a comma. append: if `True`, add the new expressions to any existing SET expressions. Otherwise, this resets the expressions. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions. """ return _apply_list_builder( *expressions, instance=self, arg="expressions", append=append, into=Expr, prefix=None, dialect=dialect, copy=copy, **opts, )
def where( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Update: """ Append to or set the WHERE expressions.
Example: >>> Update().table("tbl").set_("x = 1").where("x = 'a' OR x < 'b'").sql() "UPDATE tbl SET x = 1 WHERE x = 'a' OR x < 'b'"
Args: *expressions: the SQL code strings to parse. If an `Expr` instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. append: if `True`, AND the new expressions to any existing expression. Otherwise, this resets the expression. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: Update: the modified expression. """ return _apply_conjunction_builder( *expressions, instance=self, arg="where", append=append, into=Where, dialect=dialect, copy=copy, **opts, )
def from_( self, expression: ExpOrStr | None = None, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Update: """ Set the FROM expression.
Example: >>> Update().table("my_table").set_("x = 1").from_("baz").sql() 'UPDATE my_table SET x = 1 FROM baz'
Args: expression : the SQL code strings to parse. If a `From` instance is passed, this is used as-is. If another `Expr` instance is passed, it will be wrapped in a `From`. If nothing is passed in then a from is not applied to the expression dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Update expression. """ if not expression: return maybe_copy(self, copy)
return _apply_builder( expression=expression, instance=self, arg="from_", into=From, prefix="FROM", dialect=dialect, copy=copy, **opts, )
def with_( self, alias: ExpOrStr, as_: ExpOrStr, recursive: bool | None = None, materialized: bool | None = None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Update: """ Append to or set the common table expressions.
Example: >>> Update().table("my_table").set_("x = 1").from_("baz").with_("baz", "SELECT id FROM foo").sql() 'WITH baz AS (SELECT id FROM foo) UPDATE my_table SET x = 1 FROM baz'
Args: alias: the SQL code string to parse as the table name. If an `Expr` instance is passed, this is used as-is. as_: the SQL code string to parse as the table expression. If an `Expr` instance is passed, it will be used as-is. recursive: set the RECURSIVE part of the expression. Defaults to `False`. materialized: set the MATERIALIZED part of the expression. append: if `True`, add to any existing expressions. Otherwise, this resets the expressions. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified expression. """ return _apply_cte_builder( self, alias, as_, recursive=recursive, materialized=materialized, append=append, dialect=dialect, copy=copy, **opts, )
class Merge(Expression, DML): arg_types = { "this": True, "using": True, "on": False, "using_cond": False, "whens": True, "with_": False, "returning": False, }
class When(Expression): arg_types = {"matched": True, "source": False, "condition": False, "then": True}
class Whens(Expression): """Wraps around one or more WHEN [NOT] MATCHED [...] clauses."""
arg_types = {"expressions": True}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555"""sqlglot expressions functions."""
from __future__ import annotations
import typing as t
from sqlglot.expressions.core import ( Expression, Func, Binary, SubqueryPredicate, ExpOrStr, maybe_parse, maybe_copy,)
# Re-export from focused submodules (backward compatibility)from sqlglot.expressions.math import * # noqa: F401,F403from sqlglot.expressions.string import * # noqa: F401,F403from sqlglot.expressions.temporal import * # noqa: F401,F403from sqlglot.expressions.aggregate import * # noqa: F401,F403from sqlglot.expressions.array import * # noqa: F401,F403from sqlglot.expressions.json import * # noqa: F401,F403
if t.TYPE_CHECKING: from sqlglot.expressions.datatypes import DataType, DATA_TYPE from typing_extensions import Unpack from sqlglot._typing import ParserArgs
# Cast / type conversion
class Cast(Expression, Func): is_cast: t.ClassVar[bool] = True arg_types = { "this": True, "to": True, "format": False, "safe": False, "action": False, "default": False, }
@property def name(self) -> str: return self.this.name
@property def to(self) -> DataType: return self.args["to"]
@property def output_name(self) -> str: return self.name
def is_type(self, *dtypes: DATA_TYPE) -> bool: """ Checks whether this Cast's DataType matches one of the provided data types. Nested types like arrays or structs will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
Args: dtypes: the data types to compare this Cast's DataType to.
Returns: True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType. """ return self.to.is_type(*dtypes)
class TryCast(Cast): arg_types = { **Cast.arg_types, "requires_string": False, "null_on_text_overflow": False, "probe_date_format": False, }
class JSONCast(Cast): pass
class CastToStrType(Expression, Func): arg_types = {"this": True, "to": True}
class Convert(Expression, Func): arg_types = {"this": True, "expression": True, "style": False, "safe": False}
# Conditional
class If(Expression, Func): arg_types = {"this": True, "true": True, "false": False} _sql_names = ["IF", "IIF"]
class Case(Expression, Func): arg_types = {"this": False, "ifs": True, "default": False}
def when( self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts: Unpack[ParserArgs], ) -> Case: instance = maybe_copy(self, copy) instance.append( "ifs", If( this=maybe_parse(condition, copy=copy, **opts), true=maybe_parse(then, copy=copy, **opts), ), ) return instance
def else_(self, condition: ExpOrStr, copy: bool = True, **opts: Unpack[ParserArgs]) -> Case: instance = maybe_copy(self, copy) instance.set("default", maybe_parse(condition, copy=copy, **opts)) return instance
class Coalesce(Expression, Func): arg_types = {"this": True, "expressions": False, "is_nvl": False, "is_null": False} is_var_len_args = True _sql_names = ["COALESCE", "IFNULL", "NVL"]
class DecodeCase(Expression, Func): arg_types = {"expressions": True} is_var_len_args = True
class EqualNull(Expression, Func): arg_types = {"this": True, "expression": True}
class Greatest(Expression, Func): arg_types = {"this": True, "expressions": False, "ignore_nulls": True} is_var_len_args = True
class Least(Expression, Func): arg_types = {"this": True, "expressions": False, "ignore_nulls": True} is_var_len_args = True
class Nullif(Expression, Func): arg_types = {"this": True, "expression": True}
class ObjectTransform(Expression, Func): arg_types = {"this": True, "keep": False, "set_": False}
class Nvl2(Expression, Func): arg_types = {"this": True, "true": True, "false": False}
class Try(Expression, Func): pass
# Predicates / misc functions
class Collate(Expression, Binary, Func): pass
class Collation(Expression, Func): pass
class ConnectByRoot(Expression, Func): pass
class CheckXml(Expression, Func): arg_types = {"this": True, "disable_auto_convert": False}
class Exists(Expression, Func, SubqueryPredicate): arg_types = {"this": True, "expression": False}
# Type coercions / lax types
class Float64(Expression, Func): arg_types = {"this": True, "expression": False}
class Int64(Expression, Func): pass
class IsArray(Expression, Func): pass
class IsNullValue(Expression, Func): pass
class LaxBool(Expression, Func): pass
class LaxFloat64(Expression, Func): pass
class LaxInt64(Expression, Func): pass
class LaxString(Expression, Func): pass
class ToBoolean(Expression, Func): arg_types = {"this": True, "safe": False}
class ToVariant(Expression, Func): pass
# Session / context functions
class CurrentAccount(Expression, Func): arg_types = {}
class CurrentAccountName(Expression, Func): arg_types = {}
class CurrentAvailableRoles(Expression, Func): arg_types = {}
class CurrentCatalog(Expression, Func): arg_types = {}
class CurrentClient(Expression, Func): arg_types = {}
class CurrentDatabase(Expression, Func): arg_types = {}
class CurrentIpAddress(Expression, Func): arg_types = {}
class CurrentOrganizationName(Expression, Func): arg_types = {}
class CurrentOrganizationUser(Expression, Func): arg_types = {}
class CurrentRegion(Expression, Func): arg_types = {}
class CurrentRole(Expression, Func): arg_types = {}
class CurrentRoleType(Expression, Func): arg_types = {}
class CurrentSchema(Expression, Func): arg_types = {"this": False}
class CurrentSchemas(Expression, Func): arg_types = {"this": False}
class CurrentSecondaryRoles(Expression, Func): arg_types = {}
class CurrentSession(Expression, Func): arg_types = {}
class CurrentStatement(Expression, Func): arg_types = {}
class CurrentTransaction(Expression, Func): arg_types = {}
class CurrentUser(Expression, Func): arg_types = {"this": False}
class CurrentUserId(Expression, Func): arg_types = {}
class CurrentVersion(Expression, Func): arg_types = {}
class CurrentWarehouse(Expression, Func): arg_types = {}
class SessionUser(Expression, Func): arg_types = {}
# ML / AI
class AIClassify(Expression, Func): arg_types = {"this": True, "categories": True, "config": False} _sql_names = ["AI_CLASSIFY"]
class AIEmbed(Expression, Func): arg_types = {"expressions": True} is_var_len_args = True _sql_names = ["AI_EMBED"]
class AISimilarity(Expression, Func): arg_types = {"expressions": True} is_var_len_args = True _sql_names = ["AI_SIMILARITY"]
class AIGenerate(Expression, Func): arg_types = {"expressions": True} is_var_len_args = True _sql_names = ["AI_GENERATE"]
class FeaturesAtTime(Expression, Func): arg_types = {"this": True, "time": False, "num_rows": False, "ignore_feature_nulls": False}
class GenerateEmbedding(Expression, Func): arg_types = {"this": True, "expression": True, "params_struct": False, "is_text": False}
class GenerateText(Expression, Func): arg_types = {"this": True, "expression": False, "params_struct": False}
class GenerateTable(Expression, Func): arg_types = {"this": True, "expression": False, "params_struct": False}
class GenerateBool(Expression, Func): arg_types = {"this": True, "expression": False, "params_struct": False}
class GenerateInt(Expression, Func): arg_types = {"this": True, "expression": False, "params_struct": False}
class GenerateDouble(Expression, Func): arg_types = {"this": True, "expression": False, "params_struct": False}
class MLForecast(Expression, Func): arg_types = {"this": True, "expression": False, "params_struct": False}
class AIForecast(Expression, Func): arg_types = { "this": True, "data_col": False, "timestamp_col": False, "model": False, "id_cols": False, "horizon": False, "forecast_end_timestamp": False, "confidence_level": False, "output_historical_time_series": False, "context_window": False, }
class MLTranslate(Expression, Func): arg_types = {"this": True, "expression": True, "params_struct": True}
class Predict(Expression, Func): arg_types = {"this": True, "expression": True, "params_struct": False}
class VectorSearch(Expression, Func): arg_types = { "this": True, "column_to_search": True, "query_table": True, "query_column_to_search": False, "top_k": False, "distance_type": False, "options": False, }
# Data reading
class ReadCSV(Expression, Func): _sql_names = ["READ_CSV"] is_var_len_args = True arg_types = {"this": True, "expressions": False}
class ReadParquet(Expression, Func): is_var_len_args = True arg_types = {"expressions": True}
# XML
class XMLElement(Expression, Func): _sql_names = ["XMLELEMENT"] arg_types = {"this": True, "expressions": False, "evalname": False}
class GetIgnoreCase(Expression, Func): arg_types = {"this": True, "expression": True}
class XMLGet(Expression, Func): _sql_names = ["XMLGET"] arg_types = {"this": True, "expression": True, "instance": False}
class XMLTable(Expression, Func): arg_types = { "this": True, "namespaces": False, "passing": False, "columns": False, "by_ref": False, }
# Network / domain
class Host(Expression, Func): pass
class NetFunc(Expression, Func): pass
class ParseIp(Expression, Func): arg_types = {"this": True, "type": True, "permissive": False}
class RegDomain(Expression, Func): pass
# Misc utility
class Columns(Expression, Func): arg_types = {"this": True, "unpack": False}
class Normal(Expression, Func): arg_types = {"this": True, "stddev": True, "gen": True}
class Rand(Expression, Func): _sql_names = ["RAND", "RANDOM"] arg_types = {"this": False, "lower": False, "upper": False}
class Randn(Expression, Func): arg_types = {"this": False}
class Randstr(Expression, Func): arg_types = {"this": True, "generator": False}
class RangeBucket(Expression, Func): arg_types = {"this": True, "expression": True}
class RangeN(Expression, Func): arg_types = {"this": True, "expressions": True, "each": False}
class Seq1(Expression, Func): arg_types = {"this": False}
class Seq2(Expression, Func): arg_types = {"this": False}
class Seq4(Expression, Func): arg_types = {"this": False}
class Seq8(Expression, Func): arg_types = {"this": False}
class Uniform(Expression, Func): arg_types = {"this": True, "expression": True, "gen": False, "seed": False}
class Uuid(Expression, Func): _sql_names = ["UUID", "GEN_RANDOM_UUID", "GENERATE_UUID", "UUID_STRING"]
arg_types = {"this": False, "name": False, "is_string": False}
class WeekStart(Expression, Func): pass
class WidthBucket(Expression, Func): arg_types = { "this": True, "min_value": False, "max_value": False, "num_buckets": False, "threshold": False, }
class Zipf(Expression, Func): arg_types = {"this": True, "elementcount": True, "gen": True}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252"""sqlglot expressions - JSON functions."""
from __future__ import annotations
from sqlglot.expressions.core import Expression, Func, AggFunc, Binary, Predicate
class CheckJson(Expression, Func): arg_types = {"this": True}
class JSONArray(Expression, Func): arg_types = { "expressions": False, "null_handling": False, "return_type": False, "strict": False, } is_var_len_args = True
class JSONArrayAgg(Expression, AggFunc): arg_types = { "this": True, "order": False, "null_handling": False, "return_type": False, "strict": False, }
class JSONArrayAppend(Expression, Func): arg_types = {"this": True, "expressions": True} is_var_len_args = True _sql_names = ["JSON_ARRAY_APPEND"]
class JSONArrayContains(Expression, Binary, Predicate, Func): arg_types = {"this": True, "expression": True, "json_type": False} _sql_names = ["JSON_ARRAY_CONTAINS"]
class JSONArrayInsert(Expression, Func): arg_types = {"this": True, "expressions": True} is_var_len_args = True _sql_names = ["JSON_ARRAY_INSERT"]
class JSONBContains(Expression, Binary, Predicate, Func): _sql_names = ["JSONB_CONTAINS"]
class JSONBContainsAllTopKeys(Expression, Binary, Predicate, Func): pass
class JSONBContainsTopKey(Expression, Binary, Predicate, Func): pass
class JSONBContainsAnyTopKeys(Expression, Binary, Predicate, Func): pass
class JSONBDeleteAtPath(Expression, Binary, Func): pass
class JSONBPathExists(Expression, Binary, Predicate, Func): pass
class JSONBExists(Expression, Func): arg_types = {"this": True, "path": True} _sql_names = ["JSONB_EXISTS"]
class JSONBExtract(Expression, Binary, Func): _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(Expression, Binary, Func): arg_types = {"this": True, "expression": True, "json_type": False} _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONBObjectAgg(Expression, AggFunc): arg_types = {"this": True, "expression": True}
class JSONBool(Expression, Func): pass
class JSONExists(Expression, Func): arg_types = { "this": True, "path": True, "passing": False, "on_condition": False, "from_dcolonqmark": False, } _hash_raw_args = True
class JSONExtract(Expression, Binary, Func): arg_types = { "this": True, "expression": True, "only_json_types": False, "expressions": False, "variant_extract": False, "json_query": False, "option": False, "quote": False, "on_condition": False, "requires_json": False, "emits": False, } _sql_names = ["JSON_EXTRACT"] is_var_len_args = True
@property def output_name(self) -> str: return self.expression.output_name if not self.expressions else ""
class JSONExtractArray(Expression, Func): arg_types = {"this": True, "expression": False} _sql_names = ["JSON_EXTRACT_ARRAY"]
class JSONExtractScalar(Expression, Binary, Func): arg_types = { "this": True, "expression": True, "only_json_types": False, "expressions": False, "json_type": False, "scalar_only": False, "json_subtype": False, } _sql_names = ["JSON_EXTRACT_SCALAR"] is_var_len_args = True
@property def output_name(self) -> str: return self.expression.output_name
class JSONFormat(Expression, Func): arg_types = {"this": False, "options": False, "is_json": False, "to_json": False} _sql_names = ["JSON_FORMAT"]
class JSONKeys(Expression, Func): arg_types = {"this": True, "expression": False, "expressions": False} is_var_len_args = True _sql_names = ["JSON_KEYS"]
class JSONKeysAtDepth(Expression, Func): arg_types = {"this": True, "expression": False, "mode": False}
class JSONObject(Expression, Func): arg_types = { "expressions": False, "null_handling": False, "unique_keys": False, "return_type": False, "encoding": False, }
class JSONObjectAgg(Expression, AggFunc): arg_types = { "expressions": False, "null_handling": False, "unique_keys": False, "return_type": False, "encoding": False, }
class JSONRemove(Expression, Func): arg_types = {"this": True, "expressions": True} is_var_len_args = True _sql_names = ["JSON_REMOVE"]
class JSONSet(Expression, Func): arg_types = {"this": True, "expressions": True} is_var_len_args = True _sql_names = ["JSON_SET"]
class JSONStripNulls(Expression, Func): arg_types = { "this": True, "expression": False, "include_arrays": False, "remove_empty": False, } _sql_names = ["JSON_STRIP_NULLS"]
class StripNullValue(Expression, Func): pass
class JSONTable(Expression, Func): arg_types = { "this": True, "schema": True, "path": False, "error_handling": False, "empty_handling": False, }
class JSONType(Expression, Func): arg_types = {"this": True, "expression": False} _sql_names = ["JSON_TYPE"]
class ObjectId(Expression, Func): arg_types = {"this": True, "expression": False}
class ObjectInsert(Expression, Func): arg_types = { "this": True, "key": True, "value": True, "update_flag": False, }
class OpenJSON(Expression, Func): arg_types = {"this": True, "path": False, "expressions": False}
class FromJson(Expression, Func): arg_types = {"this": True, "expression": True, "options": False}
class ParseJSON(Expression, Func): # BigQuery, Snowflake have PARSE_JSON, Presto has JSON_PARSE # Snowflake also has TRY_PARSE_JSON, which is represented using `safe` _sql_names = ["PARSE_JSON", "JSON_PARSE"] arg_types = {"this": True, "expression": False, "safe": False, "is_literal": False}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286"""sqlglot expressions - math, trigonometry, and bitwise functions."""
from __future__ import annotations
from sqlglot.expressions.core import Expression, Func, AggFunc
# Trigonometric
class Acos(Expression, Func): pass
class Acosh(Expression, Func): pass
class Asin(Expression, Func): pass
class Asinh(Expression, Func): pass
class Atan(Expression, Func): arg_types = {"this": True, "expression": False}
class Atanh(Expression, Func): pass
class Atan2(Expression, Func): arg_types = {"this": True, "expression": True}
class Cos(Expression, Func): pass
class Cosh(Expression, Func): pass
class Cot(Expression, Func): pass
class Coth(Expression, Func): pass
class Csc(Expression, Func): pass
class Csch(Expression, Func): pass
class Degrees(Expression, Func): pass
class Radians(Expression, Func): pass
class Sec(Expression, Func): pass
class Sech(Expression, Func): pass
class Sin(Expression, Func): pass
class Sinh(Expression, Func): pass
class Tan(Expression, Func): pass
class Tanh(Expression, Func): pass
# Geometric distance / similarity
class CosineDistance(Expression, Func): arg_types = {"this": True, "expression": True}
class DotProduct(Expression, Func): arg_types = {"this": True, "expression": True}
class EuclideanDistance(Expression, Func): arg_types = {"this": True, "expression": True}
class JarowinklerSimilarity(Expression, Func): arg_types = { "this": True, "expression": True, "case_insensitive": False, "integer_scale": False, }
class ManhattanDistance(Expression, Func): arg_types = {"this": True, "expression": True}
# Basic arithmetic / math
class Abs(Expression, Func): pass
class Cbrt(Expression, Func): pass
class Ceil(Expression, Func): arg_types = {"this": True, "decimals": False, "to": False} _sql_names = ["CEIL", "CEILING"]
class Exp(Expression, Func): pass
class Factorial(Expression, Func): pass
class Floor(Expression, Func): arg_types = {"this": True, "decimals": False, "to": False}
class IsInf(Expression, Func): _sql_names = ["IS_INF", "ISINF"]
class IsNan(Expression, Func): _sql_names = ["IS_NAN", "ISNAN"]
class Ln(Expression, Func): pass
class Log(Expression, Func): arg_types = {"this": True, "expression": False}
class Negative(Expression, Func): pass
class Nanvl(Expression, Func): arg_types = {"this": True, "expression": True}
class Pi(Expression, Func): arg_types = {}
class Rint(Expression, Func): pass
class Round(Expression, Func): arg_types = { "this": True, "decimals": False, "truncate": False, "casts_non_integer_decimals": False, }
class Sign(Expression, Func): _sql_names = ["SIGN", "SIGNUM"]
class Sqrt(Expression, Func): pass
class Trunc(Expression, Func): arg_types = {"this": True, "decimals": False, "fractions_supported": False} _sql_names = ["TRUNC", "TRUNCATE"]
# Safe arithmetic
class SafeAdd(Expression, Func): arg_types = {"this": True, "expression": True}
class SafeDivide(Expression, Func): arg_types = {"this": True, "expression": True}
class SafeMultiply(Expression, Func): arg_types = {"this": True, "expression": True}
class SafeNegate(Expression, Func): pass
class SafeSubtract(Expression, Func): arg_types = {"this": True, "expression": True}
# Bitwise
class BitwiseAndAgg(Expression, AggFunc): pass
class BitwiseCount(Expression, Func): pass
class BitwiseOrAgg(Expression, AggFunc): pass
class BitwiseXorAgg(Expression, AggFunc): pass
class BitmapBitPosition(Expression, Func): pass
class BitmapBucketNumber(Expression, Func): pass
class BitmapConstructAgg(Expression, AggFunc): pass
class BitmapCount(Expression, Func): pass
class BitmapOrAgg(Expression, AggFunc): pass
class Booland(Expression, Func): arg_types = {"this": True, "expression": True, "round_input": False}
class Boolnot(Expression, Func): arg_types = {"this": True, "round_input": False}
class Boolor(Expression, Func): arg_types = {"this": True, "expression": True, "round_input": False}
class BoolxorAgg(Expression, AggFunc): pass
class Getbit(Expression, Func): _sql_names = ["GETBIT", "GET_BIT"] # zero_is_msb means the most significant bit is indexed 0 arg_types = {"this": True, "expression": True, "zero_is_msb": False}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673"""sqlglot expressions properties."""
from __future__ import annotations
import typing as tfrom enum import auto
from sqlglot.expressions.core import ColumnConstraintKind, Expression, Literal, convertfrom sqlglot.helper import AutoName
class Property(Expression): arg_types = {"this": True, "value": True}
class GrantPrivilege(Expression): arg_types = {"this": True, "expressions": False}
class GrantPrincipal(Expression): arg_types = {"this": True, "kind": False}
class AllowedValuesProperty(Expression): arg_types = {"expressions": True}
class AggregateKeyProperty(Property): arg_types = {"expressions": True}
class AlgorithmProperty(Property): arg_types = {"this": True}
class ApiProperty(Property): arg_types = {}
class ApplicationProperty(Property): arg_types = {}
class AutoIncrementProperty(Property): arg_types = {"this": True}
class AutoRefreshProperty(Property): arg_types = { "this": False, "cadence": False, "offset": False, "randomize": False, "expressions": False, "settings": False, "append": False, }
class BackupProperty(Property): arg_types = {"this": True}
class BuildProperty(Property): arg_types = {"this": True}
class BlockCompressionProperty(Property): arg_types = { "autotemp": False, "always": False, "default": False, "manual": False, "never": False, }
class CalledOnNullInputProperty(Property): arg_types = {}
class CatalogProperty(Property): arg_types = {}
class CharacterSetProperty(Property): arg_types = {"this": True, "default": True}
class ChecksumProperty(Property): arg_types = {"on": False, "default": False}
class ClusterProperty(Property): arg_types = {"this": False, "expressions": False}
class CollateProperty(Property): arg_types = {"this": True, "default": False}
class ComputeProperty(Property): arg_types = {}
class CopyGrantsProperty(Property): arg_types = {}
class DataBlocksizeProperty(Property): arg_types = { "size": False, "units": False, "minimum": False, "maximum": False, "default": False, }
class DataDeletionProperty(Property): arg_types = {"on": True, "filter_column": False, "retention_period": False}
class DatabaseProperty(Property): arg_types = {}
class DefinerProperty(Property): arg_types = {"this": True} _hash_raw_args = True
class DistKeyProperty(Property): arg_types = {"this": True}
class DistributedByProperty(Property): arg_types = {"expressions": False, "kind": True, "buckets": False, "order": False}
class DistStyleProperty(Property): arg_types = {"this": True}
class DuplicateKeyProperty(Property): arg_types = {"expressions": True}
class EngineProperty(Property): arg_types = {"this": True}
class UuidProperty(Property): arg_types = {"this": True}
class HeapProperty(Property): arg_types = {}
class HybridProperty(Property): arg_types = {}
class HandlerProperty(Property): arg_types = {"this": True}
class ParameterStyleProperty(Property): arg_types = {"this": True}
class ToTableProperty(Property): arg_types = {"this": True}
class ExecuteAsProperty(Property): arg_types = {"this": True}
class ExternalProperty(Property): arg_types = {"this": False}
class FallbackProperty(Property): arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property): arg_types = {"this": False, "expressions": False, "hive_format": False}
class CredentialsProperty(Property): arg_types = {"expressions": True}
class FreespaceProperty(Property): arg_types = {"this": True, "percent": False}
class GlobalProperty(Property): arg_types = {}
class IcebergProperty(Property): arg_types = {}
class InheritsProperty(Property): arg_types = {"expressions": True}
class InputModelProperty(Property): arg_types = {"this": True}
class OutputModelProperty(Property): arg_types = {"this": True}
class IsolatedLoadingProperty(Property): arg_types = {"no": False, "concurrent": False, "target": False}
class JournalProperty(Property): arg_types = { "no": False, "dual": False, "before": False, "local": False, "after": False, }
class LanguageProperty(Property): arg_types = {"this": True}
class EnviromentProperty(Property): arg_types = {"expressions": True}
class ClusteredByProperty(Property): arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
class DictProperty(Property): arg_types = {"this": True, "kind": True, "settings": False}
class DictSubProperty(Property): pass
class DictRange(Property): arg_types = {"this": True, "min": True, "max": True}
class DynamicProperty(Property): arg_types = {}
class OnCluster(Property): arg_types = {"this": True}
class EmptyProperty(Property): arg_types = {}
class LikeProperty(Property): arg_types = {"this": True, "expressions": False}
class LocationProperty(Property): arg_types = {"this": True}
class LockProperty(Property): arg_types = {"this": True}
class LockingProperty(Property): arg_types = { "this": False, "kind": True, "for_or_in": False, "lock_type": True, "override": False, }
class LogProperty(Property): arg_types = {"no": True}
class MaskingProperty(Property): arg_types = {}
class MaterializedProperty(Property): arg_types = {"this": False}
class MergeBlockRatioProperty(Property): arg_types = {"this": False, "no": False, "default": False, "percent": False}
class ModuleProperty(Property): arg_types = {"this": True, "expressions": False}
class NetworkProperty(Property): arg_types = {}
class NoPrimaryIndexProperty(Property): arg_types = {}
class OnProperty(Property): arg_types = {"this": True}
class OnCommitProperty(Property): arg_types = {"delete": False}
class PartitionedByProperty(Property): arg_types = {"this": True}
class PartitionedByBucket(Property): arg_types = {"this": True, "expression": True}
class PartitionByTruncate(Property): arg_types = {"this": True, "expression": True}
class PartitionByRangeProperty(Property): arg_types = {"partition_expressions": True, "create_expressions": True}
class PartitionByRangePropertyDynamic(Expression): arg_types = {"this": False, "start": True, "end": True, "every": True}
class RollupProperty(Property): arg_types = {"expressions": True}
class RollupIndex(Expression): arg_types = {"this": True, "expressions": True, "from_index": False, "properties": False}
class RowAccessProperty(Property): arg_types = {"this": False, "expressions": False}
class PartitionByListProperty(Property): arg_types = {"partition_expressions": True, "create_expressions": True}
class PartitionList(Expression): arg_types = {"this": True, "expressions": True}
class RefreshTriggerProperty(Property): arg_types = { "method": False, "kind": False, "every": False, "unit": False, "starts": False, }
class UniqueKeyProperty(Property): arg_types = {"expressions": True}
class PartitionBoundSpec(Expression): # this -> IN / MODULUS, expression -> REMAINDER, from_expressions -> FROM (...), to_expressions -> TO (...) arg_types = { "this": False, "expression": False, "from_expressions": False, "to_expressions": False, }
class PartitionedOfProperty(Property): # this -> parent_table (schema), expression -> FOR VALUES ... / DEFAULT arg_types = {"this": True, "expression": True}
class PhysicalProperty(Property): arg_types = {"this": True, "value": False}
class StreamingTableProperty(Property): arg_types = {}
class RemoteWithConnectionModelProperty(Property): arg_types = {"this": True}
class ReturnsProperty(Property): arg_types = {"this": False, "is_table": False, "table": False, "null": False}
class StrictProperty(Property): arg_types = {}
class RowFormatProperty(Property): arg_types = {"this": True}
class RowFormatDelimitedProperty(Property): # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml arg_types = { "fields": False, "escaped": False, "collection_items": False, "map_keys": False, "lines": False, "null": False, "serde": False, }
class RowFormatSerdeProperty(Property): arg_types = {"this": True, "serde_properties": False}
class QueryTransform(Expression): arg_types = { "expressions": True, "command_script": True, "schema": False, "row_format_before": False, "record_writer": False, "row_format_after": False, "record_reader": False, }
class SampleProperty(Property): arg_types = {"this": True}
class SchemaCommentProperty(Property): arg_types = {"this": True}
class SemanticView(Expression): arg_types = { "this": True, "metrics": False, "dimensions": False, "facts": False, "where": False, }
class SerdeProperties(Property): arg_types = {"expressions": True, "with_": False}
class SetProperty(Property): arg_types = {"multi": True}
class SharingProperty(Property): arg_types = {"this": False}
class SetConfigProperty(Property): arg_types = {"this": True}
class SettingsProperty(Property): arg_types = {"expressions": True}
class SortKeyProperty(Property): arg_types = {"this": True, "compound": False}
class SqlReadWriteProperty(Property): arg_types = {"this": True}
class SqlSecurityProperty(Property): arg_types = {"this": True}
class StabilityProperty(Property): arg_types = {"this": True}
class StorageHandlerProperty(Property): arg_types = {"this": True}
class StorageProperty(Property): arg_types = {"expressions": True}
class UsingProperty(Property): # kind: JAR, FILE, or ARCHIVE; this: the resource path (string literal) arg_types = {"this": True, "kind": True}
class TemporaryProperty(Property): arg_types = {"this": False}
class VirtualProperty(Property): arg_types = {}
class SecureProperty(Property): arg_types = {}
class SecurityIntegrationProperty(Property): arg_types = {}
class Tags(Property, ColumnConstraintKind): arg_types = {"expressions": True}
class TableSpaceProperty(Property): arg_types = {"this": True}
class PropertiesLocation(AutoName): POST_CREATE = auto() POST_NAME = auto() POST_SCHEMA = auto() POST_WITH = auto() POST_ALIAS = auto() POST_EXPRESSION = auto() POST_INDEX = auto() UNSUPPORTED = auto()
class TransformModelProperty(Property): arg_types = {"expressions": True}
class TransientProperty(Property): arg_types = {"this": False}
class UnloggedProperty(Property): arg_types = {}
class UsingTemplateProperty(Property): arg_types = {"this": True}
class ViewAttributeProperty(Property): arg_types = {"this": True}
class VolatileProperty(Property): arg_types = {"this": False}
class WithDataProperty(Property): arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property): arg_types = {"this": True}
class WithSchemaBindingProperty(Property): arg_types = {"this": True}
class WithSystemVersioningProperty(Property): arg_types = { "on": False, "this": False, "data_consistency": False, "retention_period": False, "with_": True, }
class WithProcedureOptions(Property): arg_types = {"expressions": True}
class EncodeProperty(Property): arg_types = {"this": True, "properties": False, "key": False}
class IncludeProperty(Property): arg_types = {"this": True, "alias": False, "column_def": False}
class ForceProperty(Property): arg_types = {}
class Properties(Expression): arg_types = {"expressions": True}
NAME_TO_PROPERTY: t.ClassVar[dict[str, type[Property]]] = { "ALGORITHM": AlgorithmProperty, "AUTO_INCREMENT": AutoIncrementProperty, "CHARACTER SET": CharacterSetProperty, "CLUSTERED_BY": ClusteredByProperty, "COLLATE": CollateProperty, "COMMENT": SchemaCommentProperty, "CREDENTIALS": CredentialsProperty, "DEFINER": DefinerProperty, "DISTKEY": DistKeyProperty, "DISTRIBUTED_BY": DistributedByProperty, "DISTSTYLE": DistStyleProperty, "ENGINE": EngineProperty, "EXECUTE AS": ExecuteAsProperty, "FORMAT": FileFormatProperty, "LANGUAGE": LanguageProperty, "LOCATION": LocationProperty, "LOCK": LockProperty, "PARTITIONED_BY": PartitionedByProperty, "RETURNS": ReturnsProperty, "ROW_FORMAT": RowFormatProperty, "SORTKEY": SortKeyProperty, "ENCODE": EncodeProperty, "INCLUDE": IncludeProperty, }
PROPERTY_TO_NAME: t.ClassVar[dict[type[Property], str]] = { v: k for k, v in NAME_TO_PROPERTY.items() }
# CREATE property locations # Form: schema specified # create [POST_CREATE] # table a [POST_NAME] # (b int) [POST_SCHEMA] # with ([POST_WITH]) # index (b) [POST_INDEX] # # Form: alias selection # create [POST_CREATE] # table a [POST_NAME] # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] # index (c) [POST_INDEX] Location: t.ClassVar[type[PropertiesLocation]] = PropertiesLocation
@classmethod def from_dict(cls, properties_dict: dict) -> Properties: expressions = [] for key, value in properties_dict.items(): property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) if property_cls: expressions.append(property_cls(this=convert(value))) else: expressions.append(Property(this=Literal.string(key), value=convert(value)))
return cls(expressions=expressions)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329"""sqlglot expressions query."""
from __future__ import annotations
import typing as t
from sqlglot.errors import ParseErrorfrom sqlglot.helper import trait, ensure_listfrom sqlglot.expressions.core import ( Aliases, Column, Condition, Distinct, Dot, DynamicIdentifier, Expr, Expression, Func, Hint, Identifier, In, Var, _apply_builder, _apply_child_list_builder, _apply_list_builder, _apply_conjunction_builder, _apply_set_operation, ExpOrStr, QUERY_MODIFIERS, maybe_parse, maybe_copy, to_identifier, convert, and_, alias_, column,)
if t.TYPE_CHECKING: from sqlglot.dialects.dialect import DialectType from sqlglot.expressions.datatypes import DataType from sqlglot.expressions.constraints import ColumnConstraint from sqlglot.expressions.ddl import Create from sqlglot.expressions.array import Unnest from sqlglot._typing import E, ParserArgs, ParserNoDialectArgs from typing_extensions import Unpack
S = t.TypeVar("S", bound="SetOperation") Q = t.TypeVar("Q", bound="Query")
def _apply_cte_builder( instance: E, alias: ExpOrStr, as_: ExpOrStr, recursive: bool | None = None, materialized: bool | None = None, append: bool = True, dialect: DialectType = None, copy: bool = True, scalar: bool | None = None, **opts: Unpack[ParserNoDialectArgs],) -> E: alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts) as_expression = maybe_parse(as_, dialect=dialect, copy=copy, **opts) if scalar and not isinstance(as_expression, Subquery): # scalar CTE must be wrapped in a subquery as_expression = Subquery(this=as_expression) cte = CTE(this=as_expression, alias=alias_expression, materialized=materialized, scalar=scalar) return _apply_child_list_builder( cte, instance=instance, arg="with_", append=append, copy=copy, into=With, properties={"recursive": recursive} if recursive else {}, )
@traitclass Selectable(Expr): @property def selects(self) -> list[Expr]: raise NotImplementedError("Subclasses must implement selects")
@property def named_selects(self) -> list[str]: return _named_selects(self)
def _named_selects(self: Expr) -> list[str]: selectable = t.cast(Selectable, self) return [select.output_name for select in selectable.selects]
@traitclass DerivedTable(Selectable): @property def selects(self) -> list[Expr]: this = self.this return this.selects if isinstance(this, Query) else []
@traitclass UDTF(DerivedTable): @property def selects(self) -> list[Expr]: alias = self.args.get("alias") return alias.columns if alias else []
@traitclass Query(Selectable): """Trait for any SELECT/UNION/etc. query expression."""
@property def ctes(self) -> list[CTE]: with_ = self.args.get("with_") return with_.expressions if with_ else []
def select( self: Q, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Q: raise NotImplementedError("Query objects must implement `select`")
def subquery(self, alias: ExpOrStr | None = None, copy: bool = True) -> Subquery: """ Returns a `Subquery` that wraps around this query.
Example: >>> subquery = Select().select("x").from_("tbl").subquery() >>> Select().select("x").from_(subquery).sql() 'SELECT x FROM (SELECT x FROM tbl)'
Args: alias: an optional alias for the subquery. copy: if `False`, modify this expression instance in-place. """ instance = maybe_copy(self, copy) if not isinstance(alias, Expr): alias = TableAlias(this=to_identifier(alias)) if alias else None
return Subquery(this=instance, alias=alias)
def limit( self: Q, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Q: """ Adds a LIMIT clause to this query.
Example: >>> Select().select("1").union(Select().select("1")).limit(1).sql() 'SELECT 1 UNION SELECT 1 LIMIT 1'
Args: expression: the SQL code string to parse. This can also be an integer. If a `Limit` instance is passed, it will be used as-is. If another `Expr` instance is passed, it will be wrapped in a `Limit`. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: A limited Select expression. """ return _apply_builder( expression=expression, instance=self, arg="limit", into=Limit, prefix="LIMIT", dialect=dialect, copy=copy, into_arg="expression", **opts, )
def offset( self: Q, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Q: """ Set the OFFSET expression.
Example: >>> Select().from_("tbl").select("x").offset(10).sql() 'SELECT x FROM tbl OFFSET 10'
Args: expression: the SQL code string to parse. This can also be an integer. If a `Offset` instance is passed, this is used as-is. If another `Expr` instance is passed, it will be wrapped in a `Offset`. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Select expression. """ return _apply_builder( expression=expression, instance=self, arg="offset", into=Offset, prefix="OFFSET", dialect=dialect, copy=copy, into_arg="expression", **opts, )
def order_by( self: Q, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Q: """ Set the ORDER BY expression.
Example: >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 'SELECT x FROM tbl ORDER BY x DESC'
Args: *expressions: the SQL code strings to parse. If a `Group` instance is passed, this is used as-is. If another `Expr` instance is passed, it will be wrapped in a `Order`. append: if `True`, add to any existing expressions. Otherwise, this flattens all the `Order` expression into a single expression. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Select expression. """ return _apply_child_list_builder( *expressions, instance=self, arg="order", append=append, copy=copy, prefix="ORDER BY", into=Order, dialect=dialect, **opts, )
def where( self: Q, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Q: """ Append to or set the WHERE expressions.
Examples: >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Args: *expressions: the SQL code strings to parse. If an `Expr` instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. append: if `True`, AND the new expressions to any existing expression. Otherwise, this resets the expression. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified expression. """ return _apply_conjunction_builder( *[expr.this if isinstance(expr, Where) else expr for expr in expressions], instance=self, arg="where", append=append, into=Where, dialect=dialect, copy=copy, **opts, )
def with_( self: Q, alias: ExpOrStr, as_: ExpOrStr, recursive: bool | None = None, materialized: bool | None = None, append: bool = True, dialect: DialectType = None, copy: bool = True, scalar: bool | None = None, **opts: Unpack[ParserNoDialectArgs], ) -> Q: """ Append to or set the common table expressions.
Example: >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Args: alias: the SQL code string to parse as the table name. If an `Expr` instance is passed, this is used as-is. as_: the SQL code string to parse as the table expression. If an `Expr` instance is passed, it will be used as-is. recursive: set the RECURSIVE part of the expression. Defaults to `False`. materialized: set the MATERIALIZED part of the expression. append: if `True`, add to any existing expressions. Otherwise, this resets the expressions. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. scalar: if `True`, this is a scalar common table expression. opts: other options to use to parse the input expressions.
Returns: The modified expression. """ return _apply_cte_builder( self, alias, as_, recursive=recursive, materialized=materialized, append=append, dialect=dialect, copy=copy, scalar=scalar, **opts, )
def union( self, *expressions: ExpOrStr, distinct: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Union: """ Builds a UNION expression.
Example: >>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Args: expressions: the SQL code strings. If `Expr` instances are passed, they will be used as-is. distinct: set the DISTINCT flag if and only if this is true. dialect: the dialect used to parse the input expression. opts: other options to use to parse the input expressions.
Returns: The new Union expression. """ return union(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
def intersect( self, *expressions: ExpOrStr, distinct: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Intersect: """ Builds an INTERSECT expression.
Example: >>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Args: expressions: the SQL code strings. If `Expr` instances are passed, they will be used as-is. distinct: set the DISTINCT flag if and only if this is true. dialect: the dialect used to parse the input expression. opts: other options to use to parse the input expressions.
Returns: The new Intersect expression. """ return intersect(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
def except_( self, *expressions: ExpOrStr, distinct: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Except: """ Builds an EXCEPT expression.
Example: >>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Args: expressions: the SQL code strings. If `Expr` instance are passed, they will be used as-is. distinct: set the DISTINCT flag if and only if this is true. dialect: the dialect used to parse the input expression. opts: other options to use to parse the input expressions.
Returns: The new Except expression. """ return except_(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
class QueryBand(Expression): arg_types = {"this": True, "scope": False, "update": False}
class RecursiveWithSearch(Expression): arg_types = { "kind": True, "this": True, "expression": True, "to": False, "default": False, "using": False, }
class With(Expression): arg_types = { "expressions": False, "recursive": False, "search": False, "cycle": False, "udfs": False, }
@property def recursive(self) -> bool: return bool(self.args.get("recursive"))
class CTE(Expression, DerivedTable): arg_types = { "this": True, "alias": True, "scalar": False, "materialized": False, "key_expressions": False, }
class ProjectionDef(Expression): arg_types = {"this": True, "expression": True}
class TableAlias(Expression): arg_types = {"this": False, "columns": False}
@property def columns(self) -> list[t.Any]: return self.args.get("columns") or []
class BitString(Expression, Condition): is_primitive = True
class HexString(Expression, Condition): arg_types = {"this": True, "is_integer": False} is_primitive = True
class ByteString(Expression, Condition): arg_types = {"this": True, "is_bytes": False} is_primitive = True _hash_raw_args = True
class RawString(Expression, Condition): is_primitive = True _hash_raw_args = True
class UnicodeString(Expression, Condition): arg_types = {"this": True, "escape": False} _hash_raw_args = True
class ColumnPosition(Expression): arg_types = {"this": False, "position": True}
class ColumnDef(Expression): arg_types = { "this": True, "kind": False, "constraints": False, "exists": False, "position": False, "default": False, "output": False, }
@property def constraints(self) -> list[ColumnConstraint]: return self.args.get("constraints") or []
@property def kind(self) -> DataType | None: return self.args.get("kind")
class Changes(Expression): arg_types = {"information": True, "at_before": False, "end": False}
class Connect(Expression): arg_types = {"start": False, "connect": True, "nocycle": False}
class Prior(Expression): pass
class Into(Expression): arg_types = { "this": False, "temporary": False, "unlogged": False, "bulk_collect": False, "expressions": False, }
class From(Expression): @property def name(self) -> str: return self.this.name
@property def alias_or_name(self) -> str: return self.this.alias_or_name
class Having(Expression): pass
class Index(Expression): arg_types = { "this": False, "table": False, "unique": False, "primary": False, "amp": False, # teradata "params": False, }
class ConditionalInsert(Expression): arg_types = {"this": True, "expression": False, "else_": False}
class MultitableInserts(Expression): arg_types = {"with_": False, "expressions": True, "kind": False, "source": True}
class OnCondition(Expression): arg_types = {"error": False, "empty": False, "null": False}
class Introducer(Expression): arg_types = {"this": True, "expression": True}
class National(Expression): is_primitive = True _hash_raw_args = True
class Partition(Expression): arg_types = {"expressions": True, "subpartition": False}
class PartitionRange(Expression): arg_types = {"this": True, "expression": False, "expressions": False}
class PartitionId(Expression): pass
class Fetch(Expression): arg_types = { "direction": False, "count": False, "limit_options": False, }
class Grant(Expression): arg_types = { "privileges": True, "kind": False, "securable": True, "principals": True, "grant_option": False, }
class Revoke(Expression): arg_types = {**Grant.arg_types, "cascade": False}
class Group(Expression): arg_types = { "expressions": False, "grouping_sets": False, "cube": False, "rollup": False, "totals": False, "all": False, }
class Cube(Expression): arg_types = {"expressions": False}
class Rollup(Expression): arg_types = {"expressions": False}
class GroupingSets(Expression): arg_types = {"expressions": True}
class Lambda(Expression): arg_types = {"this": True, "expressions": True}
class Limit(Expression): arg_types = { "this": False, "expression": True, "offset": False, "limit_options": False, "expressions": False, }
@property def is_limit_all(self) -> bool: limit_expression = self.args.get("expression") return isinstance(limit_expression, Var) and limit_expression.name.upper() == "ALL"
class LimitOptions(Expression): arg_types = { "percent": False, "rows": False, "with_ties": False, }
class Join(Expression): arg_types = { "this": True, "on": False, "side": False, "kind": False, "using": False, "method": False, "global_": False, "hint": False, "match_condition": False, # Snowflake "directed": False, # Snowflake "expressions": False, "pivots": False, }
@property def method(self) -> str: return self.text("method").upper()
@property def kind(self) -> str: return self.text("kind").upper()
@property def side(self) -> str: return self.text("side").upper()
@property def hint(self) -> str: return self.text("hint").upper()
@property def alias_or_name(self) -> str: return self.this.alias_or_name
@property def is_semi_or_anti_join(self) -> bool: return self.kind in ("SEMI", "ANTI")
def on( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Join: """ Append to or set the ON expressions.
Example: >>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 'JOIN x ON y = 1'
Args: *expressions: the SQL code strings to parse. If an `Expr` instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. append: if `True`, AND the new expressions to any existing expression. Otherwise, this resets the expression. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Join expression. """ join = _apply_conjunction_builder( *expressions, instance=self, arg="on", append=append, dialect=dialect, copy=copy, **opts, )
if join.kind == "CROSS": join.set("kind", None)
return join
def using( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Join: """ Append to or set the USING expressions.
Example: >>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 'JOIN x USING (foo, bla)'
Args: *expressions: the SQL code strings to parse. If an `Expr` instance is passed, it will be used as-is. append: if `True`, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Join expression. """ join = _apply_list_builder( *expressions, instance=self, arg="using", append=append, dialect=dialect, copy=copy, **opts, )
if join.kind == "CROSS": join.set("kind", None)
return join
class Lateral(Expression, UDTF): arg_types = { "this": True, "view": False, "outer": False, "alias": False, "cross_apply": False, # True -> CROSS APPLY, False -> OUTER APPLY "ordinality": False, }
@property def selects(self) -> list[Expr]: from sqlglot.expressions.array import Unnest
columns = super().selects
# UNNEST ... WITH ORDINALITY stores the ordinality column's name in Unnest.offset offset = self.this.args.get("offset") if isinstance(self.this, Unnest) else None if isinstance(offset, Identifier): columns = columns + [offset]
return columns
class TableFromRows(Expression, UDTF): arg_types = { "this": True, "alias": False, "joins": False, "pivots": False, "sample": False, }
class MatchRecognizeMeasure(Expression): arg_types = { "this": True, "window_frame": False, }
class MatchRecognize(Expression): arg_types = { "partition_by": False, "order": False, "measures": False, "rows": False, "after": False, "pattern": False, "define": False, "alias": False, }
class Final(Expression): pass
class Offset(Expression): arg_types = {"this": False, "expression": True, "expressions": False}
class Order(Expression): arg_types = {"this": False, "expressions": True, "siblings": False}
class WithFill(Expression): arg_types = { "from_": False, "to": False, "step": False, "interpolate": False, }
class SkipJSONColumn(Expression): arg_types = {"regexp": False, "expression": True}
class Cluster(Expression): arg_types = {"expressions": True}
class Distribute(Order): pass
class Sort(Order): pass
class Qualify(Expression): pass
class InputOutputFormat(Expression): arg_types = {"input_format": False, "output_format": False}
class Return(Expression): pass
class Tuple(Expression): arg_types = {"expressions": False}
def isin( self, *expressions: t.Any, query: ExpOrStr | None = None, unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None, copy: bool = True, **opts: Unpack[ParserArgs], ) -> In: return In( this=maybe_copy(self, copy), expressions=[convert(e, copy=copy) for e in expressions], query=maybe_parse(query, copy=copy, **opts) if query else None, unnest=( Unnest( expressions=[ maybe_parse(e, copy=copy, **opts) for e in t.cast(list[ExpOrStr], ensure_list(unnest)) ] ) if unnest else None ), )
class QueryOption(Expression): arg_types = {"this": True, "expression": False}
# FOR { XML | JSON } query modifier; `kind` is the discriminant ("XML" or "JSON").class ForClause(Expression): arg_types = {"kind": True, "expressions": False}
class WithTableHint(Expression): arg_types = {"expressions": True}
class IndexTableHint(Expression): arg_types = {"this": True, "expressions": False, "target": False}
class HistoricalData(Expression): arg_types = {"this": True, "kind": True, "expression": True}
class Put(Expression): arg_types = {"this": True, "target": True, "properties": False}
class Get(Expression): arg_types = {"this": True, "target": True, "properties": False}
class ListStage(Expression): """Lists files in a Snowflake stage or Git repository clone."""
arg_types = {"this": True, "pattern": False}
class Table(Expression, Selectable): arg_types = { "this": False, "alias": False, "db": False, "catalog": False, "laterals": False, "joins": False, "pivots": False, "hints": False, "system_time": False, "version": False, "format": False, "pattern": False, "ordinality": False, "when": False, "only": False, "partition": False, "changes": False, "rows_from": False, "sample": False, "indexed": False, }
@property def name(self) -> str: this = self.this if not this or (isinstance(this, Func) and not isinstance(this, DynamicIdentifier)): return "" return this.name
@property def db(self) -> str: return self.text("db")
@property def catalog(self) -> str: return self.text("catalog")
@property def selects(self) -> list[Expr]: return []
@property def named_selects(self) -> list[str]: return []
@property def parts(self) -> list[Expr]: """Return the parts of a table in order catalog, db, table.""" parts: list[Expr] = []
for arg in ("catalog", "db", "this"): part = self.args.get(arg)
if isinstance(part, Dot): parts.extend(part.flatten()) elif isinstance(part, Expr): parts.append(part)
return parts
def to_column(self, copy: bool = True) -> Expr: parts = self.parts last_part = parts[-1]
if isinstance(last_part, Identifier): col: Expr = column(*reversed(parts[0:4]), fields=parts[4:], copy=copy) # type: ignore else: # This branch will be reached if a function or array is wrapped in a `Table` col = last_part
alias = self.args.get("alias") if alias: col = alias_(col, alias.this, copy=copy)
return col
def _is_star(expression: Expr) -> bool: stack = [expression] while stack: node = stack.pop() if isinstance(node, SetOperation): stack.append(node.this) stack.append(node.expression) elif isinstance(node, Subquery): stack.append(node.this) elif node.is_star: return True return False
class SetOperation(Expression, Query): arg_types = { "with_": False, "this": True, "expression": True, "distinct": False, "by_name": False, "side": False, "kind": False, "on": False, **QUERY_MODIFIERS, }
def select( self: S, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> S: this = maybe_copy(self, copy) this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) this.expression.unnest().select( *expressions, append=append, dialect=dialect, copy=False, **opts ) return this
@property def named_selects(self) -> list[str]: expr: Expr = self while isinstance(expr, SetOperation): if expr.args.get("by_name"): left = t.cast(Selectable, expr.this.unnest()).named_selects right = t.cast(Selectable, expr.expression.unnest()).named_selects return list(dict.fromkeys(left + right))
expr = expr.this.unnest() return _named_selects(expr)
@property def is_star(self) -> bool: return _is_star(self)
@property def selects(self) -> list[Expr]: expr: Expr = self while isinstance(expr, SetOperation): expr = expr.this.unnest() return getattr(expr, "selects", [])
@property def left(self) -> Query: return self.this
@property def right(self) -> Query: return self.expression
@property def kind(self) -> str: return self.text("kind").upper()
@property def side(self) -> str: return self.text("side").upper()
class Union(SetOperation): pass
class Except(SetOperation): pass
class Intersect(SetOperation): pass
class Values(Expression, UDTF): arg_types = { "expressions": True, "alias": False, "order": False, "limit": False, "offset": False, }
class Version(Expression): """ Time travel, iceberg, bigquery etc https://trino.io/docs/current/connector/iceberg.html?highlight=snapshot#using-snapshots https://www.databricks.com/blog/2019/02/04/introducing-delta-time-travel-for-large-scale-data-lakes.html https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver16 this is either TIMESTAMP or VERSION kind is ("AS OF", "BETWEEN") """
arg_types = {"this": True, "kind": True, "expression": False}
class Schema(Expression): arg_types = {"this": False, "expressions": False}
class Lock(Expression): arg_types = {"update": True, "expressions": False, "wait": False, "key": False}
class Select(Expression, Query): arg_types = { "with_": False, "kind": False, "expressions": False, "hint": False, "distinct": False, "into": False, "from_": False, "operation_modifiers": False, "exclude": False, **QUERY_MODIFIERS, }
def from_( self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Select: """ Set the FROM expression.
Example: >>> Select().from_("tbl").select("x").sql() 'SELECT x FROM tbl'
Args: expression : the SQL code strings to parse. If a `From` instance is passed, this is used as-is. If another `Expr` instance is passed, it will be wrapped in a `From`. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Select expression. """ return _apply_builder( expression=expression, instance=self, arg="from_", into=From, prefix="FROM", dialect=dialect, copy=copy, **opts, )
def group_by( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Select: """ Set the GROUP BY expression.
Example: >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Args: *expressions: the SQL code strings to parse. If a `Group` instance is passed, this is used as-is. If another `Expr` instance is passed, it will be wrapped in a `Group`. If nothing is passed in then a group by is not applied to the expression append: if `True`, add to any existing expressions. Otherwise, this flattens all the `Group` expression into a single expression. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Select expression. """ if not expressions: return self if not copy else self.copy()
return _apply_child_list_builder( *expressions, instance=self, arg="group", append=append, copy=copy, prefix="GROUP BY", into=Group, dialect=dialect, **opts, )
def sort_by( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Select: """ Set the SORT BY expression.
Example: >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive") 'SELECT x FROM tbl SORT BY x DESC'
Args: *expressions: the SQL code strings to parse. If a `Group` instance is passed, this is used as-is. If another `Expr` instance is passed, it will be wrapped in a `SORT`. append: if `True`, add to any existing expressions. Otherwise, this flattens all the `Order` expression into a single expression. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Select expression. """ return _apply_child_list_builder( *expressions, instance=self, arg="sort", append=append, copy=copy, prefix="SORT BY", into=Sort, dialect=dialect, **opts, )
def cluster_by( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Select: """ Set the CLUSTER BY expression.
Example: >>> Select().from_("tbl").select("x").cluster_by("x").sql(dialect="hive") 'SELECT x FROM tbl CLUSTER BY x'
Args: *expressions: the SQL code strings to parse. If a `Group` instance is passed, this is used as-is. If another `Expr` instance is passed, it will be wrapped in a `Cluster`. append: if `True`, add to any existing expressions. Otherwise, this flattens all the `Order` expression into a single expression. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Select expression. """ return _apply_child_list_builder( *expressions, instance=self, arg="cluster", append=append, copy=copy, prefix="CLUSTER BY", into=Cluster, dialect=dialect, **opts, )
def select( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Select: return _apply_list_builder( *expressions, instance=self, arg="expressions", append=append, dialect=dialect, into=Expr, copy=copy, **opts, )
def lateral( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Select: """ Append to or set the LATERAL expressions.
Example: >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Args: *expressions: the SQL code strings to parse. If an `Expr` instance is passed, it will be used as-is. append: if `True`, add to any existing expressions. Otherwise, this resets the expressions. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Select expression. """ return _apply_list_builder( *expressions, instance=self, arg="laterals", append=append, into=Lateral, prefix="LATERAL VIEW", dialect=dialect, copy=copy, **opts, )
def join( self, expression: ExpOrStr, on: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None, using: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None, append: bool = True, join_type: str | None = None, join_alias: Identifier | str | None = None, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Select: """ Append to or set the JOIN expressions.
Example: >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 'SELECT 1 FROM a JOIN b USING (x, y, z)'
Use `join_type` to change the type of join:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Args: expression: the SQL code string to parse. If an `Expr` instance is passed, it will be used as-is. on: optionally specify the join "on" criteria as a SQL string. If an `Expr` instance is passed, it will be used as-is. using: optionally specify the join "using" criteria as a SQL string. If an `Expr` instance is passed, it will be used as-is. append: if `True`, add to any existing expressions. Otherwise, this resets the expressions. join_type: if set, alter the parsed join type. join_alias: an optional alias for the joined source. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: Select: the modified expression. """ parse_args: ParserArgs = {"dialect": dialect, **opts} try: expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) except ParseError: expression = maybe_parse(expression, into=(Join, Expr), **parse_args)
join = expression if isinstance(expression, Join) else Join(this=expression)
if isinstance(join.this, Select): join.this.replace(join.this.subquery())
if join_type: new_join: Join = maybe_parse(f"FROM _ {join_type} JOIN _", **parse_args).find(Join) method = new_join.method side = new_join.side kind = new_join.kind
if method: join.set("method", method) if side: join.set("side", side) if kind: join.set("kind", kind)
if on: on_exprs: list[ExpOrStr] = ensure_list(on) on = and_(*on_exprs, dialect=dialect, copy=copy, **opts) join.set("on", on)
if using: using_exprs: list[ExpOrStr] = ensure_list(using) join = _apply_list_builder( *using_exprs, instance=join, arg="using", append=append, copy=copy, into=Identifier, **opts, )
if join_alias: join.set("this", alias_(join.this, join_alias, table=True))
return _apply_list_builder( join, instance=self, arg="joins", append=append, copy=copy, **opts, )
def having( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Select: """ Append to or set the HAVING expressions.
Example: >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Args: *expressions: the SQL code strings to parse. If an `Expr` instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. append: if `True`, AND the new expressions to any existing expression. Otherwise, this resets the expression. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.
Returns: The modified Select expression. """ return _apply_conjunction_builder( *expressions, instance=self, arg="having", append=append, into=Having, dialect=dialect, copy=copy, **opts, )
def window( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Select: return _apply_list_builder( *expressions, instance=self, arg="windows", append=append, into=Window, dialect=dialect, copy=copy, **opts, )
def qualify( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Select: return _apply_conjunction_builder( *expressions, instance=self, arg="qualify", append=append, into=Qualify, dialect=dialect, copy=copy, **opts, )
def distinct(self, *ons: ExpOrStr | None, distinct: bool = True, copy: bool = True) -> Select: """ Set the OFFSET expression.
Example: >>> Select().from_("tbl").select("x").distinct().sql() 'SELECT DISTINCT x FROM tbl'
Args: ons: the expressions to distinct on distinct: whether the Select should be distinct copy: if `False`, modify this expression instance in-place.
Returns: Select: the modified expression. """ instance = maybe_copy(self, copy) on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None instance.set("distinct", Distinct(on=on) if distinct else None) return instance
def ctas( self, table: ExpOrStr, properties: dict | None = None, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Create: """ Convert this expression to a CREATE TABLE AS statement.
Example: >>> Select().select("*").from_("tbl").ctas("x").sql() 'CREATE TABLE x AS SELECT * FROM tbl'
Args: table: the SQL code string to parse as the table name. If another `Expr` instance is passed, it will be used as-is. properties: an optional mapping of table properties dialect: the dialect used to parse the input table. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input table.
Returns: The new Create expression. """ instance = maybe_copy(self, copy) table_expression = maybe_parse(table, into=Table, dialect=dialect, **opts)
properties_expression = None if properties: from sqlglot.expressions.properties import Properties as _Properties
properties_expression = _Properties.from_dict(properties)
from sqlglot.expressions.ddl import Create as _Create
return _Create( this=table_expression, kind="TABLE", expression=instance, properties=properties_expression, )
def lock(self, update: bool = True, copy: bool = True) -> Select: """ Set the locking read mode for this expression.
Examples: >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Args: update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. copy: if `False`, modify this expression instance in-place.
Returns: The modified expression. """ inst = maybe_copy(self, copy) inst.set("locks", [Lock(update=update)])
return inst
def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select: """ Set hints for this expression.
Examples: >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark") 'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Args: hints: The SQL code strings to parse as the hints. If an `Expr` instance is passed, it will be used as-is. dialect: The dialect used to parse the hints. copy: If `False`, modify this expression instance in-place.
Returns: The modified expression. """ inst = maybe_copy(self, copy) inst.set( "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints]) )
return inst
@property def named_selects(self) -> list[str]: selects = []
for e in self.expressions: if e.alias_or_name: selects.append(e.output_name) elif isinstance(e, Aliases): selects.extend([a.name for a in e.aliases]) return selects
@property def is_star(self) -> bool: return any(expression.is_star for expression in self.expressions)
@property def selects(self) -> list[Expr]: return self.expressions
class Subquery(Expression, DerivedTable, Query): is_subquery: t.ClassVar[bool] = True arg_types = { "this": True, "alias": False, "with_": False, **QUERY_MODIFIERS, }
def unnest(self) -> Expr: """Returns the first non subquery.""" expression: Expr = self while isinstance(expression, Subquery): expression = expression.this return expression
def unwrap(self) -> Subquery: expression = self while expression.same_parent and expression.is_wrapper: expression = t.cast(Subquery, expression.parent) return expression
def select( self, *expressions: ExpOrStr | None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs], ) -> Subquery: this = maybe_copy(self, copy) inner = this.unnest() if hasattr(inner, "select"): inner.select(*expressions, append=append, dialect=dialect, copy=False, **opts) return this
@property def is_wrapper(self) -> bool: """ Whether this Subquery acts as a simple wrapper around another expression.
SELECT * FROM (((SELECT * FROM t))) ^ This corresponds to a "wrapper" Subquery node """ return all(v is None for k, v in self.args.items() if k != "this")
@property def is_star(self) -> bool: return _is_star(self)
@property def output_name(self) -> str: return self.alias
class TableSample(Expression): arg_types = { "expressions": False, "method": False, "bucket_numerator": False, "bucket_denominator": False, "bucket_field": False, "percent": False, "rows": False, "size": False, "seed": False, }
class Tag(Expression): """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
arg_types = { "this": False, "prefix": False, "postfix": False, }
class Pivot(Expression): arg_types = { "this": False, "alias": False, "expressions": False, "fields": False, "unpivot": False, "using": False, "group": False, "columns": False, "include_nulls": False, "default_on_null": False, "into": False, "with_": False, "identify_pivot_strings": False, "prefixed_pivot_columns": False, "pivot_column_naming": False, "value_columns_first": False, }
@property def unpivot(self) -> bool: return bool(self.args.get("unpivot"))
@property def fields(self) -> list[Expr]: return self.args.get("fields", [])
def output_columns(self, pre_pivot_columns: t.Iterable[str]) -> dict[str, str]: """ Returns an ordered map of post-rename output column name -> pre-rename source-side name, in the order the (UN)PIVOT produces them.
For callers that just want the names, iterate the dict (or call .keys()): >>> from sqlglot import parse_one, exp >>> piv = parse_one("SELECT * FROM t UNPIVOT(val FOR name IN (a, b))").find(exp.Pivot) >>> list(piv.output_columns(["a", "b", "c"])) ['c', 'name', 'val']
AST shape: PIVOT(SUM(val) FOR name IN ('a', 'b')): expressions: aggregate(s), e.g. [Sum(this=Column(val))] fields: [In(this=Column(name), expressions=[Literal('a'), Literal('b')])] columns: optional explicit output identifiers (e.g. set by Snowflake)
UNPIVOT(val FOR name IN (a, b)): expressions: value Identifier(s), or Tuple(Identifiers) for multi-value fields: [In(this=Identifier(name), expressions=[Column(a), Column(b)])] For literal-aliased entries (`a AS 'x'`) the IN expressions are wrapped in PivotAlias(this=Column, alias=Literal).
Args: pre_pivot_columns: Columns visible to the operator before it runs (e.g. the source table or subquery's projections). """ if self.unpivot: excluded: set[str] = set() name_columns: list[Identifier] = [] for field in self.fields: if not isinstance(field, In): continue if isinstance(field.this, Identifier): name_columns.append(field.this) for e in field.expressions: excluded.update(c.output_name for c in e.find_all(Column)) value_columns = [ ident for e in self.expressions for ident in (e.expressions if isinstance(e, Tuple) else [e]) if isinstance(ident, Identifier) ] # T-SQL emits the value column(s) ahead of the name column, everyone else emits them after it ordered = ( value_columns + name_columns if self.args.get("value_columns_first") else name_columns + value_columns ) outputs = [i.name for i in ordered] else: excluded = {c.output_name for c in self.find_all(Column)} outputs = [c.output_name for c in self.args.get("columns") or []] if not outputs: outputs = [c.alias_or_name for c in self.expressions]
if not excluded or not outputs: return {}
pre_rename = [c for c in pre_pivot_columns if c not in excluded] + outputs
alias = self.args.get("alias") renames = alias.args.get("columns") if alias else None
# `PIVOT(...) AS alias(c1, c2, ...)` renames the operator's output columns # positionally from the front (DuckDB, Snowflake): the user's names cover # the leading N output columns, remaining columns keep their auto names. if renames: rename_names = [r.name for r in renames] post_rename = rename_names + pre_rename[len(rename_names) :] else: post_rename = pre_rename
return dict(zip(post_rename, pre_rename))
class UnpivotColumns(Expression): arg_types = {"this": True, "expressions": True}
class Window(Expression, Condition): arg_types = { "this": True, "partition_by": False, "order": False, "spec": False, "alias": False, "over": False, "first": False, }
class WindowSpec(Expression): arg_types = { "kind": False, "start": False, "start_side": False, "end": False, "end_side": False, "exclude": False, }
class PartitionByExcluding(Expression): arg_types = {"expressions": True}
class PreWhere(Expression): pass
class Where(Expression): pass
class Analyze(Expression): arg_types = { "kind": False, "tables": False, "options": False, "mode": False, "partition": False, "expression": False, "properties": False, }
class AnalyzeStatistics(Expression): arg_types = { "kind": True, "option": False, "this": False, "expressions": False, }
class AnalyzeHistogram(Expression): arg_types = { "this": True, "expressions": True, "expression": False, "update_options": False, }
class AnalyzeSample(Expression): arg_types = {"kind": True, "sample": True}
class AnalyzeListChainedRows(Expression): arg_types = {"expression": False}
class AnalyzeDelete(Expression): arg_types = {"kind": False}
class AnalyzeWith(Expression): arg_types = {"expressions": True}
class AnalyzeValidate(Expression): arg_types = { "kind": True, "this": False, "expression": False, }
class AnalyzeColumns(Expression): pass
class UsingData(Expression): pass
class AddPartition(Expression): arg_types = {"this": True, "exists": False, "location": False}
class AttachOption(Expression): arg_types = {"this": True, "expression": False}
class DropPartition(Expression): arg_types = {"expressions": True, "exists": False}
class ReplaceColumns(Expression): arg_types = {"expressions": True}
class ReplacePartition(Expression): arg_types = {"expression": True, "source": True}
class TranslateCharacters(Expression): arg_types = {"this": True, "expression": True, "with_error": False}
class OverflowTruncateBehavior(Expression): arg_types = {"this": False, "with_count": True}
class JSON(Expression): arg_types = {"this": False, "with_": False, "unique": False}
class JSONPath(Expression): arg_types = {"expressions": True}
@property def output_name(self) -> str: last_segment = self.expressions[-1].this return last_segment if isinstance(last_segment, str) else ""
class JSONPathPart(Expression): arg_types = {}
class JSONPathFilter(JSONPathPart): arg_types = {"this": True} _hash_raw_args = True
class JSONPathKey(JSONPathPart): arg_types = {"this": True, "quoted": False} _hash_raw_args = True
class JSONPathRecursive(JSONPathPart): arg_types = {"this": False} _hash_raw_args = True
class JSONPathRoot(JSONPathPart): pass
class JSONPathScript(JSONPathPart): arg_types = {"this": True} _hash_raw_args = True
class JSONPathSlice(JSONPathPart): arg_types = {"start": False, "end": False, "step": False}
class JSONPathSelector(JSONPathPart): arg_types = {"this": True}
class JSONPathSubscript(JSONPathPart): arg_types = {"this": True}
class JSONPathUnion(JSONPathPart): arg_types = {"expressions": True} _hash_raw_args = True
class JSONPathWildcard(JSONPathPart): pass
class FormatJson(Expression): pass
class JSONKeyValue(Expression): arg_types = {"this": True, "expression": True}
class JSONColumnDef(Expression): arg_types = { "this": False, "kind": False, "path": False, "nested_schema": False, "ordinality": False, "format_json": False, }
class JSONSchema(Expression): arg_types = {"expressions": True}
class JSONValue(Expression): arg_types = { "this": True, "path": True, "returning": False, "on_condition": False, }
class JSONValueArray(Expression, Func): arg_types = {"this": True, "expression": False}
class OpenJSONColumnDef(Expression): arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
class JSONExtractQuote(Expression): arg_types = { "option": True, "scalar": False, }
class ScopeResolution(Expression): arg_types = {"this": False, "expression": True}
class Stream(Expression): pass
class ModelAttribute(Expression): arg_types = {"this": True, "expression": True}
class XMLNamespace(Expression): pass
class XMLKeyValueOption(Expression): arg_types = {"this": True, "expression": False}
class Semicolon(Expression): arg_types = {}
class TableColumn(Expression): @property def output_name(self) -> str: return self.name
class Variadic(Expression): pass
class StoredProcedure(Expression): arg_types = {"this": True, "expressions": False, "wrapped": False}
class Block(Expression): arg_types = {"expressions": True, "begin": False}
class IfBlock(Expression): arg_types = {"this": True, "true": True, "false": False}
class CaseStatement(Expression): arg_types = {"this": False, "ifs": True, "default": False}
class WhileBlock(Expression): arg_types = {"this": True, "body": True, "label": False}
class LoopBlock(Expression): arg_types = {"body": True, "label": False}
class RepeatBlock(Expression): arg_types = {"body": True, "until": True, "label": False}
class Leave(Expression): pass
class Iterate(Expression): pass
class EndStatement(Expression): arg_types = {}
# https://trino.io/docs/current/udf.htmlclass FunctionSpecification(Expression): arg_types = { "this": True, "characteristics": False, "properties": False, "expression": True, }
UNWRAPPED_QUERIES = (Select, SetOperation)
def union( *expressions: ExpOrStr, distinct: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Union: """ Initializes a syntax tree for the `UNION` operation.
Example: >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Args: expressions: the SQL code strings, corresponding to the `UNION`'s operands. If `Expr` instances are passed, they will be used as-is. distinct: set the DISTINCT flag if and only if this is true. dialect: the dialect used to parse the input expression. copy: whether to copy the expression. opts: other options to use to parse the input expressions.
Returns: The new Union instance. """ assert len(expressions) >= 2, "At least two expressions are required by `union`." return _apply_set_operation( *expressions, set_operation=Union, distinct=distinct, dialect=dialect, copy=copy, **opts )
def intersect( *expressions: ExpOrStr, distinct: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Intersect: """ Initializes a syntax tree for the `INTERSECT` operation.
Example: >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Args: expressions: the SQL code strings, corresponding to the `INTERSECT`'s operands. If `Expr` instances are passed, they will be used as-is. distinct: set the DISTINCT flag if and only if this is true. dialect: the dialect used to parse the input expression. copy: whether to copy the expression. opts: other options to use to parse the input expressions.
Returns: The new Intersect instance. """ assert len(expressions) >= 2, "At least two expressions are required by `intersect`." return _apply_set_operation( *expressions, set_operation=Intersect, distinct=distinct, dialect=dialect, copy=copy, **opts )
def except_( *expressions: ExpOrStr, distinct: bool = True, dialect: DialectType = None, copy: bool = True, **opts: Unpack[ParserNoDialectArgs],) -> Except: """ Initializes a syntax tree for the `EXCEPT` operation.
Example: >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Args: expressions: the SQL code strings, corresponding to the `EXCEPT`'s operands. If `Expr` instances are passed, they will be used as-is. distinct: set the DISTINCT flag if and only if this is true. dialect: the dialect used to parse the input expression. copy: whether to copy the expression. opts: other options to use to parse the input expressions.
Returns: The new Except instance. """ assert len(expressions) >= 2, "At least two expressions are required by `except_`." return _apply_set_operation( *expressions, set_operation=Except, distinct=distinct, dialect=dialect, copy=copy, **opts )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608"""sqlglot expressions - string, encoding, hashing, and regex functions."""
from __future__ import annotations
from sqlglot.expressions.core import Expression, Func, Binary, Predicate
# String basics
class Ascii(Expression, Func): pass
class BitLength(Expression, Func): pass
class ByteLength(Expression, Func): pass
class Chr(Expression, Func): arg_types = {"expressions": True, "charset": False} is_var_len_args = True _sql_names = ["CHR", "CHAR"]
class Concat(Expression, Func): arg_types = {"expressions": True, "safe": False, "coalesce": False} is_var_len_args = True
class ConcatWs(Concat): arg_types = {**Concat.arg_types, "flatten": False} _sql_names = ["CONCAT_WS"]
class Contains(Expression, Func): arg_types = {"this": True, "expression": True, "json_scope": False}
class Elt(Expression, Func): arg_types = {"this": True, "expressions": True} is_var_len_args = True
class EndsWith(Expression, Func): _sql_names = ["ENDS_WITH", "ENDSWITH"] arg_types = {"this": True, "expression": True}
class Format(Expression, Func): arg_types = {"this": True, "expressions": False} is_var_len_args = True
class Initcap(Expression, Func): arg_types = {"this": True, "expression": False}
class IsAscii(Expression, Func): pass
class Left(Expression, Func): arg_types = {"this": True, "expression": True, "negative_length_returns_empty": False}
class Length(Expression, Func): arg_types = {"this": True, "binary": False, "encoding": False} _sql_names = ["LENGTH", "LEN", "CHAR_LENGTH", "CHARACTER_LENGTH"]
class Levenshtein(Expression, Func): arg_types = { "this": True, "expression": False, "ins_cost": False, "del_cost": False, "sub_cost": False, "max_dist": False, }
class Lower(Expression, Func): _sql_names = ["LOWER", "LCASE"]
class MatchAgainst(Expression, Func): arg_types = {"this": True, "expressions": True, "modifier": False}
class Normalize(Expression, Func): arg_types = {"this": True, "form": False, "is_casefold": False}
class NumberToStr(Expression, Func): arg_types = {"this": True, "format": True, "culture": False}
class Overlay(Expression, Func): arg_types = {"this": True, "expression": True, "from_": True, "for_": False}
class Pad(Expression, Func): arg_types = {"this": True, "expression": True, "fill_pattern": False, "is_left": True}
class Repeat(Expression, Func): arg_types = {"this": True, "times": True}
class Replace(Expression, Func): arg_types = {"this": True, "expression": True, "replacement": False}
class Reverse(Expression, Func): pass
class Right(Expression, Func): arg_types = {"this": True, "expression": True, "negative_length_returns_empty": False}
class RtrimmedLength(Expression, Func): pass
class Search(Expression, Func): arg_types = { "this": True, # data_to_search / search_data "expression": True, # search_query / search_string "json_scope": False, # BigQuery: JSON_VALUES | JSON_KEYS | JSON_KEYS_AND_VALUES "analyzer": False, # Both: analyzer / ANALYZER "analyzer_options": False, # BigQuery: analyzer_options_values "search_mode": False, # Snowflake: OR | AND }
class SearchIp(Expression, Func): arg_types = {"this": True, "expression": True}
class Secret(Expression, Func): arg_types = {"this": True, "expression": True}
class Soundex(Expression, Func): pass
class SoundexP123(Expression, Func): pass
class Space(Expression, Func): """ SPACE(n) → string consisting of n blank characters """
pass
class Split(Expression, Func): arg_types = { "this": True, "expression": True, "limit": False, "null_returns_null": False, "empty_delimiter_returns_whole": False, }
class SplitPart(Expression, Func): arg_types = { "this": True, "delimiter": False, "part_index": False, "part_index_zero_as_one": False, # usually part_index is 1-based, however Snowflake allows 0 and treats it as 1 "empty_delimiter_returns_whole": False, # whether the whole input string should be returned if the delimiter string is empty (i.e. Snowflake) }
class Strtok(Expression, Func): arg_types = { "this": True, "delimiter": False, "part_index": False, }
class StartsWith(Expression, Func): _sql_names = ["STARTS_WITH", "STARTSWITH"] arg_types = {"this": True, "expression": True}
class StrPosition(Expression, Func): arg_types = { "this": True, "substr": True, "position": False, "occurrence": False, "clamp_position": False, }
class StrToMap(Expression, Func): arg_types = { "this": True, "pair_delim": False, "key_value_delim": False, "duplicate_resolution_callback": False, }
class String(Expression, Func): arg_types = {"this": True, "zone": False}
class Stuff(Expression, Func): _sql_names = ["STUFF", "INSERT"] arg_types = {"this": True, "start": True, "length": True, "expression": True}
class Substring(Expression, Func): _sql_names = ["SUBSTRING", "SUBSTR"] arg_types = {"this": True, "start": False, "length": False, "zero_start": False}
class SubstringIndex(Expression, Func): """ SUBSTRING_INDEX(str, delim, count)
*count* > 0 → left slice before the *count*-th delimiter *count* < 0 → right slice after the |count|-th delimiter """
arg_types = {"this": True, "delimiter": True, "count": True}
class Translate(Expression, Func): arg_types = {"this": True, "from_": True, "to": True}
class Trim(Expression, Func): arg_types = { "this": True, "expression": False, "position": False, "collation": False, }
class Unicode(Expression, Func): arg_types = {"this": True, "empty_is_zero": False}
class Upper(Expression, Func): _sql_names = ["UPPER", "UCASE"]
class WeightString(Expression, Func): arg_types = {"this": True, "to": False}
# Encoding / base conversion
class Base64DecodeBinary(Expression, Func): arg_types = {"this": True, "alphabet": False}
class Base64DecodeString(Expression, Func): arg_types = {"this": True, "alphabet": False}
class Base64Encode(Expression, Func): arg_types = {"this": True, "max_line_length": False, "alphabet": False}
class CodePointsToBytes(Expression, Func): pass
class CodePointsToString(Expression, Func): pass
class ConvertToCharset(Expression, Func): arg_types = {"this": True, "dest": True, "source": False}
class Decode(Expression, Func): arg_types = {"this": True, "charset": True, "replace": False}
class Encode(Expression, Func): arg_types = {"this": True, "charset": True}
class FromBase(Expression, Func): arg_types = {"this": True, "expression": True}
class FromBase32(Expression, Func): pass
class FromBase64(Expression, Func): pass
class Hex(Expression, Func): arg_types = {"this": True, "case": False}
class HexDecodeString(Expression, Func): pass
class LowerHex(Hex): pass
class SafeConvertBytesToString(Expression, Func): pass
class ToBase32(Expression, Func): pass
class ToBase64(Expression, Func): pass
class ToBinary(Expression, Func): arg_types = {"this": True, "format": False, "safe": False}
class ToChar(Expression, Func): arg_types = { "this": True, "format": False, "nlsparam": False, "is_numeric": False, }
class ToCodePoints(Expression, Func): pass
class ToDecfloat(Expression, Func): arg_types = { "this": True, "format": False, }
class ToDouble(Expression, Func): arg_types = { "this": True, "format": False, "safe": False, }
class ToFile(Expression, Func): arg_types = { "this": True, "path": False, "safe": False, }
class ToNumber(Expression, Func): arg_types = { "this": True, "format": False, "nlsparam": False, "precision": False, "scale": False, "safe": False, "safe_name": False, "default": False, }
class TryBase64DecodeBinary(Expression, Func): arg_types = {"this": True, "alphabet": False}
class TryBase64DecodeString(Expression, Func): arg_types = {"this": True, "alphabet": False}
class TryHexDecodeBinary(Expression, Func): pass
class TryHexDecodeString(Expression, Func): pass
class TryToDecfloat(Expression, Func): arg_types = { "this": True, "format": False, }
class Unhex(Expression, Func): arg_types = {"this": True, "expression": False}
# Regex
class RegexpCount(Expression, Func): arg_types = { "this": True, "expression": True, "position": False, "parameters": False, }
class RegexpExtract(Expression, Func): arg_types = { "this": True, "expression": True, "position": False, "occurrence": False, "parameters": False, "group": False, "null_if_pos_overflow": False, # for transpilation target behavior }
class RegexpExtractAll(Expression, Func): arg_types = { "this": True, "expression": True, "group": False, "parameters": False, "position": False, "occurrence": False, }
class RegexpFullMatch(Expression, Binary, Predicate, Func): arg_types = {"this": True, "expression": True, "options": False}
class RegexpILike(Expression, Binary, Predicate, Func): arg_types = {"this": True, "expression": True, "flag": False}
class RegexpInstr(Expression, Func): arg_types = { "this": True, "expression": True, "position": False, "occurrence": False, "option": False, "parameters": False, "group": False, }
class RegexpReplace(Expression, Func): arg_types = { "this": True, "expression": True, "replacement": False, "position": False, "occurrence": False, "modifiers": False, "single_replace": False, }
class RegexpSplit(Expression, Func): # "mode" is Dremio-specific, appended after "limit" for from_arg_list compat arg_types = {"this": True, "expression": True, "limit": False, "mode": False}
class RegexpSubstr(Expression, Func): arg_types = { "this": True, "expression": True, "position": False, "occurrence": False, "parameters": False, "group": False, }
# Hashing / cryptographic
class Compress(Expression, Func): arg_types = {"this": True, "method": False}
class Decrypt(Expression, Func): arg_types = { "this": True, "passphrase": True, "aad": False, "encryption_method": False, "safe": False, }
class DecryptRaw(Expression, Func): arg_types = { "this": True, "key": True, "iv": True, "aad": False, "encryption_method": False, "aead": False, "safe": False, }
class DecompressBinary(Expression, Func): arg_types = {"this": True, "method": True}
class DecompressString(Expression, Func): arg_types = {"this": True, "method": True}
class Encrypt(Expression, Func): arg_types = {"this": True, "passphrase": True, "aad": False, "encryption_method": False}
class EncryptRaw(Expression, Func): arg_types = {"this": True, "key": True, "iv": True, "aad": False, "encryption_method": False}
class CityHash64(Expression, Func): arg_types = {"expressions": False} is_var_len_args = True
class FarmFingerprint(Expression, Func): arg_types = {"expressions": True} is_var_len_args = True _sql_names = ["FARM_FINGERPRINT", "FARMFINGERPRINT64"]
class MD5(Expression, Func): _sql_names = ["MD5"]
class MD5Digest(Expression, Func): arg_types = {"this": True, "expressions": False} is_var_len_args = True _sql_names = ["MD5_DIGEST"]
class MD5NumberLower64(Expression, Func): pass
class MD5NumberUpper64(Expression, Func): pass
class SHA(Expression, Func): _sql_names = ["SHA", "SHA1"]
class SHA1Digest(Expression, Func): pass
class SHA2(Expression, Func): _sql_names = ["SHA2"] arg_types = {"this": True, "length": False}
class SHA2Digest(Expression, Func): arg_types = {"this": True, "length": False}
class StandardHash(Expression, Func): arg_types = {"this": True, "expression": False}
# Parse
class ParseBignumeric(Expression, Func): pass
class ParseNumeric(Expression, Func): pass
class ParseUrl(Expression, Func): arg_types = {"this": True, "part_to_extract": False, "key": False, "permissive": False}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567"""sqlglot expressions - date, time, and timestamp functions."""
from __future__ import annotations
import typing as t
from sqlglot.expressions.core import ( Expression, Func, TimeUnit, IntervalOp, Literal, Column, TIMESTAMP_PARTS,)from sqlglot.expressions.datatypes import DataType, DType
if t.TYPE_CHECKING: from sqlglot.expressions.core import Expr, Neg
# Current date/time
class CurrentDate(Expression, Func): arg_types = {"this": False}
class CurrentDatetime(Expression, Func): arg_types = {"this": False}
class CurrentTime(Expression, Func): arg_types = {"this": False}
class CurrentTimestamp(Expression, Func): arg_types = {"this": False, "sysdate": False}
class CurrentTimestampLTZ(Expression, Func): arg_types = {}
class CurrentTimezone(Expression, Func): arg_types = {}
class Localtime(Expression, Func): arg_types = {"this": False}
class Localtimestamp(Expression, Func): arg_types = {"this": False}
class Systimestamp(Expression, Func): arg_types = {"this": False}
class UtcDate(Expression, Func): arg_types = {}
class UtcTime(Expression, Func): arg_types = {"this": False}
class UtcTimestamp(Expression, Func): arg_types = {"this": False}
# Date arithmetic
class AddMonths(Expression, Func): arg_types = {"this": True, "expression": True, "preserve_end_of_month": False}
class DateAdd(Expression, Func, IntervalOp): arg_types = {"this": True, "expression": True, "unit": False}
class DateBin(Expression, Func, IntervalOp): arg_types = {"this": True, "expression": True, "unit": False, "zone": False, "origin": False}
class DateDiff(Expression, Func, TimeUnit): _sql_names = ["DATEDIFF", "DATE_DIFF"] arg_types = { "this": True, "expression": True, "unit": False, "zone": False, "big_int": False, "date_part_boundary": False, }
class DateSub(Expression, Func, IntervalOp): arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeAdd(Expression, Func, IntervalOp): arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Expression, Func, TimeUnit): arg_types = {"this": True, "expression": True, "unit": False, "date_part_boundary": False}
class DatetimeSub(Expression, Func, IntervalOp): arg_types = {"this": True, "expression": True, "unit": False}
class MonthsBetween(Expression, Func): arg_types = {"this": True, "expression": True, "roundoff": False}
class TimeAdd(Expression, Func, TimeUnit): arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Expression, Func, TimeUnit): arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Expression, Func, TimeUnit): arg_types = {"this": True, "expression": True, "unit": False}
class TimestampAdd(Expression, Func, TimeUnit): arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Expression, Func, TimeUnit): _sql_names = ["TIMESTAMPDIFF", "TIMESTAMP_DIFF"] arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Expression, Func, TimeUnit): arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsAdd(Expression, Func, TimeUnit): # return_type is used to correctly cast the arguments of this expression when transpiling it arg_types = {"this": True, "expression": True, "unit": False, "return_type": False}
@property def return_type(self) -> DataType: return DataType.build(self.args.get("return_type") or DType.DATE)
class TsOrDsDiff(Expression, Func, TimeUnit): arg_types = {"this": True, "expression": True, "unit": False}
# Truncation
class DatetimeTrunc(Expression, Func, TimeUnit): arg_types = {"this": True, "unit": True, "zone": False}
class DateTrunc(Expression, Func): arg_types = {"unit": True, "this": True, "zone": False, "input_type_preserved": False}
def __init__(self, **args): # Across most dialects it's safe to unabbreviate the unit (e.g. 'Q' -> 'QUARTER') except Oracle # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html unabbreviate = args.pop("unabbreviate", True)
unit = args.get("unit") if isinstance(unit, TimeUnit.VAR_LIKE) and not ( isinstance(unit, Column) and len(unit.parts) != 1 ): unit_name = unit.name.upper() if unabbreviate and unit_name in TimeUnit.UNABBREVIATED_UNIT_NAME: unit_name = TimeUnit.UNABBREVIATED_UNIT_NAME[unit_name]
args["unit"] = Literal.string(unit_name)
super().__init__(**args)
@property def unit(self) -> Expr: return self.args["unit"]
class TimestampTrunc(Expression, Func, TimeUnit): arg_types = {"this": True, "unit": True, "zone": False, "input_type_preserved": False}
class TimeSlice(Expression, Func, TimeUnit): arg_types = {"this": True, "expression": True, "unit": True, "kind": False}
class TimeTrunc(Expression, Func, TimeUnit): arg_types = {"this": True, "unit": True, "zone": False}
# Date/time extraction
class Day(Expression, Func): pass
class DayOfMonth(Expression, Func): _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfWeek(Expression, Func): _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfWeekIso(Expression, Func): _sql_names = ["DAYOFWEEK_ISO", "ISODOW"]
class DayOfYear(Expression, Func): _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class Dayname(Expression, Func): arg_types = {"this": True, "abbreviated": False}
class Extract(Expression, Func): arg_types = {"this": True, "expression": True}
class GetExtract(Expression, Func): arg_types = {"this": True, "expression": True}
class Hour(Expression, Func): pass
class Minute(Expression, Func): pass
class Month(Expression, Func): pass
class Monthname(Expression, Func): arg_types = {"this": True, "abbreviated": False}
class Quarter(Expression, Func): pass
class Second(Expression, Func): pass
class ToDays(Expression, Func): pass
class Week(Expression, Func): arg_types = {"this": True, "mode": False}
class WeekOfYear(Expression, Func): _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class Year(Expression, Func): pass
class YearOfWeek(Expression, Func): _sql_names = ["YEAR_OF_WEEK", "YEAROFWEEK"]
class YearOfWeekIso(Expression, Func): _sql_names = ["YEAR_OF_WEEK_ISO", "YEAROFWEEKISO"]
# Date/time construction
class Date(Expression, Func): arg_types = {"this": False, "zone": False, "expressions": False} is_var_len_args = True
class DateFromParts(Expression, Func): _sql_names = ["DATE_FROM_PARTS", "DATEFROMPARTS"] arg_types = {"year": True, "month": False, "day": False, "allow_overflow": False}
class DateFromUnixDate(Expression, Func): pass
class Datetime(Expression, Func): arg_types = {"this": True, "expression": False}
class GapFill(Expression, Func): arg_types = { "this": True, "ts_column": True, "bucket_width": True, "partitioning_columns": False, "value_columns": False, "origin": False, "ignore_nulls": False, }
class GenerateDateArray(Expression, Func): arg_types = {"start": True, "end": True, "step": False}
class GenerateTimestampArray(Expression, Func): arg_types = {"start": True, "end": True, "step": True}
class JustifyDays(Expression, Func): pass
class JustifyHours(Expression, Func): pass
class JustifyInterval(Expression, Func): pass
class LastDay(Expression, Func, TimeUnit): _sql_names = ["LAST_DAY", "LAST_DAY_OF_MONTH"] arg_types = {"this": True, "unit": False}
class MakeInterval(Expression, Func): arg_types = { "year": False, "month": False, "week": False, "day": False, "hour": False, "minute": False, "second": False, }
class NextDay(Expression, Func): arg_types = {"this": True, "expression": True}
class PreviousDay(Expression, Func): arg_types = {"this": True, "expression": True}
class Time(Expression, Func): arg_types = {"this": False, "zone": False}
class TimeFromParts(Expression, Func): _sql_names = ["TIME_FROM_PARTS", "TIMEFROMPARTS"] arg_types = { "hour": True, "min": True, "sec": True, "nano": False, "fractions": False, "precision": False, "overflow": False, }
class Timestamp(Expression, Func): arg_types = {"this": False, "zone": False, "with_tz": False}
class TimestampFromParts(Expression, Func): _sql_names = ["TIMESTAMP_FROM_PARTS", "TIMESTAMPFROMPARTS"] arg_types = { **TIMESTAMP_PARTS, "zone": False, "milli": False, "this": False, "expression": False, }
class TimestampLtzFromParts(Expression, Func): _sql_names = ["TIMESTAMP_LTZ_FROM_PARTS", "TIMESTAMPLTZFROMPARTS"] arg_types = TIMESTAMP_PARTS.copy()
class TimestampTzFromParts(Expression, Func): _sql_names = ["TIMESTAMP_TZ_FROM_PARTS", "TIMESTAMPTZFROMPARTS"] arg_types = { **TIMESTAMP_PARTS, "zone": False, }
# Date/time conversion
class ConvertTimezone(Expression, Func): arg_types = { "source_tz": False, "target_tz": True, "timestamp": True, "options": False, }
class DateStrToDate(Expression, Func): pass
class DateToDateStr(Expression, Func): pass
class DateToDi(Expression, Func): pass
class DiToDate(Expression, Func): pass
class FromISO8601Timestamp(Expression, Func): _sql_names = ["FROM_ISO8601_TIMESTAMP"]
class FromISO8601Date(Expression, Func): _sql_names = ["FROM_ISO8601_DATE"]
class FromISO8601TimestampNanos(Expression, Func): _sql_names = ["FROM_ISO8601_TIMESTAMP_NANOS"]
class ParseDatetime(Expression, Func): arg_types = {"this": True, "format": False, "zone": False, "default_year": False}
class ParseTime(Expression, Func): arg_types = {"this": True, "format": True}
class StrToDate(Expression, Func): arg_types = {"this": True, "format": False, "safe": False, "default_year": False}
class StrToTime(Expression, Func): arg_types = { "this": True, "format": True, "zone": False, "safe": False, "target_type": False, "default_year": False, }
class StrToUnix(Expression, Func): arg_types = {"this": False, "format": False}
class TimeStrToDate(Expression, Func): pass
class TimeStrToTime(Expression, Func): arg_types = {"this": True, "zone": False}
class TimeStrToUnix(Expression, Func): pass
class TimeToStr(Expression, Func): arg_types = {"this": True, "format": True, "culture": False, "zone": False}
class TimeToTimeStr(Expression, Func): pass
class TimeToUnix(Expression, Func): pass
class TsOrDiToDi(Expression, Func): pass
class TsOrDsToDate(Expression, Func): arg_types = {"this": True, "format": False, "safe": False, "default_date": False}
class TsOrDsToDateStr(Expression, Func): pass
class TsOrDsToDatetime(Expression, Func): pass
class TsOrDsToTime(Expression, Func): arg_types = {"this": True, "format": False, "safe": False}
class TsOrDsToTimestamp(Expression, Func): pass
class UnixDate(Expression, Func): pass
class UnixMicros(Expression, Func): pass
class UnixMillis(Expression, Func): pass
class UnixSeconds(Expression, Func): pass
class UnixToStr(Expression, Func): arg_types = {"this": True, "format": False}
class UnixToTime(Expression, Func): arg_types = { "this": True, "scale": False, "zone": False, "hours": False, "minutes": False, "format": False, "target_type": False, }
SECONDS: t.ClassVar[Literal | Neg] = Literal.number(0) DECIS: t.ClassVar[Literal | Neg] = Literal.number(1) CENTIS: t.ClassVar[Literal | Neg] = Literal.number(2) MILLIS: t.ClassVar[Literal | Neg] = Literal.number(3) DECIMILLIS: t.ClassVar[Literal | Neg] = Literal.number(4) CENTIMILLIS: t.ClassVar[Literal | Neg] = Literal.number(5) MICROS: t.ClassVar[Literal | Neg] = Literal.number(6) DECIMICROS: t.ClassVar[Literal | Neg] = Literal.number(7) CENTIMICROS: t.ClassVar[Literal | Neg] = Literal.number(8) NANOS: t.ClassVar[Literal | Neg] = Literal.number(9)
class UnixToTimeStr(Expression, Func): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184from __future__ import annotations
import typing as t
from sqlglot import exp, generatorfrom sqlglot.generators.hive import HiveGeneratorfrom sqlglot.generators.trino import TrinoGenerator
def _is_iceberg_table(properties: exp.Properties) -> bool: for p in properties.expressions: if isinstance(p, exp.Property) and p.name == "table_type": return p.text("value").lower() == "iceberg"
return False
def _location_property_sql(self: AthenaTrinoGenerator, e: exp.LocationProperty) -> str: # If table_type='iceberg', the LocationProperty is called 'location' # Otherwise, it's called 'external_location' # ref: https://docs.aws.amazon.com/athena/latest/ug/create-table-as.html
prop_name = "external_location"
if isinstance(e.parent, exp.Properties): if _is_iceberg_table(e.parent): prop_name = "location"
return f"{prop_name}={self.sql(e, 'this')}"
def _partitioned_by_property_sql(self: AthenaTrinoGenerator, e: exp.PartitionedByProperty) -> str: # If table_type='iceberg' then the table property for partitioning is called 'partitioning' # If table_type='hive' it's called 'partitioned_by' # ref: https://docs.aws.amazon.com/athena/latest/ug/create-table-as.html#ctas-table-properties
prop_name = "partitioned_by"
if isinstance(e.parent, exp.Properties): if _is_iceberg_table(e.parent): prop_name = "partitioning"
return f"{prop_name}={self.sql(e, 'this')}"
def _generate_as_hive(expression: exp.Expr) -> bool: if isinstance(expression, exp.Create): if expression.kind == "TABLE": properties = expression.args.get("properties")
# CREATE EXTERNAL TABLE is Hive if properties and properties.find(exp.ExternalProperty): return True
# Any CREATE TABLE other than CREATE TABLE ... As <query> is Hive if not isinstance(expression.expression, exp.Query): # CTAS with a leading USING EXTERNAL FUNCTION clause is Trino return not ( isinstance(expression.expression, exp.Command) and expression.expression.text("this").upper() == "USING" ) else: # CREATE VIEW is Trino, but CREATE SCHEMA, CREATE DATABASE, etc, is Hive return expression.kind != "VIEW" elif isinstance(expression, (exp.Alter, exp.Drop, exp.Describe, exp.Show)): if isinstance(expression, exp.Drop) and expression.kind == "VIEW": # DROP VIEW is Trino, because CREATE VIEW is as well return False
# Everything else, e.g., ALTER statements, is Hive return True
return False
def _generator_kwargs( pretty: bool | int | None, identify: str | bool, normalize: bool, pad: int, indent: int, normalize_functions: str | bool | None, unsupported_level: t.Any, max_unsupported: int, leading_comma: bool, max_text_width: int, comments: bool,) -> dict[str, t.Any]: kwargs: dict[str, t.Any] = { "pretty": pretty, "identify": identify, "normalize": normalize, "pad": pad, "indent": indent, "normalize_functions": normalize_functions, "max_unsupported": max_unsupported, "leading_comma": leading_comma, "max_text_width": max_text_width, "comments": comments, } if unsupported_level is not None: kwargs["unsupported_level"] = unsupported_level return kwargs
class _HiveGenerator(HiveGenerator): def alter_sql(self, expression: exp.Alter) -> str: if isinstance(expression, exp.Alter) and expression.kind == "TABLE": if expression.actions and isinstance(expression.actions[0], exp.ColumnDef): new_actions = exp.Schema(expressions=expression.actions) expression.set("actions", [new_actions])
return super().alter_sql(expression)
class AthenaTrinoGenerator(TrinoGenerator): PROPERTIES_LOCATION = { **TrinoGenerator.PROPERTIES_LOCATION, exp.LocationProperty: exp.Properties.Location.POST_WITH, }
TRANSFORMS = { **TrinoGenerator.TRANSFORMS, exp.PartitionedByProperty: _partitioned_by_property_sql, exp.LocationProperty: _location_property_sql, }
class AthenaGenerator(AthenaTrinoGenerator): SELECT_KINDS: tuple[str, ...] = () SUPPORTS_DECODE_CASE = False
AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
__slots__ = ("_hive_generator", "_trino_generator")
def __init__( self, pretty: bool | int | None = None, identify: str | bool = False, normalize: bool = False, pad: int = 2, indent: int = 2, normalize_functions: str | bool | None = None, unsupported_level: t.Any = None, max_unsupported: int = 3, leading_comma: bool = False, max_text_width: int = 80, comments: bool = True, dialect: t.Any = None, hive: t.Any = None, trino: t.Any = None, ) -> None: import sqlglot.dialects.hive as hive_mod import sqlglot.dialects.trino as trino_mod
hive_dialect = hive or hive_mod.Hive() trino_dialect = trino or trino_mod.Trino()
kwargs = _generator_kwargs( pretty, identify, normalize, pad, indent, normalize_functions, unsupported_level, max_unsupported, leading_comma, max_text_width, comments, )
generator.Generator.__init__(self, dialect=dialect, **kwargs) self._hive_generator: generator.Generator = _HiveGenerator(dialect=hive_dialect, **kwargs) self._trino_generator: generator.Generator = AthenaTrinoGenerator( dialect=trino_dialect, **kwargs )
def generate(self, expression: exp.Expr, copy: bool = True) -> str: if _generate_as_hive(expression): return self._hive_generator.generate(expression, copy=copy)
return self._trino_generator.generate(expression, copy=copy)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881from __future__ import annotations
import loggingimport reimport typing as tfrom decimal import Decimalfrom fractions import Fraction
from sqlglot import exp, generator, transformsfrom sqlglot.dialects.dialect import ( arg_max_or_min_no_count, array_sort_order, date_add_interval_sql, datestrtodate_sql, filter_array_using_unnest, generate_series_sql, if_sql, inline_array_unless_query, max_or_greatest, min_or_least, no_filter_sql, no_ilike_sql, regexp_replace_sql, rename_func, sha256_sql, timestrtotime_sql, ts_or_ds_add_cast, unit_to_var, strposition_sql, groupconcat_sql, sha2_digest_sql,)from sqlglot.generator import unsupported_argsfrom sqlglot.helper import seq_get
logger = logging.getLogger("sqlglot")
JSON_EXTRACT_TYPE = t.Union[exp.JSONExtract, exp.JSONExtractScalar, exp.JSONExtractArray]
DQUOTES_ESCAPING_JSON_FUNCTIONS = ("JSON_QUERY", "JSON_VALUE", "JSON_QUERY_ARRAY")
def _derived_table_values_to_unnest(self: BigQueryGenerator, expression: exp.Values) -> str: if not expression.find_ancestor(exp.From, exp.Join): return self.values_sql(expression)
structs = [] alias = expression.args.get("alias") for tup in expression.find_all(exp.Tuple): field_aliases = ( alias.columns if alias and alias.columns else (f"_c{i}" for i in range(len(tup.expressions))) ) expressions = [ exp.PropertyEQ(this=exp.to_identifier(name), expression=fld) for name, fld in zip(field_aliases, tup.expressions) ] structs.append(exp.Struct(expressions=expressions))
# Due to `UNNEST_COLUMN_ONLY`, it is expected that the table alias be contained in the columns expression alias_name_only = exp.TableAlias(columns=[alias.this]) if alias else None return self.unnest_sql( exp.Unnest(expressions=[exp.array(*structs, copy=False)], alias=alias_name_only) )
def _returnsproperty_sql(self: BigQueryGenerator, expression: exp.ReturnsProperty) -> str: this = expression.this if isinstance(this, exp.Schema): this = f"{self.sql(this, 'this')} <{self.expressions(this)}>" else: this = self.sql(this) return f"RETURNS {this}"
def _create_sql(self: BigQueryGenerator, expression: exp.Create) -> str: returns = expression.find(exp.ReturnsProperty) if expression.kind == "FUNCTION" and returns and returns.args.get("is_table"): expression.set("kind", "TABLE FUNCTION")
if isinstance(expression.expression, (exp.Subquery, exp.Literal)): expression.set("expression", expression.expression.this)
return self.create_sql(expression)
# https://issuetracker.google.com/issues/162294746# workaround for bigquery bug when grouping by an expression and then ordering# WITH x AS (SELECT 1 y)# SELECT y + 1 z# FROM x# GROUP BY x + 1# ORDER by zdef _alias_ordered_group(expression: exp.Expr) -> exp.Expr: if isinstance(expression, exp.Select): group = expression.args.get("group") order = expression.args.get("order")
if group and order: aliases = { select.this: select.args["alias"] for select in expression.selects if isinstance(select, exp.Alias) }
for grouped in group.expressions: if grouped.is_int: continue alias = aliases.get(grouped) if alias: grouped.replace(exp.column(alias))
return expression
def _pushdown_cte_column_names(expression: exp.Expr) -> exp.Expr: """BigQuery doesn't allow column names when defining a CTE, so we try to push them down.""" if isinstance(expression, exp.CTE) and expression.alias_column_names: cte_query = expression.this
if cte_query.is_star: logger.warning( "Can't push down CTE column names for star queries. Run the query through" " the optimizer or use 'qualify' to expand the star projections first." ) return expression
column_names = expression.alias_column_names expression.args["alias"].set("columns", None)
for name, select in zip(column_names, cte_query.selects): to_replace = select
if isinstance(select, exp.Alias): select = select.this
# Inner aliases are shadowed by the CTE column names to_replace.replace(exp.alias_(select, name))
return expression
def _unnest_explode_generate_series(expression: exp.Expr) -> exp.Expr: """ Rewrites exploding GENERATE_SERIES projections into table references, e.g.
SELECT GENERATE_SERIES(1, 2) AS x -> SELECT x FROM GENERATE_SERIES(1, 2) AS x SELECT y, GENERATE_SERIES(1, 2) AS x FROM t -> SELECT y, x FROM t CROSS JOIN GENERATE_SERIES(1, 2) AS x
since BigQuery can't explode in the projection and must unnest it in the FROM clause instead. The resulting table reference is unnested downstream by `transforms.unnest_generate_series`. """ if isinstance(expression, exp.Select): for projection in expression.selects: if isinstance(series := projection.unalias(), exp.ExplodingGenerateSeries): column_name = projection.output_name or "_gen_series_value"
projection.replace(exp.column(column_name)) table = exp.Table( this=series, alias=exp.TableAlias(this=exp.to_identifier(column_name)) )
if expression.args.get("from_"): expression.join(table, copy=False, join_type="CROSS") else: expression.set("from_", exp.From(this=table))
return expression
def _array_contains_sql(self: BigQueryGenerator, expression: exp.ArrayContains) -> str: return self.sql( exp.Exists( this=exp.select("1") .from_(exp.Unnest(expressions=[expression.left]).as_("_unnest", table=["_col"])) .where(exp.column("_col").eq(expression.right)) ) )
def _widen_decimal(expression: exp.Expr) -> exp.Expr: # NUMERIC holds at most 29 integer and 9 fractional digits, e.g. DECIMAL(38, 0) needs BIGNUMERIC for node in expression.find_all(exp.DataType): if node.is_type(exp.DType.DECIMAL) and node.expressions: precision, *rest = (param.this for param in node.expressions) scale = rest[0] if rest else exp.Literal.number(0) if precision.is_int and scale.is_int: scale_digits = int(scale.name) if int(precision.name) - scale_digits > 29 or scale_digits > 9: node.set("this", exp.DType.BIGDECIMAL) return expression
def _extract_part(part: str) -> t.Callable[[BigQueryGenerator, exp.Func], str]: return lambda self, e: self.sql(exp.func("EXTRACT", exp.var(part), e.this, copy=False))
def _day_of_week_iso_sql(self: BigQueryGenerator, expression: exp.DayOfWeekIso) -> str: # DAYOFWEEK is Sunday=1..Saturday=7, ISO is Monday=1..Sunday=7 template: exp.Expr = exp.maybe_parse("(MOD(EXTRACT(DAYOFWEEK FROM :this) + 5, 7) + 1)") return self.sql(exp.replace_placeholders(template, this=expression.this))
def _array_agg_fold_sql( self: BigQueryGenerator, expression: exp.ArrayDistinct | exp.ArraySort) -> str: distinct = False ignore_nulls = False sort: exp.ArraySort | None = None agg: exp.Expr = expression while isinstance(agg, (exp.ArrayDistinct, exp.ArraySort)) and not agg.expression: if isinstance(agg, exp.ArrayDistinct): distinct = True ignore_nulls |= agg.args.get("check_null") is False elif sort is None: sort = agg agg = agg.this
order = array_sort_order(sort) if sort else None
# An ARRAY_AGG with its own ORDER BY or LIMIT can't take another if ( not isinstance(agg, exp.ArrayAgg) or isinstance(agg.this, (exp.Order, exp.Limit)) or (sort is not None and order is None) ): self.unsupported( f"{expression.sql_name()} is only supported on an ARRAY_AGG without ORDER BY or LIMIT and with a literal order" ) return self.func(expression.sql_name(), expression.this, expression.expression)
value = agg.this if isinstance(value, exp.Distinct): distinct, value = True, value.expressions[0]
folded: exp.Expr = exp.Distinct(expressions=[value]) if distinct else value if order is not None: asc, nulls_first = order keys = [exp.Ordered(this=value.copy(), desc=not asc or None, nulls_first=asc)]
# Aggregate ORDER BY only puts NULLs first when ascending, so other placements need a key if not ignore_nulls and nulls_first is not None and nulls_first != asc: if distinct: self.unsupported("ARRAY_AGG(DISTINCT) only puts NULLs first when ascending") else: is_null = value.copy().is_(exp.null()) keys.insert( 0, exp.Ordered( this=is_null, desc=nulls_first or None, nulls_first=not nulls_first ), ) folded = exp.Order(this=folded, expressions=keys) agg.set("this", folded) if ignore_nulls: # All-NULL input yields [], but an empty input still yields NULL. agg = exp.If( this=exp.Count(this=exp.Star()).eq(0), true=exp.null(), false=exp.func("COALESCE", exp.IgnoreNulls(this=agg), exp.array()), ) return self.sql(agg)
def _ts_or_ds_add_sql(self: BigQueryGenerator, expression: exp.TsOrDsAdd) -> str: return date_add_interval_sql("DATE", "ADD")(self, ts_or_ds_add_cast(expression))
def _ts_or_ds_diff_sql(self: BigQueryGenerator, expression: exp.TsOrDsDiff) -> str: expression.this.replace(exp.cast(expression.this, exp.DType.TIMESTAMP)) expression.expression.replace(exp.cast(expression.expression, exp.DType.TIMESTAMP)) unit = unit_to_var(expression) return self.func("DATE_DIFF", expression.this, expression.expression, unit)
def _unix_to_time_sql(self: BigQueryGenerator, expression: exp.UnixToTime) -> str: scale = expression.args.get("scale") timestamp = expression.this
if scale in (None, exp.UnixToTime.SECONDS): return self.func("TIMESTAMP_SECONDS", timestamp) if scale == exp.UnixToTime.MILLIS: return self.func("TIMESTAMP_MILLIS", timestamp) if scale == exp.UnixToTime.MICROS: return self.func("TIMESTAMP_MICROS", timestamp)
unix_seconds = exp.cast( exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)), exp.DType.BIGINT ) return self.func("TIMESTAMP_SECONDS", unix_seconds)
def _str_to_datetime_sql(self: BigQueryGenerator, expression: exp.StrToDate | exp.StrToTime) -> str: this = self.sql(expression, "this") dtype = "DATE" if isinstance(expression, exp.StrToDate) else "TIMESTAMP"
if expression.args.get("safe"): fmt = self.format_time( expression, self.dialect.INVERSE_FORMAT_MAPPING, self.dialect.INVERSE_FORMAT_TRIE, ) return f"SAFE_CAST({this} AS {dtype} FORMAT {fmt})"
fmt = self.format_time(expression) return self.func(f"PARSE_{dtype}", fmt, this, expression.args.get("zone"))
@unsupported_args("ins_cost", "del_cost", "sub_cost")def _levenshtein_sql(self: BigQueryGenerator, expression: exp.Levenshtein) -> str: max_dist = expression.args.get("max_dist") if max_dist: max_dist = exp.Kwarg(this=exp.var("max_distance"), expression=max_dist)
return self.func("EDIT_DISTANCE", expression.this, expression.expression, max_dist)
def _json_extract_sql(self: BigQueryGenerator, expression: JSON_EXTRACT_TYPE) -> str: upper = self.function_name(expression).upper()
dquote_escaping = upper in DQUOTES_ESCAPING_JSON_FUNCTIONS
if dquote_escaping: self._quote_json_path_key_using_brackets = False
sql = rename_func(upper)(self, expression)
if dquote_escaping: self._quote_json_path_key_using_brackets = True
return sql
class BigQueryGenerator(generator.Generator): TRY_SUPPORTED = False SUPPORTS_UESCAPE = False SUPPORTS_DECODE_CASE = False INTERVAL_ALLOWS_PLURAL_FORM = False JOIN_HINTS = False QUERY_HINTS = False TABLE_HINTS = False LIMIT_FETCH = "LIMIT" RENAME_TABLE_WITH_DB = False NVL2_SUPPORTED = False UNNEST_WITH_ORDINALITY = False CAST_TO_INT_ROUNDS = True COLLATE_IS_FUNC = True LIMIT_ONLY_LITERALS = True SUPPORTS_TABLE_ALIAS_COLUMNS = False SUPPORTS_NAMED_CTE_COLUMNS = False UNPIVOT_ALIASES_ARE_IDENTIFIERS = False JSON_KEY_VALUE_PAIR_SEP = "," NULL_ORDERING_SUPPORTED: bool | None = False IGNORE_NULLS_IN_FUNC = True JSON_PATH_SINGLE_QUOTE_ESCAPE = True CAN_IMPLEMENT_ARRAY_ANY = True SUPPORTS_TO_NUMBER = False NAMED_PLACEHOLDER_TOKEN = "@" HEX_FUNC = "TO_HEX" WITH_PROPERTIES_PREFIX = "OPTIONS" SUPPORTS_EXPLODING_PROJECTIONS = False EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False SUPPORTS_UNIX_SECONDS = True DECLARE_DEFAULT_ASSIGNMENT = "DEFAULT"
SAFE_JSON_PATH_KEY_RE = re.compile(r"^[\-\w]*$")
WINDOW_FUNCS_WITH_NULL_ORDERING = ( exp.CumeDist, exp.DenseRank, exp.FirstValue, exp.Lag, exp.LastValue, exp.Lead, exp.NthValue, exp.Ntile, exp.PercentRank, exp.Rank, exp.RowNumber, )
TS_OR_DS_TYPES: t.ClassVar = ( exp.TsOrDsToDatetime, exp.TsOrDsToTimestamp, exp.TsOrDsToTime, exp.TsOrDsToDate, )
TRANSFORMS = { **generator.Generator.TRANSFORMS, exp.AIEmbed: rename_func("EMBED"), exp.AIGenerate: rename_func("GENERATE"), exp.AISimilarity: rename_func("SIMILARITY"), exp.ApproxTopK: rename_func("APPROX_TOP_COUNT"), exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"), exp.ArgMax: arg_max_or_min_no_count("MAX_BY"), exp.ArgMin: arg_max_or_min_no_count("MIN_BY"), exp.Array: inline_array_unless_query, exp.ArrayContains: _array_contains_sql, exp.ArrayDistinct: _array_agg_fold_sql, exp.ArraySort: _array_agg_fold_sql, exp.ArrayFilter: filter_array_using_unnest, exp.ArrayRemove: filter_array_using_unnest, exp.BitwiseAndAgg: rename_func("BIT_AND"), exp.BitwiseOrAgg: rename_func("BIT_OR"), exp.BitwiseXorAgg: rename_func("BIT_XOR"), exp.BitwiseCount: rename_func("BIT_COUNT"), exp.ByteLength: rename_func("BYTE_LENGTH"), exp.Cast: transforms.preprocess( [_widen_decimal, transforms.remove_precision_parameterized_types] ), exp.CollateProperty: lambda self, e: ( f"DEFAULT COLLATE {self.sql(e, 'this')}" if e.args.get("default") else f"COLLATE {self.sql(e, 'this')}" ), exp.Commit: lambda *_: "COMMIT TRANSACTION", exp.CountIf: rename_func("COUNTIF"), exp.Create: _create_sql, exp.CTE: transforms.preprocess([_pushdown_cte_column_names]), exp.DateAdd: date_add_interval_sql("DATE", "ADD"), exp.DateDiff: lambda self, e: self.func("DATE_DIFF", e.this, e.expression, unit_to_var(e)), exp.DateFromParts: rename_func("DATE"), exp.DateStrToDate: datestrtodate_sql, exp.DateSub: date_add_interval_sql("DATE", "SUB"), exp.DatetimeAdd: date_add_interval_sql("DATETIME", "ADD"), exp.DatetimeSub: date_add_interval_sql("DATETIME", "SUB"), exp.DateFromUnixDate: rename_func("DATE_FROM_UNIX_DATE"), exp.Day: _extract_part("DAY"), exp.DayOfMonth: _extract_part("DAY"), exp.DayOfWeekIso: _day_of_week_iso_sql, exp.DayOfYear: _extract_part("DAYOFYEAR"), exp.Filter: no_filter_sql, exp.FromTimeZone: lambda self, e: self.func( "DATETIME", self.func("TIMESTAMP", e.this, e.args.get("zone")), "'UTC'" ), exp.GenerateSeries: generate_series_sql("GENERATE_ARRAY"), exp.GroupConcat: lambda self, e: groupconcat_sql( self, e, func_name="STRING_AGG", within_group=False, sep=None ), exp.Hex: lambda self, e: self.func("UPPER", self.func("TO_HEX", self.sql(e, "this"))), exp.HexString: lambda self, e: self.hexstring_sql(e, binary_function_repr="FROM_HEX"), exp.Hour: _extract_part("HOUR"), exp.If: if_sql(false_value="NULL"), exp.ILike: no_ilike_sql, exp.IntDiv: rename_func("DIV"), exp.Int64: rename_func("INT64"), exp.JSONBool: rename_func("BOOL"), exp.JSONExtract: _json_extract_sql, exp.JSONExtractArray: _json_extract_sql, exp.JSONExtractScalar: _json_extract_sql, exp.JSONFormat: lambda self, e: self.func( "TO_JSON" if e.args.get("to_json") else "TO_JSON_STRING", e.this, e.args.get("options"), ), exp.JSONKeysAtDepth: rename_func("JSON_KEYS"), exp.JSONValueArray: rename_func("JSON_VALUE_ARRAY"), exp.Levenshtein: _levenshtein_sql, exp.Max: max_or_greatest, exp.MD5: lambda self, e: self.func("TO_HEX", self.func("MD5", e.this)), exp.MD5Digest: rename_func("MD5"), exp.Min: min_or_least, exp.Month: _extract_part("MONTH"), exp.Normalize: lambda self, e: self.func( "NORMALIZE_AND_CASEFOLD" if e.args.get("is_casefold") else "NORMALIZE", e.this, e.args.get("form"), ), exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", exp.Quarter: _extract_part("QUARTER"), exp.RegexpExtract: lambda self, e: self.func( "REGEXP_EXTRACT", e.this, e.expression, e.args.get("position"), e.args.get("occurrence"), ), exp.RegexpExtractAll: lambda self, e: self.func("REGEXP_EXTRACT_ALL", e.this, e.expression), exp.RegexpReplace: regexp_replace_sql, exp.RegexpLike: rename_func("REGEXP_CONTAINS"), exp.ReturnsProperty: _returnsproperty_sql, exp.Rollback: lambda *_: "ROLLBACK TRANSACTION", exp.ParseTime: lambda self, e: self.func("PARSE_TIME", self.format_time(e), e.this), exp.ParseDatetime: lambda self, e: self.func("PARSE_DATETIME", self.format_time(e), e.this), exp.Select: transforms.preprocess( [ _unnest_explode_generate_series, transforms.explode_projection_to_unnest(), transforms.unqualify_unnest, transforms.eliminate_distinct_on, _alias_ordered_group, transforms.eliminate_semi_and_anti_joins, ] ), exp.SHA: rename_func("SHA1"), exp.SHA2: sha256_sql, exp.SHA1Digest: rename_func("SHA1"), exp.SHA2Digest: sha2_digest_sql, exp.StabilityProperty: lambda self, e: ( "DETERMINISTIC" if e.name == "IMMUTABLE" else "NOT DETERMINISTIC" ), exp.String: rename_func("STRING"), exp.StrPosition: lambda self, e: strposition_sql( self, e, func_name="INSTR", supports_position=True, supports_occurrence=True ), exp.StrToDate: _str_to_datetime_sql, exp.StrToTime: _str_to_datetime_sql, exp.SessionUser: lambda *_: "SESSION_USER()", exp.Table: transforms.preprocess([transforms.unnest_generate_series]), exp.TimeAdd: date_add_interval_sql("TIME", "ADD"), exp.TimeFromParts: rename_func("TIME"), exp.TimestampFromParts: rename_func("DATETIME"), exp.TimeSub: date_add_interval_sql("TIME", "SUB"), exp.TimestampAdd: date_add_interval_sql("TIMESTAMP", "ADD"), exp.TimestampDiff: rename_func("TIMESTAMP_DIFF"), exp.TimestampSub: date_add_interval_sql("TIMESTAMP", "SUB"), exp.TimeStrToTime: timestrtotime_sql, exp.Transaction: lambda *_: "BEGIN TRANSACTION", exp.TsOrDsAdd: _ts_or_ds_add_sql, exp.TsOrDsDiff: _ts_or_ds_diff_sql, exp.TsOrDsToTime: rename_func("TIME"), exp.TsOrDsToDatetime: rename_func("DATETIME"), exp.TsOrDsToTimestamp: rename_func("TIMESTAMP"), exp.Unhex: rename_func("FROM_HEX"), exp.UnixDate: rename_func("UNIX_DATE"), exp.UnixToTime: _unix_to_time_sql, exp.Uuid: lambda *_: "GENERATE_UUID()", exp.Values: _derived_table_values_to_unnest, exp.VariancePop: rename_func("VAR_POP"), exp.WeekOfYear: _extract_part("ISOWEEK"), exp.Year: _extract_part("YEAR"), exp.SafeDivide: rename_func("SAFE_DIVIDE"), }
SUPPORTED_JSON_PATH_PARTS = { exp.JSONPathKey, exp.JSONPathRoot, exp.JSONPathSubscript, }
TYPE_MAPPING = { **generator.Generator.TYPE_MAPPING, exp.DType.BIGDECIMAL: "BIGNUMERIC", exp.DType.BIGINT: "INT64", exp.DType.BINARY: "BYTES", exp.DType.BLOB: "BYTES", exp.DType.BOOLEAN: "BOOL", exp.DType.CHAR: "STRING", exp.DType.DECIMAL: "NUMERIC", exp.DType.DOUBLE: "FLOAT64", exp.DType.FLOAT: "FLOAT64", exp.DType.INT: "INT64", exp.DType.NCHAR: "STRING", exp.DType.NVARCHAR: "STRING", exp.DType.SMALLINT: "INT64", exp.DType.TEXT: "STRING", exp.DType.TIMESTAMP: "DATETIME", exp.DType.TIMESTAMPNTZ: "DATETIME", exp.DType.TIMESTAMPTZ: "TIMESTAMP", exp.DType.TIMESTAMPLTZ: "TIMESTAMP", exp.DType.TINYINT: "INT64", exp.DType.ROWVERSION: "BYTES", exp.DType.UUID: "STRING", exp.DType.VARBINARY: "BYTES", exp.DType.VARCHAR: "STRING", exp.DType.VARIANT: "ANY TYPE", }
PROPERTIES_LOCATION = { **generator.Generator.PROPERTIES_LOCATION, exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, }
# WINDOW comes after QUALIFY # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#window_clause # BigQuery requires QUALIFY before WINDOW AFTER_HAVING_MODIFIER_TRANSFORMS = { "qualify": generator.AFTER_HAVING_MODIFIER_TRANSFORMS["qualify"], "windows": generator.AFTER_HAVING_MODIFIER_TRANSFORMS["windows"], }
# from: https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#reserved_keywords RESERVED_KEYWORDS = { "all", "and", "any", "array", "as", "asc", "assert_rows_modified", "at", "between", "by", "case", "cast", "collate", "contains", "create", "cross", "cube", "current", "default", "define", "desc", "distinct", "else", "end", "enum", "escape", "except", "exclude", "exists", "extract", "false", "fetch", "following", "for", "from", "full", "group", "grouping", "groups", "hash", "having", "if", "ignore", "in", "inner", "intersect", "interval", "into", "is", "join", "lateral", "left", "like", "limit", "lookup", "merge", "natural", "new", "no", "not", "null", "nulls", "of", "on", "or", "order", "outer", "over", "partition", "preceding", "proto", "qualify", "range", "recursive", "respect", "right", "rollup", "rows", "select", "set", "some", "struct", "tablesample", "then", "to", "treat", "true", "unbounded", "union", "unnest", "using", "when", "where", "window", "with", "within", }
def frombase_sql(self, expression: exp.FromBase) -> str: # Hex is the only base BigQuery can cast from, and the sign goes before the prefix, e.g. -0xff if expression.expression.name != "16": self.unsupported("FROM_BASE is only supported for base 16") return self.function_fallback_sql(expression)
prefixed = exp.func( "REGEXP_REPLACE", expression.this, exp.Literal.string("^([+-]?)"), exp.Literal.string("\\10x"), copy=False, ) return self.sql(exp.cast(prefixed, exp.DType.BIGINT, copy=False))
def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: node: exp.Expr = expression while node.parent and not isinstance(node.parent, (exp.Window, exp.AggFunc, exp.Select)): node = node.parent if isinstance(node.parent, exp.Window) and node.arg_key == "this": self.unsupported("APPROX_QUANTILES does not support window functions") return self.function_fallback_sql(expression)
# The k/n quantile is APPROX_QUANTILES(x, n)[k], e.g. 0.95 -> n = 20, k = 19. n is at most # 100,000, so the quantile has at most 5 decimal places, and Decimal comparisons are exact quantile = expression.args["quantile"] weight = expression.args.get("weight") value = Decimal(quantile.to_py()) if quantile.is_number else None if ( value is None or not 0 <= value <= 1 or round(value, 5) != value or (weight and (not weight.is_number or weight.to_py() != 1)) ): self.unsupported("APPROX_QUANTILE needs a literal quantile and no weight") return self.function_fallback_sql(expression)
fraction = Fraction(value) quantiles = exp.func("APPROX_QUANTILES", expression.this, fraction.denominator, copy=False) return self.sql(quantiles[fraction.numerator])
def weekstart_sql(self, expression: exp.WeekStart) -> str: if expression.this.name.upper() == "SUNDAY": # BigQuery specific optimization since WEEK(SUNDAY) == WEEK return "WEEK"
return self.func("WEEK", expression.this)
def datetrunc_sql(self, expression: exp.DateTrunc) -> str: unit = expression.unit unit_sql = unit.name if unit.is_string else self.sql(unit) return self.func("DATE_TRUNC", expression.this, unit_sql, expression.args.get("zone"))
def mod_sql(self, expression: exp.Mod) -> str: this = expression.this expr = expression.expression return self.func( "MOD", this.unnest() if isinstance(this, exp.Paren) else this, expr.unnest() if isinstance(expr, exp.Paren) else expr, )
def column_parts(self, expression: exp.Column) -> str: if expression.meta_get("quoted_column"): # If a column reference is of the form `dataset.table`.name, we need # to preserve the quoted table path, otherwise the reference breaks table_parts = ".".join(p.name for p in expression.parts[:-1]) table_path = self.sql(exp.Identifier(this=table_parts, quoted=True)) return f"{table_path}.{self.sql(expression, 'this')}"
return super().column_parts(expression)
def table_parts(self, expression: exp.Table) -> str: # Depending on the context, `x.y` may not resolve to the same data source as `x`.`y`, so # we need to make sure the correct quoting is used in each case. # # For example, if there is a CTE x that clashes with a schema name, then the former will # return the table y in that schema, whereas the latter will return the CTE's y column: # # - WITH x AS (SELECT [1, 2] AS y) SELECT * FROM x, `x.y` -> cross join # - WITH x AS (SELECT [1, 2] AS y) SELECT * FROM x, `x`.`y` -> implicit unnest if expression.meta_get("quoted_table"): table_parts = ".".join(p.name for p in expression.parts) return self.sql(exp.Identifier(this=table_parts, quoted=True))
return super().table_parts(expression)
def timetostr_sql(self, expression: exp.TimeToStr) -> str: this = expression.this if isinstance(this, exp.TsOrDsToDatetime): func_name = "FORMAT_DATETIME" elif isinstance(this, exp.TsOrDsToTimestamp): func_name = "FORMAT_TIMESTAMP" elif isinstance(this, exp.TsOrDsToTime): func_name = "FORMAT_TIME" else: func_name = "FORMAT_DATE"
time_expr = this if isinstance(this, self.TS_OR_DS_TYPES) else expression return self.func( func_name, self.format_time(expression), time_expr.this, expression.args.get("zone") )
def eq_sql(self, expression: exp.EQ) -> str: # Operands of = cannot be NULL in BigQuery if isinstance(expression.left, exp.Null) or isinstance(expression.right, exp.Null): if not isinstance(expression.parent, exp.Update): return "NULL"
return self.binary(expression, "=")
def attimezone_sql(self, expression: exp.AtTimeZone) -> str: parent = expression.parent
# BigQuery allows CAST(.. AS {STRING|TIMESTAMP} [FORMAT <fmt> [AT TIME ZONE <tz>]]). # Only the TIMESTAMP one should use the below conversion, when AT TIME ZONE is included. if not isinstance(parent, exp.Cast) or not parent.to.is_type("text"): return self.func( "TIMESTAMP", self.func("DATETIME", expression.this, expression.args.get("zone")) )
return super().attimezone_sql(expression)
def trycast_sql(self, expression: exp.TryCast) -> str: return self.cast_sql(expression, safe_prefix="SAFE_")
def bracket_sql(self, expression: exp.Bracket) -> str: this = expression.this expressions = expression.expressions
if len(expressions) == 1 and this and this.is_type(exp.DType.STRUCT): arg = expressions[0] if arg.type is None: from sqlglot.optimizer.annotate_types import annotate_types
arg = annotate_types(arg, dialect=self.dialect)
if arg.type and arg.type.this in exp.DataType.TEXT_TYPES: # BQ doesn't support bracket syntax with string values for structs return f"{self.sql(this)}.{arg.name}"
expressions_sql = self.expressions(expression, flat=True) offset = expression.args.get("offset")
if offset == 0: expressions_sql = f"OFFSET({expressions_sql})" elif offset == 1: expressions_sql = f"ORDINAL({expressions_sql})" elif offset is not None: self.unsupported(f"Unsupported array offset: {offset}")
if expression.args.get("safe"): expressions_sql = f"SAFE_{expressions_sql}"
return f"{self.sql(this)}[{expressions_sql}]"
def in_unnest_op(self, expression: exp.Unnest) -> str: return self.sql(expression)
def version_sql(self, expression: exp.Version) -> str: if expression.name == "TIMESTAMP": expression.set("this", "SYSTEM_TIME") return super().version_sql(expression)
def contains_sql(self, expression: exp.Contains) -> str: this = expression.this expr = expression.expression
if isinstance(this, exp.Lower) and isinstance(expr, exp.Lower): this = this.this expr = expr.this
return self.func("CONTAINS_SUBSTR", this, expr, expression.args.get("json_scope"))
def parsejson_sql(self, expression: exp.ParseJSON) -> str: if expression.args.get("is_literal"): return f"JSON {self.sql(expression, 'this')}" return super().parsejson_sql(expression)
def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: this = expression.this
# This ensures that inline type-annotated ARRAY literals like ARRAY<INT64>[1, 2, 3] # are roundtripped unaffected. The inner check excludes ARRAY(SELECT ...) expressions, # because they aren't literals and so the above syntax is invalid BigQuery. if isinstance(this, exp.Array): elem = seq_get(this.expressions, 0) if not (elem and elem.find(exp.Query)): return f"{self.sql(expression, 'to')}{self.sql(this)}"
return super().cast_sql(expression, safe_prefix=safe_prefix)
def clusterproperty_sql(self, expression: exp.ClusterProperty) -> str: if expression.this: self.unsupported(f"Unsupported CLUSTER BY {self.sql(expression, 'this')}") return "" return self.op_expressions("CLUSTER BY", expression)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782from __future__ import annotations
import datetimeimport typing as t
from sqlglot import exp, generatorfrom sqlglot.dialects.dialect import ( arg_max_or_min_no_count, inline_array_sql, jarowinkler_similarity, json_extract_segments, json_path_key_only_name, length_or_char_length_sql, no_pivot_sql, rename_func, remove_from_array_using_filter, sha256_sql, strposition_sql, var_map_sql, weekstart_unit_to_str, unit_to_var, trim_sql, sha2_digest_sql,)from sqlglot.generator import unsupported_argsfrom sqlglot.helper import is_intfrom collections import defaultdict
DATETIME_DELTA = t.Union[exp.DateAdd, exp.DateDiff, exp.DateSub, exp.TimestampSub, exp.TimestampAdd]
def _unix_to_time_sql(self: ClickHouseGenerator, expression: exp.UnixToTime) -> str: scale = expression.args.get("scale") timestamp = expression.this
if scale in (None, exp.UnixToTime.SECONDS): return self.func("fromUnixTimestamp", exp.cast(timestamp, exp.DType.BIGINT)) if scale == exp.UnixToTime.MILLIS: return self.func("fromUnixTimestamp64Milli", exp.cast(timestamp, exp.DType.BIGINT)) if scale == exp.UnixToTime.MICROS: return self.func("fromUnixTimestamp64Micro", exp.cast(timestamp, exp.DType.BIGINT)) if scale == exp.UnixToTime.NANOS: return self.func("fromUnixTimestamp64Nano", exp.cast(timestamp, exp.DType.BIGINT))
return self.func( "fromUnixTimestamp", exp.cast(exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)), exp.DType.BIGINT), )
def _lower_func(sql: str) -> str: index = sql.index("(") return sql[:index].lower() + sql[index:]
def _quantile_sql(self: ClickHouseGenerator, expression: exp.Quantile) -> str: quantile = expression.args["quantile"] args = f"({self.sql(expression, 'this')})"
if isinstance(quantile, exp.Array): func = self.func("quantiles", *quantile) else: func = self.func("quantile", quantile)
return func + args
def _datetime_delta_sql(name: str) -> t.Callable[[generator.Generator, DATETIME_DELTA], str]: def _delta_sql(self: generator.Generator, expression: DATETIME_DELTA) -> str: if not expression.unit: return rename_func(name)(self, expression)
return self.func( name, unit_to_var(expression), expression.expression, expression.this, expression.args.get("zone"), )
return _delta_sql
def _timestrtotime_sql(self: ClickHouseGenerator, expression: exp.TimeStrToTime): ts = expression.this
tz = expression.args.get("zone") if tz and isinstance(ts, exp.Literal): # Clickhouse will not accept timestamps that include a UTC offset, so we must remove them. # The first step to removing is parsing the string with `datetime.datetime.fromisoformat`. # # In python <3.11, `fromisoformat()` can only parse timestamps of millisecond (3 digit) # or microsecond (6 digit) precision. It will error if passed any other number of fractional # digits, so we extract the fractional seconds and pad to 6 digits before parsing. ts_string = ts.name.strip()
# separate [date and time] from [fractional seconds and UTC offset] ts_parts = ts_string.split(".") if len(ts_parts) == 2: # separate fractional seconds and UTC offset offset_sep = "+" if "+" in ts_parts[1] else "-" ts_frac_parts = ts_parts[1].split(offset_sep) num_frac_parts = len(ts_frac_parts)
# pad to 6 digits if fractional seconds present ts_frac_parts[0] = ts_frac_parts[0].ljust(6, "0") ts_string = "".join( [ ts_parts[0], # date and time ".", ts_frac_parts[0], # fractional seconds offset_sep if num_frac_parts > 1 else "", ts_frac_parts[1] if num_frac_parts > 1 else "", # utc offset (if present) ] )
# return literal with no timezone, eg turn '2020-01-01 12:13:14-08:00' into '2020-01-01 12:13:14' # this is because Clickhouse encodes the timezone as a data type parameter and throws an error if # it's part of the timestamp string ts_without_tz = ( datetime.datetime.fromisoformat(ts_string).replace(tzinfo=None).isoformat(sep=" ") ) ts = exp.Literal.string(ts_without_tz)
# Non-nullable DateTime64 with microsecond precision expressions = [exp.DataTypeParam(this=tz)] if tz else [] datatype = exp.DType.DATETIME64.into_expr( expressions=[exp.DataTypeParam(this=exp.Literal.number(6)), *expressions], nullable=False, )
return self.sql(exp.cast(ts, datatype, dialect=self.dialect))
def _map_sql(self: ClickHouseGenerator, expression: exp.Map | exp.VarMap) -> str: if not (expression.parent and expression.parent.arg_key == "settings"): return _lower_func(var_map_sql(self, expression))
keys = expression.args.get("keys") values = expression.args.get("values")
if not isinstance(keys, exp.Array) or not isinstance(values, exp.Array): self.unsupported("Cannot convert array columns into map.") return ""
args = [] for key, value in zip(keys.expressions, values.expressions): args.append(f"{self.sql(key)}: {self.sql(value)}")
csv_args = ", ".join(args)
return f"{{{csv_args}}}"
def _json_cast_sql(self: ClickHouseGenerator, expression: exp.JSONCast) -> str: this = self.sql(expression, "this") to = expression.to to_sql = self.sql(to)
if to.expressions: to_sql = self.sql(exp.to_identifier(to_sql))
return f"{this}.:{to_sql}"
class ClickHouseGenerator(generator.Generator): BYTE_STRING_FUNCTION = "unhex" SELECT_KINDS: tuple[str, ...] = () TRY_SUPPORTED = False SUPPORTS_UESCAPE = False SUPPORTS_DECODE_CASE = False
AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
QUERY_HINTS = False STRUCT_DELIMITER = ("(", ")") NVL2_SUPPORTED = False ALTER_SET_TYPE = "TYPE" SUPPORTS_ALTER_COLUMN_IF_EXISTS = True TABLESAMPLE_REQUIRES_PARENS = False TABLESAMPLE_SIZE_IS_ROWS = False TABLESAMPLE_KEYWORDS = "SAMPLE" LAST_DAY_SUPPORTS_DATE_PART = False CAN_IMPLEMENT_ARRAY_ANY = True SUPPORTS_TO_NUMBER = False JOIN_HINTS = False TABLE_HINTS = False GROUPINGS_SEP = "" SET_OP_MODIFIERS = False SET_OP_LIMITS = True ARRAY_SIZE_NAME = "LENGTH" WRAP_DERIVED_VALUES = False AUTO_REFRESH_BARE_INTERVALS = True
STRING_TYPE_MAPPING: t.ClassVar = { exp.DType.BLOB: "String", exp.DType.CHAR: "String", exp.DType.LONGBLOB: "String", exp.DType.LONGTEXT: "String", exp.DType.MEDIUMBLOB: "String", exp.DType.MEDIUMTEXT: "String", exp.DType.TINYBLOB: "String", exp.DType.TINYTEXT: "String", exp.DType.TEXT: "String", exp.DType.VARBINARY: "String", exp.DType.VARCHAR: "String", }
SUPPORTED_JSON_PATH_PARTS = { exp.JSONPathKey, exp.JSONPathRoot, exp.JSONPathSubscript, }
TYPE_MAPPING = { **generator.Generator.TYPE_MAPPING, exp.DType.BLOB: "String", exp.DType.CHAR: "String", exp.DType.LONGBLOB: "String", exp.DType.LONGTEXT: "String", exp.DType.MEDIUMBLOB: "String", exp.DType.MEDIUMTEXT: "String", exp.DType.TINYBLOB: "String", exp.DType.TINYTEXT: "String", exp.DType.TEXT: "String", exp.DType.VARBINARY: "String", exp.DType.VARCHAR: "String", exp.DType.ARRAY: "Array", exp.DType.BOOLEAN: "Bool", exp.DType.BIGINT: "Int64", exp.DType.DATE32: "Date32", exp.DType.DATETIME: "DateTime", exp.DType.DATETIME2: "DateTime", exp.DType.SMALLDATETIME: "DateTime", exp.DType.DATETIME64: "DateTime64", exp.DType.DECIMAL: "Decimal", exp.DType.DECIMAL32: "Decimal32", exp.DType.DECIMAL64: "Decimal64", exp.DType.DECIMAL128: "Decimal128", exp.DType.DECIMAL256: "Decimal256", exp.DType.TIMESTAMP: "DateTime", exp.DType.TIMESTAMPNTZ: "DateTime", exp.DType.TIMESTAMPTZ: "DateTime", exp.DType.DOUBLE: "Float64", exp.DType.ENUM: "Enum", exp.DType.ENUM8: "Enum8", exp.DType.ENUM16: "Enum16", exp.DType.FIXEDSTRING: "FixedString", exp.DType.FLOAT: "Float32", exp.DType.INT: "Int32", exp.DType.MEDIUMINT: "Int32", exp.DType.INT128: "Int128", exp.DType.INT256: "Int256", exp.DType.LOWCARDINALITY: "LowCardinality", exp.DType.MAP: "Map", exp.DType.NESTED: "Nested", exp.DType.NOTHING: "Nothing", exp.DType.SMALLINT: "Int16", exp.DType.STRUCT: "Tuple", exp.DType.TINYINT: "Int8", exp.DType.UBIGINT: "UInt64", exp.DType.UINT: "UInt32", exp.DType.UINT128: "UInt128", exp.DType.UINT256: "UInt256", exp.DType.USMALLINT: "UInt16", exp.DType.UTINYINT: "UInt8", exp.DType.IPV4: "IPv4", exp.DType.IPV6: "IPv6", exp.DType.POINT: "Point", exp.DType.RING: "Ring", exp.DType.LINESTRING: "LineString", exp.DType.MULTILINESTRING: "MultiLineString", exp.DType.POLYGON: "Polygon", exp.DType.MULTIPOLYGON: "MultiPolygon", exp.DType.AGGREGATEFUNCTION: "AggregateFunction", exp.DType.SIMPLEAGGREGATEFUNCTION: "SimpleAggregateFunction", exp.DType.DYNAMIC: "Dynamic", }
TRANSFORMS = { **{k: v for k, v in generator.Generator.TRANSFORMS.items() if k != exp.AutoRefreshProperty}, exp.AnyValue: rename_func("any"), exp.ApproxDistinct: rename_func("uniq"), exp.ArrayDistinct: rename_func("arrayDistinct"), exp.ArrayConcat: rename_func("arrayConcat"), exp.ArrayContains: rename_func("has"), exp.ArrayFilter: lambda self, e: self.func("arrayFilter", e.expression, e.this), exp.Transform: lambda self, e: self.func("arrayMap", e.expression, e.this), exp.ArrayRemove: remove_from_array_using_filter, exp.ArrayReverse: rename_func("arrayReverse"), exp.ArraySlice: rename_func("arraySlice"), exp.ArraySum: rename_func("arraySum"), exp.ArrayMax: rename_func("arrayMax"), exp.ArrayMin: rename_func("arrayMin"), exp.ArgMax: arg_max_or_min_no_count("argMax"), exp.ArgMin: arg_max_or_min_no_count("argMin"), exp.Array: inline_array_sql, exp.BitwiseAndAgg: rename_func("groupBitAnd"), exp.BitwiseOrAgg: rename_func("groupBitOr"), exp.BitwiseXorAgg: rename_func("groupBitXor"), exp.CityHash64: rename_func("cityHash64"), exp.CastToStrType: rename_func("CAST"), exp.CurrentDatabase: rename_func("CURRENT_DATABASE"), exp.CurrentSchemas: rename_func("CURRENT_SCHEMAS"), exp.CountIf: rename_func("countIf"), exp.CosineDistance: rename_func("cosineDistance"), exp.CompressColumnConstraint: lambda self, e: ( f"CODEC({self.expressions(e, key='this', flat=True)})" ), exp.ComputedColumnConstraint: lambda self, e: ( f"{'MATERIALIZED' if e.args.get('persisted') else 'ALIAS'} {self.sql(e, 'this')}" ), exp.CurrentDate: lambda self, e: self.func("CURRENT_DATE"), exp.CurrentVersion: rename_func("VERSION"), exp.DateAdd: _datetime_delta_sql("DATE_ADD"), exp.DateDiff: _datetime_delta_sql("DATE_DIFF"), exp.DateStrToDate: rename_func("toDate"), exp.DateSub: _datetime_delta_sql("DATE_SUB"), exp.DayOfMonth: rename_func("toDayOfMonth"), exp.DayOfWeekIso: rename_func("toDayOfWeek"), exp.DayOfYear: rename_func("toDayOfYear"), exp.Explode: rename_func("arrayJoin"), exp.FarmFingerprint: rename_func("farmFingerprint64"), exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL", exp.IsInf: rename_func("isInfinite"), exp.IsNan: rename_func("isNaN"), exp.JarowinklerSimilarity: jarowinkler_similarity("jaroWinklerSimilarity"), exp.JSONCast: _json_cast_sql, exp.JSONExtract: json_extract_segments("JSONExtractRaw", quoted_index=False), exp.JSONExtractScalar: json_extract_segments("JSONExtractString", quoted_index=False), exp.JSONPathKey: json_path_key_only_name, exp.JSONPathRoot: lambda *_: "", exp.Length: length_or_char_length_sql, exp.Map: _map_sql, exp.Median: rename_func("median"), exp.Nullif: rename_func("nullIf"), exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", exp.Pivot: no_pivot_sql, exp.Quantile: _quantile_sql, exp.RegexpLike: lambda self, e: self.func("match", e.this, e.expression), exp.Rand: rename_func("randCanonical"), exp.StartsWith: rename_func("startsWith"), exp.Struct: rename_func("tuple"), exp.Trunc: rename_func("trunc"), exp.EndsWith: rename_func("endsWith"), exp.EuclideanDistance: rename_func("L2Distance"), exp.StrPosition: lambda self, e: strposition_sql( self, e, func_name="POSITION", supports_position=True, use_ansi_position=False, ), exp.TimeToStr: lambda self, e: self.func( "formatDateTime", e.this.this if isinstance(e.this, exp.TsOrDsToTimestamp) else e.this, self.format_time(e), e.args.get("zone"), ), exp.TimeStrToTime: _timestrtotime_sql, exp.TimestampAdd: _datetime_delta_sql("TIMESTAMP_ADD"), exp.TimestampSub: _datetime_delta_sql("TIMESTAMP_SUB"), exp.Typeof: rename_func("toTypeName"), exp.VarMap: _map_sql, exp.Xor: lambda self, e: self.func("xor", e.this, e.expression), exp.MD5Digest: rename_func("MD5"), exp.MD5: lambda self, e: self.func("LOWER", self.func("HEX", self.func("MD5", e.this))), exp.SHA: rename_func("SHA1"), exp.SHA1Digest: rename_func("SHA1"), exp.SHA2: sha256_sql, exp.SHA2Digest: sha2_digest_sql, exp.Split: lambda self, e: self.func( "splitByString", e.args.get("expression"), e.this, e.args.get("limit") ), exp.RegexpSplit: lambda self, e: self.func( "splitByRegexp", e.args.get("expression"), e.this, e.args.get("limit") ), exp.UnixToTime: _unix_to_time_sql, exp.Trim: lambda self, e: trim_sql(self, e, default_trim_type="BOTH"), exp.Variance: rename_func("varSamp"), exp.VariancePop: rename_func("varPop"), exp.WeekOfYear: rename_func("toISOWeek"), exp.YearOfWeekIso: rename_func("toISOYear"), exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), exp.Stddev: rename_func("stddevSamp"), exp.Chr: rename_func("CHAR"), exp.Lag: rename_func("lag"), exp.Lead: rename_func("lead"), exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")( rename_func("editDistance") ), exp.ParseDatetime: lambda self, e: self.func( "parseDateTime", e.this, e.args.get("format"), e.args.get("zone") ), }
PROPERTIES_LOCATION = { **generator.Generator.PROPERTIES_LOCATION, exp.AutoRefreshProperty: exp.Properties.Location.POST_NAME, exp.DefinerProperty: exp.Properties.Location.POST_SCHEMA, exp.OnCluster: exp.Properties.Location.POST_NAME, exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, exp.ToTableProperty: exp.Properties.Location.POST_NAME, exp.UuidProperty: exp.Properties.Location.POST_NAME, exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, }
# There's no list in docs, but it can be found in Clickhouse code # see `ClickHouse/src/Parsers/ParserCreate*.cpp` ON_CLUSTER_TARGETS: t.ClassVar = { "SCHEMA", # Transpiled CREATE SCHEMA may have OnCluster property set "DATABASE", "TABLE", "VIEW", "DICTIONARY", "INDEX", "FUNCTION", "NAMED COLLECTION", }
# https://clickhouse.com/docs/en/sql-reference/data-types/nullable NON_NULLABLE_TYPES: t.ClassVar = { exp.DType.ARRAY, exp.DType.MAP, exp.DType.STRUCT, exp.DType.POINT, exp.DType.RING, exp.DType.LINESTRING, exp.DType.MULTILINESTRING, exp.DType.POLYGON, exp.DType.MULTIPOLYGON, }
@unsupported_args("json_scope") def contains_sql(self, expression: exp.Contains) -> str: # ClickHouse has no CONTAINS; the comparison needs parentheses inside another operator result = exp.StrPosition(this=expression.this, substr=expression.expression) > 0 if isinstance(expression.parent, exp.Binary) and not isinstance( expression.parent, exp.Connector ): return self.sql(exp.paren(result, copy=False)) return self.sql(result)
def groupconcat_sql(self, expression: exp.GroupConcat) -> str: this = expression.this separator = expression.args.get("separator")
if isinstance(this, exp.Limit) and this.this: limit = this this = limit.this.pop() return self.sql( exp.ParameterizedAgg( this="groupConcat", params=[this], expressions=[separator, limit.expression], ) )
if separator: return self.sql( exp.ParameterizedAgg( this="groupConcat", params=[this], expressions=[separator], ) )
return self.func("groupConcat", this)
def select_sql(self, expression: exp.Select) -> str: limit = expression.args.get("limit") if isinstance(limit, exp.Fetch) and not expression.args.get("order"): count = limit.args.get("count") expression.set( "limit", exp.Limit(expression=count if count is not None else exp.Literal.number(1)) ) return super().select_sql(expression)
def offset_sql(self, expression: exp.Offset) -> str: offset = super().offset_sql(expression)
# OFFSET ... FETCH syntax requires a "ROW" or "ROWS" keyword # https://clickhouse.com/docs/sql-reference/statements/select/offset parent = expression.parent if isinstance(parent, exp.Select) and isinstance(parent.args.get("limit"), exp.Fetch): offset = f"{offset} ROWS"
return offset
def strtodate_sql(self, expression: exp.StrToDate) -> str: strtodate_sql = self.function_fallback_sql(expression)
if not isinstance(expression.parent, exp.Cast): # StrToDate returns DATEs in other dialects (eg. postgres), so # this branch aims to improve the transpilation to clickhouse return self.cast_sql(exp.cast(expression, "DATE"))
return strtodate_sql
def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: this = expression.this
if isinstance(this, exp.StrToDate) and expression.to == exp.DType.DATETIME.into_expr(): return self.sql(this)
this = this.unnest() if ( isinstance(this, exp.JSONExtract) and this.args.get("requires_json") and expression.to.is_type(*exp.DataType.TEXT_TYPES) ): return self.func("JSONExtract", this, exp.Literal.string("Nullable(String)"))
return super().cast_sql(expression, safe_prefix=safe_prefix)
def trycast_sql(self, expression: exp.TryCast) -> str: dtype = expression.to if not dtype.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True): # Casting x into Nullable(T) appears to behave similarly to TRY_CAST(x AS T) dtype.set("nullable", True)
return super().cast_sql(expression)
def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: this = self.json_path_part(expression.this) return str(int(this) + 1) if is_int(this) else this
def likeproperty_sql(self, expression: exp.LikeProperty) -> str: return f"AS {self.sql(expression, 'this')}"
def _any_to_has( self, expression: exp.EQ | exp.NEQ, default: t.Callable[[t.Any], str], prefix: str = "", ) -> str: if isinstance(expression.left, exp.Any): arr = expression.left this = expression.right elif isinstance(expression.right, exp.Any): arr = expression.right this = expression.left else: return default(expression)
return prefix + self.func("has", arr.this.unnest(), this)
def eq_sql(self, expression: exp.EQ) -> str: return self._any_to_has(expression, super().eq_sql)
def neq_sql(self, expression: exp.NEQ) -> str: return self._any_to_has(expression, super().neq_sql, "NOT ")
def regexpcount_sql(self, expression: exp.RegexpCount) -> str: this = expression.this pattern = expression.expression position = expression.args.get("position") parameters = expression.args.get("parameters")
if position: # SUBSTRING counts bytes in ClickHouse, the position counts characters this = self.func("substringUTF8", this, position)
if parameters: flags = parameters.name if parameters.is_string else "" if not parameters.is_string or set(flags) - set("cims"): self.unsupported("Only literal 'c', 'i', 'm' and 's' regexp flags are supported") # "c" (case-sensitive) is the default, and the last of "c" and "i" wins if flags.rfind("c") > flags.rfind("i"): flags = flags.replace("i", "") flags = "".join(f for f in flags if f in "ims") if flags: # countMatches has no flags argument, so they are embedded in the pattern pattern = self.func("CONCAT", exp.Literal.string(f"(?{flags})"), pattern)
return self.func("countMatches", this, pattern)
def regexpilike_sql(self, expression: exp.RegexpILike) -> str: # Manually add a flag to make the search case-insensitive regex = self.func("CONCAT", "'(?i)'", expression.expression) return self.func("match", expression.this, regex)
def datatype_sql(self, expression: exp.DataType) -> str: # String is the standard ClickHouse type, every other variant is just an alias. # Additionally, any supplied length parameter will be ignored. # # https://clickhouse.com/docs/en/sql-reference/data-types/string if expression.this in self.STRING_TYPE_MAPPING: dtype = "String" else: dtype = super().datatype_sql(expression)
# This section changes the type to `Nullable(...)` if the following conditions hold: # - It's marked as nullable - this ensures we won't wrap ClickHouse types with `Nullable` # and change their semantics # - It's not the key type of a `Map`. This is because ClickHouse enforces the following # constraint: "Type of Map key must be a type, that can be represented by integer or # String or FixedString (possibly LowCardinality) or UUID or IPv6" # - It's not a composite type, e.g. `Nullable(Array(...))` is not a valid type parent = expression.parent nullable = expression.args.get("nullable") if nullable is True or ( nullable is None and not ( isinstance(parent, exp.DataType) and parent.is_type(exp.DType.MAP, check_nullable=True) and expression.index in (None, 0) ) and not expression.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True) ): dtype = f"Nullable({dtype})"
return dtype
def cte_sql(self, expression: exp.CTE) -> str: if expression.args.get("scalar"): this = self.sql(expression, "this") alias = self.sql(expression, "alias") return f"{this} AS {alias}"
return super().cte_sql(expression)
def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: return super().after_limit_modifiers(expression) + [ ( self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True) if expression.args.get("settings") else "" ), ( self.seg("FORMAT ") + self.sql(expression, "format") if expression.args.get("format") else "" ), ]
def placeholder_sql(self, expression: exp.Placeholder) -> str: return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
def oncluster_sql(self, expression: exp.OnCluster) -> str: return f"ON CLUSTER {self.sql(expression, 'this')}"
def _refresh_interval_sql(self, expression: exp.Expr) -> str: if isinstance(expression, exp.Add): return f"{self._refresh_interval_sql(expression.this)} {self._refresh_interval_sql(expression.expression)}" return self.sql(expression.assert_is(exp.Interval))
def autorefreshproperty_sql(self, expression: exp.AutoRefreshProperty) -> str: cadence = self.sql(expression, "cadence") interval = expression.this schedule = ( f" {cadence} {self._refresh_interval_sql(interval)}" if cadence and interval else "" ) offset = expression.args.get("offset") offset = f" OFFSET {self._refresh_interval_sql(offset)}" if offset else "" randomize = expression.args.get("randomize") randomize = f" RANDOMIZE FOR {self._refresh_interval_sql(randomize)}" if randomize else "" dependencies = self.expressions(expression, flat=True) dependencies = f" DEPENDS ON {dependencies}" if dependencies else "" settings = self.sql(expression, "settings") settings = f" {settings}" if settings else "" append = " APPEND" if expression.args.get("append") else ""
return f"REFRESH{schedule}{offset}{randomize}{dependencies}{settings}{append}"
def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: if expression.kind in self.ON_CLUSTER_TARGETS and locations.get( exp.Properties.Location.POST_NAME ): this_name = self.sql( expression.this if isinstance(expression.this, exp.Schema) else expression, "this", ) this_properties = " ".join( [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]] ) this_schema = self.schema_columns_sql(expression.this) this_schema = f"{self.sep()}{this_schema}" if this_schema else ""
return f"{this_name}{self.sep()}{this_properties}{this_schema}"
return super().createable_sql(expression, locations)
def create_sql(self, expression: exp.Create) -> str: # The comment property comes last in CTAS statements, i.e. after the query query = expression.expression if isinstance(query, exp.Query): comment_prop = expression.find(exp.SchemaCommentProperty) if comment_prop: comment_prop.pop() if not isinstance(query, exp.Subquery): query.replace(exp.paren(query)) else: comment_prop = None
create_sql = super().create_sql(expression)
comment_sql = self.sql(comment_prop) comment_sql = f" {comment_sql}" if comment_sql else ""
return f"{create_sql}{comment_sql}"
def prewhere_sql(self, expression: exp.PreWhere) -> str: this = self.indent(self.sql(expression, "this")) return f"{self.seg('PREWHERE')}{self.sep()}{this}"
def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: this = self.sql(expression, "this") this = f" {this}" if this else "" expr = self.sql(expression, "expression") expr = f" {expr}" if expr else "" index_type = self.sql(expression, "index_type") index_type = f" TYPE {index_type}" if index_type else "" granularity = self.sql(expression, "granularity") granularity = f" GRANULARITY {granularity}" if granularity else ""
return f"INDEX{this}{expr}{index_type}{granularity}"
def partition_sql(self, expression: exp.Partition) -> str: return f"PARTITION {self.expressions(expression, flat=True)}"
def partitionid_sql(self, expression: exp.PartitionId) -> str: return f"ID {self.sql(expression.this)}"
def replacepartition_sql(self, expression: exp.ReplacePartition) -> str: return f"REPLACE {self.sql(expression.expression)} FROM {self.sql(expression, 'source')}"
def projectiondef_sql(self, expression: exp.ProjectionDef) -> str: return f"PROJECTION {self.sql(expression.this)} {self.wrap(expression.expression)}"
def nestedjsonselect_sql(self, expression: exp.NestedJSONSelect) -> str: return f"{self.sql(expression, 'this')}.^{self.sql(expression, 'expression')}"
def is_sql(self, expression: exp.Is) -> str: is_sql = super().is_sql(expression)
if isinstance(expression.parent, exp.Not): # value IS NOT NULL -> NOT (value IS NULL) is_sql = self.wrap(is_sql)
return is_sql
def in_sql(self, expression: exp.In) -> str: in_sql = super().in_sql(expression)
if isinstance(expression.parent, exp.Not) and expression.args.get("is_global"): in_sql = in_sql.replace("GLOBAL IN", "GLOBAL NOT IN", 1)
return in_sql
def not_sql(self, expression: exp.Not) -> str: if isinstance(expression.this, exp.In): if expression.this.args.get("is_global"): # let `GLOBAL IN` child interpose `NOT` return self.sql(expression, "this")
expression.set("this", exp.paren(expression.this, copy=False))
return super().not_sql(expression)
def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: # If the VALUES clause contains tuples of expressions, we need to treat it # as a table since Clickhouse will automatically alias it as such. alias = expression.args.get("alias")
if alias and alias.args.get("columns") and expression.expressions: values = expression.expressions[0].expressions values_as_table = any(isinstance(value, exp.Tuple) for value in values) else: values_as_table = True
return super().values_sql(expression, values_as_table=values_as_table)
def timestamptrunc_sql(self, expression: exp.DateTrunc | exp.TimestampTrunc) -> str: unit = weekstart_unit_to_str(self, expression) # https://clickhouse.com/docs/whats-new/changelog/2023#improvement if self.dialect.version < (23, 12) and unit and unit.is_string: unit = exp.Literal.string(unit.name.lower()) return self.func("dateTrunc", unit, expression.this, expression.args.get("zone"))
def datetrunc_sql(self, expression: exp.DateTrunc) -> str: return self.timestamptrunc_sql(expression)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127from __future__ import annotations
from sqlglot import exp, transformsfrom sqlglot.dialects.dialect import ( date_delta_sql, timestamptrunc_sql, groupconcat_sql,)from sqlglot.generators.spark import SparkGenerator
class DatabricksGenerator(SparkGenerator): TABLESAMPLE_SEED_KEYWORD = "REPEATABLE" COPY_PARAMS_ARE_WRAPPED = False COPY_PARAMS_EQ_REQUIRED = True JSON_PATH_SINGLE_QUOTE_ESCAPE = False JSON_PATH_KEY_QUOTED_FORCES_BRACKETS = True SAFE_JSON_PATH_KEY_RE = exp.SAFE_IDENTIFIER_RE QUOTE_JSON_PATH = False PARSE_JSON_NAME: str | None = "PARSE_JSON"
TRANSFORMS = { k: v for k, v in { **SparkGenerator.TRANSFORMS, exp.CurrentVersion: lambda *_: "CURRENT_VERSION()", exp.DateAdd: date_delta_sql("DATEADD"), exp.DateDiff: date_delta_sql("DATEDIFF"), exp.DatetimeAdd: lambda self, e: self.func( "TIMESTAMPADD", e.unit, e.expression, e.this ), exp.DatetimeSub: lambda self, e: self.func( "TIMESTAMPADD", e.unit, exp.Mul(this=e.expression, expression=exp.Literal.number(-1)), e.this, ), exp.DatetimeTrunc: timestamptrunc_sql(), exp.GroupConcat: groupconcat_sql, exp.Select: transforms.preprocess( [ transforms.eliminate_distinct_on, transforms.unnest_to_explode, transforms.any_to_exists, ] ), exp.JSONExtract: lambda self, e: f"{self.sql(e, 'this')}:{self.sql(e, 'expression')}", exp.JSONPathRoot: lambda self, e: ( "$" if isinstance(e.parent and e.parent.parent, exp.JSONExtractScalar) else "" ), exp.ToChar: lambda self, e: ( self.cast_sql(exp.Cast(this=e.this, to=exp.DataType(this="STRING"))) if e.args.get("is_numeric") else self.function_fallback_sql(e) ), exp.CurrentCatalog: lambda *_: "CURRENT_CATALOG()", exp.RegexpLike: None, exp.TryCast: None, exp.RegrAvgx: lambda self, e: self._regr_sql(e), exp.RegrSxx: lambda self, e: self._regr_sql(e), exp.RegrSyy: lambda self, e: self._regr_sql(e), }.items() if v is not None }
TYPE_MAPPING = { **SparkGenerator.TYPE_MAPPING, exp.DType.NULL: "VOID", }
def create_sql(self, expression: exp.Create) -> str: body = expression.expression if ( body and not isinstance(body, exp.Return) and expression.kind == "FUNCTION" and any(p.args.get("is_table") for p in expression.find_all(exp.ReturnsProperty)) ): expression.set("expression", exp.Return(this=body)) return super().create_sql(expression)
def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: constraint = expression.find(exp.GeneratedAsIdentityColumnConstraint) kind = expression.kind if ( constraint and isinstance(kind, exp.DataType) and kind.this in exp.DataType.INTEGER_TYPES ): # only BIGINT generated identity constraints are supported expression.set("kind", exp.DType.BIGINT.into_expr())
return super().columndef_sql(expression, sep)
def timeserieskey_sql(self, expression: exp.TimeseriesKey) -> str: return f"{self.sql(expression, 'this')} TIMESERIES"
def jsonpath_sql(self, expression: exp.JSONPath) -> str: path = super().jsonpath_sql(expression)
if isinstance(expression.parent, exp.JSONExtractScalar): path = self.escape_str(path) return f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
return path
def uniform_sql(self, expression: exp.Uniform) -> str: gen = expression.args.get("gen") seed = expression.args.get("seed")
# From Snowflake UNIFORM(min, max, gen) as RANDOM(), RANDOM(seed), or constant value -> Extract seed if gen: seed = gen.this
return self.func("UNIFORM", expression.this, expression.expression, seed)
def _regr_sql(self, expression: exp.RegrAvgx | exp.RegrSxx | exp.RegrSyy) -> str: name = expression.sql_name() x = expression.expression if isinstance(x, exp.Distinct): return self.func(name, exp.Distinct(expressions=[expression.this]), *x.expressions) return self.func(name, expression.this, x)
def clusterproperty_sql(self, expression): this = self.sql(expression, "this") or f"({self.expressions(expression, flat=True)})" return f"CLUSTER BY {this}"tasks/tasksmith-ff5cea929429/environment/source/sqlglot.pngAdded

Large File Pointer Details
- SHA256: 293ebd63d6e3564f945bd23fe6d5ad50034d5b85133831c1ba47b2dfa1c76f6e
- Pointer size: 129 Bytes
- Size of remote file: 7.36 kB
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/hive.pyAdded+139
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/materialize.pyAdded+18
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/mysql.pyAdded+175
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/oracle.pyAdded+120
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/postgres.pyAdded+160
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/presto.pyAdded+73
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/prql.pyAdded+32
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/redshift.pyAdded+67
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/risingwave.pyAdded+26
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/singlestore.pyAdded+64
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/snowflake.pyAdded+202
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/solr.pyAdded+20
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/spark.pyAdded+47
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/spark2.pyAdded+41
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/sqlite.pyAdded+46
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/starrocks.pyAdded+51
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/tableau.pyAdded+18
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/teradata.pyAdded+81
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/trino.pyAdded+26
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/tsql.pyAdded+196
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/diff.pyAdded+447
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/errors.pyAdded+176
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/__init__.pyAdded+90
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/context.pyAdded+112
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/env.pyAdded+335
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/python.pyAdded+557
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/table.pyAdded+157
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/__init__.pyAdded+54
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/aggregate.pyAdded+329
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/array.pyAdded+394
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/builders.pyAdded+1197
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/constraints.pyAdded+247
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/core.pyAdded+3138
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/datatypes.pyAdded+467
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/ddl.pyAdded+447
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/dml.pyAdded+528
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/functions.pyAdded+555
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/json.pyAdded+252
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/math.pyAdded+286
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/properties.pyAdded+673
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/query.pyAdded+2329
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/string.pyAdded+608
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/temporal.pyAdded+567
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generator.pyAdded
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/__init__.pyAdded
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/athena.pyAdded+184
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/bigquery.pyAdded+881
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/clickhouse.pyAdded+782
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/databricks.pyAdded+127