ybelkada HF Staff commited on
Commit
04a71cc
·
verified ·
1 Parent(s): 5844099

Harbor format: 871 coding_baseline tasks (part 59)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-ff5cea929429/environment/source/sqlglot.png +3 -0
  2. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/hive.py +139 -0
  3. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/materialize.py +18 -0
  4. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/mysql.py +175 -0
  5. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/oracle.py +120 -0
  6. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/postgres.py +160 -0
  7. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/presto.py +73 -0
  8. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/prql.py +32 -0
  9. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/redshift.py +67 -0
  10. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/risingwave.py +26 -0
  11. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/singlestore.py +64 -0
  12. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/snowflake.py +202 -0
  13. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/solr.py +20 -0
  14. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/spark.py +47 -0
  15. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/spark2.py +41 -0
  16. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/sqlite.py +46 -0
  17. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/starrocks.py +51 -0
  18. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/tableau.py +18 -0
  19. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/teradata.py +81 -0
  20. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/trino.py +26 -0
  21. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/tsql.py +196 -0
  22. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/diff.py +447 -0
  23. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/errors.py +176 -0
  24. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/__init__.py +90 -0
  25. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/context.py +112 -0
  26. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/env.py +335 -0
  27. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/python.py +557 -0
  28. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/table.py +157 -0
  29. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/__init__.py +54 -0
  30. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/aggregate.py +329 -0
  31. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/array.py +394 -0
  32. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/builders.py +1197 -0
  33. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/constraints.py +247 -0
  34. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/core.py +3138 -0
  35. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/datatypes.py +467 -0
  36. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/ddl.py +447 -0
  37. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/dml.py +528 -0
  38. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/functions.py +555 -0
  39. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/json.py +252 -0
  40. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/math.py +286 -0
  41. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/properties.py +673 -0
  42. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/query.py +2329 -0
  43. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/string.py +608 -0
  44. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/temporal.py +567 -0
  45. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generator.py +0 -0
  46. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/__init__.py +0 -0
  47. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/athena.py +184 -0
  48. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/bigquery.py +881 -0
  49. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/clickhouse.py +782 -0
  50. tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/databricks.py +127 -0
tasks/tasksmith-ff5cea929429/environment/source/sqlglot.png ADDED

Git LFS Details

  • SHA256: 293ebd63d6e3564f945bd23fe6d5ad50034d5b85133831c1ba47b2dfa1c76f6e
  • Pointer size: 129 Bytes
  • Size of remote file: 7.36 kB
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/hive.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from copy import deepcopy
4
+ from collections import defaultdict
5
+
6
+ from sqlglot import exp, jsonpath, tokens
7
+ from sqlglot.dialects.dialect import (
8
+ Dialect,
9
+ NormalizationStrategy,
10
+ )
11
+ from sqlglot.generators.hive import HiveGenerator
12
+ from sqlglot.parsers.hive import HiveParser
13
+ from sqlglot.tokens import TokenType
14
+ from sqlglot.optimizer.annotate_types import TypeAnnotator
15
+ from sqlglot.typing.hive import EXPRESSION_METADATA
16
+
17
+
18
+ class Hive(Dialect):
19
+ ALIAS_POST_TABLESAMPLE = True
20
+ IDENTIFIERS_CAN_START_WITH_DIGIT = True
21
+ SUPPORTS_USER_DEFINED_TYPES = False
22
+ SAFE_DIVISION = True
23
+ CONCAT_WS_COALESCE = True
24
+ ARRAY_AGG_INCLUDES_NULLS = None
25
+ REGEXP_EXTRACT_DEFAULT_GROUP = 1
26
+ ALTER_TABLE_SUPPORTS_CASCADE = True
27
+
28
+ # https://spark.apache.org/docs/latest/sql-ref-identifier.html#description
29
+ NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
30
+
31
+ EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
32
+
33
+ # https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362046#LanguageManualUDF-StringFunctions
34
+ # https://github.com/apache/hive/blob/master/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java#L266-L269
35
+ INITCAP_DEFAULT_DELIMITER_CHARS = " \t\n\r\f\u000b\u001c\u001d\u001e\u001f"
36
+
37
+ # Support only the non-ANSI mode (default for Hive, Spark2, Spark)
38
+ COERCES_TO = defaultdict(set, deepcopy(TypeAnnotator.COERCES_TO))
39
+ for target_type in {
40
+ *exp.DataType.NUMERIC_TYPES,
41
+ *exp.DataType.TEMPORAL_TYPES,
42
+ exp.DType.INTERVAL,
43
+ }:
44
+ COERCES_TO[target_type] |= exp.DataType.TEXT_TYPES
45
+
46
+ TIME_MAPPING = {
47
+ "y": "%Y",
48
+ "Y": "%Y",
49
+ "YYYY": "%Y",
50
+ "yyyy": "%Y",
51
+ "YY": "%y",
52
+ "yy": "%y",
53
+ "MMMM": "%B",
54
+ "MMM": "%b",
55
+ # Hive 4.0+ parses MM/dd/HH/hh/mm/ss strictly (java.time.DateTimeFormatter, see
56
+ # HIVE-25458/HIVE-25576)
57
+ "MM": "%mstrict",
58
+ "M": "%-m",
59
+ "dd": "%dstrict",
60
+ "d": "%-d",
61
+ "HH": "%Hstrict",
62
+ "H": "%-H",
63
+ "hh": "%Istrict",
64
+ "h": "%-I",
65
+ "mm": "%Mstrict",
66
+ "m": "%-M",
67
+ "ss": "%Sstrict",
68
+ "s": "%-S",
69
+ "SSSSSS": "%f",
70
+ "a": "%p",
71
+ "DD": "%j",
72
+ "D": "%-j",
73
+ "E": "%a",
74
+ "EE": "%a",
75
+ "EEE": "%a",
76
+ "EEEE": "%A",
77
+ "z": "%Z",
78
+ "Z": "%z",
79
+ }
80
+
81
+ DATE_FORMAT = "'yyyy-MM-dd'"
82
+ DATEINT_FORMAT = "'yyyyMMdd'"
83
+ TIME_FORMAT = "'yyyy-MM-dd HH:mm:ss'"
84
+
85
+ class JSONPathTokenizer(jsonpath.JSONPathTokenizer):
86
+ VAR_TOKENS = {
87
+ *jsonpath.JSONPathTokenizer.VAR_TOKENS,
88
+ TokenType.DASH,
89
+ }
90
+
91
+ UNESCAPED_SEQUENCES = {
92
+ "\\0": "\0",
93
+ "\\Z": "\x1a",
94
+ "\\%": "\\%",
95
+ "\\_": "\\_",
96
+ "\\a": "a",
97
+ "\\f": "f",
98
+ "\\v": "v",
99
+ }
100
+
101
+ class Tokenizer(tokens.Tokenizer):
102
+ NUMERIC_ESCAPES = {"u": (16, 4, 4, 0xFFFF), "0": (8, 3, 3, 0x7F)}
103
+ DROP_UNKNOWN_ESCAPES = True
104
+ LONE_SURROGATE_REPLACEMENT = "?"
105
+ QUOTES = ["'", '"']
106
+ IDENTIFIERS = ["`"]
107
+ STRING_ESCAPES = ["\\"]
108
+
109
+ SINGLE_TOKENS = {
110
+ **tokens.Tokenizer.SINGLE_TOKENS,
111
+ "$": TokenType.PARAMETER,
112
+ }
113
+
114
+ KEYWORDS = {
115
+ **tokens.Tokenizer.KEYWORDS,
116
+ "ADD ARCHIVE": TokenType.COMMAND,
117
+ "ADD ARCHIVES": TokenType.COMMAND,
118
+ "ADD FILE": TokenType.COMMAND,
119
+ "ADD FILES": TokenType.COMMAND,
120
+ "ADD JAR": TokenType.COMMAND,
121
+ "ADD JARS": TokenType.COMMAND,
122
+ "MINUS": TokenType.EXCEPT,
123
+ "MSCK REPAIR": TokenType.COMMAND,
124
+ "REFRESH": TokenType.REFRESH,
125
+ "SERDEPROPERTIES": TokenType.SERDE_PROPERTIES,
126
+ }
127
+
128
+ NUMERIC_LITERALS = {
129
+ "L": "BIGINT",
130
+ "S": "SMALLINT",
131
+ "Y": "TINYINT",
132
+ "D": "DOUBLE",
133
+ "F": "FLOAT",
134
+ "BD": "DECIMAL",
135
+ }
136
+
137
+ Parser = HiveParser
138
+
139
+ Generator = HiveGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/materialize.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot.dialects.postgres import Postgres
4
+ from sqlglot.generators.materialize import MaterializeGenerator
5
+ from sqlglot.parsers.materialize import MaterializeParser
6
+
7
+
8
+ class Materialize(Postgres):
9
+ NORMALIZE_NOT_NULL = True
10
+
11
+ UNESCAPED_SEQUENCES = {"\\a": "a", "\\v": "v"}
12
+
13
+ class Tokenizer(Postgres.Tokenizer):
14
+ NUMERIC_ESCAPES = {"u": (16, 4, 4, 0xFFFF), "U": (16, 8, 8, 0x10FFFF)}
15
+
16
+ Parser = MaterializeParser
17
+
18
+ Generator = MaterializeGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/mysql.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot import tokens
4
+ from sqlglot.dialects.dialect import (
5
+ Dialect,
6
+ NormalizationStrategy,
7
+ UsingColumnOrder,
8
+ )
9
+ from sqlglot.generators.mysql import MySQLGenerator
10
+ from sqlglot.parsers.mysql import MySQLParser
11
+ from sqlglot.tokens import TokenType
12
+ from sqlglot.typing.mysql import EXPRESSION_METADATA
13
+
14
+
15
+ class MySQL(Dialect):
16
+ PROMOTE_TO_INFERRED_DATETIME_TYPE = True
17
+ USING_COLUMN_ORDER = UsingColumnOrder.LEFT_TABLE
18
+
19
+ # https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
20
+ IDENTIFIERS_CAN_START_WITH_DIGIT = True
21
+
22
+ # We default to treating all identifiers as case-sensitive, since it matches MySQL's
23
+ # behavior on Linux systems. For MacOS and Windows systems, one can override this
24
+ # setting by specifying `dialect="mysql, normalization_strategy = lowercase"`.
25
+ #
26
+ # See also https://dev.mysql.com/doc/refman/8.2/en/identifier-case-sensitivity.html
27
+ NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_SENSITIVE
28
+
29
+ TIME_FORMAT = "'%Y-%m-%d %T'"
30
+ DPIPE_IS_STRING_CONCAT = False
31
+ CONCAT_WS_COALESCE = True
32
+ SUPPORTS_USER_DEFINED_TYPES = False
33
+ SAFE_DIVISION = True
34
+ SAFE_TO_ELIMINATE_DOUBLE_NEGATION = False
35
+ LEAST_GREATEST_IGNORES_NULLS = False
36
+
37
+ EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
38
+
39
+ # https://prestodb.io/docs/current/functions/datetime.html#mysql-date-functions
40
+ TIME_MAPPING = {
41
+ "%M": "%B",
42
+ "%c": "%-m",
43
+ "%e": "%-d",
44
+ "%h": "%I",
45
+ "%i": "%M",
46
+ "%s": "%S",
47
+ "%u": "%W",
48
+ "%k": "%-H",
49
+ "%l": "%-I",
50
+ "%r": "%I:%M:%S %p",
51
+ "%T": "%H:%M:%S",
52
+ "%W": "%A",
53
+ "%x": "%G",
54
+ # %v (ISO week) is unmapped due to collision with %V (roundtrip issue)
55
+ }
56
+
57
+ VALID_INTERVAL_UNITS = {
58
+ *Dialect.VALID_INTERVAL_UNITS,
59
+ "SECOND_MICROSECOND",
60
+ "MINUTE_MICROSECOND",
61
+ "MINUTE_SECOND",
62
+ "HOUR_MICROSECOND",
63
+ "HOUR_SECOND",
64
+ "HOUR_MINUTE",
65
+ "DAY_MICROSECOND",
66
+ "DAY_SECOND",
67
+ "DAY_MINUTE",
68
+ "DAY_HOUR",
69
+ "YEAR_MONTH",
70
+ }
71
+
72
+ UNESCAPED_SEQUENCES = {
73
+ "\\0": "\0",
74
+ "\\Z": "\x1a",
75
+ "\\%": "\\%",
76
+ "\\_": "\\_",
77
+ "\\a": "a",
78
+ "\\f": "f",
79
+ "\\v": "v",
80
+ }
81
+
82
+ class Tokenizer(tokens.Tokenizer):
83
+ QUOTES = ["'", '"']
84
+ COMMENTS = ["--", "#", ("/*", "*/")]
85
+ IDENTIFIERS = ["`"]
86
+ STRING_ESCAPES = ["'", '"', "\\"]
87
+ BIT_STRINGS = [("b'", "'"), ("B'", "'"), ("0b", "")]
88
+ HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", "")]
89
+ # https://dev.mysql.com/doc/refman/8.4/en/string-literals.html
90
+ DROP_UNKNOWN_ESCAPES = True
91
+
92
+ NESTED_COMMENTS = False
93
+ DASH_COMMENT_REQUIRES_BOUNDARY = True
94
+ COMMENTS_TERMINATE_AT_NEWLINE_ONLY = True
95
+
96
+ KEYWORDS = {
97
+ **tokens.Tokenizer.KEYWORDS,
98
+ "BLOB": TokenType.BLOB,
99
+ "CHARSET": TokenType.CHARACTER_SET,
100
+ "DISTINCTROW": TokenType.DISTINCT,
101
+ "EXPLAIN": TokenType.DESCRIBE,
102
+ "FORCE": TokenType.FORCE,
103
+ "IGNORE": TokenType.IGNORE,
104
+ "KEY": TokenType.KEY,
105
+ "LOCK TABLES": TokenType.COMMAND,
106
+ "LONGBLOB": TokenType.LONGBLOB,
107
+ "LONGTEXT": TokenType.LONGTEXT,
108
+ "MEDIUMBLOB": TokenType.MEDIUMBLOB,
109
+ "MEDIUMINT": TokenType.MEDIUMINT,
110
+ "MEDIUMTEXT": TokenType.MEDIUMTEXT,
111
+ "MEMBER OF": TokenType.MEMBER_OF,
112
+ "MOD": TokenType.MOD,
113
+ "SEPARATOR": TokenType.SEPARATOR,
114
+ "SERIAL": TokenType.SERIAL,
115
+ "SIGNED": TokenType.BIGINT,
116
+ "SIGNED INTEGER": TokenType.BIGINT,
117
+ "START": TokenType.BEGIN,
118
+ "TIMESTAMP": TokenType.TIMESTAMPTZ,
119
+ "TINYBLOB": TokenType.TINYBLOB,
120
+ "TINYTEXT": TokenType.TINYTEXT,
121
+ "UNLOCK TABLES": TokenType.COMMAND,
122
+ "UNSIGNED": TokenType.UBIGINT,
123
+ "UNSIGNED INTEGER": TokenType.UBIGINT,
124
+ "YEAR": TokenType.YEAR,
125
+ "_ARMSCII8": TokenType.INTRODUCER,
126
+ "_ASCII": TokenType.INTRODUCER,
127
+ "_BIG5": TokenType.INTRODUCER,
128
+ "_BINARY": TokenType.INTRODUCER,
129
+ "_CP1250": TokenType.INTRODUCER,
130
+ "_CP1251": TokenType.INTRODUCER,
131
+ "_CP1256": TokenType.INTRODUCER,
132
+ "_CP1257": TokenType.INTRODUCER,
133
+ "_CP850": TokenType.INTRODUCER,
134
+ "_CP852": TokenType.INTRODUCER,
135
+ "_CP866": TokenType.INTRODUCER,
136
+ "_CP932": TokenType.INTRODUCER,
137
+ "_DEC8": TokenType.INTRODUCER,
138
+ "_EUCJPMS": TokenType.INTRODUCER,
139
+ "_EUCKR": TokenType.INTRODUCER,
140
+ "_GB18030": TokenType.INTRODUCER,
141
+ "_GB2312": TokenType.INTRODUCER,
142
+ "_GBK": TokenType.INTRODUCER,
143
+ "_GEOSTD8": TokenType.INTRODUCER,
144
+ "_GREEK": TokenType.INTRODUCER,
145
+ "_HEBREW": TokenType.INTRODUCER,
146
+ "_HP8": TokenType.INTRODUCER,
147
+ "_KEYBCS2": TokenType.INTRODUCER,
148
+ "_KOI8R": TokenType.INTRODUCER,
149
+ "_KOI8U": TokenType.INTRODUCER,
150
+ "_LATIN1": TokenType.INTRODUCER,
151
+ "_LATIN2": TokenType.INTRODUCER,
152
+ "_LATIN5": TokenType.INTRODUCER,
153
+ "_LATIN7": TokenType.INTRODUCER,
154
+ "_MACCE": TokenType.INTRODUCER,
155
+ "_MACROMAN": TokenType.INTRODUCER,
156
+ "_SJIS": TokenType.INTRODUCER,
157
+ "_SWE7": TokenType.INTRODUCER,
158
+ "_TIS620": TokenType.INTRODUCER,
159
+ "_UCS2": TokenType.INTRODUCER,
160
+ "_UJIS": TokenType.INTRODUCER,
161
+ # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
162
+ "_UTF8": TokenType.INTRODUCER,
163
+ "_UTF16": TokenType.INTRODUCER,
164
+ "_UTF16LE": TokenType.INTRODUCER,
165
+ "_UTF32": TokenType.INTRODUCER,
166
+ "_UTF8MB3": TokenType.INTRODUCER,
167
+ "_UTF8MB4": TokenType.INTRODUCER,
168
+ "@@": TokenType.SESSION_PARAMETER,
169
+ }
170
+
171
+ COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.REPLACE} - {TokenType.SHOW}
172
+
173
+ Parser = MySQLParser
174
+
175
+ Generator = MySQLGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/oracle.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import string
4
+ import typing as t
5
+
6
+ from sqlglot import exp, tokens
7
+ from sqlglot.dialects.dialect import (
8
+ Dialect,
9
+ NormalizationStrategy,
10
+ )
11
+ from sqlglot.generators.oracle import OracleGenerator
12
+ from sqlglot.parsers.oracle import OracleParser
13
+ from sqlglot.tokens import TokenType
14
+
15
+
16
+ class Oracle(Dialect):
17
+ ALIAS_POST_TABLESAMPLE = True
18
+ LOCKING_READS_SUPPORTED = True
19
+ TABLESAMPLE_SIZE_IS_PERCENT = True
20
+ NULL_ORDERING = "nulls_are_large"
21
+ ON_CONDITION_EMPTY_BEFORE_ERROR = False
22
+ ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
23
+ DISABLES_ALIAS_REF_EXPANSION = True
24
+
25
+ # See section 8: https://docs.oracle.com/cd/A97630_01/server.920/a96540/sql_elements9a.htm
26
+ NORMALIZATION_STRATEGY = NormalizationStrategy.UPPERCASE
27
+
28
+ # https://docs.oracle.com/database/121/SQLRF/sql_elements004.htm#SQLRF00212
29
+ # https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
30
+ TIME_MAPPING = {
31
+ "D": "%u", # Day of week (1-7)
32
+ "DAY": "%A", # name of day
33
+ "DD": "%d", # day of month (1-31)
34
+ "DDD": "%j", # day of year (1-366)
35
+ "DY": "%a", # abbreviated name of day
36
+ "HH": "%I", # Hour of day (1-12)
37
+ "HH12": "%I", # alias for HH
38
+ "HH24": "%H", # Hour of day (0-23)
39
+ "IW": "%V", # Calendar week of year (1-52 or 1-53), as defined by the ISO 8601 standard
40
+ "IYYY": "%G", # 4-digit year of the ISO 8601 week-numbering calendar
41
+ "MI": "%M", # Minute (0-59)
42
+ "MM": "%m", # Month (01-12; January = 01)
43
+ "MON": "%b", # Abbreviated name of month
44
+ "MONTH": "%B", # Name of month
45
+ "SS": "%S", # Second (0-59)
46
+ "WW": "%W", # Week of year (1-53)
47
+ "YY": "%y", # 15
48
+ "YYYY": "%Y", # 2015
49
+ "FF6": "%f", # only 6 digits are supported in python formats
50
+ }
51
+
52
+ PSEUDOCOLUMNS = {"ROWNUM", "ROWID", "OBJECT_ID", "OBJECT_VALUE", "LEVEL"}
53
+
54
+ def can_quote(self, identifier: exp.Identifier, identify: str | bool = "safe") -> bool:
55
+ # Disable quoting for pseudocolumns as it may break queries e.g
56
+ # `WHERE "ROWNUM" = ...` does not work but `WHERE ROWNUM = ...` does
57
+ return (
58
+ identifier.quoted or not isinstance(identifier.parent, exp.Pseudocolumn)
59
+ ) and super().can_quote(identifier, identify=identify)
60
+
61
+ class Tokenizer(tokens.Tokenizer):
62
+ VAR_SINGLE_TOKENS = {"@", "$", "#"}
63
+
64
+ UNICODE_STRINGS = [
65
+ (prefix + q, q)
66
+ for q in t.cast(list[str], tokens.Tokenizer.QUOTES)
67
+ for prefix in ("U", "u")
68
+ ]
69
+
70
+ # https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Literals.html
71
+ # Alternative quoting, e.g. q'[it's]': the delimiters are part of the quote, so the
72
+ # text in between is taken as is, without escapes
73
+ RAW_STRINGS = [
74
+ (f"{prefix}'{start}", f"{end}'")
75
+ for prefix in ("q", "Q")
76
+ for start, end in (
77
+ ("[", "]"),
78
+ ("{", "}"),
79
+ ("(", ")"),
80
+ ("<", ">"),
81
+ *(
82
+ (c, c)
83
+ for c in string.ascii_letters + string.digits + string.punctuation
84
+ if c not in "[{(<"
85
+ ),
86
+ )
87
+ ]
88
+ NATIONAL_RAW_STRINGS = [
89
+ (prefix + start, end)
90
+ for start, end in t.cast(list[tuple[str, str]], RAW_STRINGS)
91
+ for prefix in ("n", "N")
92
+ ]
93
+ STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = False
94
+
95
+ NESTED_COMMENTS = False
96
+
97
+ KEYWORDS = {
98
+ **tokens.Tokenizer.KEYWORDS,
99
+ "(+)": TokenType.JOIN_MARKER,
100
+ # https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Comparison-Conditions.html
101
+ "^=": TokenType.NEQ,
102
+ "BINARY_DOUBLE": TokenType.DOUBLE,
103
+ "BINARY_FLOAT": TokenType.FLOAT,
104
+ "BULK COLLECT INTO": TokenType.BULK_COLLECT_INTO,
105
+ "COLUMNS": TokenType.COLUMN,
106
+ "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE,
107
+ "MINUS": TokenType.EXCEPT,
108
+ "NVARCHAR2": TokenType.NVARCHAR,
109
+ "ORDER SIBLINGS BY": TokenType.ORDER_SIBLINGS_BY,
110
+ "SAMPLE": TokenType.TABLE_SAMPLE,
111
+ "START": TokenType.BEGIN,
112
+ "SUBPARTITION": TokenType.PARTITION,
113
+ "TOP": TokenType.TOP,
114
+ "VARCHAR2": TokenType.VARCHAR,
115
+ "SYSTIMESTAMP": TokenType.SYSTIMESTAMP,
116
+ }
117
+
118
+ Parser = OracleParser
119
+
120
+ Generator = OracleGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/postgres.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot import exp, tokens
4
+ from sqlglot.dialects.dialect import Dialect
5
+ from sqlglot.generators.postgres import PostgresGenerator
6
+ from sqlglot.parsers.postgres import PostgresParser
7
+ from sqlglot.tokens import TokenType
8
+ from sqlglot.typing.postgres import EXPRESSION_METADATA
9
+
10
+
11
+ class Postgres(Dialect):
12
+ EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
13
+ INDEX_OFFSET = 1
14
+ ASCII_ONLY_NORMALIZATION = True
15
+ # Normalizing `x IS NOT NULL` to `NOT x IS NULL` is unsafe due to row values,
16
+ # e.g. `ROW(1, NULL) IS NOT NULL` is false whereas `NOT ROW(1, NULL) IS NULL` is true
17
+ NORMALIZE_NOT_NULL = False
18
+ TYPED_DIVISION = True
19
+ CONCAT_COALESCE = True
20
+ CONCAT_WS_COALESCE = True
21
+ NULL_ORDERING = "nulls_are_large"
22
+ SUPPORTS_LIMIT_ALL = True
23
+ TIME_FORMAT = "'YYYY-MM-DD HH24:MI:SS'"
24
+ TABLESAMPLE_SIZE_IS_PERCENT = True
25
+ TABLES_REFERENCEABLE_AS_COLUMNS = True
26
+
27
+ DEFAULT_FUNCTIONS_COLUMN_NAMES = {
28
+ exp.ExplodingGenerateSeries: "generate_series",
29
+ }
30
+
31
+ TIME_MAPPING = {
32
+ "d": "%u", # 1-based day of week
33
+ "D": "%u", # 1-based day of week
34
+ "dd": "%d", # day of month
35
+ "DD": "%d", # day of month
36
+ "ddd": "%j", # zero padded day of year
37
+ "DDD": "%j", # zero padded day of year
38
+ "FMDD": "%-d", # - is no leading zero for Python; same for FM in postgres
39
+ "FMDDD": "%-j", # day of year
40
+ "FMHH12": "%-I", # 9
41
+ "FMHH24": "%-H", # 9
42
+ "FMMI": "%-M", # Minute
43
+ "FMMM": "%-m", # 1
44
+ "FMSS": "%-S", # Second
45
+ "HH12": "%I", # 09
46
+ "HH24": "%H", # 09
47
+ "iw": "%V", # ISO 8601 week of year
48
+ "IW": "%V", # ISO 8601 week of year
49
+ "iyyy": "%G", # ISO 8601 week-numbering year
50
+ "IYYY": "%G", # ISO 8601 week-numbering year
51
+ "mi": "%M", # zero padded minute
52
+ "MI": "%M", # zero padded minute
53
+ "mm": "%m", # 01
54
+ "MM": "%m", # 01
55
+ "OF": "%z", # utc offset
56
+ "ss": "%S", # zero padded second
57
+ "SS": "%S", # zero padded second
58
+ "TMDay": "%A", # TM is locale dependent
59
+ "TMDy": "%a",
60
+ "TMMon": "%b", # Sep
61
+ "TMMonth": "%B", # September
62
+ "day": "%Aenlower", # tuesday
63
+ "dy": "%aenlower", # tue
64
+ "TZ": "%Z", # uppercase timezone name
65
+ "US": "%f", # zero padded microsecond
66
+ "ww": "%U", # 1-based week of year
67
+ "WW": "%U", # 1-based week of year
68
+ "yy": "%y", # 15
69
+ "YY": "%y", # 15
70
+ "yyy": "%Ythree", # 015
71
+ "YYY": "%Ythree", # 015
72
+ "yyyy": "%Y", # 2015
73
+ "YYYY": "%Y", # 2015
74
+ }
75
+
76
+ UNESCAPED_SEQUENCES = {"\\a": "a"}
77
+
78
+ class Tokenizer(tokens.Tokenizer):
79
+ NUMERIC_ESCAPES = {
80
+ "x": (16, 1, 2, 0xFF),
81
+ "u": (16, 4, 4, 0xFFFF),
82
+ "U": (16, 8, 8, 0x10FFFF),
83
+ "0": (8, 1, 3, 0o777),
84
+ }
85
+ NUMERIC_ESCAPES_ARE_BYTES = True
86
+ DROP_UNKNOWN_ESCAPES = True
87
+ BIT_STRINGS = [("b'", "'"), ("B'", "'")]
88
+ HEX_STRINGS = [("x'", "'"), ("X'", "'")]
89
+ BYTE_STRINGS = [("e'", "'"), ("E'", "'")]
90
+ UNICODE_STRINGS = [("U&'", "'"), ("u&'", "'")]
91
+ BYTE_STRING_ESCAPES = ["'", "\\"]
92
+ HEREDOC_STRINGS = ["$"]
93
+
94
+ HEREDOC_TAG_IS_IDENTIFIER = True
95
+ HEREDOC_STRING_ALTERNATIVE = TokenType.PARAMETER
96
+
97
+ COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.LOCK}
98
+
99
+ KEYWORDS = {
100
+ **tokens.Tokenizer.KEYWORDS,
101
+ "~": TokenType.RLIKE,
102
+ "@@": TokenType.DAT,
103
+ "@?": TokenType.AT_QMARK,
104
+ "@>": TokenType.AT_GT,
105
+ "<@": TokenType.LT_AT,
106
+ "?&": TokenType.QMARK_AMP,
107
+ "?|": TokenType.QMARK_PIPE,
108
+ "#-": TokenType.HASH_DASH,
109
+ "|/": TokenType.PIPE_SLASH,
110
+ "||/": TokenType.DPIPE_SLASH,
111
+ "^@": TokenType.CARET_AT,
112
+ "BEGIN": TokenType.BEGIN,
113
+ "BIGSERIAL": TokenType.BIGSERIAL,
114
+ "CSTRING": TokenType.PSEUDO_TYPE,
115
+ "DECLARE": TokenType.COMMAND,
116
+ "DO": TokenType.COMMAND,
117
+ "EXEC": TokenType.COMMAND,
118
+ "HSTORE": TokenType.HSTORE,
119
+ "INT8": TokenType.BIGINT,
120
+ "MONEY": TokenType.MONEY,
121
+ "NAME": TokenType.NAME,
122
+ "OID": TokenType.OBJECT_IDENTIFIER,
123
+ "ONLY": TokenType.ONLY,
124
+ "POINT": TokenType.POINT,
125
+ "REFRESH": TokenType.COMMAND,
126
+ "REINDEX": TokenType.COMMAND,
127
+ "RESET": TokenType.COMMAND,
128
+ "SERIAL": TokenType.SERIAL,
129
+ "SMALLSERIAL": TokenType.SMALLSERIAL,
130
+ "TEMP": TokenType.TEMPORARY,
131
+ "TYPE": TokenType.TYPE,
132
+ "REGCLASS": TokenType.OBJECT_IDENTIFIER,
133
+ "REGCOLLATION": TokenType.OBJECT_IDENTIFIER,
134
+ "REGCONFIG": TokenType.OBJECT_IDENTIFIER,
135
+ "REGDICTIONARY": TokenType.OBJECT_IDENTIFIER,
136
+ "REGNAMESPACE": TokenType.OBJECT_IDENTIFIER,
137
+ "REGOPER": TokenType.OBJECT_IDENTIFIER,
138
+ "REGOPERATOR": TokenType.OBJECT_IDENTIFIER,
139
+ "REGPROC": TokenType.OBJECT_IDENTIFIER,
140
+ "REGPROCEDURE": TokenType.OBJECT_IDENTIFIER,
141
+ "REGROLE": TokenType.OBJECT_IDENTIFIER,
142
+ "REGTYPE": TokenType.OBJECT_IDENTIFIER,
143
+ "FLOAT": TokenType.DOUBLE,
144
+ "XML": TokenType.XML,
145
+ "VARIADIC": TokenType.VARIADIC,
146
+ "INOUT": TokenType.INOUT,
147
+ }
148
+ KEYWORDS.pop("/*+")
149
+ KEYWORDS.pop("DIV")
150
+
151
+ SINGLE_TOKENS = {
152
+ **tokens.Tokenizer.SINGLE_TOKENS,
153
+ "$": TokenType.HEREDOC_STRING,
154
+ }
155
+
156
+ VAR_SINGLE_TOKENS = {"$"}
157
+
158
+ Parser = PostgresParser
159
+
160
+ Generator = PostgresGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/presto.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing as t
4
+
5
+ from sqlglot import tokens
6
+ from sqlglot.dialects.dialect import (
7
+ Dialect,
8
+ NormalizationStrategy,
9
+ )
10
+ from sqlglot.dialects.mysql import MySQL
11
+ from sqlglot.generators.presto import PrestoGenerator
12
+ from sqlglot.parsers.presto import PrestoParser
13
+ from sqlglot.tokens import TokenType
14
+ from sqlglot.typing.presto import EXPRESSION_METADATA
15
+
16
+
17
+ class Presto(Dialect):
18
+ INDEX_OFFSET = 1
19
+ NULL_ORDERING = "nulls_are_last"
20
+ TIME_FORMAT = MySQL.TIME_FORMAT
21
+ STRICT_STRING_CONCAT = True
22
+ TYPED_DIVISION = True
23
+ TABLESAMPLE_SIZE_IS_PERCENT = True
24
+ LOG_BASE_FIRST: bool | None = None
25
+ SUPPORTS_LIMIT_ALL = True
26
+ SUPPORTS_VALUES_DEFAULT = False
27
+ LEAST_GREATEST_IGNORES_NULLS = False
28
+ UUID_IS_STRING_TYPE = False
29
+
30
+ TIME_MAPPING = MySQL.TIME_MAPPING
31
+
32
+ # https://github.com/trinodb/trino/issues/17
33
+ # https://github.com/trinodb/trino/issues/12289
34
+ # https://github.com/prestodb/presto/issues/2863
35
+ NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
36
+
37
+ EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
38
+
39
+ SUPPORTED_SETTINGS = {
40
+ *Dialect.SUPPORTED_SETTINGS,
41
+ "variant_extract_is_json_extract",
42
+ }
43
+
44
+ class Tokenizer(tokens.Tokenizer):
45
+ HEX_STRINGS = [("x'", "'"), ("X'", "'")]
46
+ UNICODE_STRINGS = [
47
+ (prefix + q, q)
48
+ for q in t.cast(list[str], tokens.Tokenizer.QUOTES)
49
+ for prefix in ("U&", "u&")
50
+ ]
51
+
52
+ NESTED_COMMENTS = False
53
+
54
+ KEYWORDS = {
55
+ **tokens.Tokenizer.KEYWORDS,
56
+ "DEALLOCATE PREPARE": TokenType.COMMAND,
57
+ "DESCRIBE INPUT": TokenType.COMMAND,
58
+ "DESCRIBE OUTPUT": TokenType.COMMAND,
59
+ "RESET SESSION": TokenType.COMMAND,
60
+ "START": TokenType.BEGIN,
61
+ "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE,
62
+ "ROW": TokenType.STRUCT,
63
+ "IPADDRESS": TokenType.IPADDRESS,
64
+ "IPPREFIX": TokenType.IPPREFIX,
65
+ "TDIGEST": TokenType.TDIGEST,
66
+ "HYPERLOGLOG": TokenType.HLLSKETCH,
67
+ }
68
+ KEYWORDS.pop("/*+")
69
+ KEYWORDS.pop("QUALIFY")
70
+
71
+ Parser = PrestoParser
72
+
73
+ Generator = PrestoGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/prql.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot import tokens
4
+ from sqlglot.dialects.dialect import Dialect
5
+ from sqlglot.generators.prql import PRQLGenerator
6
+ from sqlglot.parsers.prql import PRQLParser
7
+ from sqlglot.tokens import TokenType
8
+
9
+
10
+ class PRQL(Dialect):
11
+ DPIPE_IS_STRING_CONCAT = False
12
+
13
+ Generator = PRQLGenerator
14
+
15
+ class Tokenizer(tokens.Tokenizer):
16
+ IDENTIFIERS = ["`"]
17
+ QUOTES = ["'", '"']
18
+
19
+ SINGLE_TOKENS = {
20
+ **tokens.Tokenizer.SINGLE_TOKENS,
21
+ "=": TokenType.ALIAS,
22
+ "'": TokenType.QUOTE,
23
+ '"': TokenType.QUOTE,
24
+ "`": TokenType.IDENTIFIER,
25
+ "#": TokenType.COMMENT,
26
+ }
27
+
28
+ KEYWORDS = {
29
+ **tokens.Tokenizer.KEYWORDS,
30
+ }
31
+
32
+ Parser = PRQLParser
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/redshift.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot.typing.redshift import EXPRESSION_METADATA
4
+ from sqlglot.dialects.dialect import NormalizationStrategy
5
+ from sqlglot.dialects.postgres import Postgres
6
+ from sqlglot.generators.redshift import RedshiftGenerator
7
+ from sqlglot.parsers.redshift import RedshiftParser
8
+ from sqlglot.tokens import TokenType
9
+
10
+
11
+ class Redshift(Postgres):
12
+ # https://docs.aws.amazon.com/redshift/latest/dg/r_names.html
13
+ NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
14
+
15
+ NORMALIZE_NOT_NULL = True
16
+
17
+ EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
18
+ SUPPORTS_USER_DEFINED_TYPES = False
19
+ INDEX_OFFSET = 0
20
+ COPY_PARAMS_ARE_CSV = False
21
+ HEX_LOWERCASE = True
22
+ HAS_DISTINCT_ARRAY_CONSTRUCTORS = True
23
+ COALESCE_COMPARISON_NON_STANDARD = True
24
+ REGEXP_EXTRACT_POSITION_OVERFLOW_RETURNS_NULL = False
25
+ ARRAY_FUNCS_PROPAGATES_NULLS = True
26
+
27
+ # ref: https://docs.aws.amazon.com/redshift/latest/dg/r_FORMAT_strings.html
28
+ TIME_FORMAT = "'YYYY-MM-DD HH24:MI:SS'"
29
+
30
+ TIME_MAPPING = {
31
+ **Postgres.TIME_MAPPING,
32
+ "MON": "%b",
33
+ "MONTH": "%B",
34
+ }
35
+
36
+ Parser = RedshiftParser
37
+
38
+ UNESCAPED_SEQUENCES = {"\\a": "a", "\\v": "v"}
39
+
40
+ class Tokenizer(Postgres.Tokenizer):
41
+ NUMERIC_ESCAPES = {"0": (8, 1, 3, 0o777)}
42
+ NUMERIC_ESCAPES_ARE_BYTES = True
43
+ DROP_UNKNOWN_ESCAPES = True
44
+ BIT_STRINGS = []
45
+ HEX_STRINGS = []
46
+ STRING_ESCAPES = ["\\", "'"]
47
+
48
+ KEYWORDS = {
49
+ **Postgres.Tokenizer.KEYWORDS,
50
+ "(+)": TokenType.JOIN_MARKER,
51
+ "BINARY VARYING": TokenType.VARBINARY,
52
+ "CURRENT_USER_ID": TokenType.CURRENT_USER_ID,
53
+ "HLLSKETCH": TokenType.HLLSKETCH,
54
+ "MINUS": TokenType.EXCEPT,
55
+ "SUPER": TokenType.SUPER,
56
+ "TOP": TokenType.TOP,
57
+ "UNLOAD": TokenType.COMMAND,
58
+ "USER": TokenType.CURRENT_USER,
59
+ "VARBYTE": TokenType.VARBINARY,
60
+ }
61
+ KEYWORDS.pop("VALUES")
62
+
63
+ # Redshift allows # to appear as a table identifier prefix
64
+ SINGLE_TOKENS = Postgres.Tokenizer.SINGLE_TOKENS.copy()
65
+ SINGLE_TOKENS.pop("#")
66
+
67
+ Generator = RedshiftGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/risingwave.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot.dialects.postgres import Postgres
4
+ from sqlglot.generators.risingwave import RisingWaveGenerator
5
+ from sqlglot.parsers.risingwave import RisingWaveParser
6
+ from sqlglot.tokens import TokenType
7
+
8
+
9
+ class RisingWave(Postgres):
10
+ NORMALIZE_NOT_NULL = True
11
+
12
+ REQUIRES_PARENTHESIZED_STRUCT_ACCESS = True
13
+ SUPPORTS_STRUCT_STAR_EXPANSION = True
14
+
15
+ UNESCAPED_SEQUENCES = {"\\a": "a", "\\v": "v"}
16
+
17
+ class Tokenizer(Postgres.Tokenizer):
18
+ KEYWORDS = {
19
+ **Postgres.Tokenizer.KEYWORDS,
20
+ "SINK": TokenType.SINK,
21
+ "SOURCE": TokenType.SOURCE,
22
+ }
23
+
24
+ Parser = RisingWaveParser
25
+
26
+ Generator = RisingWaveGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/singlestore.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlglot import TokenType
2
+ from sqlglot.dialects.mysql import MySQL
3
+ from sqlglot.generators.singlestore import SingleStoreGenerator
4
+ from sqlglot.parsers.singlestore import SingleStoreParser, cast_to_time6
5
+
6
+
7
+ class SingleStore(MySQL):
8
+ SUPPORTS_ORDER_BY_ALL = True
9
+
10
+ MYSQL_INVERSE_TIME_MAPPING = MySQL.INVERSE_TIME_MAPPING
11
+ MYSQL_INVERSE_TIME_TRIE = MySQL.INVERSE_TIME_TRIE
12
+ CAST_TO_TIME6 = staticmethod(cast_to_time6)
13
+
14
+ TIME_MAPPING: dict[str, str] = {
15
+ "D": "%u", # Day of week (1-7)
16
+ "DD": "%d", # day of month (01-31)
17
+ "DY": "%a", # abbreviated name of day
18
+ "HH": "%I", # Hour of day (01-12)
19
+ "HH12": "%I", # alias for HH
20
+ "HH24": "%H", # Hour of day (00-23)
21
+ "MI": "%M", # Minute (00-59)
22
+ "MM": "%m", # Month (01-12; January = 01)
23
+ "MON": "%b", # Abbreviated name of month
24
+ "MONTH": "%B", # Name of month
25
+ "SS": "%S", # Second (00-59)
26
+ "RR": "%y", # 15
27
+ "YY": "%y", # 15
28
+ "YYYY": "%Y", # 2015
29
+ "FF6": "%f", # only 6 digits are supported in python formats
30
+ }
31
+
32
+ VECTOR_TYPE_ALIASES = {
33
+ "I8": "TINYINT",
34
+ "I16": "SMALLINT",
35
+ "I32": "INT",
36
+ "I64": "BIGINT",
37
+ "F32": "FLOAT",
38
+ "F64": "DOUBLE",
39
+ }
40
+
41
+ INVERSE_VECTOR_TYPE_ALIASES = {v: k for k, v in VECTOR_TYPE_ALIASES.items()}
42
+
43
+ class Tokenizer(MySQL.Tokenizer):
44
+ BYTE_STRINGS = [("e'", "'"), ("E'", "'")]
45
+
46
+ KEYWORDS = {
47
+ **MySQL.Tokenizer.KEYWORDS,
48
+ "BSON": TokenType.JSONB,
49
+ "GEOGRAPHYPOINT": TokenType.GEOGRAPHYPOINT,
50
+ "TIMESTAMP": TokenType.TIMESTAMP,
51
+ "UTC_DATE": TokenType.UTC_DATE,
52
+ "UTC_TIME": TokenType.UTC_TIME,
53
+ "UTC_TIMESTAMP": TokenType.UTC_TIMESTAMP,
54
+ ":>": TokenType.COLON_GT,
55
+ "!:>": TokenType.NCOLON_GT,
56
+ "::$": TokenType.DCOLONDOLLAR,
57
+ "::%": TokenType.DCOLONPERCENT,
58
+ "::?": TokenType.DCOLONQMARK,
59
+ "RECORD": TokenType.STRUCT,
60
+ }
61
+
62
+ Parser = SingleStoreParser
63
+
64
+ Generator = SingleStoreGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/snowflake.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot import exp, jsonpath, tokens
4
+ from sqlglot.dialects.dialect import (
5
+ Dialect,
6
+ NormalizationStrategy,
7
+ )
8
+ from sqlglot.generators.snowflake import SnowflakeGenerator
9
+ from sqlglot.parsers.snowflake import (
10
+ SnowflakeParser,
11
+ )
12
+ from sqlglot.tokens import TokenType
13
+ from sqlglot.typing.snowflake import EXPRESSION_METADATA
14
+
15
+
16
+ class Snowflake(Dialect):
17
+ # https://docs.snowflake.com/en/sql-reference/identifiers-syntax
18
+ NORMALIZATION_STRATEGY = NormalizationStrategy.UPPERCASE
19
+ # https://docs.snowflake.com/en/sql-reference/data-types-text#escape-sequences
20
+ UNESCAPED_SEQUENCES = {"\\a": "a", "\\v": "v"}
21
+ NULL_ORDERING = "nulls_are_large"
22
+ TIME_FORMAT = "'YYYY-MM-DD HH24:MI:SS'"
23
+ SUPPORTS_USER_DEFINED_TYPES = False
24
+ PREFER_CTE_ALIAS_COLUMN = True
25
+ SUPPORTS_POSITIONAL_COLUMN_REFS = True
26
+ TABLESAMPLE_SIZE_IS_PERCENT = True
27
+ COPY_PARAMS_ARE_CSV = False
28
+ ARRAY_AGG_INCLUDES_NULLS = None
29
+ ARRAY_FUNCS_PROPAGATES_NULLS = True
30
+ ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
31
+ ALTER_TABLE_DROP_REQUIRED_FOR_EACH_COLUMN = False
32
+ TRY_CAST_REQUIRES_STRING = True
33
+ SUPPORTS_ALIAS_REFS_IN_JOIN_CONDITIONS = True
34
+ LEAST_GREATEST_IGNORES_NULLS = False
35
+ UUID_IS_STRING_TYPE = True
36
+ STAR_ILIKE_BACKSLASH_ESCAPE = True
37
+
38
+ # https://docs.snowflake.com/en/sql-reference/functions/split_to_table
39
+ DEFAULT_FUNCTIONS_COLUMN_NAMES = {
40
+ exp.SplitToTable: ("seq", "index", "value"),
41
+ }
42
+
43
+ EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
44
+
45
+ # https://docs.snowflake.com/en/en/sql-reference/functions/initcap
46
+ INITCAP_DEFAULT_DELIMITER_CHARS = ' \t\n\r\f\v!?@"^#$&~_,.:;+\\-*%/|\\[\\](){}<>'
47
+
48
+ INVERSE_TIME_MAPPING = {
49
+ "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'
50
+ }
51
+
52
+ TIME_MAPPING = {
53
+ "YYYY": "%Y",
54
+ "yyyy": "%Y",
55
+ "YY": "%y",
56
+ "yy": "%y",
57
+ "MMMM": "%B",
58
+ "mmmm": "%B",
59
+ "MON": "%b",
60
+ "mon": "%b",
61
+ "MM": "%m",
62
+ "mm": "%m",
63
+ "DD": "%d",
64
+ "dd": "%-d",
65
+ "DY": "%a",
66
+ "dy": "%w",
67
+ "HH24": "%H",
68
+ "hh24": "%H",
69
+ "HH12": "%I",
70
+ "hh12": "%I",
71
+ "MI": "%M",
72
+ "mi": "%M",
73
+ "SS": "%S",
74
+ "ss": "%S",
75
+ "FF": "%f_nine", # %f_ internal representation with precision specified
76
+ "ff": "%f_nine",
77
+ "FF0": "%f_zero",
78
+ "ff0": "%f_zero",
79
+ "FF1": "%f_one",
80
+ "ff1": "%f_one",
81
+ "FF2": "%f_two",
82
+ "ff2": "%f_two",
83
+ "FF3": "%f_three",
84
+ "ff3": "%f_three",
85
+ "FF4": "%f_four",
86
+ "ff4": "%f_four",
87
+ "FF5": "%f_five",
88
+ "ff5": "%f_five",
89
+ "FF6": "%f",
90
+ "ff6": "%f",
91
+ "FF7": "%f_seven",
92
+ "ff7": "%f_seven",
93
+ "FF8": "%f_eight",
94
+ "ff8": "%f_eight",
95
+ "FF9": "%f_nine",
96
+ "ff9": "%f_nine",
97
+ "TZHTZM": "%z",
98
+ "tzhtzm": "%z",
99
+ "TZH:TZM": "%:z", # internal representation for ±HH:MM
100
+ "tzh:tzm": "%:z",
101
+ "TZH": "%-z", # internal representation ±HH
102
+ "tzh": "%-z",
103
+ '"T"': "T", # remove the optional double quotes around the separator between the date and time
104
+ # Seems like Snowflake treats AM/PM in the format string as equivalent,
105
+ # only the time (stamp) value's AM/PM affects the output
106
+ "AM": "%p",
107
+ "am": "%p",
108
+ "PM": "%p",
109
+ "pm": "%p",
110
+ }
111
+
112
+ DATE_PART_MAPPING = {
113
+ **Dialect.DATE_PART_MAPPING,
114
+ "ISOWEEK": "WEEKISO",
115
+ # The base Dialect maps EPOCH_SECOND -> EPOCH, but we need to preserve
116
+ # EPOCH_SECOND as a distinct value for two reasons:
117
+ # 1. Type annotation: EPOCH_SECOND returns BIGINT, while EPOCH returns DOUBLE
118
+ # 2. Transpilation: DuckDB's EPOCH() returns float, so we cast EPOCH_SECOND
119
+ # to BIGINT to match Snowflake's integer behavior
120
+ # Without this override, EXTRACT(EPOCH_SECOND FROM ts) would be normalized
121
+ # to EXTRACT(EPOCH FROM ts) and lose the integer semantics.
122
+ "EPOCH_SECOND": "EPOCH_SECOND",
123
+ "EPOCH_SECONDS": "EPOCH_SECOND",
124
+ }
125
+
126
+ PSEUDOCOLUMNS = {"LEVEL"}
127
+
128
+ def can_quote(self, identifier: exp.Identifier, identify: str | bool = "safe") -> bool:
129
+ # This disables quoting DUAL in SELECT ... FROM DUAL, because Snowflake treats an
130
+ # unquoted DUAL keyword in a special way and does not map it to a user-defined table
131
+ return super().can_quote(identifier, identify) and not (
132
+ isinstance(identifier.parent, exp.Table)
133
+ and not identifier.quoted
134
+ and identifier.name.lower() == "dual"
135
+ )
136
+
137
+ class JSONPathTokenizer(jsonpath.JSONPathTokenizer):
138
+ SINGLE_TOKENS = jsonpath.JSONPathTokenizer.SINGLE_TOKENS.copy()
139
+ SINGLE_TOKENS.pop("$")
140
+
141
+ Parser = SnowflakeParser
142
+
143
+ class Tokenizer(tokens.Tokenizer):
144
+ STRING_ESCAPES = ["\\", "'"]
145
+ NUMERIC_ESCAPES = {"x": (16, 2, 2, 0xFF), "u": (16, 4, 4, 0xFFFF), "0": (8, 1, 3, 0xFF)}
146
+ DROP_UNKNOWN_ESCAPES = True
147
+ HEX_STRINGS = [("x'", "'"), ("X'", "'")]
148
+ RAW_STRINGS = ["$$"]
149
+ COMMENTS = ["--", "//", ("/*", "*/")]
150
+ NESTED_COMMENTS = False
151
+
152
+ KEYWORDS = {
153
+ **tokens.Tokenizer.KEYWORDS,
154
+ "(+)": TokenType.JOIN_MARKER,
155
+ "BYTEINT": TokenType.INT,
156
+ "FILE://": TokenType.URI_START,
157
+ "FILE FORMAT": TokenType.FILE_FORMAT,
158
+ "GET": TokenType.GET,
159
+ "INTEGRATION": TokenType.INTEGRATION,
160
+ "LS": TokenType.LIST,
161
+ "MATCH_CONDITION": TokenType.MATCH_CONDITION,
162
+ "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE,
163
+ "MINUS": TokenType.EXCEPT,
164
+ "NCHAR VARYING": TokenType.VARCHAR,
165
+ "PACKAGE": TokenType.PACKAGE,
166
+ "POLICY": TokenType.POLICY,
167
+ "POOL": TokenType.POOL,
168
+ "PUT": TokenType.PUT,
169
+ "UNDROP": TokenType.UNDROP,
170
+ "REMOVE": TokenType.COMMAND,
171
+ "RM": TokenType.COMMAND,
172
+ "ROLE": TokenType.ROLE,
173
+ "RULE": TokenType.RULE,
174
+ "SAMPLE": TokenType.TABLE_SAMPLE,
175
+ "SEMANTIC VIEW": TokenType.SEMANTIC_VIEW,
176
+ "SQL_DOUBLE": TokenType.DOUBLE,
177
+ "SQL_VARCHAR": TokenType.VARCHAR,
178
+ "STAGE": TokenType.STAGE,
179
+ "STORAGE INTEGRATION": TokenType.STORAGE_INTEGRATION,
180
+ "STREAMLIT": TokenType.STREAMLIT,
181
+ "TAG": TokenType.TAG,
182
+ "TIMESTAMP_TZ": TokenType.TIMESTAMPTZ,
183
+ "TOP": TokenType.TOP,
184
+ "VOLUME": TokenType.VOLUME,
185
+ "WAREHOUSE": TokenType.WAREHOUSE,
186
+ # https://docs.snowflake.com/en/sql-reference/data-types-numeric#float
187
+ # FLOAT is a synonym for DOUBLE in Snowflake
188
+ "FLOAT": TokenType.DOUBLE,
189
+ }
190
+ KEYWORDS.pop("/*+")
191
+
192
+ SINGLE_TOKENS = {
193
+ **tokens.Tokenizer.SINGLE_TOKENS,
194
+ "$": TokenType.PARAMETER,
195
+ "!": TokenType.EXCLAMATION,
196
+ }
197
+
198
+ VAR_SINGLE_TOKENS = {"$"}
199
+
200
+ COMMANDS = tokens.Tokenizer.COMMANDS - {TokenType.SHOW}
201
+
202
+ Generator = SnowflakeGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/solr.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlglot import tokens
2
+ from sqlglot.dialects.dialect import Dialect, NormalizationStrategy
3
+ from sqlglot.generators.solr import SolrGenerator
4
+ from sqlglot.parsers.solr import SolrParser
5
+
6
+
7
+ # https://solr.apache.org/guide/solr/latest/query-guide/sql-query.html
8
+
9
+
10
+ class Solr(Dialect):
11
+ NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
12
+ DPIPE_IS_STRING_CONCAT = False
13
+
14
+ Generator = SolrGenerator
15
+
16
+ Parser = SolrParser
17
+
18
+ class Tokenizer(tokens.Tokenizer):
19
+ QUOTES = ["'"]
20
+ IDENTIFIERS = ["`"]
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/spark.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing as t
4
+
5
+ from sqlglot.dialects.spark2 import Spark2
6
+ from sqlglot.generators.spark import SparkGenerator
7
+ from sqlglot.parsers.spark import SparkParser
8
+ from sqlglot.tokens import TokenType
9
+ from sqlglot.typing.spark import EXPRESSION_METADATA
10
+
11
+
12
+ class Spark(Spark2):
13
+ SUPPORTS_ORDER_BY_ALL = True
14
+ SUPPORTS_LIMIT_ALL = True
15
+ SUPPORTS_NULL_TYPE = True
16
+ ARRAY_FUNCS_PROPAGATES_NULLS = True
17
+ EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
18
+
19
+ # Spark 3+ parses MM/dd/HH/hh/mm/ss strictly, unlike Spark 2 (SimpleDateFormat)
20
+ TIME_MAPPING = {
21
+ **Spark2.TIME_MAPPING,
22
+ "MM": "%mstrict",
23
+ "dd": "%dstrict",
24
+ "HH": "%Hstrict",
25
+ "hh": "%Istrict",
26
+ "mm": "%Mstrict",
27
+ "ss": "%Sstrict",
28
+ }
29
+
30
+ class Tokenizer(Spark2.Tokenizer):
31
+ NUMERIC_ESCAPES = {"u": (16, 4, 4, 0xFFFF), "U": (16, 8, 8, 0x10FFFF), "0": (8, 3, 3, 0x7F)}
32
+ STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = False
33
+
34
+ RAW_STRINGS = [
35
+ (prefix + q, q)
36
+ for q in t.cast(list[str], Spark2.Tokenizer.QUOTES)
37
+ for prefix in ("r", "R")
38
+ ]
39
+
40
+ KEYWORDS = {
41
+ **Spark2.Tokenizer.KEYWORDS,
42
+ "DECLARE": TokenType.DECLARE,
43
+ }
44
+
45
+ Parser = SparkParser
46
+
47
+ Generator = SparkGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/spark2.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot.dialects.hive import Hive
4
+ from sqlglot.generators.spark2 import Spark2Generator
5
+ from sqlglot.parsers.spark2 import Spark2Parser
6
+ from sqlglot.tokens import TokenType
7
+ from sqlglot.typing.spark2 import EXPRESSION_METADATA
8
+
9
+
10
+ class Spark2(Hive):
11
+ ALTER_TABLE_SUPPORTS_CASCADE = False
12
+
13
+ EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
14
+
15
+ # Spark 2.x parses MM/dd/HH/hh/mm/ss leniently (SimpleDateFormat), unlike strict Hive/Spark 3+
16
+ TIME_MAPPING = {
17
+ **Hive.TIME_MAPPING,
18
+ "MM": "%m",
19
+ "dd": "%d",
20
+ "HH": "%H",
21
+ "hh": "%I",
22
+ "mm": "%M",
23
+ "ss": "%S",
24
+ }
25
+
26
+ # https://spark.apache.org/docs/latest/api/sql/index.html#initcap
27
+ # https://docs.databricks.com/aws/en/sql/language-manual/functions/initcap
28
+ # https://github.com/apache/spark/blob/master/common/unsafe/src/main/java/org/apache/spark/unsafe/types/UTF8String.java#L859-L905
29
+ INITCAP_DEFAULT_DELIMITER_CHARS = " "
30
+
31
+ class Tokenizer(Hive.Tokenizer):
32
+ HEX_STRINGS = [("X'", "'"), ("x'", "'")]
33
+
34
+ KEYWORDS = {
35
+ **Hive.Tokenizer.KEYWORDS,
36
+ "TIMESTAMP": TokenType.TIMESTAMPTZ,
37
+ }
38
+
39
+ Parser = Spark2Parser
40
+
41
+ Generator = Spark2Generator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/sqlite.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot import tokens
4
+ from sqlglot.dialects.dialect import (
5
+ Dialect,
6
+ NormalizationStrategy,
7
+ UsingColumnOrder,
8
+ )
9
+ from sqlglot.generators.sqlite import SQLiteGenerator
10
+ from sqlglot.parsers.sqlite import SQLiteParser
11
+ from sqlglot.tokens import TokenType
12
+
13
+
14
+ class SQLite(Dialect):
15
+ # https://sqlite.org/forum/forumpost/5e575586ac5c711b?raw
16
+ NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
17
+ ASCII_ONLY_NORMALIZATION = True
18
+ TYPED_DIVISION = True
19
+ SAFE_DIVISION = True
20
+ SAFE_TO_ELIMINATE_DOUBLE_NEGATION = False
21
+ USING_COLUMN_ORDER = UsingColumnOrder.IN_PLACE
22
+ CONCAT_COALESCE = True
23
+ CONCAT_WS_COALESCE = True
24
+
25
+ class Tokenizer(tokens.Tokenizer):
26
+ IDENTIFIERS = ['"', ("[", "]"), "`"]
27
+ HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", ""), ("0X", "")]
28
+
29
+ NESTED_COMMENTS = False
30
+ COMMENTS_TERMINATE_AT_NEWLINE_ONLY = True
31
+
32
+ KEYWORDS = {
33
+ **tokens.Tokenizer.KEYWORDS,
34
+ "ATTACH": TokenType.ATTACH,
35
+ "DETACH": TokenType.DETACH,
36
+ "INDEXED BY": TokenType.INDEXED_BY,
37
+ "MATCH": TokenType.MATCH,
38
+ }
39
+
40
+ KEYWORDS.pop("/*+")
41
+
42
+ COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.REPLACE}
43
+
44
+ Parser = SQLiteParser
45
+
46
+ Generator = SQLiteGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/starrocks.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot import exp
4
+ from sqlglot.dialects.dialect import UsingColumnOrder
5
+ from sqlglot.dialects.mysql import MySQL
6
+ from sqlglot.generators.starrocks import StarRocksGenerator
7
+ from sqlglot.parsers.starrocks import StarRocksParser
8
+ from sqlglot.tokens import TokenType
9
+
10
+
11
+ class StarRocks(MySQL):
12
+ STRICT_JSON_PATH_SYNTAX = False
13
+ INDEX_OFFSET = 1
14
+ USING_COLUMN_ORDER = UsingColumnOrder.USING_LIST
15
+
16
+ DEFAULT_FUNCTIONS_COLUMN_NAMES = {
17
+ exp.GenerateSeries: "generate_series",
18
+ }
19
+
20
+ class Tokenizer(MySQL.Tokenizer):
21
+ # Unlike MySQL, "#" doesn't start a comment
22
+ COMMENTS = ["--", ("/*", "*/")]
23
+ DASH_COMMENT_REQUIRES_BOUNDARY = False
24
+ COMMENTS_TERMINATE_AT_NEWLINE_ONLY = False
25
+
26
+ KEYWORDS = {
27
+ **MySQL.Tokenizer.KEYWORDS,
28
+ "ADMIN": TokenType.COMMAND,
29
+ "BACKUP": TokenType.COMMAND,
30
+ "CANCEL": TokenType.COMMAND,
31
+ "DEALLOCATE": TokenType.COMMAND,
32
+ "EXPORT": TokenType.COMMAND,
33
+ "HLL": TokenType.HLLSKETCH,
34
+ "INSTALL": TokenType.COMMAND,
35
+ "LARGEINT": TokenType.INT128,
36
+ "PAUSE": TokenType.COMMAND,
37
+ "RECOVER": TokenType.COMMAND,
38
+ "REFRESH": TokenType.REFRESH,
39
+ "RESTORE": TokenType.COMMAND,
40
+ "RESUME": TokenType.COMMAND,
41
+ "STOP": TokenType.COMMAND,
42
+ "SUBMIT": TokenType.COMMAND,
43
+ "UNINSTALL": TokenType.COMMAND,
44
+ }
45
+ KEYWORDS.pop("IGNORE")
46
+ KEYWORDS.pop("#>")
47
+ KEYWORDS.pop("#>>")
48
+
49
+ Parser = StarRocksParser
50
+
51
+ Generator = StarRocksGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/tableau.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot import tokens
4
+ from sqlglot.dialects.dialect import Dialect
5
+ from sqlglot.generators.tableau import TableauGenerator
6
+ from sqlglot.parsers.tableau import TableauParser
7
+
8
+
9
+ class Tableau(Dialect):
10
+ LOG_BASE_FIRST = False
11
+
12
+ class Tokenizer(tokens.Tokenizer):
13
+ IDENTIFIERS = [("[", "]")]
14
+ QUOTES = ["'", '"']
15
+
16
+ Generator = TableauGenerator
17
+
18
+ Parser = TableauParser
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/teradata.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot import tokens
4
+ from sqlglot.dialects.dialect import Dialect
5
+ from sqlglot.generators.teradata import TeradataGenerator
6
+ from sqlglot.parsers.teradata import TeradataParser
7
+ from sqlglot.tokens import TokenType
8
+
9
+
10
+ class Teradata(Dialect):
11
+ TYPED_DIVISION = True
12
+
13
+ TIME_MAPPING = {
14
+ "YY": "%y",
15
+ "Y4": "%Y",
16
+ "YYYY": "%Y",
17
+ "M4": "%B",
18
+ "M3": "%b",
19
+ "M": "%-M",
20
+ "MI": "%M",
21
+ "MM": "%m",
22
+ "MMM": "%b",
23
+ "MMMM": "%B",
24
+ "D": "%-d",
25
+ "DD": "%d",
26
+ "D3": "%j",
27
+ "DDD": "%j",
28
+ "H": "%-H",
29
+ "HH": "%H",
30
+ "HH24": "%H",
31
+ "S": "%-S",
32
+ "SS": "%S",
33
+ "SSSSSS": "%f",
34
+ "E": "%a",
35
+ "EE": "%a",
36
+ "E3": "%a",
37
+ "E4": "%A",
38
+ "EEE": "%a",
39
+ "EEEE": "%A",
40
+ }
41
+
42
+ class Tokenizer(tokens.Tokenizer):
43
+ # Tested each of these and they work, although there is no
44
+ # Teradata documentation explicitly mentioning them.
45
+ HEX_STRINGS = [("X'", "'"), ("x'", "'"), ("0x", "")]
46
+ # https://docs.teradata.com/r/Teradata-Database-SQL-Functions-Operators-Exprs-and-Predicates/March-2017/Comparison-Operators-and-Functions/Comparison-Operators/ANSI-Compliance
47
+ # https://docs.teradata.com/r/SQL-Functions-Operators-Exprs-and-Predicates/June-2017/Arithmetic-Trigonometric-Hyperbolic-Operators/Functions
48
+ KEYWORDS = {
49
+ **tokens.Tokenizer.KEYWORDS,
50
+ "**": TokenType.DSTAR,
51
+ "^=": TokenType.NEQ,
52
+ "BYTEINT": TokenType.SMALLINT,
53
+ "COLLECT": TokenType.COMMAND,
54
+ "DEL": TokenType.DELETE,
55
+ "EQ": TokenType.EQ,
56
+ "GE": TokenType.GTE,
57
+ "GT": TokenType.GT,
58
+ "HELP": TokenType.COMMAND,
59
+ "INS": TokenType.INSERT,
60
+ "LE": TokenType.LTE,
61
+ "LOCKING": TokenType.LOCK,
62
+ "LT": TokenType.LT,
63
+ "MINUS": TokenType.EXCEPT,
64
+ "MOD": TokenType.MOD,
65
+ "NE": TokenType.NEQ,
66
+ "NOT=": TokenType.NEQ,
67
+ "SAMPLE": TokenType.TABLE_SAMPLE,
68
+ "SEL": TokenType.SELECT,
69
+ "ST_GEOMETRY": TokenType.GEOMETRY,
70
+ "TOP": TokenType.TOP,
71
+ "UPD": TokenType.UPDATE,
72
+ }
73
+ KEYWORDS.pop("/*+")
74
+
75
+ # Teradata does not support % as a modulo operator
76
+ SINGLE_TOKENS = {**tokens.Tokenizer.SINGLE_TOKENS}
77
+ SINGLE_TOKENS.pop("%")
78
+
79
+ Parser = TeradataParser
80
+
81
+ Generator = TeradataGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/trino.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot.dialects.presto import Presto
4
+ from sqlglot.generators.trino import TrinoGenerator
5
+ from sqlglot.parsers.trino import TrinoParser
6
+ from sqlglot.tokens import TokenType
7
+
8
+
9
+ class Trino(Presto):
10
+ SUPPORTS_USER_DEFINED_TYPES = False
11
+ LOG_BASE_FIRST = True
12
+ CONCAT_WS_COALESCE = True
13
+
14
+ class Tokenizer(Presto.Tokenizer):
15
+ KEYWORDS = {
16
+ **Presto.Tokenizer.KEYWORDS,
17
+ "REFRESH": TokenType.REFRESH,
18
+ "DECLARE": TokenType.DECLARE,
19
+ }
20
+ # Trino has no `SQL SECURITY` clause, only bare `SECURITY DEFINER`/`INVOKER`;
21
+ # the merged base keyword otherwise eats the `SQL` in `LANGUAGE SQL SECURITY DEFINER`.
22
+ KEYWORDS.pop("SQL SECURITY")
23
+
24
+ Parser = TrinoParser
25
+
26
+ Generator = TrinoGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/dialects/tsql.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sqlglot import tokens
4
+ from sqlglot.dialects.dialect import (
5
+ Dialect,
6
+ NormalizationStrategy,
7
+ )
8
+ from sqlglot.generators.tsql import TSQLGenerator
9
+ from sqlglot.parsers.tsql import TSQLParser
10
+ from sqlglot.tokens import TokenType
11
+ from sqlglot.typing.tsql import EXPRESSION_METADATA
12
+
13
+
14
+ class TSQL(Dialect):
15
+ # Week truncation follows @@DATEFIRST, which defaults to 7 (Sunday)
16
+ WEEK_OFFSET = -1
17
+
18
+ LOG_BASE_FIRST = False
19
+ TYPED_DIVISION = True
20
+ CONCAT_COALESCE = True
21
+ CONCAT_WS_COALESCE = True
22
+ JSON_EXTRACT_SCALAR_SCALAR_ONLY = True
23
+ NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
24
+ ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
25
+ ALTER_TABLE_DROP_REQUIRED_FOR_EACH_COLUMN = False
26
+
27
+ TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
28
+
29
+ EXPRESSION_METADATA = EXPRESSION_METADATA.copy()
30
+
31
+ DATE_PART_MAPPING = {
32
+ **Dialect.DATE_PART_MAPPING,
33
+ "QQ": "QUARTER",
34
+ "M": "MONTH",
35
+ "Y": "DAYOFYEAR",
36
+ "WW": "WEEK",
37
+ "N": "MINUTE",
38
+ "SS": "SECOND",
39
+ "MCS": "MICROSECOND",
40
+ "TZOFFSET": "TIMEZONE_MINUTE",
41
+ "TZ": "TIMEZONE_MINUTE",
42
+ "ISO_WEEK": "WEEKISO",
43
+ "ISOWK": "WEEKISO",
44
+ "ISOWW": "WEEKISO",
45
+ }
46
+
47
+ TIME_MAPPING = {
48
+ "year": "%Y",
49
+ "dayofyear": "%j",
50
+ "day": "%d",
51
+ "dy": "%d",
52
+ "y": "%Y",
53
+ "week": "%W",
54
+ "ww": "%W",
55
+ "wk": "%W",
56
+ "isowk": "%V",
57
+ "isoww": "%V",
58
+ "iso_week": "%V",
59
+ "hour": "%h",
60
+ "hh": "%I",
61
+ "minute": "%M",
62
+ "mi": "%M",
63
+ "n": "%M",
64
+ "second": "%S",
65
+ "ss": "%S",
66
+ "s": "%-S",
67
+ "millisecond": "%f",
68
+ "ms": "%f",
69
+ "weekday": "%w",
70
+ "dw": "%w",
71
+ "month": "%m",
72
+ "mm": "%M",
73
+ "m": "%-M",
74
+ "Y": "%Y",
75
+ "YYYY": "%Y",
76
+ "YY": "%y",
77
+ "MMMM": "%B",
78
+ "MMM": "%b",
79
+ "MM": "%m",
80
+ "M": "%-m",
81
+ "dddd": "%A",
82
+ "dd": "%d",
83
+ "d": "%-d",
84
+ "HH": "%H",
85
+ "H": "%-H",
86
+ "h": "%-I",
87
+ "ffffff": "%f",
88
+ "yyyy": "%Y",
89
+ "yy": "%y",
90
+ }
91
+
92
+ CONVERT_FORMAT_MAPPING = {
93
+ "0": "%b %d %Y %-I:%M%p",
94
+ "1": "%m/%d/%y",
95
+ "2": "%y.%m.%d",
96
+ "3": "%d/%m/%y",
97
+ "4": "%d.%m.%y",
98
+ "5": "%d-%m-%y",
99
+ "6": "%d %b %y",
100
+ "7": "%b %d, %y",
101
+ "8": "%H:%M:%S",
102
+ "9": "%b %d %Y %-I:%M:%S:%f%p",
103
+ "10": "mm-dd-yy",
104
+ "11": "yy/mm/dd",
105
+ "12": "yymmdd",
106
+ "13": "%d %b %Y %H:%M:ss:%f",
107
+ "14": "%H:%M:%S:%f",
108
+ "20": "%Y-%m-%d %H:%M:%S",
109
+ "21": "%Y-%m-%d %H:%M:%S.%f",
110
+ "22": "%m/%d/%y %-I:%M:%S %p",
111
+ "23": "%Y-%m-%d",
112
+ "24": "%H:%M:%S",
113
+ "25": "%Y-%m-%d %H:%M:%S.%f",
114
+ "100": "%b %d %Y %-I:%M%p",
115
+ "101": "%m/%d/%Y",
116
+ "102": "%Y.%m.%d",
117
+ "103": "%d/%m/%Y",
118
+ "104": "%d.%m.%Y",
119
+ "105": "%d-%m-%Y",
120
+ "106": "%d %b %Y",
121
+ "107": "%b %d, %Y",
122
+ "108": "%H:%M:%S",
123
+ "109": "%b %d %Y %-I:%M:%S:%f%p",
124
+ "110": "%m-%d-%Y",
125
+ "111": "%Y/%m/%d",
126
+ "112": "%Y%m%d",
127
+ "113": "%d %b %Y %H:%M:%S:%f",
128
+ "114": "%H:%M:%S:%f",
129
+ "120": "%Y-%m-%d %H:%M:%S",
130
+ "121": "%Y-%m-%d %H:%M:%S.%f",
131
+ "126": "%Y-%m-%dT%H:%M:%S.%f",
132
+ }
133
+
134
+ FORMAT_TIME_MAPPING = {
135
+ "y": "%B %Y",
136
+ "d": "%m/%d/%Y",
137
+ "H": "%-H",
138
+ "h": "%-I",
139
+ "s": "%Y-%m-%d %H:%M:%S",
140
+ "D": "%A,%B,%Y",
141
+ "f": "%A,%B,%Y %-I:%M %p",
142
+ "F": "%A,%B,%Y %-I:%M:%S %p",
143
+ "g": "%m/%d/%Y %-I:%M %p",
144
+ "G": "%m/%d/%Y %-I:%M:%S %p",
145
+ "M": "%B %-d",
146
+ "m": "%B %-d",
147
+ "O": "%Y-%m-%dT%H:%M:%S",
148
+ "u": "%Y-%M-%D %H:%M:%S%z",
149
+ "U": "%A, %B %D, %Y %H:%M:%S%z",
150
+ "T": "%-I:%M:%S %p",
151
+ "t": "%-I:%M",
152
+ "Y": "%a %Y",
153
+ }
154
+
155
+ class Tokenizer(tokens.Tokenizer):
156
+ IDENTIFIERS = [("[", "]"), '"']
157
+ QUOTES = ["'", '"']
158
+ HEX_STRINGS = [("0x", ""), ("0X", "")]
159
+ VAR_SINGLE_TOKENS = {"@", "$", "#"}
160
+
161
+ KEYWORDS = {
162
+ **tokens.Tokenizer.KEYWORDS,
163
+ "CLUSTERED INDEX": TokenType.INDEX,
164
+ "DATETIME2": TokenType.DATETIME2,
165
+ "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
166
+ "DECLARE": TokenType.DECLARE,
167
+ "EXEC": TokenType.EXECUTE,
168
+ "GO": TokenType.COMMAND,
169
+ "IMAGE": TokenType.IMAGE,
170
+ "MONEY": TokenType.MONEY,
171
+ "NONCLUSTERED INDEX": TokenType.INDEX,
172
+ "NTEXT": TokenType.TEXT,
173
+ "OPTION": TokenType.OPTION,
174
+ "OUTPUT": TokenType.RETURNING,
175
+ "PRINT": TokenType.COMMAND,
176
+ "PROC": TokenType.PROCEDURE,
177
+ "REAL": TokenType.FLOAT,
178
+ "ROWVERSION": TokenType.ROWVERSION,
179
+ "SMALLDATETIME": TokenType.SMALLDATETIME,
180
+ "SMALLMONEY": TokenType.SMALLMONEY,
181
+ "SQL_VARIANT": TokenType.VARIANT,
182
+ "SYSTEM_USER": TokenType.CURRENT_USER,
183
+ "TOP": TokenType.TOP,
184
+ "TIMESTAMP": TokenType.ROWVERSION,
185
+ "TINYINT": TokenType.UTINYINT,
186
+ "UNIQUEIDENTIFIER": TokenType.UUID,
187
+ "UPDATE STATISTICS": TokenType.COMMAND,
188
+ "XML": TokenType.XML,
189
+ }
190
+ KEYWORDS.pop("/*+")
191
+
192
+ COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.END} - {TokenType.EXECUTE}
193
+
194
+ Parser = TSQLParser
195
+
196
+ Generator = TSQLGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/diff.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. include:: ../posts/sql_diff.md
3
+
4
+ ----
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import typing as t
10
+ from collections import defaultdict
11
+ from dataclasses import dataclass
12
+ from heapq import heappop, heappush
13
+ from itertools import chain
14
+
15
+ from sqlglot import Dialect, expressions as exp
16
+ from sqlglot.helper import seq_get
17
+
18
+ if t.TYPE_CHECKING:
19
+ from collections.abc import Iterator, Sequence
20
+ from sqlglot.dialects.dialect import DialectType
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Insert:
25
+ """Indicates that a new node has been inserted"""
26
+
27
+ expression: exp.Expr
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Remove:
32
+ """Indicates that an existing node has been removed"""
33
+
34
+ expression: exp.Expr
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Move:
39
+ """Indicates that an existing node's position within the tree has changed"""
40
+
41
+ source: exp.Expr
42
+ target: exp.Expr
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Update:
47
+ """Indicates that an existing node has been updated"""
48
+
49
+ source: exp.Expr
50
+ target: exp.Expr
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Keep:
55
+ """Indicates that an existing node hasn't been changed"""
56
+
57
+ source: exp.Expr
58
+ target: exp.Expr
59
+
60
+
61
+ if t.TYPE_CHECKING:
62
+ from sqlglot._typing import T
63
+
64
+ Edit = t.Union[Insert, Remove, Move, Update, Keep]
65
+
66
+
67
+ def diff(
68
+ source: exp.Expr,
69
+ target: exp.Expr,
70
+ matchings: list[tuple[exp.Expr, exp.Expr]] | None = None,
71
+ delta_only: bool = False,
72
+ **kwargs: t.Any,
73
+ ) -> list[Edit]:
74
+ """
75
+ Returns the list of changes between the source and the target expressions.
76
+
77
+ Examples:
78
+ >>> from sqlglot import parse_one
79
+ >>> diff(parse_one("a + b"), parse_one("a + c")) # doctest: +SKIP
80
+ [...]
81
+
82
+ Args:
83
+ source: the source expression.
84
+ target: the target expression against which the diff should be calculated.
85
+ matchings: the list of pre-matched node pairs which is used to help the algorithm's
86
+ heuristics produce better results for subtrees that are known by a caller to be matching.
87
+ Note: expression references in this list must refer to the same node objects that are
88
+ referenced in the source / target trees.
89
+ delta_only: excludes all `Keep` nodes from the diff.
90
+ kwargs: additional arguments to pass to the ChangeDistiller instance.
91
+
92
+ Returns:
93
+ the list of Insert, Remove, Move, Update and Keep objects for each node in the source and the
94
+ target expression trees. This list represents a sequence of steps needed to transform the source
95
+ expression tree into the target one.
96
+ """
97
+ matchings = matchings or []
98
+
99
+ def compute_node_mappings(
100
+ old_nodes: tuple[exp.Expr, ...], new_nodes: tuple[exp.Expr, ...]
101
+ ) -> dict[int, exp.Expr]:
102
+ node_mapping = {}
103
+ for old_node, new_node in zip(reversed(old_nodes), reversed(new_nodes)):
104
+ new_node._hash = hash(new_node)
105
+ node_mapping[id(old_node)] = new_node
106
+
107
+ return node_mapping
108
+
109
+ # if the source and target have any shared objects, that means there's an issue with the ast
110
+ # the algorithm won't work because the parent / hierarchies will be inaccurate
111
+ source_nodes = tuple(source.walk())
112
+ target_nodes = tuple(target.walk())
113
+ source_ids = {id(n) for n in source_nodes}
114
+ target_ids = {id(n) for n in target_nodes}
115
+
116
+ copy = (
117
+ len(source_nodes) != len(source_ids)
118
+ or len(target_nodes) != len(target_ids)
119
+ or source_ids & target_ids
120
+ )
121
+
122
+ source_copy = source.copy() if copy else source
123
+ target_copy = target.copy() if copy else target
124
+
125
+ try:
126
+ # We cache the hash of each new node here to speed up equality comparisons. If the input
127
+ # trees aren't copied, these hashes will be evicted before returning the edit script.
128
+ if copy and matchings:
129
+ source_mapping = compute_node_mappings(source_nodes, tuple(source_copy.walk()))
130
+ target_mapping = compute_node_mappings(target_nodes, tuple(target_copy.walk()))
131
+ matchings = [(source_mapping[id(s)], target_mapping[id(t)]) for s, t in matchings]
132
+ else:
133
+ for node in chain(reversed(source_nodes), reversed(target_nodes)):
134
+ node._hash = hash(node)
135
+
136
+ edit_script = ChangeDistiller(**kwargs).diff(
137
+ source_copy,
138
+ target_copy,
139
+ matchings=matchings,
140
+ delta_only=delta_only,
141
+ )
142
+ finally:
143
+ if not copy:
144
+ for node in chain(source_nodes, target_nodes):
145
+ node._hash = None
146
+
147
+ return edit_script
148
+
149
+
150
+ # The expression types for which Update edits are allowed.
151
+ UPDATABLE_EXPRESSION_TYPES = (
152
+ exp.Alias,
153
+ exp.Boolean,
154
+ exp.Column,
155
+ exp.DataType,
156
+ exp.Lambda,
157
+ exp.Literal,
158
+ exp.Table,
159
+ exp.Window,
160
+ )
161
+
162
+ IGNORED_LEAF_EXPRESSION_TYPES = (exp.Identifier,)
163
+
164
+
165
+ class ChangeDistiller:
166
+ """
167
+ The implementation of the Change Distiller algorithm described by Beat Fluri and Martin Pinzger in
168
+ their paper https://ieeexplore.ieee.org/document/4339230, which in turn is based on the algorithm by
169
+ Chawathe et al. described in http://ilpubs.stanford.edu:8090/115/1/1995-46.pdf.
170
+ """
171
+
172
+ def __init__(self, f: float = 0.6, t: float = 0.6, dialect: DialectType = None) -> None:
173
+ self.f = f
174
+ self.t = t
175
+ self._sql_generator = Dialect.get_or_raise(dialect).generator(comments=False)
176
+
177
+ def diff(
178
+ self,
179
+ source: exp.Expr,
180
+ target: exp.Expr,
181
+ matchings: list[tuple[exp.Expr, exp.Expr]] | None = None,
182
+ delta_only: bool = False,
183
+ ) -> list[Edit]:
184
+ matchings = matchings or []
185
+ pre_matched_nodes = {id(s): id(t) for s, t in matchings}
186
+
187
+ self._source = source
188
+ self._target = target
189
+ self._source_index = {
190
+ id(n): n for n in self._source.bfs() if not isinstance(n, IGNORED_LEAF_EXPRESSION_TYPES)
191
+ }
192
+ self._target_index = {
193
+ id(n): n for n in self._target.bfs() if not isinstance(n, IGNORED_LEAF_EXPRESSION_TYPES)
194
+ }
195
+ self._unmatched_source_nodes = set(self._source_index) - set(pre_matched_nodes)
196
+ self._unmatched_target_nodes = set(self._target_index) - set(pre_matched_nodes.values())
197
+ self._bigram_histo_cache: dict[int, defaultdict[str, int]] = {}
198
+
199
+ matching_set = self._compute_matching_set() | set(pre_matched_nodes.items())
200
+ return self._generate_edit_script(dict(matching_set), delta_only)
201
+
202
+ def _generate_edit_script(self, matchings: dict[int, int], delta_only: bool) -> list[Edit]:
203
+ edit_script: list[Edit] = []
204
+ for removed_node_id in self._unmatched_source_nodes:
205
+ edit_script.append(Remove(self._source_index[removed_node_id]))
206
+ for inserted_node_id in self._unmatched_target_nodes:
207
+ edit_script.append(Insert(self._target_index[inserted_node_id]))
208
+ for kept_source_node_id, kept_target_node_id in matchings.items():
209
+ source_node = self._source_index[kept_source_node_id]
210
+ target_node = self._target_index[kept_target_node_id]
211
+
212
+ identical_nodes = source_node == target_node
213
+
214
+ if not isinstance(source_node, UPDATABLE_EXPRESSION_TYPES) or identical_nodes:
215
+ if identical_nodes:
216
+ source_parent = source_node.parent
217
+ target_parent = target_node.parent
218
+
219
+ if (
220
+ (source_parent and not target_parent)
221
+ or (not source_parent and target_parent)
222
+ or (
223
+ source_parent
224
+ and target_parent
225
+ and matchings.get(id(source_parent)) != id(target_parent)
226
+ )
227
+ ):
228
+ edit_script.append(Move(source=source_node, target=target_node))
229
+ else:
230
+ edit_script.extend(
231
+ self._generate_move_edits(source_node, target_node, matchings)
232
+ )
233
+
234
+ source_non_expression_leaves = dict(_get_non_expression_leaves(source_node))
235
+ target_non_expression_leaves = dict(_get_non_expression_leaves(target_node))
236
+
237
+ if source_non_expression_leaves != target_non_expression_leaves:
238
+ edit_script.append(Update(source_node, target_node))
239
+ elif not delta_only:
240
+ edit_script.append(Keep(source_node, target_node))
241
+ else:
242
+ edit_script.append(Update(source_node, target_node))
243
+
244
+ return edit_script
245
+
246
+ def _generate_move_edits(
247
+ self, source: exp.Expr, target: exp.Expr, matchings: dict[int, int]
248
+ ) -> list[Move]:
249
+ source_args = [id(e) for e in _expression_only_args(source)]
250
+ target_args = [id(e) for e in _expression_only_args(target)]
251
+
252
+ args_lcs = set(
253
+ _lcs(source_args, target_args, lambda l, r: matchings.get(t.cast(int, l)) == r)
254
+ )
255
+
256
+ move_edits = []
257
+ for a in source_args:
258
+ if a not in args_lcs and a not in self._unmatched_source_nodes:
259
+ move_edits.append(
260
+ Move(source=self._source_index[a], target=self._target_index[matchings[a]])
261
+ )
262
+
263
+ return move_edits
264
+
265
+ def _compute_matching_set(self) -> set[tuple[int, int]]:
266
+ leaves_matching_set = self._compute_leaf_matching_set()
267
+ matching_set = leaves_matching_set.copy()
268
+
269
+ ordered_unmatched_source_nodes = {
270
+ id(n): None for n in self._source.bfs() if id(n) in self._unmatched_source_nodes
271
+ }
272
+ ordered_unmatched_target_nodes = {
273
+ id(n): None for n in self._target.bfs() if id(n) in self._unmatched_target_nodes
274
+ }
275
+
276
+ for source_node_id in ordered_unmatched_source_nodes:
277
+ for target_node_id in ordered_unmatched_target_nodes:
278
+ source_node = self._source_index[source_node_id]
279
+ target_node = self._target_index[target_node_id]
280
+ if _is_same_type(source_node, target_node):
281
+ source_leaf_ids = {id(l) for l in _get_expression_leaves(source_node)}
282
+ target_leaf_ids = {id(l) for l in _get_expression_leaves(target_node)}
283
+
284
+ max_leaves_num = max(len(source_leaf_ids), len(target_leaf_ids))
285
+ if max_leaves_num:
286
+ common_leaves_num = sum(
287
+ 1 if s in source_leaf_ids and t in target_leaf_ids else 0
288
+ for s, t in leaves_matching_set
289
+ )
290
+ leaf_similarity_score = common_leaves_num / max_leaves_num
291
+ else:
292
+ leaf_similarity_score = 0.0
293
+
294
+ adjusted_t = (
295
+ self.t if min(len(source_leaf_ids), len(target_leaf_ids)) > 4 else 0.4
296
+ )
297
+
298
+ if leaf_similarity_score >= 0.8 or (
299
+ leaf_similarity_score >= adjusted_t
300
+ and self._dice_coefficient(source_node, target_node) >= self.f
301
+ ):
302
+ matching_set.add((source_node_id, target_node_id))
303
+ self._unmatched_source_nodes.remove(source_node_id)
304
+ self._unmatched_target_nodes.remove(target_node_id)
305
+ ordered_unmatched_target_nodes.pop(target_node_id, None)
306
+ break
307
+
308
+ return matching_set
309
+
310
+ def _compute_leaf_matching_set(self) -> set[tuple[int, int]]:
311
+ candidate_matchings: list[tuple[float, int, int, exp.Expr, exp.Expr]] = []
312
+ source_expression_leaves = list(_get_expression_leaves(self._source))
313
+ target_expression_leaves = list(_get_expression_leaves(self._target))
314
+ for source_leaf in source_expression_leaves:
315
+ for target_leaf in target_expression_leaves:
316
+ if _is_same_type(source_leaf, target_leaf):
317
+ similarity_score = self._dice_coefficient(source_leaf, target_leaf)
318
+ if similarity_score >= self.f:
319
+ heappush(
320
+ candidate_matchings,
321
+ (
322
+ -similarity_score,
323
+ -_parent_similarity_score(source_leaf, target_leaf),
324
+ len(candidate_matchings),
325
+ source_leaf,
326
+ target_leaf,
327
+ ),
328
+ )
329
+
330
+ # Pick best matchings based on the highest score
331
+ matching_set = set()
332
+ while candidate_matchings:
333
+ _, _, _, source_leaf, target_leaf = heappop(candidate_matchings)
334
+ if (
335
+ id(source_leaf) in self._unmatched_source_nodes
336
+ and id(target_leaf) in self._unmatched_target_nodes
337
+ ):
338
+ matching_set.add((id(source_leaf), id(target_leaf)))
339
+ self._unmatched_source_nodes.remove(id(source_leaf))
340
+ self._unmatched_target_nodes.remove(id(target_leaf))
341
+
342
+ return matching_set
343
+
344
+ def _dice_coefficient(self, source: exp.Expr, target: exp.Expr) -> float:
345
+ source_histo = self._bigram_histo(source)
346
+ target_histo = self._bigram_histo(target)
347
+
348
+ total_grams = sum(source_histo.values()) + sum(target_histo.values())
349
+ if not total_grams:
350
+ return 1.0 if source == target else 0.0
351
+
352
+ overlap_len = 0
353
+ overlapping_grams = set(source_histo) & set(target_histo)
354
+ for g in overlapping_grams:
355
+ overlap_len += min(source_histo[g], target_histo[g])
356
+
357
+ return 2 * overlap_len / total_grams
358
+
359
+ def _bigram_histo(self, expression: exp.Expr) -> defaultdict[str, int]:
360
+ if id(expression) in self._bigram_histo_cache:
361
+ return self._bigram_histo_cache[id(expression)]
362
+
363
+ expression_str = self._sql_generator.generate(expression)
364
+ count = max(0, len(expression_str) - 1)
365
+ bigram_histo: defaultdict[str, int] = defaultdict(int)
366
+ for i in range(count):
367
+ bigram_histo[expression_str[i : i + 2]] += 1
368
+
369
+ self._bigram_histo_cache[id(expression)] = bigram_histo
370
+ return bigram_histo
371
+
372
+
373
+ def _get_expression_leaves(expression: exp.Expr) -> Iterator[exp.Expr]:
374
+ has_child_exprs = False
375
+
376
+ for node in expression.iter_expressions():
377
+ if not isinstance(node, IGNORED_LEAF_EXPRESSION_TYPES):
378
+ has_child_exprs = True
379
+ yield from _get_expression_leaves(node)
380
+
381
+ if not has_child_exprs:
382
+ yield expression
383
+
384
+
385
+ def _get_non_expression_leaves(expression: exp.Expr) -> Iterator[tuple[str, t.Any]]:
386
+ for arg, value in expression.args.items():
387
+ if (
388
+ value is None
389
+ or isinstance(value, exp.Expr)
390
+ or (isinstance(value, list) and isinstance(seq_get(value, 0), exp.Expr))
391
+ ):
392
+ continue
393
+
394
+ yield (arg, value)
395
+
396
+
397
+ def _is_same_type(source: exp.Expr, target: exp.Expr) -> bool:
398
+ if type(source) is type(target):
399
+ if isinstance(source, exp.Join):
400
+ return source.args.get("side") == target.args.get("side")
401
+
402
+ if isinstance(source, exp.Anonymous):
403
+ return source.this == target.this
404
+
405
+ return True
406
+
407
+ return False
408
+
409
+
410
+ def _parent_similarity_score(source: exp.Expr | None, target: exp.Expr | None) -> int:
411
+ if source is None or target is None or type(source) is not type(target):
412
+ return 0
413
+
414
+ return 1 + _parent_similarity_score(source.parent, target.parent)
415
+
416
+
417
+ def _expression_only_args(expression: exp.Expr) -> Iterator[exp.Expr]:
418
+ yield from (
419
+ arg
420
+ for arg in expression.iter_expressions()
421
+ if not isinstance(arg, IGNORED_LEAF_EXPRESSION_TYPES)
422
+ )
423
+
424
+
425
+ def _lcs(
426
+ seq_a: Sequence[T], seq_b: Sequence[T], equal: t.Callable[[T, T], bool]
427
+ ) -> Sequence[T | None]:
428
+ """Calculates the longest common subsequence"""
429
+
430
+ len_a = len(seq_a)
431
+ len_b = len(seq_b)
432
+ lcs_result = [[None] * (len_b + 1) for i in range(len_a + 1)]
433
+
434
+ for i in range(len_a + 1):
435
+ for j in range(len_b + 1):
436
+ if i == 0 or j == 0:
437
+ lcs_result[i][j] = [] # type: ignore
438
+ elif equal(seq_a[i - 1], seq_b[j - 1]):
439
+ lcs_result[i][j] = lcs_result[i - 1][j - 1] + [seq_a[i - 1]] # type: ignore
440
+ else:
441
+ lcs_result[i][j] = (
442
+ lcs_result[i - 1][j]
443
+ if len(lcs_result[i - 1][j]) > len(lcs_result[i][j - 1]) # type: ignore
444
+ else lcs_result[i][j - 1]
445
+ )
446
+
447
+ return lcs_result[len_a][len_b] # type: ignore
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/errors.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing as t
4
+ from enum import auto
5
+ from collections.abc import Sequence
6
+ from sqlglot.helper import AutoName
7
+
8
+
9
+ # ANSI escape codes for error formatting
10
+ ANSI_UNDERLINE = "\033[4m"
11
+ ANSI_RESET = "\033[0m"
12
+ ERROR_MESSAGE_CONTEXT_DEFAULT = 100
13
+
14
+
15
+ class ErrorLevel(AutoName):
16
+ IGNORE = auto()
17
+ """Ignore all errors."""
18
+
19
+ WARN = auto()
20
+ """Log all errors."""
21
+
22
+ RAISE = auto()
23
+ """Collect all errors and raise a single exception."""
24
+
25
+ IMMEDIATE = auto()
26
+ """Immediately raise an exception on the first error found."""
27
+
28
+
29
+ class SqlglotError(Exception):
30
+ pass
31
+
32
+
33
+ class UnsupportedError(SqlglotError):
34
+ pass
35
+
36
+
37
+ class ParseError(SqlglotError):
38
+ def __init__(
39
+ self,
40
+ message: str,
41
+ errors: list[dict[str, t.Any]] | None = None,
42
+ ):
43
+ super().__init__(message)
44
+ self.errors = errors or []
45
+
46
+ @classmethod
47
+ def new(
48
+ cls,
49
+ message: str,
50
+ description: str | None = None,
51
+ line: int | None = None,
52
+ col: int | None = None,
53
+ start_context: str | None = None,
54
+ highlight: str | None = None,
55
+ end_context: str | None = None,
56
+ into_expression: str | None = None,
57
+ ) -> ParseError:
58
+ return cls(
59
+ message,
60
+ [
61
+ {
62
+ "description": description,
63
+ "line": line,
64
+ "col": col,
65
+ "start_context": start_context,
66
+ "highlight": highlight,
67
+ "end_context": end_context,
68
+ "into_expression": into_expression,
69
+ }
70
+ ],
71
+ )
72
+
73
+
74
+ class TokenError(SqlglotError):
75
+ """Error raised when tokenizing fails.
76
+
77
+ When available, `start` and `end` are the offsets in the source SQL of the context
78
+ snippet quoted in the message, i.e. the snippet is `sql[start:end]`.
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ message: str,
84
+ start: int | None = None,
85
+ end: int | None = None,
86
+ ):
87
+ super().__init__(message)
88
+ self.start = start
89
+ self.end = end
90
+
91
+
92
+ class OptimizeError(SqlglotError):
93
+ pass
94
+
95
+
96
+ class SchemaError(SqlglotError):
97
+ pass
98
+
99
+
100
+ class ExecuteError(SqlglotError):
101
+ pass
102
+
103
+
104
+ def highlight_sql(
105
+ sql: str,
106
+ positions: list[tuple[int, int]],
107
+ context_length: int = ERROR_MESSAGE_CONTEXT_DEFAULT,
108
+ ) -> tuple[str, str, str, str]:
109
+ """
110
+ Highlight a SQL string using ANSI codes at the given positions.
111
+
112
+ Args:
113
+ sql: The complete SQL string.
114
+ positions: List of (start, end) tuples where both start and end are inclusive 0-based
115
+ indexes. For example, to highlight "foo" in "SELECT foo", use (7, 9).
116
+ The positions will be sorted and de-duplicated if they overlap.
117
+ context_length: Number of characters to show before the first highlight and after
118
+ the last highlight.
119
+
120
+ Returns:
121
+ A tuple of (formatted_sql, start_context, highlight, end_context) where:
122
+ - formatted_sql: The SQL with ANSI underline codes applied to highlighted sections
123
+ - start_context: Plain text before the first highlight
124
+ - highlight: Plain text from the first highlight start to the last highlight end,
125
+ including any non-highlighted text in between (no ANSI)
126
+ - end_context: Plain text after the last highlight
127
+
128
+ Note:
129
+ If positions is empty, raises a ValueError.
130
+ """
131
+ if not positions:
132
+ raise ValueError("positions must contain at least one (start, end) tuple")
133
+
134
+ start_context = ""
135
+ end_context = ""
136
+ first_highlight_start = 0
137
+ formatted_parts = []
138
+ previous_part_end = 0
139
+ sorted_positions = sorted(positions, key=lambda pos: pos[0])
140
+
141
+ if sorted_positions[0][0] > 0:
142
+ first_highlight_start = sorted_positions[0][0]
143
+ start_context = sql[max(0, first_highlight_start - context_length) : first_highlight_start]
144
+ formatted_parts.append(start_context)
145
+ previous_part_end = first_highlight_start
146
+
147
+ for start, end in sorted_positions:
148
+ highlight_start = max(start, previous_part_end)
149
+ highlight_end = end + 1
150
+ if highlight_start >= highlight_end:
151
+ continue # Skip invalid or overlapping highlights
152
+ if highlight_start > previous_part_end:
153
+ formatted_parts.append(sql[previous_part_end:highlight_start])
154
+ formatted_parts.append(f"{ANSI_UNDERLINE}{sql[highlight_start:highlight_end]}{ANSI_RESET}")
155
+ previous_part_end = highlight_end
156
+
157
+ if previous_part_end < len(sql):
158
+ end_context = sql[previous_part_end : previous_part_end + context_length]
159
+ formatted_parts.append(end_context)
160
+
161
+ formatted_sql = "".join(formatted_parts)
162
+ highlight = sql[first_highlight_start:previous_part_end]
163
+
164
+ return formatted_sql, start_context, highlight, end_context
165
+
166
+
167
+ def concat_messages(errors: Sequence[t.Any], maximum: int) -> str:
168
+ msg = [str(e) for e in errors[:maximum]]
169
+ remaining = len(errors) - maximum
170
+ if remaining > 0:
171
+ msg.append(f"... and {remaining} more")
172
+ return "\n\n".join(msg)
173
+
174
+
175
+ def merge_errors(errors: Sequence[ParseError]) -> list[dict[str, t.Any]]:
176
+ return [e_dict for error in errors for e_dict in error.errors]
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/__init__.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. include:: ../../posts/python_sql_engine.md
3
+
4
+ ----
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import time
11
+ import typing as t
12
+
13
+ from sqlglot import exp
14
+ from sqlglot.errors import ExecuteError
15
+ from sqlglot.executor.python import PythonExecutor
16
+ from sqlglot.executor.table import Table, ensure_tables
17
+ from sqlglot.helper import dict_depth
18
+ from sqlglot.optimizer import optimize
19
+ from sqlglot.optimizer.annotate_types import annotate_types
20
+ from sqlglot.planner import Plan
21
+ from sqlglot.schema import ensure_schema, flatten_schema, nested_get, nested_set
22
+
23
+ logger = logging.getLogger("sqlglot")
24
+
25
+ if t.TYPE_CHECKING:
26
+ from sqlglot.dialects.dialect import DialectType
27
+ from sqlglot.expressions import Expr
28
+ from sqlglot.schema import Schema
29
+
30
+
31
+ def execute(
32
+ sql: str | Expr,
33
+ schema: dict | Schema | None = None,
34
+ dialect: DialectType = None,
35
+ tables: dict | None = None,
36
+ ) -> Table:
37
+ """
38
+ Run a sql query against data.
39
+
40
+ Args:
41
+ sql: a sql statement.
42
+ schema: database schema.
43
+ This can either be an instance of `Schema` or a mapping in one of the following forms:
44
+ 1. {table: {col: type}}
45
+ 2. {db: {table: {col: type}}}
46
+ 3. {catalog: {db: {table: {col: type}}}}
47
+ dialect: the SQL dialect to apply during parsing (eg. "spark", "hive", "presto", "mysql").
48
+ tables: additional tables to register.
49
+
50
+ Returns:
51
+ Simple columnar data structure.
52
+ """
53
+ tables_ = ensure_tables(tables, dialect=dialect)
54
+
55
+ if not schema:
56
+ schema = {}
57
+ flattened_tables = flatten_schema(tables_.mapping, depth=dict_depth(tables_.mapping))
58
+
59
+ for keys in flattened_tables:
60
+ table = nested_get(tables_.mapping, *zip(keys, keys))
61
+ assert table is not None
62
+
63
+ for column in table.columns:
64
+ value = table[0][column]
65
+ column_type = (
66
+ annotate_types(exp.convert(value), dialect=dialect).type or type(value).__name__
67
+ )
68
+ nested_set(schema, [*keys, column], column_type)
69
+
70
+ schema = ensure_schema(schema, dialect=dialect)
71
+
72
+ if tables_.supported_table_args and tables_.supported_table_args != schema.supported_table_args:
73
+ raise ExecuteError("Tables must support the same table args as schema")
74
+
75
+ now = time.time()
76
+ expression = optimize(sql, schema, leave_tables_isolated=True, dialect=dialect)
77
+
78
+ logger.debug("Optimization finished: %f", time.time() - now)
79
+ logger.debug("Optimized SQL: %s", expression.sql(pretty=True))
80
+
81
+ plan = Plan(expression)
82
+
83
+ logger.debug("Logical Plan: %s", plan)
84
+
85
+ now = time.time()
86
+ result = PythonExecutor(tables=tables_).execute(plan)
87
+
88
+ logger.debug("Query finished: %f", time.time() - now)
89
+
90
+ return result
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/context.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing as t
4
+
5
+ from sqlglot.executor.env import ENV
6
+
7
+ if t.TYPE_CHECKING:
8
+ from sqlglot.executor.table import Table, TableIter
9
+
10
+
11
+ class Context:
12
+ """
13
+ Execution context for sql expressions.
14
+
15
+ Context is used to hold relevant data tables which can then be queried on with eval.
16
+
17
+ References to columns can either be scalar or vectors. When set_row is used, column references
18
+ evaluate to scalars while set_range evaluates to vectors. This allows convenient and efficient
19
+ evaluation of aggregation functions.
20
+ """
21
+
22
+ def __init__(
23
+ self, tables: dict[str, Table], env: dict | None = None, outer: dict | None = None
24
+ ) -> None:
25
+ """
26
+ Args
27
+ tables: representing the scope of the current execution context.
28
+ env: dictionary of functions within the execution context.
29
+ outer: readers of an enclosing query, for a subquery run once per outer row.
30
+ Own tables shadow them, as an inner alias shadows an outer one in SQL.
31
+ """
32
+ self.tables = tables
33
+ self._table: Table | None = None
34
+ range_readers = {name: table.range_reader for name, table in self.tables.items()}
35
+ row_readers = {name: table.reader for name, table in tables.items()}
36
+
37
+ if outer:
38
+ range_readers = {**outer, **range_readers}
39
+ row_readers = {**outer, **row_readers}
40
+
41
+ self.range_readers = range_readers
42
+ self.row_readers = row_readers
43
+ self.env = {**ENV, **(env or {}), "scope": self.row_readers}
44
+
45
+ def eval(self, code):
46
+ return eval(code, self.env)
47
+
48
+ def eval_tuple(self, codes):
49
+ return tuple(self.eval(code) for code in codes)
50
+
51
+ @property
52
+ def table(self) -> Table:
53
+ if self._table is None:
54
+ self._table = list(self.tables.values())[0]
55
+
56
+ for other in self.tables.values():
57
+ if self._table.columns != other.columns:
58
+ raise Exception("Columns are different.")
59
+ if len(self._table.rows) != len(other.rows):
60
+ raise Exception("Rows are different.")
61
+
62
+ return self._table
63
+
64
+ def add_columns(self, *columns: str) -> None:
65
+ for table in self.tables.values():
66
+ table.add_columns(*columns)
67
+
68
+ @property
69
+ def columns(self) -> tuple:
70
+ return self.table.columns if self.tables else ()
71
+
72
+ def __iter__(self):
73
+ self.env["scope"] = self.row_readers
74
+ for i in range(len(self.table.rows)):
75
+ for table in self.tables.values():
76
+ reader = table[i]
77
+ yield reader, self
78
+
79
+ def table_iter(self, table: str) -> TableIter:
80
+ self.env["scope"] = self.row_readers
81
+ return iter(self.tables[table])
82
+
83
+ def filter(self, condition) -> None:
84
+ rows = [reader.row for reader, _ in self if self.eval(condition)]
85
+
86
+ for table in self.tables.values():
87
+ table.rows = rows
88
+
89
+ def sort(self, key) -> None:
90
+ def sort_key(row: tuple) -> tuple:
91
+ self.set_row(row)
92
+ return tuple((t is None, t) for t in self.eval_tuple(key))
93
+
94
+ self.table.rows.sort(key=sort_key)
95
+
96
+ def set_row(self, row: tuple) -> None:
97
+ for table in self.tables.values():
98
+ table.reader.row = row
99
+ self.env["scope"] = self.row_readers
100
+
101
+ def set_index(self, index: int) -> None:
102
+ for table in self.tables.values():
103
+ table[index]
104
+ self.env["scope"] = self.row_readers
105
+
106
+ def set_range(self, start: int, end: int) -> None:
107
+ for name in self.tables:
108
+ self.range_readers[name].range = range(start, end)
109
+ self.env["scope"] = self.range_readers
110
+
111
+ def __contains__(self, table: str) -> bool:
112
+ return table in self.tables
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/env.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import inspect
3
+ import re
4
+ import statistics
5
+ from functools import wraps
6
+
7
+ from sqlglot import exp
8
+ from sqlglot.generator import Generator
9
+ from sqlglot.helper import PYTHON_VERSION, is_int, seq_get
10
+
11
+
12
+ def sql_not(value):
13
+ return None if value is None else not bool(value)
14
+
15
+
16
+ def sql_and(left, right):
17
+ left = left()
18
+ left = None if left is None else bool(left)
19
+
20
+ if left is False:
21
+ return False
22
+
23
+ right = right()
24
+ right = None if right is None else bool(right)
25
+ if right is False:
26
+ return False
27
+
28
+ return None if left is None or right is None else True
29
+
30
+
31
+ def sql_or(left, right):
32
+ left = left()
33
+ left = None if left is None else bool(left)
34
+
35
+ if left is True:
36
+ return True
37
+
38
+ right = right()
39
+ right = None if right is None else bool(right)
40
+ if right is True:
41
+ return True
42
+
43
+ return None if left is None or right is None else False
44
+
45
+
46
+ def sql_in(value, *candidates):
47
+ if value is None:
48
+ return None
49
+
50
+ has_null = False
51
+ for candidate in candidates:
52
+ if candidate is None:
53
+ has_null = True
54
+ elif value == candidate:
55
+ return True
56
+
57
+ return None if has_null else False
58
+
59
+
60
+ class reverse_key:
61
+ def __init__(self, obj):
62
+ self.obj = obj
63
+
64
+ def __eq__(self, other):
65
+ return other.obj == self.obj
66
+
67
+ def __lt__(self, other):
68
+ return other.obj < self.obj
69
+
70
+
71
+ def filter_nulls(func, empty_null=True):
72
+ @wraps(func)
73
+ def _func(values):
74
+ filtered = tuple(v for v in values if v is not None)
75
+ if not filtered and empty_null:
76
+ return None
77
+ return func(filtered)
78
+
79
+ return _func
80
+
81
+
82
+ def null_if_any(*required):
83
+ """
84
+ Decorator that makes a function return `None` if any of the `required` arguments are `None`.
85
+
86
+ This also supports decoration with no arguments, e.g.:
87
+
88
+ @null_if_any
89
+ def foo(a, b): ...
90
+
91
+ In which case all arguments are required.
92
+ """
93
+ f = None
94
+ if len(required) == 1 and callable(required[0]):
95
+ f = required[0]
96
+ required = ()
97
+
98
+ def decorator(func):
99
+ if required:
100
+ required_indices = [
101
+ i for i, param in enumerate(inspect.signature(func).parameters) if param in required
102
+ ]
103
+
104
+ def predicate(*args):
105
+ return any(args[i] is None for i in required_indices)
106
+
107
+ else:
108
+
109
+ def predicate(*args):
110
+ return any(a is None for a in args)
111
+
112
+ @wraps(func)
113
+ def _func(*args):
114
+ if predicate(*args):
115
+ return None
116
+ return func(*args)
117
+
118
+ return _func
119
+
120
+ if f:
121
+ return decorator(f)
122
+
123
+ return decorator
124
+
125
+
126
+ @null_if_any("this", "substr")
127
+ def str_position(this, substr, position=None):
128
+ position = position - 1 if position is not None else position
129
+ return this.find(substr, position) + 1
130
+
131
+
132
+ @null_if_any("this")
133
+ def substring(this, start=None, length=None):
134
+ if start is None:
135
+ return this
136
+ elif start == 0:
137
+ return ""
138
+ elif start < 0:
139
+ start = len(this) + start
140
+ else:
141
+ start -= 1
142
+
143
+ end = None if length is None else start + length
144
+
145
+ return this[start:end]
146
+
147
+
148
+ @null_if_any
149
+ def cast(this, to):
150
+ if to == exp.DType.DATE:
151
+ if isinstance(this, datetime.datetime):
152
+ return this.date()
153
+ if isinstance(this, datetime.date):
154
+ return this
155
+ if isinstance(this, str):
156
+ return datetime.date.fromisoformat(this)
157
+ if to == exp.DType.TIME:
158
+ if isinstance(this, datetime.datetime):
159
+ return this.time()
160
+ if isinstance(this, datetime.time):
161
+ return this
162
+ if isinstance(this, str):
163
+ return datetime.time.fromisoformat(this)
164
+ if to in (exp.DType.DATETIME, exp.DType.TIMESTAMP):
165
+ if isinstance(this, datetime.datetime):
166
+ return this
167
+ if isinstance(this, datetime.date):
168
+ return datetime.datetime(this.year, this.month, this.day)
169
+ if isinstance(this, str):
170
+ return datetime.datetime.fromisoformat(this)
171
+ if to == exp.DType.BOOLEAN:
172
+ return bool(this)
173
+ if to in exp.DataType.TEXT_TYPES:
174
+ return str(this)
175
+ if to in {exp.DType.FLOAT, exp.DType.DOUBLE}:
176
+ return float(this)
177
+ if to in exp.DataType.NUMERIC_TYPES:
178
+ return int(this)
179
+ raise NotImplementedError(f"Casting {this} to '{to}' not implemented.")
180
+
181
+
182
+ FIRST = 0
183
+ LAST = 1
184
+ NULL_PLACEHOLDER = 0
185
+
186
+
187
+ def ordered(this, desc, nulls_first):
188
+ if this is None:
189
+ return (FIRST if nulls_first else LAST, NULL_PLACEHOLDER)
190
+ return (LAST if nulls_first else FIRST, reverse_key(this) if desc else this)
191
+
192
+
193
+ def _like(this, e, flags=0):
194
+ return bool(
195
+ re.fullmatch(re.escape(e).replace("_", ".").replace("%", ".*"), this, re.DOTALL | flags)
196
+ )
197
+
198
+
199
+ @null_if_any
200
+ def intdiv(this, e):
201
+ if not isinstance(this, int) or not isinstance(e, int):
202
+ return int(this / e)
203
+
204
+ quotient = abs(this) // abs(e)
205
+ return quotient if (this < 0) == (e < 0) else -quotient
206
+
207
+
208
+ @null_if_any
209
+ def interval(this, unit):
210
+ plural = unit + "S"
211
+ if plural in Generator.TIME_PART_SINGULARS:
212
+ unit = plural
213
+ return datetime.timedelta(**{unit.lower(): float(this)})
214
+
215
+
216
+ def zip_not_null(*args):
217
+ return (row for row in zip(*args) if all(v is not None for v in row))
218
+
219
+
220
+ @null_if_any
221
+ def arrayconcat(*args):
222
+ result = []
223
+ for arg in args:
224
+ result.extend(arg if isinstance(arg, list) else [arg])
225
+ return result
226
+
227
+
228
+ @null_if_any("this", "expression")
229
+ def arraytostring(this, expression, null=None):
230
+ return expression.join(x for x in (x if x is not None else null for x in this) if x is not None)
231
+
232
+
233
+ @null_if_any("this", "expression")
234
+ def jsonextract(this, expression):
235
+ for path_segment in expression:
236
+ if isinstance(this, dict):
237
+ this = this.get(path_segment)
238
+ elif isinstance(this, list) and is_int(path_segment):
239
+ this = seq_get(this, int(path_segment))
240
+ else:
241
+ raise NotImplementedError(f"Unable to extract value for {this} at {path_segment}.")
242
+
243
+ if this is None:
244
+ break
245
+
246
+ return this
247
+
248
+
249
+ ENV = {
250
+ "exp": exp,
251
+ "AND": sql_and,
252
+ # aggs
253
+ "ARRAYAGG": list,
254
+ "ARRAYUNIQUEAGG": filter_nulls(lambda acc: list(set(acc))),
255
+ "AVG": filter_nulls(statistics.fmean if PYTHON_VERSION >= (3, 8) else statistics.mean), # type: ignore
256
+ "COUNT": filter_nulls(lambda acc: sum(1 for _ in acc), False),
257
+ "FIRST": lambda acc: next(iter(acc), None),
258
+ "MAX": filter_nulls(max),
259
+ "MIN": filter_nulls(min),
260
+ "SUM": filter_nulls(sum),
261
+ # scalar functions
262
+ "ABS": null_if_any(lambda this: abs(this)),
263
+ "ADD": null_if_any(lambda e, this: e + this),
264
+ "ARRAYANY": null_if_any(lambda arr, func: any(func(e) for e in arr)),
265
+ "ARRAYCONCAT": arrayconcat,
266
+ "ARRAYTOSTRING": arraytostring,
267
+ "BETWEEN": null_if_any(lambda this, low, high: low <= this and this <= high),
268
+ "BITWISEAND": null_if_any(lambda this, e: this & e),
269
+ "BITWISELEFTSHIFT": null_if_any(lambda this, e: this << e),
270
+ "BITWISEOR": null_if_any(lambda this, e: this | e),
271
+ "BITWISERIGHTSHIFT": null_if_any(lambda this, e: this >> e),
272
+ "BITWISEXOR": null_if_any(lambda this, e: this ^ e),
273
+ "CAST": cast,
274
+ "COALESCE": lambda *args: next((a for a in args if a is not None), None),
275
+ "CONCAT": null_if_any(lambda *args: "".join(args)),
276
+ "SAFECONCAT": null_if_any(lambda *args: "".join(str(arg) for arg in args)),
277
+ "CONCATWS": null_if_any(lambda this, *args: this.join(args)),
278
+ "DATEDIFF": null_if_any(lambda this, expression, *_: (this - expression).days),
279
+ "DATESTRTODATE": null_if_any(lambda arg: datetime.date.fromisoformat(arg)),
280
+ "DIV": null_if_any(lambda e, this: e / this),
281
+ "DOT": null_if_any(lambda e, this: e[this]),
282
+ "EQ": null_if_any(lambda this, e: this == e),
283
+ "EXTRACT": null_if_any(lambda this, e: getattr(e, this)),
284
+ "GT": null_if_any(lambda this, e: this > e),
285
+ "GTE": null_if_any(lambda this, e: this >= e),
286
+ "IF": lambda predicate, true, false: true if predicate else false,
287
+ "IN": sql_in,
288
+ "INT": null_if_any(int),
289
+ "INTDIV": intdiv,
290
+ "INTERVAL": interval,
291
+ "JSONEXTRACT": jsonextract,
292
+ "LEFT": null_if_any(lambda this, e: this[:e]),
293
+ "LENGTH": null_if_any(len),
294
+ "LIKE": null_if_any(lambda this, e: _like(this, e)),
295
+ "ILIKE": null_if_any(lambda this, e: _like(this, e, re.IGNORECASE)),
296
+ "LOWER": null_if_any(lambda arg: arg.lower()),
297
+ "LT": null_if_any(lambda this, e: this < e),
298
+ "LTE": null_if_any(lambda this, e: this <= e),
299
+ "MAP": null_if_any(lambda *args: dict(zip(*args))), # type: ignore
300
+ "MOD": null_if_any(lambda e, this: e % this),
301
+ "MUL": null_if_any(lambda e, this: e * this),
302
+ "NEQ": null_if_any(lambda this, e: this != e),
303
+ "ORD": null_if_any(ord),
304
+ "NOT": sql_not,
305
+ "OR": sql_or,
306
+ "ORDERED": ordered,
307
+ "POW": null_if_any(pow),
308
+ "REVERSE": null_if_any(lambda this: this[::-1]),
309
+ "RIGHT": null_if_any(lambda this, e: this[-e:]),
310
+ "ROUND": null_if_any(lambda this, decimals=None, truncate=None: round(this, ndigits=decimals)),
311
+ "STRPOSITION": str_position,
312
+ "SUB": null_if_any(lambda e, this: e - this),
313
+ "SUBSTRING": substring,
314
+ "TIMESTRTOTIME": null_if_any(lambda arg: datetime.datetime.fromisoformat(arg)),
315
+ "UPPER": null_if_any(lambda arg: arg.upper()),
316
+ "ZIPNOTNULL": zip_not_null,
317
+ "YEAR": null_if_any(lambda arg: arg.year),
318
+ "MONTH": null_if_any(lambda arg: arg.month),
319
+ "DAY": null_if_any(lambda arg: arg.day),
320
+ "CURRENTDATETIME": datetime.datetime.now,
321
+ "CURRENTTIMESTAMP": datetime.datetime.now,
322
+ "CURRENTTIME": datetime.datetime.now,
323
+ "CURRENTDATE": datetime.date.today,
324
+ "STRFTIME": null_if_any(lambda fmt, arg: datetime.datetime.fromisoformat(arg).strftime(fmt)),
325
+ "STRTOTIME": null_if_any(lambda arg, format: datetime.datetime.strptime(arg, format)),
326
+ "TRIM": null_if_any(lambda this, e=None: this.strip(e)),
327
+ "STRUCT": lambda *args: {
328
+ args[x]: args[x + 1]
329
+ for x in range(0, len(args), 2)
330
+ if (args[x + 1] is not None and args[x] is not None)
331
+ },
332
+ "UNIXTOTIME": null_if_any(
333
+ lambda arg: datetime.datetime.fromtimestamp(arg, datetime.timezone.utc)
334
+ ),
335
+ }
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/python.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import itertools
3
+ import math
4
+
5
+ from sqlglot import exp, planner, tokens
6
+ from sqlglot.dialects.dialect import Dialect
7
+ from sqlglot.errors import ExecuteError
8
+ from sqlglot.executor.context import Context
9
+ from sqlglot.executor.env import ENV
10
+ from sqlglot.executor.table import RowReader, Table
11
+ from sqlglot.generators.python import PythonGenerator
12
+ from sqlglot.optimizer.scope import build_scope
13
+
14
+ SUBQUERY_NODES = (exp.Subquery, exp.Exists, exp.All, exp.Any)
15
+
16
+
17
+ class PythonExecutor:
18
+ def __init__(self, env=None, tables=None):
19
+ self.generator = Python().generator(identify=True, comments=False)
20
+ self.env = {**ENV, **(env or {})}
21
+ self.tables = tables or {}
22
+ self._subquery_plans = {}
23
+ self._plan_names_by_sql = {}
24
+ self._ctes = None
25
+ self._outer_scope = None
26
+ self.env.update(
27
+ SUBQUERY_COMPARISON=self._subquery_comparison,
28
+ SUBQUERY_EXISTS=self._subquery_exists,
29
+ SUBQUERY_SCALAR=self._subquery_scalar,
30
+ )
31
+
32
+ def execute(self, plan, outer_scope=None):
33
+ ctes, scope = self._ctes, self._outer_scope
34
+ self._ctes, self._outer_scope = plan.ctes, outer_scope
35
+ try:
36
+ return self._execute(plan)
37
+ finally:
38
+ self._ctes, self._outer_scope = ctes, scope
39
+
40
+ def _execute(self, plan):
41
+ finished = set()
42
+ queue = set(plan.leaves)
43
+ contexts = {}
44
+
45
+ while queue:
46
+ node = queue.pop()
47
+ try:
48
+ context = self.context(
49
+ {
50
+ name: table
51
+ for dep in node.dependencies
52
+ for name, table in contexts[dep].tables.items()
53
+ }
54
+ )
55
+
56
+ if isinstance(node, planner.Scan):
57
+ contexts[node] = self.scan(node, context)
58
+ elif isinstance(node, planner.Aggregate):
59
+ contexts[node] = self.aggregate(node, context)
60
+ elif isinstance(node, planner.Join):
61
+ contexts[node] = self.join(node, context)
62
+ elif isinstance(node, planner.Sort):
63
+ contexts[node] = self.sort(node, context)
64
+ elif isinstance(node, planner.SetOperation):
65
+ contexts[node] = self.set_operation(node, context)
66
+ else:
67
+ raise NotImplementedError
68
+
69
+ if node.offset:
70
+ table = contexts[node].tables[node.name]
71
+ table.rows = table.rows[node.offset :]
72
+
73
+ finished.add(node)
74
+
75
+ for dep in node.dependents:
76
+ if all(d in contexts for d in dep.dependencies):
77
+ queue.add(dep)
78
+
79
+ for dep in node.dependencies:
80
+ if all(d in finished for d in dep.dependents):
81
+ contexts.pop(dep)
82
+ except Exception as e:
83
+ raise ExecuteError(f"Step '{node.id}' failed: {e}") from e
84
+
85
+ root = plan.root
86
+ return contexts[root].tables[root.name]
87
+
88
+ def generate(self, expression):
89
+ """Convert a SQL expression into literal Python code and compile it into bytecode."""
90
+ if not expression:
91
+ return None
92
+
93
+ expression = self._replace_subqueries(expression)
94
+ sql = self.generator.generate(expression)
95
+ return compile(sql, sql, "eval", optimize=2)
96
+
97
+ def _replace_subqueries(self, expression):
98
+ if not expression.find(*SUBQUERY_NODES):
99
+ return expression
100
+
101
+ expression = expression.copy()
102
+
103
+ while True:
104
+ subquery = expression.find(*SUBQUERY_NODES)
105
+
106
+ if subquery is None:
107
+ return expression
108
+
109
+ target, replacement = self._compile_subquery(subquery)
110
+
111
+ if target is expression:
112
+ expression = replacement
113
+ else:
114
+ target.replace(replacement)
115
+
116
+ def _compile_subquery(self, subquery):
117
+ query = subquery.this.unnest()
118
+ scope = build_scope(query)
119
+
120
+ outer_columns = list(scope.external_columns if scope else [])
121
+
122
+ plan = self._register_subquery(query)
123
+ parent = subquery.parent
124
+
125
+ if isinstance(subquery, exp.Exists):
126
+ return subquery, exp.func(
127
+ "SUBQUERY_EXISTS", plan, exp.var("scope"), *outer_columns, copy=False
128
+ )
129
+
130
+ if len(query.selects) != 1:
131
+ raise ExecuteError(
132
+ f"Subquery used as an expression returned {len(query.selects)} columns"
133
+ )
134
+
135
+ if isinstance(subquery, (exp.All, exp.Any)):
136
+ return self._compile_quantified(parent, subquery.key.upper(), plan, outer_columns)
137
+
138
+ if isinstance(parent, exp.In) and subquery is parent.args.get("query"):
139
+ return self._compile_quantified(parent, "ANY", plan, outer_columns, op="EQ")
140
+
141
+ return subquery, exp.func(
142
+ "SUBQUERY_SCALAR", plan, exp.var("scope"), *outer_columns, copy=False
143
+ )
144
+
145
+ def _compile_quantified(self, comparison, quantifier, plan, outer_columns, op=None):
146
+ if not isinstance(comparison, (exp.Binary, exp.In)):
147
+ raise ExecuteError(f"Unsupported {quantifier} subquery: expected a comparison")
148
+
149
+ return comparison, exp.func(
150
+ "SUBQUERY_COMPARISON",
151
+ comparison.this,
152
+ plan,
153
+ exp.var("scope"),
154
+ exp.Literal.string(op or comparison.key.upper()),
155
+ exp.Literal.string(quantifier),
156
+ *outer_columns,
157
+ copy=False,
158
+ )
159
+
160
+ def _register_subquery(self, query):
161
+ if self._ctes is not None and not query.args.get("with_"):
162
+ query.set("with_", self._ctes)
163
+
164
+ sql = query.sql()
165
+ name = self._plan_names_by_sql.get(sql)
166
+
167
+ if name is None:
168
+ name = self._plan_names_by_sql[sql] = f"_sq_{len(self._subquery_plans)}"
169
+ self._subquery_plans[name] = (planner.Plan(query), {})
170
+
171
+ return exp.Literal.string(name)
172
+
173
+ def _subquery_table(self, plan_name, scope, args):
174
+ plan, cache = self._subquery_plans[plan_name]
175
+
176
+ try:
177
+ return cache[args]
178
+ except KeyError:
179
+ pass
180
+ except TypeError: # an unhashable correlated value can't be memoized
181
+ cache = None
182
+
183
+ table = self.execute(plan, scope)
184
+
185
+ if cache is not None:
186
+ cache[args] = table
187
+
188
+ return table
189
+
190
+ def _subquery_exists(self, plan_name, scope, *args):
191
+ return bool(self._subquery_table(plan_name, scope, args).rows)
192
+
193
+ def _subquery_scalar(self, plan_name, scope, *args):
194
+ rows = self._subquery_table(plan_name, scope, args).rows
195
+
196
+ if len(rows) > 1:
197
+ raise ExecuteError("More than one row returned by a subquery used as an expression")
198
+
199
+ return rows[0][0] if rows else None
200
+
201
+ def _subquery_comparison(self, value, plan_name, scope, op, quantifier, *args):
202
+ compare = self.env[op]
203
+ is_any = quantifier == "ANY"
204
+ saw_null = False
205
+
206
+ for row in self._subquery_table(plan_name, scope, args).rows:
207
+ result = compare(value, row[0])
208
+
209
+ if result is None:
210
+ saw_null = True
211
+ elif bool(result) is is_any:
212
+ return is_any
213
+
214
+ return None if saw_null else not is_any
215
+
216
+ def generate_tuple(self, expressions):
217
+ """Convert an array of SQL expressions into tuple of Python byte code."""
218
+ if not expressions:
219
+ return tuple()
220
+ return tuple(self.generate(expression) for expression in expressions)
221
+
222
+ def context(self, tables):
223
+ return Context(tables, env=self.env, outer=self._outer_scope)
224
+
225
+ def table(self, expressions):
226
+ return Table(
227
+ expression.alias_or_name if isinstance(expression, exp.Expr) else expression
228
+ for expression in expressions
229
+ )
230
+
231
+ def scan(self, step, context):
232
+ source = step.source
233
+
234
+ if source and isinstance(source, exp.Expr):
235
+ source = source.name or source.alias
236
+
237
+ if source is None:
238
+ context, table_iter = self.static()
239
+ elif source in context:
240
+ if not step.projections and not step.condition:
241
+ return self.context({step.name: context.tables[source]})
242
+ table_iter = context.table_iter(source)
243
+ else:
244
+ context, table_iter = self.scan_table(step)
245
+
246
+ return self.context({step.name: self._project_and_filter(context, step, table_iter)})
247
+
248
+ def _project_and_filter(self, context, step, table_iter):
249
+ sink = self.table(step.projections if step.projections else context.columns)
250
+ condition = self.generate(step.condition)
251
+ projections = self.generate_tuple(step.projections)
252
+
253
+ for reader in table_iter:
254
+ if len(sink) >= step.offset + step.limit:
255
+ break
256
+
257
+ if condition and not context.eval(condition):
258
+ continue
259
+
260
+ if projections:
261
+ sink.append(context.eval_tuple(projections))
262
+ else:
263
+ sink.append(reader.row)
264
+
265
+ return sink
266
+
267
+ def static(self):
268
+ return self.context({}), [RowReader(())]
269
+
270
+ def scan_table(self, step):
271
+ table = self.tables.find(step.source)
272
+ context = self.context({step.source.alias_or_name: table})
273
+ return context, iter(table)
274
+
275
+ def join(self, step, context):
276
+ source = step.source_name
277
+
278
+ source_table = context.tables[source]
279
+ source_context = self.context({source: source_table})
280
+ column_ranges = {source: range(0, len(source_table.columns))}
281
+
282
+ for name, join in step.joins.items():
283
+ table = context.tables[name]
284
+ start = max(r.stop for r in column_ranges.values())
285
+ column_ranges[name] = range(start, len(table.columns) + start)
286
+ join_context = self.context({name: table})
287
+ condition = self.generate(join["condition"])
288
+ condition_context = (
289
+ self.context(
290
+ {
291
+ name: Table(
292
+ source_context.columns + join_context.columns,
293
+ column_range=column_range,
294
+ )
295
+ for name, column_range in column_ranges.items()
296
+ }
297
+ )
298
+ if condition
299
+ else None
300
+ )
301
+
302
+ if join.get("source_key"):
303
+ table = self.hash_join(
304
+ join, source_context, join_context, condition, condition_context
305
+ )
306
+ else:
307
+ table = self.nested_loop_join(
308
+ join, source_context, join_context, condition, condition_context
309
+ )
310
+
311
+ source_context = self.context(
312
+ {
313
+ name: Table(table.columns, table.rows, column_range)
314
+ for name, column_range in column_ranges.items()
315
+ }
316
+ )
317
+ if not step.condition and not step.projections:
318
+ return source_context
319
+
320
+ sink = self._project_and_filter(
321
+ source_context,
322
+ step,
323
+ (reader for reader, _ in iter(source_context)),
324
+ )
325
+
326
+ if step.projections:
327
+ return self.context({step.name: sink})
328
+ else:
329
+ return self.context(
330
+ {
331
+ name: Table(table.columns, sink.rows, table.column_range)
332
+ for name, table in source_context.tables.items()
333
+ }
334
+ )
335
+
336
+ @staticmethod
337
+ def _join_matches(row, condition, condition_context):
338
+ if not condition:
339
+ return True
340
+
341
+ condition_context.set_row(row)
342
+ return condition_context.eval(condition) is True
343
+
344
+ def nested_loop_join(self, join, source_context, join_context, condition, condition_context):
345
+ table = Table(source_context.columns + join_context.columns)
346
+ source_rows = source_context.table.rows
347
+ join_rows = join_context.table.rows
348
+ matched_source = set()
349
+ matched_join = set()
350
+
351
+ for source_index, source_row in enumerate(source_rows):
352
+ for join_index, join_row in enumerate(join_rows):
353
+ row = source_row + join_row
354
+ if self._join_matches(row, condition, condition_context):
355
+ table.append(row)
356
+ matched_source.add(source_index)
357
+ matched_join.add(join_index)
358
+
359
+ self._append_unmatched_join_rows(
360
+ table, join, source_rows, join_rows, matched_source, matched_join
361
+ )
362
+
363
+ return table
364
+
365
+ def hash_join(self, join, source_context, join_context, condition, condition_context):
366
+ source_key = self.generate_tuple(join["source_key"])
367
+ join_key = self.generate_tuple(join["join_key"])
368
+ results = collections.defaultdict(lambda: ([], []))
369
+
370
+ for index, (reader, ctx) in enumerate(source_context):
371
+ key = ctx.eval_tuple(source_key)
372
+ if all(value is not None for value in key):
373
+ results[key][0].append((index, reader.row))
374
+ for index, (reader, ctx) in enumerate(join_context):
375
+ key = ctx.eval_tuple(join_key)
376
+ if all(value is not None for value in key):
377
+ results[key][1].append((index, reader.row))
378
+
379
+ table = Table(source_context.columns + join_context.columns)
380
+ matched_source = set()
381
+ matched_join = set()
382
+
383
+ for source_group, join_group in results.values():
384
+ for (source_index, source_row), (join_index, join_row) in itertools.product(
385
+ source_group, join_group
386
+ ):
387
+ row = source_row + join_row
388
+ if self._join_matches(row, condition, condition_context):
389
+ table.append(row)
390
+ matched_source.add(source_index)
391
+ matched_join.add(join_index)
392
+
393
+ self._append_unmatched_join_rows(
394
+ table,
395
+ join,
396
+ source_context.table.rows,
397
+ join_context.table.rows,
398
+ matched_source,
399
+ matched_join,
400
+ )
401
+
402
+ return table
403
+
404
+ @staticmethod
405
+ def _append_unmatched_join_rows(
406
+ table, join, source_rows, join_rows, matched_source, matched_join
407
+ ):
408
+ side = join.get("side")
409
+ if side in ("LEFT", "FULL"):
410
+ join_nulls = (None,) * (len(table.columns) - len(source_rows[0]) if source_rows else 0)
411
+ for index, row in enumerate(source_rows):
412
+ if index not in matched_source:
413
+ table.append(row + join_nulls)
414
+
415
+ if side in ("RIGHT", "FULL"):
416
+ source_width = len(table.columns) - (len(join_rows[0]) if join_rows else 0)
417
+ source_nulls = (None,) * source_width
418
+ for index, row in enumerate(join_rows):
419
+ if index not in matched_join:
420
+ table.append(source_nulls + row)
421
+
422
+ def aggregate(self, step, context):
423
+ group_by = self.generate_tuple(step.group.values())
424
+ aggregations = self.generate_tuple(step.aggregations)
425
+ operands = self.generate_tuple(step.operands)
426
+
427
+ if operands:
428
+ operand_table = Table(self.table(step.operands).columns)
429
+
430
+ for reader, ctx in context:
431
+ operand_table.append(ctx.eval_tuple(operands))
432
+
433
+ for i, (a, b) in enumerate(zip(context.table.rows, operand_table.rows)):
434
+ context.table.rows[i] = a + b
435
+
436
+ width = len(context.columns)
437
+ context.add_columns(*operand_table.columns)
438
+
439
+ operand_table = Table(
440
+ context.columns,
441
+ context.table.rows,
442
+ range(width, width + len(operand_table.columns)),
443
+ )
444
+
445
+ context = self.context(
446
+ {
447
+ None: operand_table,
448
+ **context.tables,
449
+ }
450
+ )
451
+
452
+ context.sort(group_by)
453
+
454
+ group = None
455
+ start = 0
456
+ end = 1
457
+ length = len(context.table)
458
+ table = self.table(list(step.group) + step.aggregations)
459
+
460
+ def add_row():
461
+ table.append(group + context.eval_tuple(aggregations))
462
+
463
+ if length:
464
+ for i in range(length):
465
+ context.set_index(i)
466
+ key = context.eval_tuple(group_by)
467
+ group = key if group is None else group
468
+ end += 1
469
+ if key != group:
470
+ context.set_range(start, end - 2)
471
+ add_row()
472
+ group = key
473
+ start = end - 2
474
+ if not step.condition and len(table.rows) >= step.offset + step.limit:
475
+ break
476
+ if i == length - 1:
477
+ context.set_range(start, end - 1)
478
+ add_row()
479
+ elif step.limit > 0 and not group_by:
480
+ context.set_range(0, 0)
481
+ table.append(context.eval_tuple(aggregations))
482
+
483
+ context = self.context({step.name: table, **{name: table for name in context.tables}})
484
+
485
+ if step.projections or step.condition:
486
+ return self.context(
487
+ {step.name: self._project_and_filter(context, step, context.table_iter(step.name))}
488
+ )
489
+ return context
490
+
491
+ def sort(self, step, context):
492
+ projections = self.generate_tuple(step.projections)
493
+ projection_columns = [p.alias_or_name for p in step.projections]
494
+ all_columns = list(context.columns) + projection_columns
495
+ sink = self.table(all_columns)
496
+ for reader, ctx in context:
497
+ sink.append(reader.row + ctx.eval_tuple(projections))
498
+
499
+ sort_ctx = self.context(
500
+ {
501
+ None: sink,
502
+ **{table: sink for table in context.tables},
503
+ }
504
+ )
505
+ sort_ctx.sort(self.generate_tuple(step.key))
506
+
507
+ if not math.isinf(step.limit):
508
+ sort_ctx.table.rows = sort_ctx.table.rows[0 : step.offset + step.limit]
509
+
510
+ rows = sort_ctx.table.rows
511
+
512
+ if projection_columns:
513
+ rows = [row[len(context.columns) : len(all_columns)] for row in rows]
514
+
515
+ output = Table(projection_columns or context.columns, rows=rows)
516
+ return self.context({step.name: output})
517
+
518
+ def set_operation(self, step, context):
519
+ left = context.tables[step.left]
520
+ right = context.tables[step.right]
521
+
522
+ sink = self.table(left.columns)
523
+
524
+ if issubclass(step.op, exp.Intersect):
525
+ right_counts = collections.Counter(right.rows)
526
+ seen = set()
527
+ for row in left.rows:
528
+ if right_counts[row] and (not step.distinct or row not in seen):
529
+ sink.append(row)
530
+ seen.add(row)
531
+ if not step.distinct:
532
+ right_counts[row] -= 1
533
+ elif issubclass(step.op, exp.Except):
534
+ right_counts = collections.Counter(right.rows)
535
+ seen = set()
536
+ for row in left.rows:
537
+ if right_counts[row] and not step.distinct:
538
+ right_counts[row] -= 1
539
+ elif not right_counts[row] and (not step.distinct or row not in seen):
540
+ sink.append(row)
541
+ seen.add(row)
542
+ elif issubclass(step.op, exp.Union) and step.distinct:
543
+ sink.rows = list(set(left.rows).union(set(right.rows)))
544
+ else:
545
+ sink.rows = left.rows + right.rows
546
+
547
+ if not math.isinf(step.limit):
548
+ sink.rows = sink.rows[0 : step.offset + step.limit]
549
+
550
+ return self.context({step.name: sink})
551
+
552
+
553
+ class Python(Dialect):
554
+ class Tokenizer(tokens.Tokenizer):
555
+ STRING_ESCAPES = ["\\"]
556
+
557
+ Generator = PythonGenerator
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/executor/table.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing as t
4
+
5
+ from sqlglot.dialects.dialect import DialectType
6
+ from sqlglot.helper import dict_depth
7
+ from sqlglot.schema import AbstractMappingSchema, normalize_name
8
+
9
+
10
+ class Table:
11
+ def __init__(
12
+ self,
13
+ columns: t.Any = None,
14
+ rows: t.Any = None,
15
+ column_range: range | None = None,
16
+ ) -> None:
17
+ self.columns: t.Any = tuple(columns) if columns is not None else ()
18
+ self.column_range = column_range
19
+ self.reader: t.Any = RowReader(self.columns, self.column_range)
20
+ self.rows: t.Any = rows or []
21
+ if rows:
22
+ assert len(rows[0]) == len(self.columns)
23
+ self.range_reader = RangeReader(self)
24
+
25
+ def add_columns(self, *columns: str) -> None:
26
+ self.columns += columns
27
+ if self.column_range:
28
+ self.column_range = range(
29
+ self.column_range.start, self.column_range.stop + len(columns)
30
+ )
31
+ self.reader = RowReader(self.columns, self.column_range)
32
+
33
+ def append(self, row: t.Any) -> None:
34
+ assert len(row) == len(self.columns)
35
+ self.rows.append(row)
36
+
37
+ def pop(self) -> None:
38
+ self.rows.pop()
39
+
40
+ def to_pylist(self) -> list:
41
+ return [dict(zip(self.columns, row)) for row in self.rows]
42
+
43
+ @property
44
+ def width(self) -> int:
45
+ return len(self.columns)
46
+
47
+ def __len__(self) -> int:
48
+ return len(self.rows)
49
+
50
+ def __iter__(self) -> TableIter:
51
+ return TableIter(self)
52
+
53
+ def __getitem__(self, index: int) -> RowReader:
54
+ self.reader.row = self.rows[index]
55
+ return self.reader
56
+
57
+ def __repr__(self) -> str:
58
+ columns = tuple(
59
+ column
60
+ for i, column in enumerate(self.columns)
61
+ if not self.column_range or i in self.column_range
62
+ )
63
+ widths = {column: len(column) for column in columns}
64
+ lines = [" ".join(column for column in columns)]
65
+
66
+ for i, row in enumerate(self):
67
+ if i > 10:
68
+ break
69
+
70
+ lines.append(
71
+ " ".join(
72
+ str(row[column]).rjust(widths[column])[0 : widths[column]] for column in columns
73
+ )
74
+ )
75
+ return "\n".join(lines)
76
+
77
+
78
+ class TableIter:
79
+ def __init__(self, table: Table) -> None:
80
+ self.table = table
81
+ self.index = -1
82
+
83
+ def __iter__(self) -> TableIter:
84
+ return self
85
+
86
+ def __next__(self) -> RowReader:
87
+ self.index += 1
88
+ if self.index < len(self.table):
89
+ return self.table[self.index]
90
+ raise StopIteration
91
+
92
+
93
+ class RangeReader:
94
+ def __init__(self, table: t.Any = None) -> None:
95
+ self.table: t.Any = table
96
+ self.range = range(0)
97
+
98
+ def __len__(self) -> int:
99
+ return len(self.range)
100
+
101
+ def __getitem__(self, column: str):
102
+ return (self.table[i][column] for i in self.range)
103
+
104
+
105
+ class RowReader:
106
+ def __init__(self, columns=None, column_range=None):
107
+ self.columns = (
108
+ {column: i for i, column in enumerate(columns) if not column_range or i in column_range}
109
+ if columns is not None
110
+ else {}
111
+ )
112
+ self.row = ()
113
+
114
+ def __getitem__(self, column):
115
+ return self.row[self.columns[column]]
116
+
117
+
118
+ class Tables(AbstractMappingSchema):
119
+ pass
120
+
121
+
122
+ def ensure_tables(d: dict | None, dialect: DialectType = None) -> Tables:
123
+ return Tables(_ensure_tables(d, dialect=dialect))
124
+
125
+
126
+ def _ensure_tables(d: dict | None, dialect: DialectType = None) -> dict:
127
+ if not d:
128
+ return {}
129
+
130
+ depth = dict_depth(d)
131
+ if depth > 1:
132
+ return {
133
+ normalize_name(k, dialect=dialect, is_table=True).name: _ensure_tables(
134
+ v, dialect=dialect
135
+ )
136
+ for k, v in d.items()
137
+ }
138
+
139
+ result = {}
140
+ for table_name, table in d.items():
141
+ table_name = normalize_name(table_name, dialect=dialect).name
142
+
143
+ if isinstance(table, Table):
144
+ result[table_name] = table
145
+ else:
146
+ table = [
147
+ {
148
+ normalize_name(column_name, dialect=dialect).name: value
149
+ for column_name, value in row.items()
150
+ }
151
+ for row in table
152
+ ]
153
+ column_names = tuple(column_name for column_name in table[0]) if table else ()
154
+ rows = [tuple(row[name] for name in column_names) for row in table]
155
+ result[table_name] = Table(columns=column_names, rows=rows)
156
+
157
+ return result
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/__init__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ruff: noqa: F405
2
+ """
3
+ ## Exprs
4
+
5
+ Every AST node in SQLGlot is represented by a subclass of `Expr`.
6
+
7
+ This module contains the implementation of all supported `Expr` types. Additionally,
8
+ it exposes a number of helper functions, which are mainly used to programmatically build
9
+ SQL expressions, such as `sqlglot.expressions.select`.
10
+
11
+ ----
12
+ """
13
+
14
+ from sqlglot.expressions.core import * # noqa: F401,F403
15
+ from sqlglot.expressions.datatypes import * # noqa: F401,F403
16
+ from sqlglot.expressions.constraints import * # noqa: F401,F403
17
+ from sqlglot.expressions.properties import * # noqa: F401,F403
18
+ from sqlglot.expressions.query import * # noqa: F401,F403
19
+ from sqlglot.expressions.ddl import * # noqa: F401,F403
20
+ from sqlglot.expressions.dml import * # noqa: F401,F403
21
+ from sqlglot.expressions.math import * # noqa: F401,F403
22
+ from sqlglot.expressions.string import * # noqa: F401,F403
23
+ from sqlglot.expressions.temporal import * # noqa: F401,F403
24
+ from sqlglot.expressions.aggregate import * # noqa: F401,F403
25
+ from sqlglot.expressions.array import * # noqa: F401,F403
26
+ from sqlglot.expressions.json import * # noqa: F401,F403
27
+ from sqlglot.expressions.functions import * # noqa: F401,F403
28
+ from sqlglot.expressions.builders import * # noqa: F401,F403
29
+
30
+ # Explicitly import private helpers (not exported by star imports)
31
+ from sqlglot.expressions.core import ( # noqa: F401,E402
32
+ Expression,
33
+ _apply_builder,
34
+ _apply_child_list_builder,
35
+ _apply_list_builder,
36
+ _apply_conjunction_builder,
37
+ _apply_set_operation,
38
+ _combine,
39
+ _wrap,
40
+ _is_wrong_expression,
41
+ _to_s,
42
+ )
43
+ from sqlglot.expressions.query import _apply_cte_builder # noqa: F401,E402
44
+ from sqlglot.expressions.dml import DML # noqa: F401,E402
45
+ from sqlglot.expressions.array import _ExplodeOuter # noqa: F401,E402
46
+
47
+ from sqlglot.helper import subclasses
48
+
49
+ ALL_FUNCTIONS = subclasses(__name__, Func, {AggFunc, Anonymous, Func})
50
+ FUNCTION_BY_NAME = {name: func for func in ALL_FUNCTIONS for name in func.sql_names()}
51
+ EXPR_CLASSES: dict[str, type[Expr]] = {cls.key: cls for cls in subclasses(__name__, Expr)}
52
+
53
+ # Functions that can return multiple rows. We include anonymous functions conservatively.
54
+ SET_RETURNING_FUNCTIONS = (Anonymous, UDTF, ExplodingGenerateSeries)
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/aggregate.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions - aggregate, window, and statistical functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlglot.expressions.core import Expression, Func, AggFunc, Binary
6
+
7
+
8
+ class Agg(Expression, AggFunc):
9
+ @property
10
+ def output_name(self) -> str:
11
+ return self.this.name
12
+
13
+
14
+ class AIAgg(Expression, AggFunc):
15
+ arg_types = {"this": True, "expression": True}
16
+ _sql_names = ["AI_AGG"]
17
+
18
+
19
+ class AISummarizeAgg(Expression, AggFunc):
20
+ _sql_names = ["AI_SUMMARIZE_AGG"]
21
+
22
+
23
+ class AnyValue(Expression, AggFunc):
24
+ pass
25
+
26
+
27
+ class ApproximateSimilarity(Expression, AggFunc):
28
+ _sql_names = ["APPROXIMATE_SIMILARITY", "APPROXIMATE_JACCARD_INDEX"]
29
+
30
+
31
+ class ApproxPercentileAccumulate(Expression, AggFunc):
32
+ pass
33
+
34
+
35
+ class ApproxPercentileCombine(Expression, AggFunc):
36
+ pass
37
+
38
+
39
+ class ApproxPercentileEstimate(Expression, Func):
40
+ arg_types = {"this": True, "percentile": True}
41
+
42
+
43
+ class ApproxQuantiles(Expression, AggFunc):
44
+ arg_types = {"this": True, "expression": False}
45
+
46
+
47
+ class ApproxTopK(Expression, AggFunc):
48
+ arg_types = {"this": True, "expression": False, "counters": False}
49
+
50
+
51
+ class ApproxTopKAccumulate(Expression, AggFunc):
52
+ arg_types = {"this": True, "expression": False}
53
+
54
+
55
+ class ApproxTopKCombine(Expression, AggFunc):
56
+ arg_types = {"this": True, "expression": False}
57
+
58
+
59
+ class ApproxTopKEstimate(Expression, Func):
60
+ arg_types = {"this": True, "expression": False}
61
+
62
+
63
+ class ApproxTopSum(Expression, AggFunc):
64
+ arg_types = {"this": True, "expression": True, "count": True}
65
+
66
+
67
+ class ArgMax(Expression, AggFunc):
68
+ arg_types = {"this": True, "expression": True, "count": False}
69
+ _sql_names = ["ARG_MAX", "ARGMAX", "MAX_BY"]
70
+
71
+
72
+ class ArgMin(Expression, AggFunc):
73
+ arg_types = {"this": True, "expression": True, "count": False}
74
+ _sql_names = ["ARG_MIN", "ARGMIN", "MIN_BY"]
75
+
76
+
77
+ class ArrayAgg(Expression, AggFunc):
78
+ arg_types = {"this": True, "nulls_excluded": False}
79
+
80
+
81
+ class ArrayConcatAgg(Expression, AggFunc):
82
+ pass
83
+
84
+
85
+ class ArrayUnionAgg(Expression, AggFunc):
86
+ pass
87
+
88
+
89
+ class ArrayUniqueAgg(Expression, AggFunc):
90
+ pass
91
+
92
+
93
+ class Avg(Expression, AggFunc):
94
+ pass
95
+
96
+
97
+ class Corr(Expression, AggFunc, Binary):
98
+ # Correlation divides by variance(column). If a column has 0 variance, the denominator
99
+ # is 0 - some dialects return NaN (DuckDB) while others return NULL (Snowflake).
100
+ # `null_on_zero_variance` is set to True at parse time for dialects that return NULL.
101
+ arg_types = {"this": True, "expression": True, "null_on_zero_variance": False}
102
+
103
+
104
+ class Count(Expression, AggFunc):
105
+ arg_types = {"this": False, "expressions": False, "big_int": False}
106
+ is_var_len_args = True
107
+
108
+
109
+ class CountIf(Expression, AggFunc):
110
+ _sql_names = ["COUNT_IF", "COUNTIF"]
111
+ arg_types = {"this": True, "zero_on_all_null": False}
112
+
113
+
114
+ class CovarPop(Expression, AggFunc):
115
+ arg_types = {"this": True, "expression": True}
116
+
117
+
118
+ class CovarSamp(Expression, AggFunc):
119
+ arg_types = {"this": True, "expression": True}
120
+
121
+
122
+ class CumeDist(Expression, AggFunc):
123
+ arg_types = {"expressions": False}
124
+ is_var_len_args = True
125
+
126
+
127
+ class DenseRank(Expression, AggFunc):
128
+ arg_types = {"expressions": False}
129
+ is_var_len_args = True
130
+
131
+
132
+ class First(Expression, AggFunc):
133
+ arg_types = {"this": True, "expression": False}
134
+
135
+
136
+ class FirstValue(Expression, AggFunc):
137
+ pass
138
+
139
+
140
+ class GroupConcat(Expression, AggFunc):
141
+ arg_types = {"this": True, "separator": False, "on_overflow": False}
142
+
143
+
144
+ class Grouping(Expression, AggFunc):
145
+ arg_types = {"expressions": True}
146
+ is_var_len_args = True
147
+
148
+
149
+ class GroupingId(Expression, AggFunc):
150
+ arg_types = {"expressions": False}
151
+ is_var_len_args = True
152
+
153
+
154
+ class Kurtosis(Expression, AggFunc):
155
+ pass
156
+
157
+
158
+ class Lag(Expression, AggFunc):
159
+ arg_types = {"this": True, "offset": False, "default": False}
160
+
161
+
162
+ class Last(Expression, AggFunc):
163
+ arg_types = {"this": True, "expression": False}
164
+
165
+
166
+ class LastValue(Expression, AggFunc):
167
+ pass
168
+
169
+
170
+ class Lead(Expression, AggFunc):
171
+ arg_types = {"this": True, "offset": False, "default": False}
172
+
173
+
174
+ class LogicalAnd(Expression, AggFunc):
175
+ _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
176
+
177
+
178
+ class LogicalOr(Expression, AggFunc):
179
+ _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
180
+
181
+
182
+ class Max(Expression, AggFunc):
183
+ arg_types = {"this": True, "expressions": False}
184
+ is_var_len_args = True
185
+
186
+
187
+ class Median(Expression, AggFunc):
188
+ pass
189
+
190
+
191
+ class Min(Expression, AggFunc):
192
+ arg_types = {"this": True, "expressions": False}
193
+ is_var_len_args = True
194
+
195
+
196
+ class Minhash(Expression, AggFunc):
197
+ arg_types = {"this": True, "expressions": True}
198
+ is_var_len_args = True
199
+
200
+
201
+ class MinhashCombine(Expression, AggFunc):
202
+ pass
203
+
204
+
205
+ class Mode(Expression, AggFunc):
206
+ arg_types = {"this": False, "deterministic": False}
207
+
208
+
209
+ class Ntile(Expression, AggFunc):
210
+ arg_types = {"this": False}
211
+
212
+
213
+ class NthValue(Expression, AggFunc):
214
+ arg_types = {"this": True, "offset": True, "from_first": False}
215
+
216
+
217
+ class ObjectAgg(Expression, AggFunc):
218
+ arg_types = {"this": True, "expression": False}
219
+
220
+
221
+ class PercentileCont(Expression, AggFunc):
222
+ arg_types = {"this": True, "expression": False}
223
+
224
+
225
+ class PercentileDisc(Expression, AggFunc):
226
+ arg_types = {"this": True, "expression": False}
227
+
228
+
229
+ PERCENTILES = (PercentileCont, PercentileDisc)
230
+
231
+
232
+ class PercentRank(Expression, AggFunc):
233
+ arg_types = {"expressions": False}
234
+ is_var_len_args = True
235
+
236
+
237
+ class Quantile(Expression, AggFunc):
238
+ arg_types = {"this": True, "quantile": True}
239
+
240
+
241
+ class ApproxQuantile(Quantile):
242
+ arg_types = {
243
+ "this": True,
244
+ "quantile": True,
245
+ "accuracy": False,
246
+ "weight": False,
247
+ "error_tolerance": False,
248
+ }
249
+
250
+
251
+ class Rank(Expression, AggFunc):
252
+ arg_types = {"expressions": False}
253
+ is_var_len_args = True
254
+
255
+
256
+ class RegrAvgx(Expression, AggFunc):
257
+ arg_types = {"this": True, "expression": True}
258
+
259
+
260
+ class RegrAvgy(Expression, AggFunc):
261
+ arg_types = {"this": True, "expression": True}
262
+
263
+
264
+ class RegrCount(Expression, AggFunc):
265
+ arg_types = {"this": True, "expression": False}
266
+
267
+
268
+ class RegrIntercept(Expression, AggFunc):
269
+ arg_types = {"this": True, "expression": False}
270
+
271
+
272
+ class RegrR2(Expression, AggFunc):
273
+ arg_types = {"this": True, "expression": False}
274
+
275
+
276
+ class RegrSlope(Expression, AggFunc):
277
+ arg_types = {"this": True, "expression": False}
278
+
279
+
280
+ class RegrSxx(Expression, AggFunc):
281
+ arg_types = {"this": True, "expression": True}
282
+
283
+
284
+ class RegrSxy(Expression, AggFunc):
285
+ arg_types = {"this": True, "expression": True}
286
+
287
+
288
+ class RegrSyy(Expression, AggFunc):
289
+ arg_types = {"this": True, "expression": True}
290
+
291
+
292
+ class RegrValx(Expression, AggFunc):
293
+ arg_types = {"this": True, "expression": True}
294
+
295
+
296
+ class RegrValy(Expression, AggFunc):
297
+ arg_types = {"this": True, "expression": True}
298
+
299
+
300
+ class RowNumber(Expression, Func):
301
+ arg_types = {"this": False}
302
+
303
+
304
+ class Skewness(Expression, AggFunc):
305
+ pass
306
+
307
+
308
+ class Stddev(Expression, AggFunc):
309
+ _sql_names = ["STDDEV", "STDEV"]
310
+
311
+
312
+ class StddevPop(Expression, AggFunc):
313
+ pass
314
+
315
+
316
+ class StddevSamp(Expression, AggFunc):
317
+ pass
318
+
319
+
320
+ class Sum(Expression, AggFunc):
321
+ pass
322
+
323
+
324
+ class Variance(Expression, AggFunc):
325
+ _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
326
+
327
+
328
+ class VariancePop(Expression, AggFunc):
329
+ _sql_names = ["VARIANCE_POP", "VAR_POP"]
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/array.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions - array, map, struct, and table-valued functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ from sqlglot.expressions.core import (
7
+ Expression,
8
+ Expr,
9
+ Func,
10
+ Binary,
11
+ Predicate,
12
+ to_identifier,
13
+ )
14
+ from sqlglot.helper import trait
15
+ from sqlglot.expressions.query import UDTF
16
+
17
+
18
+ # Array creation / construction
19
+
20
+
21
+ class Array(Expression, Func):
22
+ arg_types = {
23
+ "expressions": False,
24
+ "bracket_notation": False,
25
+ "struct_name_inheritance": False,
26
+ "value_constructor": False,
27
+ }
28
+ is_var_len_args = True
29
+
30
+
31
+ class ArrayConstructCompact(Expression, Func):
32
+ arg_types = {"expressions": False}
33
+ is_var_len_args = True
34
+
35
+
36
+ class List(Expression, Func):
37
+ arg_types = {"expressions": False}
38
+ is_var_len_args = True
39
+
40
+
41
+ class ToArray(Expression, Func):
42
+ pass
43
+
44
+
45
+ # Array manipulation
46
+
47
+
48
+ class ArrayAppend(Expression, Func):
49
+ arg_types = {"this": True, "expression": True, "null_propagation": False}
50
+
51
+
52
+ class ArrayCompact(Expression, Func):
53
+ pass
54
+
55
+
56
+ class ArrayConcat(Expression, Func):
57
+ _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
58
+ arg_types = {"this": True, "expressions": False, "null_propagation": False}
59
+ is_var_len_args = True
60
+
61
+
62
+ class ArrayFilter(Expression, Func):
63
+ arg_types = {"this": True, "expression": True}
64
+ _sql_names = ["FILTER", "ARRAY_FILTER"]
65
+
66
+
67
+ class ArrayInsert(Expression, Func):
68
+ arg_types = {"this": True, "position": True, "expression": True, "offset": False}
69
+
70
+
71
+ class ArrayPrepend(Expression, Func):
72
+ arg_types = {"this": True, "expression": True, "null_propagation": False}
73
+
74
+
75
+ class ArrayRemove(Expression, Func):
76
+ arg_types = {"this": True, "expression": True, "null_propagation": False}
77
+
78
+
79
+ class ArrayRemoveAt(Expression, Func):
80
+ arg_types = {"this": True, "position": True}
81
+
82
+
83
+ class ArrayReverse(Expression, Func):
84
+ pass
85
+
86
+
87
+ class ArraySlice(Expression, Func):
88
+ """Slice by end index, or by length when is_length is set."""
89
+
90
+ arg_types = {
91
+ "this": True,
92
+ "start": True,
93
+ "end": False,
94
+ "step": False,
95
+ "zero_based": False,
96
+ "is_length": False,
97
+ }
98
+
99
+
100
+ class ArraySort(Expression, Func):
101
+ arg_types = {"this": True, "expression": False, "asc": False, "nulls_first": False}
102
+
103
+
104
+ class Shuffle(Expression, Func):
105
+ pass
106
+
107
+
108
+ # Array predicates / search
109
+
110
+
111
+ class ArrayAll(Expression, Func):
112
+ arg_types = {"this": True, "expression": True}
113
+
114
+
115
+ class ArrayAny(Expression, Func):
116
+ arg_types = {"this": True, "expression": True}
117
+
118
+
119
+ class ArrayContains(Expression, Binary, Predicate, Func):
120
+ arg_types = {"this": True, "expression": True, "ensure_variant": False, "check_null": False}
121
+ _sql_names = ["ARRAY_CONTAINS", "ARRAY_HAS"]
122
+
123
+
124
+ class ArrayContainsAll(Expression, Binary, Predicate, Func):
125
+ _sql_names = ["ARRAY_CONTAINS_ALL", "ARRAY_HAS_ALL"]
126
+
127
+
128
+ class ArrayContainedBy(Expression, Binary, Predicate, Func):
129
+ pass
130
+
131
+
132
+ class ArrayExcept(Expression, Func):
133
+ arg_types = {"this": True, "expression": True, "is_multiset": False}
134
+
135
+
136
+ class ArrayIntersect(Expression, Func):
137
+ arg_types = {"expressions": True, "is_multiset": False}
138
+ is_var_len_args = True
139
+ _sql_names = ["ARRAY_INTERSECT", "ARRAY_INTERSECTION"]
140
+
141
+
142
+ class ArrayOverlaps(Expression, Binary, Predicate, Func):
143
+ arg_types = {"this": True, "expression": True, "null_safe": False}
144
+
145
+
146
+ class ArrayPosition(Expression, Binary, Func):
147
+ arg_types = {"this": True, "expression": True, "zero_based": False}
148
+
149
+
150
+ # Array properties
151
+
152
+
153
+ class ArrayDistinct(Expression, Func):
154
+ arg_types = {"this": True, "check_null": False}
155
+
156
+
157
+ class ArrayFirst(Expression, Func):
158
+ arg_types = {"this": True, "expression": False}
159
+
160
+
161
+ class ArrayLast(Expression, Func):
162
+ pass
163
+
164
+
165
+ class ArrayMax(Expression, Func):
166
+ pass
167
+
168
+
169
+ class ArrayMin(Expression, Func):
170
+ pass
171
+
172
+
173
+ class ArraySize(Expression, Func):
174
+ arg_types = {"this": True, "expression": False}
175
+ _sql_names = ["ARRAY_SIZE", "ARRAY_LENGTH"]
176
+
177
+
178
+ class ArraySum(Expression, Func):
179
+ arg_types = {"this": True, "expression": False}
180
+
181
+
182
+ # Array conversion / utility
183
+
184
+
185
+ class ArraysZip(Expression, Func):
186
+ arg_types = {"expressions": False}
187
+ is_var_len_args = True
188
+
189
+
190
+ class ArrayToString(Expression, Func):
191
+ arg_types = {
192
+ "this": True,
193
+ "expression": True,
194
+ "null": False,
195
+ "null_is_empty": False,
196
+ "null_delim_is_null": False,
197
+ }
198
+ _sql_names = ["ARRAY_TO_STRING", "ARRAY_JOIN"]
199
+
200
+
201
+ class Flatten(Expression, Func):
202
+ pass
203
+
204
+
205
+ class StringToArray(Expression, Func):
206
+ arg_types = {"this": True, "expression": False, "null": False}
207
+ _sql_names = ["STRING_TO_ARRAY", "SPLIT_BY_STRING"]
208
+
209
+
210
+ class StrtokToArray(Expression, Func):
211
+ arg_types = {"this": True, "expression": False}
212
+
213
+
214
+ # Higher-order / lambda
215
+
216
+
217
+ class Apply(Expression, Func):
218
+ arg_types = {"this": True, "expression": True}
219
+
220
+
221
+ class Reduce(Expression, Func):
222
+ arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
223
+
224
+
225
+ class Transform(Expression, Func):
226
+ arg_types = {"this": True, "expression": True}
227
+
228
+
229
+ # Table-valued / UDTF
230
+
231
+
232
+ class GenerateSeries(Expression, Func):
233
+ arg_types = {"start": True, "end": True, "step": False, "is_end_exclusive": False}
234
+
235
+
236
+ class ExplodingGenerateSeries(GenerateSeries):
237
+ pass
238
+
239
+
240
+ class Generator(Expression, Func, UDTF):
241
+ arg_types = {"rowcount": False, "timelimit": False}
242
+
243
+
244
+ class Explode(Expression, Func, UDTF):
245
+ arg_types = {"this": True, "expressions": False}
246
+ is_var_len_args = True
247
+
248
+
249
+ class Inline(Expression, Func, UDTF):
250
+ pass
251
+
252
+
253
+ class SplitToTable(Expression, Func, UDTF):
254
+ arg_types = {"this": True, "expression": True}
255
+
256
+
257
+ class Stack(Expression, Func, UDTF):
258
+ arg_types = {"this": True, "expressions": True}
259
+ is_var_len_args = True
260
+
261
+
262
+ @trait
263
+ class ExplodeOuter(Expr):
264
+ pass
265
+
266
+
267
+ class _ExplodeOuter(Explode, ExplodeOuter):
268
+ _sql_names = ["EXPLODE_OUTER"]
269
+
270
+
271
+ class Posexplode(Explode):
272
+ pass
273
+
274
+
275
+ class PosexplodeOuter(Posexplode, ExplodeOuter):
276
+ pass
277
+
278
+
279
+ class PositionalColumn(Expression):
280
+ pass
281
+
282
+
283
+ class Unnest(Expression, Func, UDTF):
284
+ arg_types = {
285
+ "expressions": True,
286
+ "alias": False,
287
+ "offset": False,
288
+ "explode_array": False,
289
+ }
290
+
291
+ @property
292
+ def selects(self) -> list[Expr]:
293
+ columns = super().selects
294
+ offset = self.args.get("offset")
295
+ if offset:
296
+ columns = columns + [to_identifier("offset") if offset is True else offset]
297
+ return columns
298
+
299
+
300
+ # Map
301
+
302
+
303
+ class Map(Expression, Func):
304
+ arg_types = {"keys": False, "values": False}
305
+
306
+ @property
307
+ def keys(self) -> list[Expr]:
308
+ keys = self.args.get("keys")
309
+ return keys.expressions if keys else []
310
+
311
+ @property
312
+ def values(self) -> list[Expr]:
313
+ values = self.args.get("values")
314
+ return values.expressions if values else []
315
+
316
+
317
+ class MapCat(Expression, Func):
318
+ arg_types = {"this": True, "expression": True}
319
+
320
+
321
+ class MapContainsKey(Expression, Func):
322
+ arg_types = {"this": True, "key": True}
323
+
324
+
325
+ class MapDelete(Expression, Func):
326
+ arg_types = {"this": True, "expressions": True}
327
+ is_var_len_args = True
328
+
329
+
330
+ class MapFromEntries(Expression, Func):
331
+ pass
332
+
333
+
334
+ class MapInsert(Expression, Func):
335
+ arg_types = {"this": True, "key": False, "value": True, "update_flag": False}
336
+
337
+
338
+ class MapKeys(Expression, Func):
339
+ pass
340
+
341
+
342
+ class MapPick(Expression, Func):
343
+ arg_types = {"this": True, "expressions": True}
344
+ is_var_len_args = True
345
+
346
+
347
+ class MapSize(Expression, Func):
348
+ pass
349
+
350
+
351
+ class StarMap(Expression, Func):
352
+ pass
353
+
354
+
355
+ class ToMap(Expression, Func):
356
+ pass
357
+
358
+
359
+ class VarMap(Expression, Func):
360
+ arg_types = {"keys": True, "values": True}
361
+ is_var_len_args = True
362
+ var_len_arg_key = "values"
363
+
364
+ @property
365
+ def keys(self) -> list[Expr]:
366
+ return self.args["keys"].expressions
367
+
368
+ @property
369
+ def values(self) -> list[Expr]:
370
+ return self.args["values"].expressions
371
+
372
+
373
+ # Struct
374
+
375
+
376
+ class Struct(Expression, Func):
377
+ arg_types = {"expressions": False}
378
+ is_var_len_args = True
379
+
380
+
381
+ class StructExtract(Expression, Func):
382
+ arg_types = {"this": True, "expression": True}
383
+
384
+
385
+ # Geospatial
386
+
387
+
388
+ class StDistance(Expression, Func):
389
+ arg_types = {"this": True, "expression": True, "use_spheroid": False}
390
+
391
+
392
+ class StPoint(Expression, Func):
393
+ arg_types = {"this": True, "expression": True, "z": False, "m": False}
394
+ _sql_names = ["ST_POINT", "ST_MAKEPOINT"]
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/builders.py ADDED
@@ -0,0 +1,1197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions builders."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import typing as t
7
+
8
+ from sqlglot.helper import seq_get, ensure_collection, split_num_words
9
+ from sqlglot.errors import ParseError, TokenError
10
+ from sqlglot.expressions.core import (
11
+ Alias,
12
+ Anonymous,
13
+ AtTimeZone,
14
+ Between,
15
+ Binary,
16
+ BitwiseNot,
17
+ Boolean,
18
+ Bracket,
19
+ Column,
20
+ Condition,
21
+ Dot,
22
+ EQ,
23
+ Expr,
24
+ Func,
25
+ Identifier,
26
+ In,
27
+ Literal,
28
+ Neg,
29
+ Not,
30
+ Null,
31
+ Paren,
32
+ Placeholder,
33
+ TABLE_PARTS,
34
+ Var,
35
+ logger,
36
+ SAFE_IDENTIFIER_RE,
37
+ maybe_parse,
38
+ maybe_copy,
39
+ to_identifier,
40
+ convert,
41
+ alias_,
42
+ column,
43
+ )
44
+ from sqlglot.expressions.datatypes import DataType, DType, Interval
45
+ from sqlglot.expressions.query import (
46
+ CTE,
47
+ From,
48
+ Schema,
49
+ Select,
50
+ SetOperation,
51
+ Subquery,
52
+ Table,
53
+ TableAlias,
54
+ Tuple,
55
+ Values,
56
+ Where,
57
+ With,
58
+ Query,
59
+ )
60
+ from sqlglot.expressions.ddl import Alter, AlterRename, Create, RenameColumn
61
+ from sqlglot.expressions.dml import Delete, Insert, Merge, Update, When, Whens
62
+ from sqlglot.expressions.functions import Case, Cast
63
+ from sqlglot.expressions.array import Array
64
+
65
+
66
+ if t.TYPE_CHECKING:
67
+ from collections.abc import Sequence, Iterable, Iterator
68
+ from sqlglot.dialects.dialect import DialectType
69
+ from sqlglot.expressions.core import ExpOrStr
70
+ from sqlglot.expressions.datatypes import DATA_TYPE
71
+ from sqlglot._typing import ParserArgs, ParserNoDialectArgs, E, P
72
+ from typing_extensions import Unpack, Concatenate
73
+
74
+
75
+ def select(
76
+ *expressions: ExpOrStr,
77
+ dialect: DialectType = None,
78
+ copy: bool = True,
79
+ **opts: Unpack[ParserNoDialectArgs],
80
+ ) -> Select:
81
+ """
82
+ Initializes a syntax tree from one or multiple SELECT expressions.
83
+
84
+ Example:
85
+ >>> select("col1", "col2").from_("tbl").sql()
86
+ 'SELECT col1, col2 FROM tbl'
87
+
88
+ Args:
89
+ *expressions: the SQL code string to parse as the expressions of a
90
+ SELECT statement. If an Expr instance is passed, this is used as-is.
91
+ dialect: the dialect used to parse the input expressions (in the case that an
92
+ input expression is a SQL string).
93
+ **opts: other options to use to parse the input expressions (again, in the case
94
+ that an input expression is a SQL string).
95
+
96
+ Returns:
97
+ Select: the syntax tree for the SELECT statement.
98
+ """
99
+ return Select().select(*expressions, dialect=dialect, copy=copy, **opts)
100
+
101
+
102
+ def from_(
103
+ expression: ExpOrStr,
104
+ dialect: DialectType = None,
105
+ copy: bool = True,
106
+ **opts: Unpack[ParserNoDialectArgs],
107
+ ) -> Select:
108
+ """
109
+ Initializes a syntax tree from a FROM expression.
110
+
111
+ Example:
112
+ >>> from_("tbl").select("col1", "col2").sql()
113
+ 'SELECT col1, col2 FROM tbl'
114
+
115
+ Args:
116
+ *expression: the SQL code string to parse as the FROM expressions of a
117
+ SELECT statement. If an Expr instance is passed, this is used as-is.
118
+ dialect: the dialect used to parse the input expression (in the case that the
119
+ input expression is a SQL string).
120
+ **opts: other options to use to parse the input expressions (again, in the case
121
+ that the input expression is a SQL string).
122
+
123
+ Returns:
124
+ Select: the syntax tree for the SELECT statement.
125
+ """
126
+ return Select().from_(expression, dialect=dialect, copy=copy, **opts)
127
+
128
+
129
+ def update(
130
+ table: str | Table,
131
+ properties: dict[str, object] | None = None,
132
+ where: ExpOrStr | None = None,
133
+ from_: ExpOrStr | None = None,
134
+ with_: dict[str, ExpOrStr] | None = None,
135
+ dialect: DialectType = None,
136
+ copy: bool = True,
137
+ **opts: Unpack[ParserNoDialectArgs],
138
+ ) -> Update:
139
+ """
140
+ Creates an update statement.
141
+
142
+ Example:
143
+ >>> 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()
144
+ "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"
145
+
146
+ Args:
147
+ properties: dictionary of properties to SET which are
148
+ auto converted to sql objects eg None -> NULL
149
+ where: sql conditional parsed into a WHERE statement
150
+ from_: sql statement parsed into a FROM statement
151
+ with_: dictionary of CTE aliases / select statements to include in a WITH clause.
152
+ dialect: the dialect used to parse the input expressions.
153
+ copy: whether to copy the input expressions.
154
+ **opts: other options to use to parse the input expressions.
155
+
156
+ Returns:
157
+ Update: the syntax tree for the UPDATE statement.
158
+ """
159
+ update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect, copy=copy))
160
+ if properties:
161
+ update_expr.set(
162
+ "expressions",
163
+ [
164
+ EQ(this=maybe_parse(k, dialect=dialect, copy=copy, **opts), expression=convert(v))
165
+ for k, v in properties.items()
166
+ ],
167
+ )
168
+ if from_:
169
+ update_expr.set(
170
+ "from_",
171
+ maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", copy=copy, **opts),
172
+ )
173
+ if isinstance(where, Condition):
174
+ where = Where(this=where)
175
+ if where:
176
+ update_expr.set(
177
+ "where",
178
+ maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", copy=copy, **opts),
179
+ )
180
+ if with_:
181
+ cte_list = [
182
+ alias_(
183
+ CTE(this=maybe_parse(qry, dialect=dialect, copy=copy, **opts)), alias, table=True
184
+ )
185
+ for alias, qry in with_.items()
186
+ ]
187
+ update_expr.set(
188
+ "with_",
189
+ With(expressions=cte_list),
190
+ )
191
+ return update_expr
192
+
193
+
194
+ def delete(
195
+ table: ExpOrStr,
196
+ where: ExpOrStr | None = None,
197
+ returning: ExpOrStr | None = None,
198
+ dialect: DialectType = None,
199
+ **opts: Unpack[ParserNoDialectArgs],
200
+ ) -> Delete:
201
+ """
202
+ Builds a delete statement.
203
+
204
+ Example:
205
+ >>> delete("my_table", where="id > 1").sql()
206
+ 'DELETE FROM my_table WHERE id > 1'
207
+
208
+ Args:
209
+ where: sql conditional parsed into a WHERE statement
210
+ returning: sql conditional parsed into a RETURNING statement
211
+ dialect: the dialect used to parse the input expressions.
212
+ **opts: other options to use to parse the input expressions.
213
+
214
+ Returns:
215
+ Delete: the syntax tree for the DELETE statement.
216
+ """
217
+ delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
218
+ if where:
219
+ delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
220
+ if returning:
221
+ delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
222
+ return delete_expr
223
+
224
+
225
+ def insert(
226
+ expression: ExpOrStr,
227
+ into: str | Table,
228
+ columns: Sequence[str | Identifier] | None = None,
229
+ overwrite: bool | None = None,
230
+ returning: ExpOrStr | None = None,
231
+ dialect: DialectType = None,
232
+ copy: bool = True,
233
+ **opts: Unpack[ParserNoDialectArgs],
234
+ ) -> Insert:
235
+ """
236
+ Builds an INSERT statement.
237
+
238
+ Example:
239
+ >>> insert("VALUES (1, 2, 3)", "tbl").sql()
240
+ 'INSERT INTO tbl VALUES (1, 2, 3)'
241
+
242
+ Args:
243
+ expression: the sql string or expression of the INSERT statement
244
+ into: the tbl to insert data to.
245
+ columns: optionally the table's column names.
246
+ overwrite: whether to INSERT OVERWRITE or not.
247
+ returning: sql conditional parsed into a RETURNING statement
248
+ dialect: the dialect used to parse the input expressions.
249
+ copy: whether to copy the expression.
250
+ **opts: other options to use to parse the input expressions.
251
+
252
+ Returns:
253
+ Insert: the syntax tree for the INSERT statement.
254
+ """
255
+ expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
256
+ this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
257
+
258
+ if columns:
259
+ this = Schema(this=this, expressions=[to_identifier(c, copy=copy) for c in columns])
260
+
261
+ insert = Insert(this=this, expression=expr, overwrite=overwrite)
262
+
263
+ if returning:
264
+ insert = insert.returning(returning, dialect=dialect, copy=False, **opts)
265
+
266
+ return insert
267
+
268
+
269
+ def merge(
270
+ *when_exprs: ExpOrStr,
271
+ into: ExpOrStr,
272
+ using: ExpOrStr,
273
+ on: ExpOrStr,
274
+ returning: ExpOrStr | None = None,
275
+ dialect: DialectType = None,
276
+ copy: bool = True,
277
+ **opts: Unpack[ParserNoDialectArgs],
278
+ ) -> Merge:
279
+ """
280
+ Builds a MERGE statement.
281
+
282
+ Example:
283
+ >>> merge("WHEN MATCHED THEN UPDATE SET col1 = source_table.col1",
284
+ ... "WHEN NOT MATCHED THEN INSERT (col1) VALUES (source_table.col1)",
285
+ ... into="my_table",
286
+ ... using="source_table",
287
+ ... on="my_table.id = source_table.id").sql()
288
+ '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)'
289
+
290
+ Args:
291
+ *when_exprs: The WHEN clauses specifying actions for matched and unmatched rows.
292
+ into: The target table to merge data into.
293
+ using: The source table to merge data from.
294
+ on: The join condition for the merge.
295
+ returning: The columns to return from the merge.
296
+ dialect: The dialect used to parse the input expressions.
297
+ copy: Whether to copy the expression.
298
+ **opts: Other options to use to parse the input expressions.
299
+
300
+ Returns:
301
+ Merge: The syntax tree for the MERGE statement.
302
+ """
303
+ expressions: list[Expr] = []
304
+ for when_expr in when_exprs:
305
+ expression = maybe_parse(when_expr, dialect=dialect, copy=copy, into=Whens, **opts)
306
+ expressions.extend([expression] if isinstance(expression, When) else expression.expressions)
307
+
308
+ merge = Merge(
309
+ this=maybe_parse(into, dialect=dialect, copy=copy, **opts),
310
+ using=maybe_parse(using, dialect=dialect, copy=copy, **opts),
311
+ on=maybe_parse(on, dialect=dialect, copy=copy, **opts),
312
+ whens=Whens(expressions=expressions),
313
+ )
314
+ if returning:
315
+ merge = merge.returning(returning, dialect=dialect, copy=False, **opts)
316
+
317
+ if isinstance(using_clause := merge.args.get("using"), Alias):
318
+ using_clause.replace(alias_(using_clause.this, using_clause.args["alias"], table=True))
319
+
320
+ return merge
321
+
322
+
323
+ def parse_identifier(name: str | Identifier, dialect: DialectType = None) -> Identifier:
324
+ """
325
+ Parses a given string into an identifier.
326
+
327
+ Args:
328
+ name: The name to parse into an identifier.
329
+ dialect: The dialect to parse against.
330
+
331
+ Returns:
332
+ The identifier ast node.
333
+ """
334
+ if isinstance(name, str) and SAFE_IDENTIFIER_RE.match(name):
335
+ # Simple names parse to a single unquoted identifier in all dialects, so we can
336
+ # avoid the tokenizer/parser round-trip for them.
337
+ return Identifier(this=name, quoted=False)
338
+
339
+ try:
340
+ expression = maybe_parse(name, dialect=dialect, into=Identifier)
341
+ except (ParseError, TokenError):
342
+ expression = to_identifier(name)
343
+
344
+ return expression
345
+
346
+
347
+ INTERVAL_STRING_RE = re.compile(r"\s*(-?[0-9]+(?:\.[0-9]+)?)\s*([a-zA-Z]+)\s*")
348
+
349
+
350
+ INTERVAL_DAY_TIME_RE = re.compile(
351
+ r"\s*-?\s*\d+(?:\.\d+)?\s+(?:-?(?:\d+:)?\d+:\d+(?:\.\d+)?|-?(?:\d+:){1,2}|:)\s*"
352
+ )
353
+
354
+
355
+ def to_interval(interval: str | Expr) -> Interval:
356
+ """Builds an interval expression from a string like '1 day' or '5 months'."""
357
+ if isinstance(interval, Literal):
358
+ if not interval.is_string:
359
+ raise ValueError("Invalid interval string.")
360
+
361
+ interval = interval.this
362
+
363
+ interval = maybe_parse(f"INTERVAL {interval}")
364
+ assert isinstance(interval, Interval)
365
+ return interval
366
+
367
+
368
+ def to_table(
369
+ sql_path: str | Table, dialect: DialectType = None, copy: bool = True, **kwargs: object
370
+ ) -> Table:
371
+ """
372
+ Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
373
+ If a table is passed in then that table is returned.
374
+
375
+ Args:
376
+ sql_path: a `[catalog].[schema].[table]` string.
377
+ dialect: the source dialect according to which the table name will be parsed.
378
+ copy: Whether to copy a table if it is passed in.
379
+ kwargs: the kwargs to instantiate the resulting `Table` expression with.
380
+
381
+ Returns:
382
+ A table expression.
383
+ """
384
+ if isinstance(sql_path, Table):
385
+ return maybe_copy(sql_path, copy=copy)
386
+
387
+ try:
388
+ table = maybe_parse(sql_path, into=Table, dialect=dialect)
389
+ except ParseError:
390
+ catalog, db, this = split_num_words(sql_path, ".", 3)
391
+
392
+ if not this:
393
+ raise
394
+
395
+ table = table_(this, db=db, catalog=catalog)
396
+
397
+ return table.set_kwargs(kwargs)
398
+
399
+
400
+ def to_column(
401
+ sql_path: str | Column,
402
+ quoted: bool | None = None,
403
+ dialect: DialectType = None,
404
+ copy: bool = True,
405
+ **kwargs: t.Any,
406
+ ) -> Column | Dot:
407
+ """
408
+ Create a column from a `[table].[column]` sql path. Table is optional.
409
+ If a column is passed in then that column is returned.
410
+
411
+ Args:
412
+ sql_path: a `[table].[column]` string.
413
+ quoted: Whether or not to force quote identifiers.
414
+ dialect: the source dialect according to which the column name will be parsed.
415
+ copy: Whether to copy a column if it is passed in.
416
+ kwargs: the kwargs to instantiate the resulting `Column` expression with.
417
+
418
+ Returns:
419
+ A column expression.
420
+ """
421
+ if isinstance(sql_path, Column):
422
+ return maybe_copy(sql_path, copy=copy)
423
+
424
+ try:
425
+ col = maybe_parse(sql_path, into=Column, dialect=dialect)
426
+ except ParseError:
427
+ return column(*reversed(sql_path.split(".")), quoted=quoted, **kwargs)
428
+
429
+ for k, v in kwargs.items():
430
+ col.set(k, v)
431
+
432
+ if quoted:
433
+ for i in col.find_all(Identifier):
434
+ i.set("quoted", True)
435
+
436
+ return col
437
+
438
+
439
+ def subquery(
440
+ expression: ExpOrStr,
441
+ alias: Identifier | str | None = None,
442
+ dialect: DialectType = None,
443
+ copy: bool = True,
444
+ **opts: Unpack[ParserNoDialectArgs],
445
+ ) -> Select:
446
+ """
447
+ Build a subquery expression that's selected from.
448
+
449
+ Example:
450
+ >>> subquery('select x from tbl', 'bar').select('x').sql()
451
+ 'SELECT x FROM (SELECT x FROM tbl) AS bar'
452
+
453
+ Args:
454
+ expression: the SQL code strings to parse.
455
+ If an Expr instance is passed, this is used as-is.
456
+ alias: the alias name to use.
457
+ dialect: the dialect used to parse the input expression.
458
+ **opts: other options to use to parse the input expressions.
459
+
460
+ Returns:
461
+ A new Select instance with the subquery expression included.
462
+ """
463
+ expr = (
464
+ maybe_parse(expression, dialect=dialect, **opts).assert_is(Query).subquery(alias, copy=copy)
465
+ )
466
+ return Select().from_(expr, dialect=dialect, **opts)
467
+
468
+
469
+ def cast(
470
+ expression: ExpOrStr,
471
+ to: DATA_TYPE,
472
+ copy: bool = True,
473
+ dialect: DialectType = None,
474
+ **opts: Unpack[ParserNoDialectArgs],
475
+ ) -> Cast:
476
+ """Cast an expression to a data type.
477
+
478
+ Example:
479
+ >>> cast('x + 1', 'int').sql()
480
+ 'CAST(x + 1 AS INT)'
481
+
482
+ Args:
483
+ expression: The expression to cast.
484
+ to: The datatype to cast to.
485
+ copy: Whether to copy the supplied expressions.
486
+ dialect: The target dialect. This is used to prevent a re-cast in the following scenario:
487
+ - The expression to be cast is already a exp.Cast expression
488
+ - The existing cast is to a type that is logically equivalent to new type
489
+
490
+ For example, if :expression='CAST(x as DATETIME)' and :to=Type.TIMESTAMP,
491
+ but in the target dialect DATETIME is mapped to TIMESTAMP, then we will NOT return `CAST(x (as DATETIME) as TIMESTAMP)`
492
+ and instead just return the original expression `CAST(x as DATETIME)`.
493
+
494
+ This is to prevent it being output as a double cast `CAST(x (as TIMESTAMP) as TIMESTAMP)` once the DATETIME -> TIMESTAMP
495
+ mapping is applied in the target dialect generator.
496
+
497
+ Returns:
498
+ The new Cast instance.
499
+ """
500
+ expr = maybe_parse(expression, copy=copy, dialect=dialect, **opts)
501
+ data_type = DataType.build(to, copy=copy, dialect=dialect, **opts)
502
+
503
+ # dont re-cast if the expression is already a cast to the correct type
504
+ if isinstance(expr, Cast):
505
+ from sqlglot.dialects.dialect import Dialect
506
+
507
+ target_dialect = Dialect.get_or_raise(dialect)
508
+ type_mapping = target_dialect.generator_class.TYPE_MAPPING
509
+
510
+ existing_cast_type = expr.to.this
511
+ new_cast_type: DType = data_type.this
512
+ # `this` is only a plain type enum for simple types; complex ones such as
513
+ # INTERVAL nest another expression there, so the equivalence check is skipped.
514
+ types_are_equivalent = (
515
+ isinstance(existing_cast_type, DType)
516
+ and isinstance(new_cast_type, DType)
517
+ and type_mapping.get(existing_cast_type, existing_cast_type.value)
518
+ == type_mapping.get(new_cast_type, new_cast_type.value)
519
+ )
520
+
521
+ if expr.is_type(data_type) or types_are_equivalent:
522
+ return expr
523
+
524
+ expr = Cast(this=expr, to=data_type)
525
+ expr.type = data_type
526
+
527
+ return expr
528
+
529
+
530
+ def table_(
531
+ table: Identifier | str | None,
532
+ db: Identifier | str | None = None,
533
+ catalog: Identifier | str | None = None,
534
+ quoted: bool | None = None,
535
+ alias: Identifier | str | None = None,
536
+ ) -> Table:
537
+ """Build a Table.
538
+
539
+ Args:
540
+ table: Table name.
541
+ db: Database name.
542
+ catalog: Catalog name.
543
+ quote: Whether to force quotes on the table's identifiers.
544
+ alias: Table's alias.
545
+
546
+ Returns:
547
+ The new Table instance.
548
+ """
549
+ return Table(
550
+ this=to_identifier(table, quoted=quoted) if table else None,
551
+ db=to_identifier(db, quoted=quoted) if db else None,
552
+ catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
553
+ alias=TableAlias(this=to_identifier(alias)) if alias else None,
554
+ )
555
+
556
+
557
+ def values(
558
+ values: Iterable[tuple[object, ...] | Tuple],
559
+ alias: str | None = None,
560
+ columns: Iterable[str] | dict[str, DataType] | None = None,
561
+ ) -> Values:
562
+ """Build VALUES statement.
563
+
564
+ Example:
565
+ >>> values([(1, '2')]).sql()
566
+ "VALUES (1, '2')"
567
+
568
+ Args:
569
+ values: values statements that will be converted to SQL
570
+ alias: optional alias
571
+ columns: Optional list of ordered column names or ordered dictionary of column names to types.
572
+ If either are provided then an alias is also required.
573
+
574
+ Returns:
575
+ Values: the Values expression object
576
+ """
577
+ if columns and not alias:
578
+ raise ValueError("Alias is required when providing columns")
579
+
580
+ return Values(
581
+ expressions=[convert(tup) for tup in values],
582
+ alias=(
583
+ TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
584
+ if columns
585
+ else (TableAlias(this=to_identifier(alias)) if alias else None)
586
+ ),
587
+ )
588
+
589
+
590
+ def var(name: ExpOrStr | None) -> Var:
591
+ """Build a SQL variable.
592
+
593
+ Example:
594
+ >>> repr(var('x'))
595
+ 'Var(this=x)'
596
+
597
+ >>> repr(var(column('x', table='y')))
598
+ 'Var(this=x)'
599
+
600
+ Args:
601
+ name: The name of the var or an expression who's name will become the var.
602
+
603
+ Returns:
604
+ The new variable node.
605
+ """
606
+ if not name:
607
+ raise ValueError("Cannot convert empty name into var.")
608
+
609
+ if isinstance(name, Expr):
610
+ name = name.name
611
+ return Var(this=name)
612
+
613
+
614
+ def rename_table(
615
+ old_name: str | Table,
616
+ new_name: str | Table,
617
+ dialect: DialectType = None,
618
+ ) -> Alter:
619
+ """Build ALTER TABLE... RENAME... expression
620
+
621
+ Args:
622
+ old_name: The old name of the table
623
+ new_name: The new name of the table
624
+ dialect: The dialect to parse the table.
625
+
626
+ Returns:
627
+ Alter table expression
628
+ """
629
+ old_table = to_table(old_name, dialect=dialect)
630
+ new_table = to_table(new_name, dialect=dialect)
631
+ return Alter(
632
+ this=old_table,
633
+ kind="TABLE",
634
+ actions=[
635
+ AlterRename(this=new_table),
636
+ ],
637
+ )
638
+
639
+
640
+ def rename_column(
641
+ table_name: str | Table,
642
+ old_column_name: str | Column,
643
+ new_column_name: str | Column,
644
+ exists: bool | None = None,
645
+ dialect: DialectType = None,
646
+ ) -> Alter:
647
+ """Build ALTER TABLE... RENAME COLUMN... expression
648
+
649
+ Args:
650
+ table_name: Name of the table
651
+ old_column: The old name of the column
652
+ new_column: The new name of the column
653
+ exists: Whether to add the `IF EXISTS` clause
654
+ dialect: The dialect to parse the table/column.
655
+
656
+ Returns:
657
+ Alter table expression
658
+ """
659
+ table = to_table(table_name, dialect=dialect)
660
+ old_column = to_column(old_column_name, dialect=dialect)
661
+ new_column = to_column(new_column_name, dialect=dialect)
662
+ return Alter(
663
+ this=table,
664
+ kind="TABLE",
665
+ actions=[
666
+ RenameColumn(this=old_column, to=new_column, exists=exists),
667
+ ],
668
+ )
669
+
670
+
671
+ def replace_children(
672
+ expression: Expr,
673
+ fun: t.Callable[Concatenate[Expr, P], object],
674
+ *args: P.args,
675
+ **kwargs: P.kwargs,
676
+ ) -> None:
677
+ """
678
+ Replace children of an expression with the result of a lambda fun(child) -> exp.
679
+ """
680
+ for k, v in tuple(expression.args.items()):
681
+ is_list_arg = type(v) is list
682
+
683
+ child_nodes = v if is_list_arg else [v]
684
+ new_child_nodes = []
685
+
686
+ for cn in child_nodes:
687
+ if isinstance(cn, Expr):
688
+ for child_node in ensure_collection(fun(cn, *args, **kwargs)):
689
+ new_child_nodes.append(child_node)
690
+ else:
691
+ new_child_nodes.append(cn)
692
+
693
+ if is_list_arg:
694
+ expression.set(k, new_child_nodes)
695
+ else:
696
+ expression.set(k, seq_get(new_child_nodes, 0))
697
+
698
+
699
+ def replace_tree(
700
+ expression: Expr,
701
+ fun: t.Callable[[Expr], Expr],
702
+ prune: t.Callable[[Expr], bool] | None = None,
703
+ ) -> Expr:
704
+ """
705
+ Replace an entire tree with the result of function calls on each node.
706
+
707
+ This will be traversed in reverse dfs, so leaves first.
708
+ If new nodes are created as a result of function calls, they will also be traversed.
709
+ """
710
+ stack = list(expression.dfs(prune=prune))
711
+
712
+ while stack:
713
+ node = stack.pop()
714
+ new_node = fun(node)
715
+
716
+ if new_node is not node:
717
+ node.replace(new_node)
718
+
719
+ if isinstance(new_node, Expr):
720
+ stack.append(new_node)
721
+
722
+ return new_node
723
+
724
+
725
+ def find_tables(expression: Expr) -> set[Table]:
726
+ """
727
+ Find all tables referenced in a query.
728
+
729
+ Args:
730
+ expressions: The query to find the tables in.
731
+
732
+ Returns:
733
+ A set of all the tables.
734
+ """
735
+ from sqlglot.optimizer.scope import traverse_scope
736
+
737
+ return {
738
+ table
739
+ for scope in traverse_scope(expression)
740
+ for table in scope.tables
741
+ if isinstance(table, Table) and table.name and table.name not in scope.cte_sources
742
+ }
743
+
744
+
745
+ def column_table_names(expression: Expr, exclude: str = "") -> set[str]:
746
+ """
747
+ Return all table names referenced through columns in an expression.
748
+
749
+ Example:
750
+ >>> import sqlglot
751
+ >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
752
+ ['a', 'c']
753
+
754
+ Args:
755
+ expression: expression to find table names.
756
+ exclude: a table name to exclude
757
+
758
+ Returns:
759
+ A list of unique names.
760
+ """
761
+ return {
762
+ table
763
+ for table in (column.table for column in expression.find_all(Column))
764
+ if table and table != exclude
765
+ }
766
+
767
+
768
+ def table_name(table: Table | str, dialect: DialectType = None, identify: bool = False) -> str:
769
+ """Get the full name of a table as a string.
770
+
771
+ Args:
772
+ table: Table expression node or string.
773
+ dialect: The dialect to generate the table name for.
774
+ identify: Determines when an identifier should be quoted. Possible values are:
775
+ False (default): Never quote, except in cases where it's mandatory by the dialect.
776
+ True: Always quote.
777
+
778
+ Examples:
779
+ >>> from sqlglot import exp, parse_one
780
+ >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
781
+ 'a.b.c'
782
+
783
+ Returns:
784
+ The table name.
785
+ """
786
+
787
+ expr = maybe_parse(table, into=Table, dialect=dialect)
788
+
789
+ if not expr:
790
+ raise ValueError(f"Cannot parse {table}")
791
+
792
+ return ".".join(
793
+ (
794
+ part.sql(dialect=dialect, identify=True, copy=False, comments=False)
795
+ if identify or not SAFE_IDENTIFIER_RE.match(part.name)
796
+ else part.name
797
+ )
798
+ for part in expr.parts
799
+ )
800
+
801
+
802
+ def normalize_table_name(table: str | Table, dialect: DialectType = None, copy: bool = True) -> str:
803
+ """Returns a case normalized table name without quotes.
804
+
805
+ Args:
806
+ table: the table to normalize
807
+ dialect: the dialect to use for normalization rules
808
+ copy: whether to copy the expression.
809
+
810
+ Examples:
811
+ >>> normalize_table_name("`A-B`.c", dialect="bigquery")
812
+ 'A-B.c'
813
+ """
814
+ from sqlglot.optimizer.normalize_identifiers import normalize_identifiers
815
+
816
+ return ".".join(
817
+ p.name
818
+ for p in normalize_identifiers(
819
+ to_table(table, dialect=dialect, copy=copy), dialect=dialect
820
+ ).parts
821
+ )
822
+
823
+
824
+ def replace_tables(
825
+ expression: E, mapping: dict[str, str], dialect: DialectType = None, copy: bool = True
826
+ ) -> E:
827
+ """Replace all tables in expression according to the mapping.
828
+
829
+ Args:
830
+ expression: expression node to be transformed and replaced.
831
+ mapping: mapping of table names.
832
+ dialect: the dialect of the mapping table
833
+ copy: whether to copy the expression.
834
+
835
+ Examples:
836
+ >>> from sqlglot import exp, parse_one
837
+ >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
838
+ 'SELECT * FROM c /* a.b */'
839
+
840
+ Returns:
841
+ The mapped expression.
842
+ """
843
+
844
+ mapping = {normalize_table_name(k, dialect=dialect): v for k, v in mapping.items()}
845
+
846
+ def _replace_tables(node: Expr) -> Expr:
847
+ if isinstance(node, Table) and node.meta_get("replace") is not False:
848
+ original = normalize_table_name(node, dialect=dialect)
849
+ new_name = mapping.get(original)
850
+
851
+ if new_name:
852
+ table = to_table(
853
+ new_name,
854
+ **{k: v for k, v in node.args.items() if k not in TABLE_PARTS},
855
+ dialect=dialect,
856
+ )
857
+ table.add_comments([original])
858
+ return table
859
+ return node
860
+
861
+ return expression.transform(_replace_tables, copy=copy) # type: ignore
862
+
863
+
864
+ OPERATORS = (AtTimeZone, Between, Binary, BitwiseNot, In, Neg, Not)
865
+
866
+
867
+ def _is_operand(placeholder: Placeholder) -> bool:
868
+ parent = placeholder.parent
869
+ if isinstance(parent, (Bracket, In)):
870
+ return placeholder.arg_key == "this"
871
+ return isinstance(parent, OPERATORS)
872
+
873
+
874
+ def _takes_query(placeholder: Placeholder) -> bool:
875
+ parent = placeholder.parent
876
+ if isinstance(parent, In):
877
+ return placeholder.arg_key == "expressions" and len(parent.expressions) == 1
878
+ if isinstance(parent, Func):
879
+ return len(list(parent.iter_expressions())) == 1
880
+ if isinstance(parent, Table):
881
+ return isinstance(parent.parent, (Create, Subquery))
882
+ return not parent or isinstance(parent, (CTE, Paren, SetOperation))
883
+
884
+
885
+ def _replace_placeholder(placeholder: Placeholder, expression: Expr) -> Expr:
886
+ if (
887
+ isinstance(expression, Query)
888
+ and not isinstance(expression, Subquery)
889
+ and not _takes_query(placeholder)
890
+ ):
891
+ return expression.subquery(copy=False)
892
+ if (
893
+ _is_operand(placeholder)
894
+ and isinstance(expression, OPERATORS)
895
+ and not isinstance(expression, Dot)
896
+ ):
897
+ return Paren(this=expression)
898
+ return expression
899
+
900
+
901
+ def replace_placeholders(expression: Expr, *args: object, **kwargs: t.Any) -> Expr:
902
+ """Replace placeholders in an expression.
903
+
904
+ Args:
905
+ expression: expression node to be transformed and replaced.
906
+ args: positional names that will substitute unnamed placeholders in the given order.
907
+ kwargs: keyword arguments that will substitute named placeholders.
908
+
909
+ Examples:
910
+ >>> from sqlglot import exp, parse_one
911
+ >>> replace_placeholders(
912
+ ... parse_one("select * from :tbl where ? = ?"),
913
+ ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
914
+ ... ).sql()
915
+ "SELECT * FROM foo WHERE str_col = 'b'"
916
+
917
+ Returns:
918
+ The mapped expression.
919
+ """
920
+
921
+ def _replace_placeholders(node: Expr, args: Iterator[object], **kwargs: object) -> Expr:
922
+ if isinstance(node, Placeholder):
923
+ if node.this:
924
+ new_name = kwargs.get(node.this)
925
+ if new_name is not None:
926
+ return _replace_placeholder(node, convert(new_name))
927
+ else:
928
+ try:
929
+ return _replace_placeholder(node, convert(next(args)))
930
+ except StopIteration:
931
+ pass
932
+ return node
933
+
934
+ return expression.transform(_replace_placeholders, iter(args), **kwargs)
935
+
936
+
937
+ def expand(
938
+ expression: Expr,
939
+ sources: dict[str, Query | t.Callable[[], Query]],
940
+ dialect: DialectType = None,
941
+ copy: bool = True,
942
+ ) -> Expr:
943
+ """Transforms an expression by expanding all referenced sources into subqueries.
944
+
945
+ Examples:
946
+ >>> from sqlglot import parse_one
947
+ >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
948
+ 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
949
+
950
+ >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
951
+ 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
952
+
953
+ Args:
954
+ expression: The expression to expand.
955
+ sources: A dict of name to query or a callable that provides a query on demand.
956
+ dialect: The dialect of the sources dict or the callable.
957
+ copy: Whether to copy the expression during transformation. Defaults to True.
958
+
959
+ Returns:
960
+ The transformed expression.
961
+ """
962
+ normalized_sources = {normalize_table_name(k, dialect=dialect): v for k, v in sources.items()}
963
+
964
+ def _expand(node: Expr):
965
+ if isinstance(node, Table):
966
+ name = normalize_table_name(node, dialect=dialect)
967
+ source = normalized_sources.get(name)
968
+
969
+ if source:
970
+ # Create a subquery with the same alias (or table name if no alias)
971
+ parsed_source = source() if callable(source) else source
972
+ subquery = parsed_source.subquery(node.alias or name)
973
+ subquery.comments = [f"source: {name}"]
974
+
975
+ # Continue expanding within the subquery
976
+ return subquery.transform(_expand, copy=False)
977
+
978
+ return node
979
+
980
+ return expression.transform(_expand, copy=copy)
981
+
982
+
983
+ def func(
984
+ name: str, *args: t.Any, copy: bool = True, dialect: DialectType = None, **kwargs: t.Any
985
+ ) -> Func:
986
+ """
987
+ Returns a Func expression.
988
+
989
+ Examples:
990
+ >>> func("abs", 5).sql()
991
+ 'ABS(5)'
992
+
993
+ >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
994
+ 'CAST(5 AS DOUBLE)'
995
+
996
+ Args:
997
+ name: the name of the function to build.
998
+ args: the args used to instantiate the function of interest.
999
+ copy: whether to copy the argument expressions.
1000
+ dialect: the source dialect.
1001
+ kwargs: the kwargs used to instantiate the function of interest.
1002
+
1003
+ Note:
1004
+ The arguments `args` and `kwargs` are mutually exclusive.
1005
+
1006
+ Returns:
1007
+ An instance of the function of interest, or an anonymous function, if `name` doesn't
1008
+ correspond to an existing `sqlglot.expressions.Func` class.
1009
+ """
1010
+ if args and kwargs:
1011
+ raise ValueError("Can't use both args and kwargs to instantiate a function.")
1012
+
1013
+ from sqlglot.dialects.dialect import Dialect
1014
+
1015
+ dialect = Dialect.get_or_raise(dialect)
1016
+
1017
+ converted: list[Expr] = [maybe_parse(arg, dialect=dialect, copy=copy) for arg in args]
1018
+ kwargs = {key: maybe_parse(value, dialect=dialect, copy=copy) for key, value in kwargs.items()}
1019
+
1020
+ constructor = dialect.parser_class.FUNCTIONS.get(name.upper())
1021
+ if constructor:
1022
+ if converted:
1023
+ try:
1024
+ function = constructor(converted)
1025
+ except TypeError:
1026
+ function = constructor(converted, dialect=dialect)
1027
+ elif constructor.__name__ == "from_arg_list":
1028
+ function = constructor.__self__(**kwargs) # type: ignore
1029
+ else:
1030
+ from sqlglot.expressions import FUNCTION_BY_NAME as _FUNCTION_BY_NAME
1031
+
1032
+ constructor = _FUNCTION_BY_NAME.get(name.upper())
1033
+ if constructor:
1034
+ function = constructor(**kwargs)
1035
+ else:
1036
+ raise ValueError(
1037
+ f"Unable to convert '{name}' into a Func. Either manually construct "
1038
+ "the Func expression of interest or parse the function call."
1039
+ )
1040
+ else:
1041
+ kwargs = kwargs or {"expressions": converted}
1042
+ function = Anonymous(this=name, **kwargs)
1043
+
1044
+ for error_message in function.error_messages(converted):
1045
+ raise ValueError(error_message)
1046
+
1047
+ return function
1048
+
1049
+
1050
+ def case(
1051
+ expression: ExpOrStr | None = None,
1052
+ copy: bool = True,
1053
+ **opts: Unpack[ParserArgs],
1054
+ ) -> Case:
1055
+ """
1056
+ Initialize a CASE statement.
1057
+
1058
+ Example:
1059
+ case().when("a = 1", "foo").else_("bar")
1060
+
1061
+ Args:
1062
+ expression: Optionally, the input expression (not all dialects support this)
1063
+ copy: whether to copy the argument expressions.
1064
+ **opts: Extra keyword arguments for parsing `expression`
1065
+ """
1066
+ if expression is not None:
1067
+ this = maybe_parse(expression, copy=copy, **opts)
1068
+ else:
1069
+ this = None
1070
+ return Case(this=this, ifs=[])
1071
+
1072
+
1073
+ def array(
1074
+ *expressions: ExpOrStr,
1075
+ copy: bool = True,
1076
+ dialect: DialectType = None,
1077
+ **kwargs: Unpack[ParserNoDialectArgs],
1078
+ ) -> Array:
1079
+ """
1080
+ Returns an array.
1081
+
1082
+ Examples:
1083
+ >>> array(1, 'x').sql()
1084
+ 'ARRAY(1, x)'
1085
+
1086
+ Args:
1087
+ expressions: the expressions to add to the array.
1088
+ copy: whether to copy the argument expressions.
1089
+ dialect: the source dialect.
1090
+ kwargs: the kwargs used to instantiate the function of interest.
1091
+
1092
+ Returns:
1093
+ An array expression.
1094
+ """
1095
+ return Array(
1096
+ expressions=[
1097
+ maybe_parse(expression, copy=copy, dialect=dialect, **kwargs)
1098
+ for expression in expressions
1099
+ ]
1100
+ )
1101
+
1102
+
1103
+ def tuple_(
1104
+ *expressions: ExpOrStr,
1105
+ copy: bool = True,
1106
+ dialect: DialectType = None,
1107
+ **kwargs: Unpack[ParserNoDialectArgs],
1108
+ ) -> Tuple:
1109
+ """
1110
+ Returns an tuple.
1111
+
1112
+ Examples:
1113
+ >>> tuple_(1, 'x').sql()
1114
+ '(1, x)'
1115
+
1116
+ Args:
1117
+ expressions: the expressions to add to the tuple.
1118
+ copy: whether to copy the argument expressions.
1119
+ dialect: the source dialect.
1120
+ kwargs: the kwargs used to instantiate the function of interest.
1121
+
1122
+ Returns:
1123
+ A tuple expression.
1124
+ """
1125
+ return Tuple(
1126
+ expressions=[
1127
+ maybe_parse(expression, copy=copy, dialect=dialect, **kwargs)
1128
+ for expression in expressions
1129
+ ]
1130
+ )
1131
+
1132
+
1133
+ def true() -> Boolean:
1134
+ """
1135
+ Returns a true Boolean expression.
1136
+ """
1137
+ return Boolean(this=True)
1138
+
1139
+
1140
+ def false() -> Boolean:
1141
+ """
1142
+ Returns a false Boolean expression.
1143
+ """
1144
+ return Boolean(this=False)
1145
+
1146
+
1147
+ def null() -> Null:
1148
+ """
1149
+ Returns a Null expression.
1150
+ """
1151
+ return Null()
1152
+
1153
+
1154
+ def apply_index_offset(
1155
+ this: Expr,
1156
+ expressions: list[E],
1157
+ offset: int,
1158
+ dialect: DialectType = None,
1159
+ ) -> list[E]:
1160
+ if not offset or len(expressions) != 1:
1161
+ return expressions
1162
+
1163
+ expression = expressions[0]
1164
+
1165
+ from sqlglot.optimizer.annotate_types import annotate_types
1166
+ from sqlglot.optimizer.simplify import simplify
1167
+
1168
+ if not this.type:
1169
+ annotate_types(this, dialect=dialect)
1170
+
1171
+ if t.cast(DataType, this.type).this not in (
1172
+ DType.UNKNOWN,
1173
+ DType.ARRAY,
1174
+ ):
1175
+ return expressions
1176
+
1177
+ if not expression.type:
1178
+ annotate_types(expression, dialect=dialect)
1179
+
1180
+ if t.cast(DataType, expression.type).this in DataType.INTEGER_TYPES:
1181
+ logger.info("Applying array index offset (%s)", offset)
1182
+ expression = simplify(expression + offset)
1183
+ return [expression]
1184
+
1185
+ return expressions
1186
+
1187
+
1188
+ NONNULL_CONSTANTS = (
1189
+ Literal,
1190
+ Boolean,
1191
+ )
1192
+
1193
+ CONSTANTS = (
1194
+ Literal,
1195
+ Boolean,
1196
+ Null,
1197
+ )
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/constraints.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions constraints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlglot.expressions.core import Expression, ColumnConstraintKind
6
+
7
+
8
+ class IndexConstraintOption(Expression):
9
+ arg_types = {
10
+ "key_block_size": False,
11
+ "using": False,
12
+ "parser": False,
13
+ "comment": False,
14
+ "visible": False,
15
+ "engine_attr": False,
16
+ "secondary_engine_attr": False,
17
+ }
18
+
19
+
20
+ class Reference(Expression):
21
+ arg_types = {"this": True, "expressions": False, "options": False}
22
+
23
+
24
+ class ColumnConstraint(Expression):
25
+ arg_types = {"this": False, "kind": True}
26
+
27
+ @property
28
+ def kind(self) -> ColumnConstraintKind | Reference:
29
+ return self.args["kind"]
30
+
31
+
32
+ class AutoIncrementColumnConstraint(Expression, ColumnConstraintKind):
33
+ pass
34
+
35
+
36
+ class InvisibleColumnConstraint(Expression, ColumnConstraintKind):
37
+ arg_types = {}
38
+
39
+
40
+ class ZeroFillColumnConstraint(ColumnConstraint):
41
+ arg_types = {}
42
+
43
+
44
+ class BinaryColumnConstraint(ColumnConstraint):
45
+ arg_types = {}
46
+
47
+
48
+ class PeriodForSystemTimeConstraint(Expression, ColumnConstraintKind):
49
+ arg_types = {"this": True, "expression": True}
50
+
51
+
52
+ class CaseSpecificColumnConstraint(Expression, ColumnConstraintKind):
53
+ arg_types = {"not_": True}
54
+
55
+
56
+ class CharacterSetColumnConstraint(Expression, ColumnConstraintKind):
57
+ pass
58
+
59
+
60
+ class CheckColumnConstraint(Expression, ColumnConstraintKind):
61
+ arg_types = {"this": True, "enforced": False}
62
+
63
+
64
+ class AssumeColumnConstraint(Expression, ColumnConstraintKind):
65
+ pass
66
+
67
+
68
+ class ClusteredColumnConstraint(Expression, ColumnConstraintKind):
69
+ pass
70
+
71
+
72
+ class CollateColumnConstraint(Expression, ColumnConstraintKind):
73
+ pass
74
+
75
+
76
+ class CommentColumnConstraint(Expression, ColumnConstraintKind):
77
+ pass
78
+
79
+
80
+ class CompressColumnConstraint(Expression, ColumnConstraintKind):
81
+ arg_types = {"this": False}
82
+
83
+
84
+ class DateFormatColumnConstraint(Expression, ColumnConstraintKind):
85
+ pass
86
+
87
+
88
+ class DefaultColumnConstraint(Expression, ColumnConstraintKind):
89
+ pass
90
+
91
+
92
+ class EncodeColumnConstraint(Expression, ColumnConstraintKind):
93
+ pass
94
+
95
+
96
+ class ExcludeColumnConstraint(Expression, ColumnConstraintKind):
97
+ pass
98
+
99
+
100
+ class EphemeralColumnConstraint(Expression, ColumnConstraintKind):
101
+ arg_types = {"this": False}
102
+
103
+
104
+ class WithOperator(Expression):
105
+ arg_types = {"this": True, "op": True}
106
+
107
+
108
+ class GeneratedAsIdentityColumnConstraint(Expression, ColumnConstraintKind):
109
+ # this: True -> ALWAYS, this: False -> BY DEFAULT
110
+ arg_types = {
111
+ "this": False,
112
+ "expression": False,
113
+ "on_null": False,
114
+ "start": False,
115
+ "increment": False,
116
+ "minvalue": False,
117
+ "maxvalue": False,
118
+ "cycle": False,
119
+ "order": False,
120
+ }
121
+
122
+
123
+ class GeneratedAsRowColumnConstraint(Expression, ColumnConstraintKind):
124
+ arg_types = {"start": False, "hidden": False}
125
+
126
+
127
+ class IndexColumnConstraint(Expression, ColumnConstraintKind):
128
+ arg_types = {
129
+ "this": False,
130
+ "expressions": False,
131
+ "kind": False,
132
+ "index_type": False,
133
+ "options": False,
134
+ "expression": False, # Clickhouse
135
+ "granularity": False,
136
+ }
137
+
138
+
139
+ class InlineLengthColumnConstraint(Expression, ColumnConstraintKind):
140
+ pass
141
+
142
+
143
+ class NonClusteredColumnConstraint(Expression, ColumnConstraintKind):
144
+ pass
145
+
146
+
147
+ class NotForReplicationColumnConstraint(Expression, ColumnConstraintKind):
148
+ arg_types = {}
149
+
150
+
151
+ class MaskingPolicyColumnConstraint(Expression, ColumnConstraintKind):
152
+ arg_types = {"this": True, "expressions": False}
153
+
154
+
155
+ class NotNullColumnConstraint(Expression, ColumnConstraintKind):
156
+ arg_types = {"allow_null": False}
157
+
158
+
159
+ class OnUpdateColumnConstraint(Expression, ColumnConstraintKind):
160
+ pass
161
+
162
+
163
+ class PrimaryKeyColumnConstraint(Expression, ColumnConstraintKind):
164
+ arg_types = {"desc": False, "options": False}
165
+
166
+
167
+ class TitleColumnConstraint(Expression, ColumnConstraintKind):
168
+ pass
169
+
170
+
171
+ class UniqueColumnConstraint(Expression, ColumnConstraintKind):
172
+ arg_types = {
173
+ "this": False,
174
+ "index_type": False,
175
+ "on_conflict": False,
176
+ "nulls": False,
177
+ "options": False,
178
+ }
179
+
180
+
181
+ class UppercaseColumnConstraint(Expression, ColumnConstraintKind):
182
+ arg_types = {}
183
+
184
+
185
+ class WatermarkColumnConstraint(Expression):
186
+ arg_types = {"this": True, "expression": True}
187
+
188
+
189
+ class PathColumnConstraint(Expression, ColumnConstraintKind):
190
+ pass
191
+
192
+
193
+ class ProjectionPolicyColumnConstraint(Expression, ColumnConstraintKind):
194
+ pass
195
+
196
+
197
+ class ComputedColumnConstraint(Expression, ColumnConstraintKind):
198
+ arg_types = {"this": True, "persisted": False, "not_null": False, "data_type": False}
199
+
200
+
201
+ class InOutColumnConstraint(Expression, ColumnConstraintKind):
202
+ arg_types = {"input_": False, "output": False, "variadic": False}
203
+
204
+
205
+ class Constraint(Expression):
206
+ arg_types = {"this": True, "expressions": True}
207
+
208
+
209
+ class ForeignKey(Expression):
210
+ arg_types = {
211
+ "this": False,
212
+ "expressions": False,
213
+ "reference": False,
214
+ "delete": False,
215
+ "update": False,
216
+ "options": False,
217
+ }
218
+
219
+
220
+ class ColumnPrefix(Expression):
221
+ arg_types = {"this": True, "expression": True}
222
+
223
+
224
+ class PrimaryKey(Expression):
225
+ arg_types = {"this": False, "expressions": True, "options": False, "include": False}
226
+
227
+
228
+ # https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-ddl-create-table-constraint
229
+ class TimeseriesKey(Expression):
230
+ pass
231
+
232
+
233
+ class IndexParameters(Expression):
234
+ arg_types = {
235
+ "using": False,
236
+ "include": False,
237
+ "columns": False,
238
+ "with_storage": False,
239
+ "partition_by": False,
240
+ "tablespace": False,
241
+ "where": False,
242
+ "on": False,
243
+ }
244
+
245
+
246
+ class AddConstraint(Expression):
247
+ arg_types = {"expressions": True}
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/core.py ADDED
@@ -0,0 +1,3138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions core - base classes, traits, operators, and helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import logging
7
+ import math
8
+ import numbers
9
+ import re
10
+ import sys
11
+ import textwrap
12
+ import typing as t
13
+ from builtins import type as Type
14
+ from collections import deque
15
+ from collections.abc import Collection, Iterator, Mapping, MutableMapping, Sequence
16
+ from copy import deepcopy
17
+ from decimal import Decimal, InvalidOperation
18
+ from functools import reduce
19
+
20
+ from sqlglot._typing import E, GeneratorNoDialectArgs, ParserNoDialectArgs, T
21
+ from sqlglot.errors import ParseError
22
+ from sqlglot.helper import (
23
+ camel_to_snake_case,
24
+ ensure_list,
25
+ seq_get,
26
+ to_bool,
27
+ trait,
28
+ )
29
+ from sqlglot.tokenizer_core import Token
30
+
31
+ if t.TYPE_CHECKING:
32
+ from typing_extensions import Concatenate, Self, Unpack
33
+
34
+ from sqlglot._typing import P
35
+ from sqlglot.dialects.dialect import DialectType
36
+ from sqlglot.expressions.datatypes import DATA_TYPE, DataType, DType, Interval
37
+ from sqlglot.expressions.query import Select
38
+
39
+ R = t.TypeVar("R")
40
+
41
+ logger = logging.getLogger("sqlglot")
42
+
43
+ SQLGLOT_META: str = "sqlglot.meta"
44
+ SQLGLOT_ANONYMOUS = "sqlglot.anonymous"
45
+ TABLE_PARTS = ("this", "db", "catalog")
46
+ COLUMN_PARTS = ("this", "table", "db", "catalog")
47
+ POSITION_META_KEYS: tuple[str, ...] = ("line", "col", "start", "end")
48
+ UNITTEST: bool = "unittest" in sys.modules or "pytest" in sys.modules
49
+
50
+
51
+ @trait
52
+ class Expr:
53
+ """
54
+ The base class for all expressions in a syntax tree. Each Expr encapsulates any necessary
55
+ context, such as its child expressions, their names (arg keys), and whether a given child expression
56
+ is optional or not.
57
+
58
+ Attributes:
59
+ key: a unique key for each class in the Expr hierarchy. This is useful for hashing
60
+ and representing expressions as strings.
61
+ arg_types: determines the arguments (child nodes) supported by an expression. It maps
62
+ arg keys to booleans that indicate whether the corresponding args are optional.
63
+ parent: a reference to the parent expression (or None, in case of root expressions).
64
+ arg_key: the arg key an expression is associated with, i.e. the name its parent expression
65
+ uses to refer to it.
66
+ index: the index of an expression if it is inside of a list argument in its parent.
67
+ comments: a list of comments that are associated with a given expression. This is used in
68
+ order to preserve comments when transpiling SQL code.
69
+ type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
70
+ optimizer, in order to enable some transformations that require type information.
71
+ meta: a dictionary that can be used to store useful metadata for a given expression.
72
+
73
+ Example:
74
+ >>> class Foo(Expr):
75
+ ... arg_types = {"this": True, "expression": False}
76
+
77
+ The above definition informs us that Foo is an Expr that requires an argument called
78
+ "this" and may also optionally receive an argument called "expression".
79
+
80
+ Args:
81
+ args: a mapping used for retrieving the arguments of an expression, given their arg keys.
82
+ """
83
+
84
+ key: t.ClassVar[str] = "expression"
85
+ arg_types: t.ClassVar[dict[str, bool]] = {"this": True}
86
+ required_args: t.ClassVar[set[str]] = {"this"}
87
+ is_var_len_args: t.ClassVar[bool] = False
88
+ var_len_arg_key: t.ClassVar[str] = "expressions"
89
+ _hash_raw_args: t.ClassVar[bool] = False
90
+ is_subquery: t.ClassVar[bool] = False
91
+ is_cast: t.ClassVar[bool] = False
92
+ is_data_type: t.ClassVar[bool] = False
93
+
94
+ args: dict[str, t.Any]
95
+ parent: Expr | None
96
+ arg_key: str | None
97
+ index: int | None
98
+ comments: list[str] | None
99
+ _type: DataType | None
100
+ _meta: dict[str, t.Any] | None
101
+ _hash: int | None
102
+
103
+ @classmethod
104
+ def __init_subclass__(cls, **kwargs: t.Any) -> None:
105
+ super().__init_subclass__(**kwargs)
106
+ # When an Expr class is created, its key is automatically set
107
+ # to be the lowercase version of the class' name.
108
+ cls.key = cls.__name__.lower()
109
+ cls.required_args = {k for k, v in cls.arg_types.items() if v}
110
+ # This is so that docstrings are not inherited in pdoc
111
+ setattr(cls, "__doc__", getattr(cls, "__doc__", None) or "")
112
+
113
+ is_primitive: t.ClassVar[bool] = False
114
+
115
+ def __init__(self, **args: object) -> None:
116
+ self.args: dict[str, t.Any] = args
117
+ self.parent: Expr | None = None
118
+ self.arg_key: str | None = None
119
+ self.index: int | None = None
120
+ self.comments: list[str] | None = None
121
+ self._type: DataType | None = None
122
+ self._meta: dict[str, t.Any] | None = None
123
+ self._hash: int | None = None
124
+
125
+ if not self.is_primitive:
126
+ for arg_key, value in self.args.items():
127
+ self._set_parent(arg_key, value)
128
+
129
+ @property
130
+ def this(self) -> t.Any:
131
+ """
132
+ Retrieves the argument with key "this".
133
+ """
134
+ raise NotImplementedError
135
+
136
+ @property
137
+ def expression(self) -> t.Any:
138
+ """
139
+ Retrieves the argument with key "expression".
140
+ """
141
+ raise NotImplementedError
142
+
143
+ @property
144
+ def expressions(self) -> list[t.Any]:
145
+ """
146
+ Retrieves the argument with key "expressions".
147
+ """
148
+ raise NotImplementedError
149
+
150
+ def text(self, key: str) -> str:
151
+ """
152
+ Returns a textual representation of the argument corresponding to "key". This can only be used
153
+ for args that are strings or leaf Expr instances, such as identifiers and literals.
154
+ """
155
+ raise NotImplementedError
156
+
157
+ @property
158
+ def is_string(self) -> bool:
159
+ """
160
+ Checks whether a Literal expression is a string.
161
+ """
162
+ raise NotImplementedError
163
+
164
+ @property
165
+ def is_number(self) -> bool:
166
+ """
167
+ Checks whether a Literal expression is a number.
168
+ """
169
+ raise NotImplementedError
170
+
171
+ def to_py(self) -> t.Any:
172
+ """
173
+ Returns a Python object equivalent of the SQL node.
174
+ """
175
+ raise NotImplementedError
176
+
177
+ @property
178
+ def is_int(self) -> bool:
179
+ """
180
+ Checks whether an expression is an integer.
181
+ """
182
+ raise NotImplementedError
183
+
184
+ @property
185
+ def is_star(self) -> bool:
186
+ """Checks whether an expression is a star."""
187
+ raise NotImplementedError
188
+
189
+ @property
190
+ def alias(self) -> str:
191
+ """
192
+ Returns the alias of the expression, or an empty string if it's not aliased.
193
+ """
194
+ raise NotImplementedError
195
+
196
+ @property
197
+ def alias_column_names(self) -> list[str]:
198
+ raise NotImplementedError
199
+
200
+ @property
201
+ def name(self) -> str:
202
+ raise NotImplementedError
203
+
204
+ @property
205
+ def alias_or_name(self) -> str:
206
+ raise NotImplementedError
207
+
208
+ @property
209
+ def output_name(self) -> str:
210
+ """
211
+ Name of the output column if this expression is a selection.
212
+
213
+ If the Expr has no output name, an empty string is returned.
214
+
215
+ Example:
216
+ >>> from sqlglot import parse_one
217
+ >>> parse_one("SELECT a").expressions[0].output_name
218
+ 'a'
219
+ >>> parse_one("SELECT b AS c").expressions[0].output_name
220
+ 'c'
221
+ >>> parse_one("SELECT 1 + 2").expressions[0].output_name
222
+ ''
223
+ """
224
+ raise NotImplementedError
225
+
226
+ @property
227
+ def type(self) -> DataType | None:
228
+ raise NotImplementedError
229
+
230
+ @type.setter
231
+ def type(self, dtype: DataType | DType | str | None) -> None:
232
+ raise NotImplementedError
233
+
234
+ def is_type(self, *dtypes: DATA_TYPE) -> bool:
235
+ raise NotImplementedError
236
+
237
+ def is_leaf(self) -> bool:
238
+ raise NotImplementedError
239
+
240
+ @property
241
+ def meta(self) -> dict[str, t.Any]:
242
+ raise NotImplementedError
243
+
244
+ def meta_get(self, key: str, default: t.Any = None) -> t.Any:
245
+ raise NotImplementedError
246
+
247
+ def __deepcopy__(self, memo: t.Any) -> Expr:
248
+ raise NotImplementedError
249
+
250
+ def copy(self: E) -> E:
251
+ """
252
+ Returns a deep copy of the expression.
253
+ """
254
+ raise NotImplementedError
255
+
256
+ def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None:
257
+ raise NotImplementedError
258
+
259
+ def pop_comments(self) -> list[str]:
260
+ raise NotImplementedError
261
+
262
+ def append(self, arg_key: str, value: t.Any) -> None:
263
+ """
264
+ Appends value to arg_key if it's a list or sets it as a new list.
265
+
266
+ Args:
267
+ arg_key (str): name of the list expression arg
268
+ value (Any): value to append to the list
269
+ """
270
+ raise NotImplementedError
271
+
272
+ def set(
273
+ self,
274
+ arg_key: str,
275
+ value: object,
276
+ index: int | None = None,
277
+ overwrite: bool = True,
278
+ ) -> None:
279
+ """
280
+ Sets arg_key to value.
281
+
282
+ Args:
283
+ arg_key: name of the expression arg.
284
+ value: value to set the arg to.
285
+ index: if the arg is a list, this specifies what position to add the value in it.
286
+ overwrite: assuming an index is given, this determines whether to overwrite the
287
+ list entry instead of only inserting a new value (i.e., like list.insert).
288
+ """
289
+ raise NotImplementedError
290
+
291
+ def _set_parent(self, arg_key: str, value: object, index: int | None = None) -> None:
292
+ raise NotImplementedError
293
+
294
+ @property
295
+ def depth(self) -> int:
296
+ """
297
+ Returns the depth of this tree.
298
+ """
299
+ raise NotImplementedError
300
+
301
+ def iter_expressions(self: E, reverse: bool = False) -> Iterator[E]:
302
+ """Yields the key and expression for all arguments, exploding list args."""
303
+ raise NotImplementedError
304
+
305
+ def find(self, *expression_types: Type[E], bfs: bool = True) -> E | None:
306
+ """
307
+ Returns the first node in this tree which matches at least one of
308
+ the specified types.
309
+
310
+ Args:
311
+ expression_types: the expression type(s) to match.
312
+ bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
313
+
314
+ Returns:
315
+ The node which matches the criteria or None if no such node was found.
316
+ """
317
+ raise NotImplementedError
318
+
319
+ def find_all(self, *expression_types: Type[E], bfs: bool = True) -> Iterator[E]:
320
+ """
321
+ Returns a generator object which visits all nodes in this tree and only
322
+ yields those that match at least one of the specified expression types.
323
+
324
+ Args:
325
+ expression_types: the expression type(s) to match.
326
+ bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
327
+
328
+ Returns:
329
+ The generator object.
330
+ """
331
+ raise NotImplementedError
332
+
333
+ def find_ancestor(self, *expression_types: Type[E]) -> E | None:
334
+ """
335
+ Returns a nearest parent matching expression_types.
336
+
337
+ Args:
338
+ expression_types: the expression type(s) to match.
339
+
340
+ Returns:
341
+ The parent node.
342
+ """
343
+ raise NotImplementedError
344
+
345
+ @property
346
+ def parent_select(self) -> Select | None:
347
+ """
348
+ Returns the parent select statement.
349
+ """
350
+ raise NotImplementedError
351
+
352
+ @property
353
+ def same_parent(self) -> bool:
354
+ """Returns if the parent is the same class as itself."""
355
+ raise NotImplementedError
356
+
357
+ def root(self) -> Expr:
358
+ """
359
+ Returns the root expression of this tree.
360
+ """
361
+ raise NotImplementedError
362
+
363
+ def walk(
364
+ self, bfs: bool = True, prune: t.Callable[[Expr], bool] | None = None
365
+ ) -> Iterator[Expr]:
366
+ """
367
+ Returns a generator object which visits all nodes in this tree.
368
+
369
+ Args:
370
+ bfs: if set to True the BFS traversal order will be applied,
371
+ otherwise the DFS traversal will be used instead.
372
+ prune: callable that returns True if the generator should stop traversing
373
+ this branch of the tree.
374
+
375
+ Returns:
376
+ the generator object.
377
+ """
378
+ raise NotImplementedError
379
+
380
+ def dfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
381
+ """
382
+ Returns a generator object which visits all nodes in this tree in
383
+ the DFS (Depth-first) order.
384
+
385
+ Returns:
386
+ The generator object.
387
+ """
388
+ raise NotImplementedError
389
+
390
+ def bfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
391
+ """
392
+ Returns a generator object which visits all nodes in this tree in
393
+ the BFS (Breadth-first) order.
394
+
395
+ Returns:
396
+ The generator object.
397
+ """
398
+ raise NotImplementedError
399
+
400
+ def unnest(self) -> Expr:
401
+ """
402
+ Returns the first non parenthesis child or self.
403
+ """
404
+ raise NotImplementedError
405
+
406
+ def unalias(self) -> Expr:
407
+ """
408
+ Returns the inner expression if this is an Alias.
409
+ """
410
+ raise NotImplementedError
411
+
412
+ def unnest_operands(self) -> tuple[Expr, ...]:
413
+ """
414
+ Returns unnested operands as a tuple.
415
+ """
416
+ raise NotImplementedError
417
+
418
+ def flatten(self, unnest: bool = True) -> Iterator[Expr]:
419
+ """
420
+ Returns a generator which yields child nodes whose parents are the same class.
421
+
422
+ A AND B AND C -> [A, B, C]
423
+ """
424
+ raise NotImplementedError
425
+
426
+ def to_s(self) -> str:
427
+ """
428
+ Same as __repr__, but includes additional information which can be useful
429
+ for debugging, like empty or missing args and the AST nodes' object IDs.
430
+ """
431
+ raise NotImplementedError
432
+
433
+ def sql(
434
+ self, dialect: DialectType = None, copy: bool = True, **opts: Unpack[GeneratorNoDialectArgs]
435
+ ) -> str:
436
+ """
437
+ Returns SQL string representation of this tree.
438
+
439
+ Args:
440
+ dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
441
+ opts: other `sqlglot.generator.Generator` options.
442
+
443
+ Returns:
444
+ The SQL string.
445
+ """
446
+ raise NotImplementedError
447
+
448
+ def transform(
449
+ self, fun: t.Callable[..., T], *args: object, copy: bool = True, **kwargs: object
450
+ ) -> T:
451
+ """
452
+ Visits all tree nodes (excluding already transformed ones)
453
+ and applies the given transformation function to each node.
454
+
455
+ Args:
456
+ fun: a function which takes a node as an argument and returns a
457
+ new transformed node or the same node without modifications. If the function
458
+ returns None, then the corresponding node will be removed from the syntax tree.
459
+ copy: if set to True a new tree instance is constructed, otherwise the tree is
460
+ modified in place.
461
+
462
+ Returns:
463
+ The transformed tree.
464
+ """
465
+ raise NotImplementedError
466
+
467
+ def replace(self, expression: T) -> T:
468
+ """
469
+ Swap out this expression with a new expression.
470
+
471
+ For example::
472
+
473
+ >>> import sqlglot
474
+ >>> tree = sqlglot.parse_one("SELECT x FROM tbl")
475
+ >>> tree.find(sqlglot.exp.Column).replace(sqlglot.exp.column("y"))
476
+ Column(
477
+ this=Identifier(this=y, quoted=False))
478
+ >>> tree.sql()
479
+ 'SELECT y FROM tbl'
480
+
481
+ Args:
482
+ expression (T): new node
483
+
484
+ Returns:
485
+ T: The new expression or expressions.
486
+ """
487
+ raise NotImplementedError
488
+
489
+ def pop(self: E) -> E:
490
+ """
491
+ Remove this expression from its AST.
492
+
493
+ Returns:
494
+ The popped expression.
495
+ """
496
+ raise NotImplementedError
497
+
498
+ def assert_is(self, type_: Type[E]) -> E:
499
+ """
500
+ Assert that this `Expr` is an instance of `type_`.
501
+
502
+ If it is NOT an instance of `type_`, this raises an assertion error.
503
+ Otherwise, this returns this expression.
504
+
505
+ Examples:
506
+ This is useful for type security in chained expressions:
507
+
508
+ >>> import sqlglot
509
+ >>> sqlglot.parse_one("SELECT x from y").assert_is(sqlglot.exp.Select).select("z").sql()
510
+ 'SELECT x, z FROM y'
511
+ """
512
+ raise NotImplementedError
513
+
514
+ def error_messages(self, args: Sequence[object] | None = None) -> list[str]:
515
+ """
516
+ Checks if this expression is valid (e.g. all mandatory args are set).
517
+
518
+ Args:
519
+ args: a sequence of values that were used to instantiate a Func expression. This is used
520
+ to check that the provided arguments don't exceed the function argument limit.
521
+
522
+ Returns:
523
+ A list of error messages for all possible errors that were found.
524
+ """
525
+ raise NotImplementedError
526
+
527
+ def dump(self) -> list[dict[str, t.Any]]:
528
+ """
529
+ Dump this Expr to a JSON-serializable dict.
530
+ """
531
+ from sqlglot.serde import dump
532
+
533
+ return dump(self)
534
+
535
+ @classmethod
536
+ def load(cls, obj: list[dict[str, Any]] | None) -> Expr:
537
+ """
538
+ Load a dict (as returned by `Expr.dump`) into an Expr instance.
539
+ """
540
+ from sqlglot.serde import load
541
+
542
+ result = load(obj)
543
+ assert isinstance(result, Expr)
544
+ return result
545
+
546
+ def and_(
547
+ self,
548
+ *expressions: ExpOrStr | None,
549
+ dialect: DialectType = None,
550
+ copy: bool = True,
551
+ wrap: bool = True,
552
+ **opts: Unpack[ParserNoDialectArgs],
553
+ ) -> Condition:
554
+ """
555
+ AND this condition with one or multiple expressions.
556
+
557
+ Example:
558
+ >>> condition("x=1").and_("y=1").sql()
559
+ 'x = 1 AND y = 1'
560
+
561
+ Args:
562
+ *expressions: the SQL code strings to parse.
563
+ If an `Expr` instance is passed, it will be used as-is.
564
+ dialect: the dialect used to parse the input expression.
565
+ copy: whether to copy the involved expressions (only applies to Exprs).
566
+ wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
567
+ precedence issues, but can be turned off when the produced AST is too deep and
568
+ causes recursion-related issues.
569
+ opts: other options to use to parse the input expressions.
570
+
571
+ Returns:
572
+ The new And condition.
573
+ """
574
+ raise NotImplementedError
575
+
576
+ def or_(
577
+ self,
578
+ *expressions: ExpOrStr | None,
579
+ dialect: DialectType = None,
580
+ copy: bool = True,
581
+ wrap: bool = True,
582
+ **opts: Unpack[ParserNoDialectArgs],
583
+ ) -> Condition:
584
+ """
585
+ OR this condition with one or multiple expressions.
586
+
587
+ Example:
588
+ >>> condition("x=1").or_("y=1").sql()
589
+ 'x = 1 OR y = 1'
590
+
591
+ Args:
592
+ *expressions: the SQL code strings to parse.
593
+ If an `Expr` instance is passed, it will be used as-is.
594
+ dialect: the dialect used to parse the input expression.
595
+ copy: whether to copy the involved expressions (only applies to Exprs).
596
+ wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
597
+ precedence issues, but can be turned off when the produced AST is too deep and
598
+ causes recursion-related issues.
599
+ opts: other options to use to parse the input expressions.
600
+
601
+ Returns:
602
+ The new Or condition.
603
+ """
604
+ raise NotImplementedError
605
+
606
+ def not_(self, copy: bool = True) -> Not:
607
+ """
608
+ Wrap this condition with NOT.
609
+
610
+ Example:
611
+ >>> condition("x=1").not_().sql()
612
+ 'NOT x = 1'
613
+
614
+ Args:
615
+ copy: whether to copy this object.
616
+
617
+ Returns:
618
+ The new Not instance.
619
+ """
620
+ raise NotImplementedError
621
+
622
+ def update_positions(
623
+ self: E,
624
+ other: Token | Expr | None = None,
625
+ line: int | None = None,
626
+ col: int | None = None,
627
+ start: int | None = None,
628
+ end: int | None = None,
629
+ ) -> E:
630
+ """
631
+ Update this expression with positions from a token or other expression.
632
+
633
+ Args:
634
+ other: a token or expression to update this expression with.
635
+ line: the line number to use if other is None
636
+ col: column number
637
+ start: start char index
638
+ end: end char index
639
+
640
+ Returns:
641
+ The updated expression.
642
+ """
643
+ raise NotImplementedError
644
+
645
+ def as_(
646
+ self,
647
+ alias: str | Identifier,
648
+ quoted: bool | None = None,
649
+ dialect: DialectType = None,
650
+ copy: bool = True,
651
+ table: bool | Sequence[str | Identifier] = False,
652
+ **opts: Unpack[ParserNoDialectArgs],
653
+ ) -> Expr:
654
+ raise NotImplementedError
655
+
656
+ def _binop(self, klass: Type[E], other: t.Any, reverse: bool = False) -> E:
657
+ raise NotImplementedError
658
+
659
+ def __getitem__(self, other: ExpOrStr | tuple[ExpOrStr, ...]) -> Bracket:
660
+ raise NotImplementedError
661
+
662
+ def __iter__(self) -> Iterator:
663
+ raise NotImplementedError
664
+
665
+ def isin(
666
+ self,
667
+ *expressions: t.Any,
668
+ query: ExpOrStr | None = None,
669
+ unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
670
+ dialect: DialectType = None,
671
+ copy: bool = True,
672
+ **opts: Unpack[ParserNoDialectArgs],
673
+ ) -> In:
674
+ raise NotImplementedError
675
+
676
+ def between(
677
+ self, low: t.Any, high: t.Any, copy: bool = True, symmetric: bool | None = None
678
+ ) -> Between:
679
+ raise NotImplementedError
680
+
681
+ def is_(self, other: ExpOrStr) -> Is:
682
+ raise NotImplementedError
683
+
684
+ def like(self, other: ExpOrStr) -> Like:
685
+ raise NotImplementedError
686
+
687
+ def ilike(self, other: ExpOrStr) -> ILike:
688
+ raise NotImplementedError
689
+
690
+ def eq(self, other: t.Any) -> EQ:
691
+ raise NotImplementedError
692
+
693
+ def neq(self, other: t.Any) -> NEQ:
694
+ raise NotImplementedError
695
+
696
+ def rlike(self, other: ExpOrStr) -> RegexpLike:
697
+ raise NotImplementedError
698
+
699
+ def div(self, other: ExpOrStr, typed: bool = False, safe: bool = False) -> Div:
700
+ raise NotImplementedError
701
+
702
+ def asc(self, nulls_first: bool = True) -> Ordered:
703
+ raise NotImplementedError
704
+
705
+ def desc(self, nulls_first: bool = False) -> Ordered:
706
+ raise NotImplementedError
707
+
708
+ def __lt__(self, other: t.Any) -> LT:
709
+ raise NotImplementedError
710
+
711
+ def __le__(self, other: t.Any) -> LTE:
712
+ raise NotImplementedError
713
+
714
+ def __gt__(self, other: t.Any) -> GT:
715
+ raise NotImplementedError
716
+
717
+ def __ge__(self, other: t.Any) -> GTE:
718
+ raise NotImplementedError
719
+
720
+ def __add__(self, other: t.Any) -> Add:
721
+ raise NotImplementedError
722
+
723
+ def __radd__(self, other: t.Any) -> Add:
724
+ raise NotImplementedError
725
+
726
+ def __sub__(self, other: t.Any) -> Sub:
727
+ raise NotImplementedError
728
+
729
+ def __rsub__(self, other: t.Any) -> Sub:
730
+ raise NotImplementedError
731
+
732
+ def __mul__(self, other: t.Any) -> Mul:
733
+ raise NotImplementedError
734
+
735
+ def __rmul__(self, other: t.Any) -> Mul:
736
+ raise NotImplementedError
737
+
738
+ def __truediv__(self, other: t.Any) -> Div:
739
+ raise NotImplementedError
740
+
741
+ def __rtruediv__(self, other: t.Any) -> Div:
742
+ raise NotImplementedError
743
+
744
+ def __floordiv__(self, other: t.Any) -> IntDiv:
745
+ raise NotImplementedError
746
+
747
+ def __rfloordiv__(self, other: t.Any) -> IntDiv:
748
+ raise NotImplementedError
749
+
750
+ def __mod__(self, other: t.Any) -> Mod:
751
+ raise NotImplementedError
752
+
753
+ def __rmod__(self, other: t.Any) -> Mod:
754
+ raise NotImplementedError
755
+
756
+ def __pow__(self, other: t.Any) -> Pow:
757
+ raise NotImplementedError
758
+
759
+ def __rpow__(self, other: t.Any) -> Pow:
760
+ raise NotImplementedError
761
+
762
+ def __and__(self, other: t.Any) -> And:
763
+ raise NotImplementedError
764
+
765
+ def __rand__(self, other: t.Any) -> And:
766
+ raise NotImplementedError
767
+
768
+ def __or__(self, other: t.Any) -> Or:
769
+ raise NotImplementedError
770
+
771
+ def __ror__(self, other: t.Any) -> Or:
772
+ raise NotImplementedError
773
+
774
+ def __neg__(self) -> Neg:
775
+ raise NotImplementedError
776
+
777
+ def __invert__(self) -> Not:
778
+ raise NotImplementedError
779
+
780
+ def pipe(
781
+ self, func: t.Callable[Concatenate[Self, P], R], *args: P.args, **kwargs: P.kwargs
782
+ ) -> R:
783
+ """Apply a function to `Self` (the current instance) and return the result.
784
+
785
+ Doing `expr.pipe(func, *args, **kwargs)` is equivalent to `func(expr, *args, **kwargs)`.
786
+
787
+ It allows you to chain operations in a fluent way on any given function that takes `Self` as its first argument.
788
+
789
+ Tip:
790
+ If `func` doesn't take `Self` as it's first argument, you can use a lambda to work around it.
791
+
792
+ Args:
793
+ func: The function to apply. It should take `Self` as its first argument, followed by any additional arguments specified in `*args` and `**kwargs`.
794
+ *args: Additional positional arguments to pass to `func` after `Self`.
795
+ **kwargs: Additional keyword arguments to pass to `func`.
796
+
797
+ Returns:
798
+ The result of applying `func` to `Self` with the given arguments.
799
+ """
800
+ return func(self, *args, **kwargs)
801
+
802
+ def apply(
803
+ self, func: t.Callable[Concatenate[Self, P], t.Any], *args: P.args, **kwargs: P.kwargs
804
+ ) -> Self:
805
+ """Apply a function to `Self` (the current instance) for side effects, and return `Self`.
806
+
807
+ Useful for inspecting intermediate expressions in a method chain by simply adding/removing `apply` calls, especially when combined with `pipe`.
808
+
809
+ Tip:
810
+ If `func` doesn't take `Self` as it's first argument, you can use a lambda to work around it.
811
+
812
+ Args:
813
+ func: The function to apply. It should take `Self` as its first argument, followed by any additional arguments specified in `*args` and `**kwargs`.
814
+ *args: Additional positional arguments to pass to `func` after `Self`.
815
+ **kwargs: Additional keyword arguments to pass to `func`.
816
+
817
+ Returns:
818
+ The same instance.
819
+ """
820
+ func(self, *args, **kwargs)
821
+ return self
822
+
823
+
824
+ class Expression(Expr):
825
+ __slots__ = (
826
+ "args",
827
+ "parent",
828
+ "arg_key",
829
+ "index",
830
+ "comments",
831
+ "_type",
832
+ "_meta",
833
+ "_hash",
834
+ )
835
+
836
+ def __eq__(self, other: object) -> bool:
837
+ return self is other or (type(self) is type(other) and hash(self) == hash(other))
838
+
839
+ def __ne__(self, other: object) -> bool:
840
+ return not self.__eq__(other)
841
+
842
+ def __hash__(self) -> int:
843
+ if self._hash is None:
844
+ nodes: list[Expr] = []
845
+ stack: list[Expr] = [self]
846
+
847
+ # Collect nodes, finding child expressions inline instead of via the
848
+ # iter_expressions generator (whose per-node generator object dominates the
849
+ # hash's cost). reversed(nodes) is a valid post-order regardless of DFS/BFS.
850
+ while stack:
851
+ node = stack.pop()
852
+ nodes.append(node)
853
+
854
+ for v in node.args.values():
855
+ if isinstance(v, Expr):
856
+ if v._hash is None:
857
+ stack.append(v)
858
+ elif type(v) is list:
859
+ for x in v:
860
+ if isinstance(x, Expr) and x._hash is None:
861
+ stack.append(x)
862
+
863
+ for node in reversed(nodes):
864
+ hash_ = hash(node.key)
865
+
866
+ if node._hash_raw_args:
867
+ for k in sorted(node.args):
868
+ v = node.args[k]
869
+ if v:
870
+ hash_ = hash((hash_, k, tuple(v) if type(v) is list else v))
871
+ else:
872
+ for k in sorted(node.args):
873
+ v = node.args[k]
874
+ vt = type(v)
875
+
876
+ if vt is list:
877
+ for x in v:
878
+ if x is not None and x is not False:
879
+ hash_ = hash((hash_, k, x.lower() if type(x) is str else x))
880
+ else:
881
+ hash_ = hash((hash_, k))
882
+ elif v is not None and v is not False:
883
+ hash_ = hash((hash_, k, v.lower() if vt is str else v))
884
+
885
+ node._hash = hash_
886
+ assert self._hash
887
+ return self._hash
888
+
889
+ def __reduce__(
890
+ self,
891
+ ) -> tuple[
892
+ t.Callable[[list[dict[str, t.Any]] | None], Expr | DType | None],
893
+ tuple[list[dict[str, t.Any]]],
894
+ ]:
895
+ from sqlglot.serde import dump, load
896
+
897
+ return (load, (dump(self),))
898
+
899
+ @property
900
+ def this(self) -> t.Any:
901
+ return self.args.get("this")
902
+
903
+ @property
904
+ def expression(self) -> t.Any:
905
+ return self.args.get("expression")
906
+
907
+ @property
908
+ def expressions(self) -> list[t.Any]:
909
+ return self.args.get("expressions") or []
910
+
911
+ def text(self, key: str) -> str:
912
+ field = self.args.get(key)
913
+ if isinstance(field, str):
914
+ return field
915
+ if isinstance(field, (Identifier, Literal, Var)):
916
+ return field.this
917
+ if isinstance(field, (Star, Null)):
918
+ return field.name
919
+ return ""
920
+
921
+ @property
922
+ def is_string(self) -> bool:
923
+ return isinstance(self, Literal) and self.args["is_string"]
924
+
925
+ @property
926
+ def is_number(self) -> bool:
927
+ return (isinstance(self, Literal) and not self.args["is_string"]) or (
928
+ isinstance(self, Neg) and self.this.is_number
929
+ )
930
+
931
+ def to_py(self) -> t.Any:
932
+ raise ValueError(f"{self} cannot be converted to a Python object.")
933
+
934
+ @property
935
+ def is_int(self) -> bool:
936
+ return self.is_number and isinstance(self.to_py(), int)
937
+
938
+ @property
939
+ def is_star(self) -> bool:
940
+ return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
941
+
942
+ @property
943
+ def alias(self) -> str:
944
+ alias = self.args.get("alias")
945
+ if isinstance(alias, Expression):
946
+ return alias.name
947
+ return self.text("alias")
948
+
949
+ @property
950
+ def alias_column_names(self) -> list[str]:
951
+ table_alias = self.args.get("alias")
952
+ if not table_alias:
953
+ return []
954
+ return [c.name for c in table_alias.args.get("columns") or []]
955
+
956
+ @property
957
+ def name(self) -> str:
958
+ return self.text("this")
959
+
960
+ @property
961
+ def alias_or_name(self) -> str:
962
+ return self.alias or self.name
963
+
964
+ @property
965
+ def output_name(self) -> str:
966
+ return ""
967
+
968
+ @property
969
+ def type(self) -> DataType | None:
970
+ if self.is_data_type:
971
+ return self # type: ignore[return-value]
972
+ if self.is_cast:
973
+ return self._type or self.to # type: ignore[attr-defined]
974
+ return self._type
975
+
976
+ @type.setter
977
+ def type(self, dtype: DataType | DType | str | None) -> None:
978
+ if dtype and type(dtype).__name__ != "DataType":
979
+ from sqlglot.expressions.datatypes import DataType as _DataType
980
+
981
+ dtype = _DataType.build(dtype)
982
+ self._type = dtype # type: ignore[assignment]
983
+
984
+ def is_type(self, *dtypes: DATA_TYPE) -> bool:
985
+ t = self._type
986
+ return t is not None and t.is_type(*dtypes)
987
+
988
+ def is_leaf(self) -> bool:
989
+ return not any((isinstance(v, Expr) or type(v) is list) and v for v in self.args.values())
990
+
991
+ @property
992
+ def meta(self) -> dict[str, t.Any]:
993
+ if self._meta is None:
994
+ self._meta = {}
995
+ return self._meta
996
+
997
+ def meta_get(self, key: str, default: t.Any = None) -> t.Any:
998
+ """Reads a meta value without allocating the meta dict (unlike the `meta` property)."""
999
+ meta = self._meta
1000
+ return meta.get(key, default) if meta is not None else default
1001
+
1002
+ def __deepcopy__(self, memo: t.Any) -> Expr:
1003
+ root = self.__class__()
1004
+ stack: list[tuple[Expr, Expr]] = [(self, root)]
1005
+
1006
+ while stack:
1007
+ node, copy = stack.pop()
1008
+
1009
+ if node.comments is not None:
1010
+ copy.comments = deepcopy(node.comments)
1011
+ if node._type is not None:
1012
+ copy._type = deepcopy(node._type)
1013
+ if node._meta is not None:
1014
+ copy._meta = deepcopy(node._meta)
1015
+ if node._hash is not None:
1016
+ copy._hash = node._hash
1017
+
1018
+ for k, vs in node.args.items():
1019
+ if isinstance(vs, Expr):
1020
+ stack.append((vs, vs.__class__()))
1021
+ copy.set(k, stack[-1][-1])
1022
+ elif type(vs) is list:
1023
+ copy.args[k] = []
1024
+
1025
+ for v in vs:
1026
+ if isinstance(v, Expr):
1027
+ stack.append((v, v.__class__()))
1028
+ copy.append(k, stack[-1][-1])
1029
+ else:
1030
+ copy.append(k, v)
1031
+ else:
1032
+ copy.args[k] = vs
1033
+
1034
+ return root
1035
+
1036
+ def copy(self: E) -> E:
1037
+ return deepcopy(self)
1038
+
1039
+ def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None:
1040
+ if self.comments is None:
1041
+ self.comments = []
1042
+
1043
+ if comments:
1044
+ for comment in comments:
1045
+ _, *meta = comment.split(SQLGLOT_META)
1046
+ if meta:
1047
+ for kv in "".join(meta).split(","):
1048
+ k, *v = kv.split("=")
1049
+ self.meta[k.strip()] = to_bool(v[0].strip() if v else True)
1050
+
1051
+ if not prepend:
1052
+ self.comments.append(comment)
1053
+
1054
+ if prepend:
1055
+ self.comments = comments + self.comments
1056
+
1057
+ def pop_comments(self) -> list[str]:
1058
+ comments = self.comments or []
1059
+ self.comments = None
1060
+ return comments
1061
+
1062
+ def append(self, arg_key: str, value: t.Any) -> None:
1063
+ node: Expr | None = self
1064
+ while node and node._hash is not None:
1065
+ node._hash = None
1066
+ node = node.parent
1067
+
1068
+ if type(self.args.get(arg_key)) is not list:
1069
+ self.args[arg_key] = []
1070
+ self._set_parent(arg_key, value)
1071
+ values = self.args[arg_key]
1072
+ if isinstance(value, Expr):
1073
+ value.index = len(values)
1074
+ values.append(value)
1075
+
1076
+ def set(
1077
+ self,
1078
+ arg_key: str,
1079
+ value: object,
1080
+ index: int | None = None,
1081
+ overwrite: bool = True,
1082
+ ) -> None:
1083
+ node: Expr | None = self
1084
+
1085
+ while node and node._hash is not None:
1086
+ node._hash = None
1087
+ node = node.parent
1088
+
1089
+ if index is not None:
1090
+ expressions = self.args.get(arg_key) or []
1091
+
1092
+ if seq_get(expressions, index) is None:
1093
+ return
1094
+
1095
+ if value is None:
1096
+ expressions.pop(index)
1097
+ for v in expressions[index:]:
1098
+ v.index = v.index - 1
1099
+ return
1100
+
1101
+ if isinstance(value, list):
1102
+ expressions.pop(index)
1103
+ expressions[index:index] = value
1104
+ elif overwrite:
1105
+ expressions[index] = value
1106
+ else:
1107
+ expressions.insert(index, value)
1108
+
1109
+ value = expressions
1110
+ elif value is None:
1111
+ self.args.pop(arg_key, None)
1112
+ return
1113
+
1114
+ self.args[arg_key] = value
1115
+ self._set_parent(arg_key, value, index)
1116
+
1117
+ def _set_parent(self, arg_key: str, value: object, index: int | None = None) -> None:
1118
+ if isinstance(value, Expr):
1119
+ value.parent = self
1120
+ value.arg_key = arg_key
1121
+ value.index = index
1122
+ elif isinstance(value, list):
1123
+ for i, v in enumerate(value):
1124
+ if isinstance(v, Expr):
1125
+ v.parent = self
1126
+ v.arg_key = arg_key
1127
+ v.index = i
1128
+
1129
+ def set_kwargs(self, kwargs: Mapping[str, object]) -> Self:
1130
+ """Set multiples keyword arguments at once, using `.set()` method.
1131
+
1132
+ Args:
1133
+ kwargs (Mapping[str, object]): a `Mapping` of arg keys to values to set.
1134
+ Returns:
1135
+ Self: The same `Expression` with the updated arguments.
1136
+ """
1137
+ if kwargs:
1138
+ for k, v in kwargs.items():
1139
+ self.set(k, v)
1140
+ return self
1141
+
1142
+ @property
1143
+ def depth(self) -> int:
1144
+ if self.parent:
1145
+ return self.parent.depth + 1
1146
+ return 0
1147
+
1148
+ def iter_expressions(self: E, reverse: bool = False) -> Iterator[E]:
1149
+ for vs in reversed(self.args.values()) if reverse else self.args.values():
1150
+ if isinstance(vs, list):
1151
+ for v in reversed(vs) if reverse else vs:
1152
+ if isinstance(v, Expr):
1153
+ yield t.cast(E, v)
1154
+ elif isinstance(vs, Expr):
1155
+ yield t.cast(E, vs)
1156
+
1157
+ def find(self, *expression_types: Type[E], bfs: bool = True) -> E | None:
1158
+ return next(self.find_all(*expression_types, bfs=bfs), None)
1159
+
1160
+ def find_all(self, *expression_types: Type[E], bfs: bool = True) -> Iterator[E]:
1161
+ for expression in self.walk(bfs=bfs):
1162
+ if isinstance(expression, expression_types):
1163
+ yield expression
1164
+
1165
+ def find_ancestor(self, *expression_types: Type[E]) -> E | None:
1166
+ ancestor = self.parent
1167
+ while ancestor and not isinstance(ancestor, expression_types):
1168
+ ancestor = ancestor.parent
1169
+ return ancestor # type: ignore[return-value]
1170
+
1171
+ @property
1172
+ def parent_select(self) -> Select | None:
1173
+ from sqlglot.expressions.query import Select as _Select
1174
+
1175
+ return self.find_ancestor(_Select)
1176
+
1177
+ @property
1178
+ def same_parent(self) -> bool:
1179
+ return type(self.parent) is self.__class__
1180
+
1181
+ def root(self) -> Expr:
1182
+ expression: Expr = self
1183
+ while expression.parent:
1184
+ expression = expression.parent
1185
+ return expression
1186
+
1187
+ def walk(
1188
+ self, bfs: bool = True, prune: t.Callable[[Expr], bool] | None = None
1189
+ ) -> Iterator[Expr]:
1190
+ if bfs:
1191
+ yield from self.bfs(prune=prune)
1192
+ else:
1193
+ yield from self.dfs(prune=prune)
1194
+
1195
+ def dfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
1196
+ stack = [self]
1197
+
1198
+ while stack:
1199
+ node = stack.pop()
1200
+ yield node
1201
+ if prune and prune(node):
1202
+ continue
1203
+ for v in node.iter_expressions(reverse=True):
1204
+ stack.append(v)
1205
+
1206
+ def bfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
1207
+ queue: deque[Expr] = deque()
1208
+ queue.append(self)
1209
+
1210
+ while queue:
1211
+ node = queue.popleft()
1212
+ yield node
1213
+ if prune and prune(node):
1214
+ continue
1215
+ for v in node.iter_expressions():
1216
+ queue.append(v)
1217
+
1218
+ def unnest(self) -> Expr:
1219
+ expression = self
1220
+ while type(expression) is Paren:
1221
+ expression = expression.this
1222
+ return expression
1223
+
1224
+ def unalias(self) -> Expr:
1225
+ if isinstance(self, Alias):
1226
+ return self.this
1227
+ return self
1228
+
1229
+ def unnest_operands(self) -> tuple[Expr, ...]:
1230
+ return tuple(arg.unnest() for arg in self.iter_expressions())
1231
+
1232
+ def flatten(self, unnest: bool = True) -> Iterator[Expr]:
1233
+ for node in self.dfs(prune=lambda n: bool(n.parent and type(n) is not self.__class__)):
1234
+ if type(node) is not self.__class__:
1235
+ yield node.unnest() if unnest and not node.is_subquery else node
1236
+
1237
+ def __str__(self) -> str:
1238
+ return self.sql()
1239
+
1240
+ def __repr__(self) -> str:
1241
+ return _to_s(self)
1242
+
1243
+ def to_s(self) -> str:
1244
+ return _to_s(self, verbose=True)
1245
+
1246
+ def sql(
1247
+ self, dialect: DialectType = None, copy: bool = True, **opts: Unpack[GeneratorNoDialectArgs]
1248
+ ) -> str:
1249
+ from sqlglot.dialects.dialect import Dialect
1250
+
1251
+ return Dialect.get_or_raise(dialect).generate(self, copy=copy, **opts)
1252
+
1253
+ def transform(
1254
+ self, fun: t.Callable[..., T], *args: object, copy: bool = True, **kwargs: object
1255
+ ) -> T:
1256
+ root: t.Any = None
1257
+ new_node: t.Any = None
1258
+
1259
+ for node in (self.copy() if copy else self).dfs(prune=lambda n: n is not new_node):
1260
+ parent, arg_key, index = node.parent, node.arg_key, node.index
1261
+ new_node = fun(node, *args, **kwargs)
1262
+
1263
+ if not root:
1264
+ root = new_node
1265
+ elif parent and arg_key and new_node is not node:
1266
+ parent.set(arg_key, new_node, index)
1267
+
1268
+ assert root
1269
+ return root
1270
+
1271
+ def replace(self, expression: T) -> T:
1272
+ parent = self.parent
1273
+
1274
+ if not parent or parent is expression:
1275
+ return expression
1276
+
1277
+ key = self.arg_key
1278
+
1279
+ if key:
1280
+ value = parent.args.get(key)
1281
+
1282
+ if type(expression) is list and isinstance(value, Expr):
1283
+ # We are trying to replace an Expr with a list, so it's assumed that
1284
+ # the intention was to really replace the parent of this expression.
1285
+ if value.parent:
1286
+ value.parent.replace(expression)
1287
+ else:
1288
+ parent.set(key, expression, self.index)
1289
+
1290
+ if expression is not self:
1291
+ self.parent = None
1292
+ self.arg_key = None
1293
+ self.index = None
1294
+
1295
+ return expression
1296
+
1297
+ def pop(self: E) -> E:
1298
+ self.replace(None)
1299
+ return self
1300
+
1301
+ def assert_is(self, type_: Type[E]) -> E:
1302
+ if not isinstance(self, type_):
1303
+ raise AssertionError(f"{self} is not {type_}.")
1304
+ return self
1305
+
1306
+ def error_messages(self, args: Sequence[object] | None = None) -> list[str]:
1307
+ if UNITTEST:
1308
+ for k in self.args:
1309
+ if k not in self.arg_types:
1310
+ raise TypeError(f"Unexpected keyword: '{k}' for {self.__class__}")
1311
+
1312
+ errors: list[str] | None = None
1313
+
1314
+ for k in self.required_args:
1315
+ v = self.args.get(k)
1316
+ if v is None or (isinstance(v, list) and not v):
1317
+ if errors is None:
1318
+ errors = []
1319
+ errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
1320
+
1321
+ if (
1322
+ args
1323
+ and isinstance(self, Func)
1324
+ and len(args) > len(self.arg_types)
1325
+ and not self.is_var_len_args
1326
+ ):
1327
+ if errors is None:
1328
+ errors = []
1329
+ errors.append(
1330
+ f"The number of provided arguments ({len(args)}) is greater than "
1331
+ f"the maximum number of supported arguments ({len(self.arg_types)})"
1332
+ )
1333
+
1334
+ return errors or []
1335
+
1336
+ def and_(
1337
+ self,
1338
+ *expressions: ExpOrStr | None,
1339
+ dialect: DialectType = None,
1340
+ copy: bool = True,
1341
+ wrap: bool = True,
1342
+ **opts: Unpack[ParserNoDialectArgs],
1343
+ ) -> Condition:
1344
+ return and_(self, *expressions, dialect=dialect, copy=copy, wrap=wrap, **opts)
1345
+
1346
+ def or_(
1347
+ self,
1348
+ *expressions: ExpOrStr | None,
1349
+ dialect: DialectType = None,
1350
+ copy: bool = True,
1351
+ wrap: bool = True,
1352
+ **opts: Unpack[ParserNoDialectArgs],
1353
+ ) -> Condition:
1354
+ return or_(self, *expressions, dialect=dialect, copy=copy, wrap=wrap, **opts)
1355
+
1356
+ def not_(self, copy: bool = True) -> Not:
1357
+ return not_(self, copy=copy)
1358
+
1359
+ def update_positions(
1360
+ self: E,
1361
+ other: Token | Expr | None = None,
1362
+ line: int | None = None,
1363
+ col: int | None = None,
1364
+ start: int | None = None,
1365
+ end: int | None = None,
1366
+ ) -> E:
1367
+ if isinstance(other, Token):
1368
+ meta = self.meta
1369
+ meta["line"] = other.line
1370
+ meta["col"] = other.col
1371
+ meta["start"] = other.start
1372
+ meta["end"] = other.end
1373
+ elif other is not None:
1374
+ other_meta = other._meta
1375
+ if other_meta:
1376
+ meta = self.meta
1377
+ for k in POSITION_META_KEYS:
1378
+ if k in other_meta:
1379
+ meta[k] = other_meta[k]
1380
+ else:
1381
+ meta = self.meta
1382
+ meta["line"] = line
1383
+ meta["col"] = col
1384
+ meta["start"] = start
1385
+ meta["end"] = end
1386
+ return self
1387
+
1388
+ def as_(
1389
+ self,
1390
+ alias: str | Identifier,
1391
+ quoted: bool | None = None,
1392
+ dialect: DialectType = None,
1393
+ copy: bool = True,
1394
+ table: bool | Sequence[str | Identifier] = False,
1395
+ **opts: Unpack[ParserNoDialectArgs],
1396
+ ) -> Expr:
1397
+ return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, table=table, **opts)
1398
+
1399
+ def _binop(self, klass: Type[E], other: t.Any, reverse: bool = False) -> E:
1400
+ this = self.copy()
1401
+ other = convert(other, copy=True)
1402
+ if not isinstance(this, klass) and not isinstance(other, klass):
1403
+ this = _wrap(this, Binary)
1404
+ other = _wrap(other, Binary)
1405
+ if reverse:
1406
+ return klass(this=other, expression=this)
1407
+ return klass(this=this, expression=other)
1408
+
1409
+ def __getitem__(self, other: ExpOrStr | tuple[ExpOrStr, ...]) -> Bracket:
1410
+ return Bracket(
1411
+ this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
1412
+ )
1413
+
1414
+ def __iter__(self) -> Iterator:
1415
+ if "expressions" in self.arg_types:
1416
+ return iter(self.args.get("expressions") or [])
1417
+ # We define this because __getitem__ converts Expr into an iterable, which is
1418
+ # problematic because one can hit infinite loops if they do "for x in some_expr: ..."
1419
+ # See: https://peps.python.org/pep-0234/
1420
+ raise TypeError(f"'{self.__class__.__name__}' object is not iterable")
1421
+
1422
+ def isin(
1423
+ self,
1424
+ *expressions: t.Any,
1425
+ query: ExpOrStr | None = None,
1426
+ unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
1427
+ dialect: DialectType = None,
1428
+ copy: bool = True,
1429
+ **opts: Unpack[ParserNoDialectArgs],
1430
+ ) -> In:
1431
+ from sqlglot.expressions.query import Query
1432
+
1433
+ subquery: Expr | None = None
1434
+ if query:
1435
+ subquery = maybe_parse(query, dialect=dialect, copy=copy, **opts)
1436
+ if isinstance(subquery, Query):
1437
+ subquery = subquery.subquery(copy=False)
1438
+ unnest_list: list[ExpOrStr] = ensure_list(unnest)
1439
+ return In(
1440
+ this=maybe_copy(self, copy),
1441
+ expressions=[convert(e, copy=copy) for e in expressions],
1442
+ query=subquery,
1443
+ unnest=(
1444
+ _lazy_unnest(
1445
+ expressions=[
1446
+ maybe_parse(e, dialect=dialect, copy=copy, **opts) for e in unnest_list
1447
+ ]
1448
+ )
1449
+ if unnest
1450
+ else None
1451
+ ),
1452
+ )
1453
+
1454
+ def between(
1455
+ self, low: t.Any, high: t.Any, copy: bool = True, symmetric: bool | None = None
1456
+ ) -> Between:
1457
+ between = Between(
1458
+ this=maybe_copy(self, copy),
1459
+ low=convert(low, copy=copy),
1460
+ high=convert(high, copy=copy),
1461
+ )
1462
+ if symmetric is not None:
1463
+ between.set("symmetric", symmetric)
1464
+
1465
+ return between
1466
+
1467
+ def is_(self, other: ExpOrStr) -> Is:
1468
+ return self._binop(Is, other)
1469
+
1470
+ def like(self, other: ExpOrStr) -> Like:
1471
+ return self._binop(Like, other)
1472
+
1473
+ def ilike(self, other: ExpOrStr) -> ILike:
1474
+ return self._binop(ILike, other)
1475
+
1476
+ def eq(self, other: t.Any) -> EQ:
1477
+ return self._binop(EQ, other)
1478
+
1479
+ def neq(self, other: t.Any) -> NEQ:
1480
+ return self._binop(NEQ, other)
1481
+
1482
+ def rlike(self, other: ExpOrStr) -> RegexpLike:
1483
+ return self._binop(RegexpLike, other)
1484
+
1485
+ def div(self, other: ExpOrStr, typed: bool = False, safe: bool = False) -> Div:
1486
+ div = self._binop(Div, other)
1487
+ div.set("typed", typed)
1488
+ div.set("safe", safe)
1489
+ return div
1490
+
1491
+ def asc(self, nulls_first: bool = True) -> Ordered:
1492
+ return Ordered(this=self.copy(), nulls_first=nulls_first)
1493
+
1494
+ def desc(self, nulls_first: bool = False) -> Ordered:
1495
+ return Ordered(this=self.copy(), desc=True, nulls_first=nulls_first)
1496
+
1497
+ def __lt__(self, other: t.Any) -> LT:
1498
+ return self._binop(LT, other)
1499
+
1500
+ def __le__(self, other: t.Any) -> LTE:
1501
+ return self._binop(LTE, other)
1502
+
1503
+ def __gt__(self, other: t.Any) -> GT:
1504
+ return self._binop(GT, other)
1505
+
1506
+ def __ge__(self, other: t.Any) -> GTE:
1507
+ return self._binop(GTE, other)
1508
+
1509
+ def __add__(self, other: t.Any) -> Add:
1510
+ return self._binop(Add, other)
1511
+
1512
+ def __radd__(self, other: t.Any) -> Add:
1513
+ return self._binop(Add, other, reverse=True)
1514
+
1515
+ def __sub__(self, other: t.Any) -> Sub:
1516
+ return self._binop(Sub, other)
1517
+
1518
+ def __rsub__(self, other: t.Any) -> Sub:
1519
+ return self._binop(Sub, other, reverse=True)
1520
+
1521
+ def __mul__(self, other: t.Any) -> Mul:
1522
+ return self._binop(Mul, other)
1523
+
1524
+ def __rmul__(self, other: t.Any) -> Mul:
1525
+ return self._binop(Mul, other, reverse=True)
1526
+
1527
+ def __truediv__(self, other: t.Any) -> Div:
1528
+ return self._binop(Div, other)
1529
+
1530
+ def __rtruediv__(self, other: t.Any) -> Div:
1531
+ return self._binop(Div, other, reverse=True)
1532
+
1533
+ def __floordiv__(self, other: t.Any) -> IntDiv:
1534
+ return self._binop(IntDiv, other)
1535
+
1536
+ def __rfloordiv__(self, other: t.Any) -> IntDiv:
1537
+ return self._binop(IntDiv, other, reverse=True)
1538
+
1539
+ def __mod__(self, other: t.Any) -> Mod:
1540
+ return self._binop(Mod, other)
1541
+
1542
+ def __rmod__(self, other: t.Any) -> Mod:
1543
+ return self._binop(Mod, other, reverse=True)
1544
+
1545
+ def __pow__(self, other: t.Any) -> Pow:
1546
+ return self._binop(Pow, other)
1547
+
1548
+ def __rpow__(self, other: t.Any) -> Pow:
1549
+ return self._binop(Pow, other, reverse=True)
1550
+
1551
+ def __and__(self, other: t.Any) -> And:
1552
+ return self._binop(And, other)
1553
+
1554
+ def __rand__(self, other: t.Any) -> And:
1555
+ return self._binop(And, other, reverse=True)
1556
+
1557
+ def __or__(self, other: t.Any) -> Or:
1558
+ return self._binop(Or, other)
1559
+
1560
+ def __ror__(self, other: t.Any) -> Or:
1561
+ return self._binop(Or, other, reverse=True)
1562
+
1563
+ def __neg__(self) -> Neg:
1564
+ return Neg(this=_wrap(self.copy(), Binary))
1565
+
1566
+ def __invert__(self) -> Not:
1567
+ return not_(self.copy())
1568
+
1569
+
1570
+ IntoType = t.Union[Type[Expr], Collection[Type[Expr]]]
1571
+ ExpOrStr = t.Union[int, str, Expr]
1572
+
1573
+
1574
+ @trait
1575
+ class Condition(Expr):
1576
+ """Logical conditions like x AND y, or simply x"""
1577
+
1578
+
1579
+ @trait
1580
+ class Predicate(Condition):
1581
+ """Any condition that evaluates to a boolean, e.g. x = y, x LIKE 'a%', a @> b."""
1582
+
1583
+
1584
+ class Cache(Expression):
1585
+ arg_types = {
1586
+ "this": True,
1587
+ "lazy": False,
1588
+ "options": False,
1589
+ "expression": False,
1590
+ }
1591
+
1592
+
1593
+ class Uncache(Expression):
1594
+ arg_types = {"this": True, "exists": False}
1595
+
1596
+
1597
+ class Refresh(Expression):
1598
+ arg_types = {
1599
+ "this": True,
1600
+ "kind": True,
1601
+ "partition_start": False,
1602
+ "partition_end": False,
1603
+ "force": False,
1604
+ "mode": False,
1605
+ }
1606
+
1607
+
1608
+ class LockingStatement(Expression):
1609
+ arg_types = {"this": True, "expression": True}
1610
+
1611
+
1612
+ @trait
1613
+ class ColumnConstraintKind(Expr):
1614
+ pass
1615
+
1616
+
1617
+ @trait
1618
+ class SubqueryPredicate(Predicate):
1619
+ pass
1620
+
1621
+
1622
+ class All(Expression, SubqueryPredicate):
1623
+ pass
1624
+
1625
+
1626
+ class Any(Expression, SubqueryPredicate):
1627
+ pass
1628
+
1629
+
1630
+ @trait
1631
+ class Binary(Condition):
1632
+ arg_types: t.ClassVar[dict[str, bool]] = {"this": True, "expression": True}
1633
+
1634
+ @property
1635
+ def left(self) -> Expr:
1636
+ return self.args["this"]
1637
+
1638
+ @property
1639
+ def right(self) -> Expr:
1640
+ return self.args["expression"]
1641
+
1642
+
1643
+ @trait
1644
+ class Connector(Binary):
1645
+ pass
1646
+
1647
+
1648
+ @trait
1649
+ class Func(Condition):
1650
+ """
1651
+ The base class for all function expressions.
1652
+
1653
+ Attributes:
1654
+ is_var_len_args (bool): if set to True the argument identified by var_len_arg_key will be
1655
+ treated as a variable length argument and the argument's value will be stored as a list.
1656
+ var_len_arg_key (str): the arg_types key that collects the variable length arguments.
1657
+ Arguments preceding it in arg_types are filled positionally; those following it (e.g.
1658
+ dialect flags) are never populated by from_arg_list.
1659
+ _sql_names (list): the SQL name (1st item in the list) and aliases (subsequent items) for this
1660
+ function expression. These values are used to map this node to a name during parsing as
1661
+ well as to provide the function's name during SQL string generation. By default the SQL
1662
+ name is set to the expression's class name transformed to snake case.
1663
+ """
1664
+
1665
+ is_var_len_args: t.ClassVar[bool] = False
1666
+ var_len_arg_key: t.ClassVar[str] = "expressions"
1667
+ _sql_names: t.ClassVar[list[str]] = []
1668
+
1669
+ @classmethod
1670
+ def from_arg_list(cls, args: Sequence[object]) -> Self:
1671
+ if cls.is_var_len_args:
1672
+ all_arg_keys = tuple(cls.arg_types)
1673
+ var_len_index = all_arg_keys.index(cls.var_len_arg_key)
1674
+
1675
+ args_dict = {arg_key: arg for arg, arg_key in zip(args, all_arg_keys[:var_len_index])}
1676
+ args_dict[cls.var_len_arg_key] = args[var_len_index:]
1677
+ else:
1678
+ args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
1679
+
1680
+ return cls(**args_dict)
1681
+
1682
+ @classmethod
1683
+ def sql_names(cls) -> list[str]:
1684
+ if cls is Func:
1685
+ raise NotImplementedError(
1686
+ "SQL name is only supported by concrete function implementations"
1687
+ )
1688
+ if not cls._sql_names:
1689
+ return [camel_to_snake_case(cls.__name__)]
1690
+ return cls._sql_names
1691
+
1692
+ @classmethod
1693
+ def sql_name(cls) -> str:
1694
+ sql_names = cls.sql_names()
1695
+ assert sql_names, f"Expected non-empty 'sql_names' for Func: {cls.__name__}."
1696
+ return sql_names[0]
1697
+
1698
+ @classmethod
1699
+ def default_parser_mappings(cls) -> dict[str, t.Callable[[Sequence[object]], Self]]:
1700
+ return {name: cls.from_arg_list for name in cls.sql_names()}
1701
+
1702
+
1703
+ @trait
1704
+ class AggFunc(Func):
1705
+ pass
1706
+
1707
+
1708
+ class Column(Expression, Condition):
1709
+ # "shadow" marks a column whose qualifier is shadowed by a projection alias, so it must be
1710
+ # rendered unqualified in dialects where PROJECTION_ALIASES_SHADOW_SOURCE_NAMES is set
1711
+ arg_types = {
1712
+ "this": True,
1713
+ "table": False,
1714
+ "db": False,
1715
+ "catalog": False,
1716
+ "join_mark": False,
1717
+ "shadow": False,
1718
+ }
1719
+
1720
+ @property
1721
+ def table(self) -> str:
1722
+ return self.text("table")
1723
+
1724
+ @property
1725
+ def db(self) -> str:
1726
+ return self.text("db")
1727
+
1728
+ @property
1729
+ def catalog(self) -> str:
1730
+ return self.text("catalog")
1731
+
1732
+ @property
1733
+ def output_name(self) -> str:
1734
+ return self.name
1735
+
1736
+ @property
1737
+ def parts(self) -> list[Expr]:
1738
+ """Return the parts of a column in order catalog, db, table, name."""
1739
+ return [
1740
+ self.args[part] for part in ("catalog", "db", "table", "this") if self.args.get(part)
1741
+ ]
1742
+
1743
+ def to_dot(self, include_dots: bool = True) -> Expr:
1744
+ """Converts the column into a dot expression."""
1745
+ parts = self.parts
1746
+ parent = self.parent
1747
+
1748
+ if include_dots:
1749
+ while isinstance(parent, Dot):
1750
+ parts.append(parent.expression)
1751
+ parent = parent.parent
1752
+
1753
+ return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]
1754
+
1755
+
1756
+ class Literal(Expression, Condition):
1757
+ arg_types = {"this": True, "is_string": True}
1758
+ _hash_raw_args = True
1759
+ is_primitive = True
1760
+
1761
+ @classmethod
1762
+ def number(cls, number: object) -> Literal | Neg:
1763
+ lit = cls(this=str(number), is_string=False)
1764
+ try:
1765
+ to_py = lit.to_py()
1766
+ if not isinstance(to_py, str) and to_py < 0:
1767
+ lit.set("this", str(abs(to_py)))
1768
+ return Neg(this=lit)
1769
+ except Exception:
1770
+ pass
1771
+ return lit
1772
+
1773
+ @classmethod
1774
+ def string(cls, string: object) -> Literal:
1775
+ return cls(this=str(string), is_string=True)
1776
+
1777
+ @property
1778
+ def output_name(self) -> str:
1779
+ return self.name
1780
+
1781
+ def to_py(self) -> int | str | Decimal:
1782
+ if self.is_number:
1783
+ try:
1784
+ return int(self.this)
1785
+ except ValueError:
1786
+ try:
1787
+ return Decimal(self.this)
1788
+ except InvalidOperation as e:
1789
+ raise ValueError(f"Invalid numeric literal: {self.this!r}") from e
1790
+ return self.this
1791
+
1792
+
1793
+ class Var(Expression):
1794
+ is_primitive = True
1795
+
1796
+
1797
+ class WithinGroup(Expression):
1798
+ arg_types = {"this": True, "expression": False}
1799
+
1800
+
1801
+ class Pseudocolumn(Column):
1802
+ pass
1803
+
1804
+
1805
+ class Hint(Expression):
1806
+ arg_types = {"expressions": True}
1807
+
1808
+
1809
+ class JoinHint(Expression):
1810
+ arg_types = {"this": True, "expressions": True}
1811
+
1812
+
1813
+ class Identifier(Expression):
1814
+ arg_types = {
1815
+ "this": True,
1816
+ "quoted": False,
1817
+ "global_": False,
1818
+ "temporary": False,
1819
+ }
1820
+ is_primitive = True
1821
+ _hash_raw_args = True
1822
+
1823
+ @property
1824
+ def quoted(self) -> bool:
1825
+ return bool(self.args.get("quoted"))
1826
+
1827
+ @property
1828
+ def output_name(self) -> str:
1829
+ return self.name
1830
+
1831
+
1832
+ # https://docs.snowflake.com/en/sql-reference/identifier-literal
1833
+ # "expressions" holds the arguments when the resolved identifier is invoked as a
1834
+ # function, e.g. `IDENTIFIER('my_func')(1, 2)`
1835
+ class DynamicIdentifier(Expression, Func):
1836
+ arg_types = {"this": True, "expressions": False}
1837
+
1838
+ @property
1839
+ def name(self) -> str:
1840
+ return self.this.name if self.this else ""
1841
+
1842
+
1843
+ class Opclass(Expression):
1844
+ arg_types = {"this": True, "expression": True}
1845
+
1846
+
1847
+ class Star(Expression):
1848
+ arg_types = {"except_": False, "replace": False, "rename": False, "ilike": False}
1849
+
1850
+ @property
1851
+ def name(self) -> str:
1852
+ return "*"
1853
+
1854
+ @property
1855
+ def output_name(self) -> str:
1856
+ return self.name
1857
+
1858
+
1859
+ class Parameter(Expression, Condition):
1860
+ arg_types = {"this": True, "expression": False}
1861
+
1862
+
1863
+ class SessionParameter(Expression, Condition):
1864
+ arg_types = {"this": True, "kind": False}
1865
+
1866
+
1867
+ class Placeholder(Expression, Condition):
1868
+ arg_types = {"this": False, "kind": False, "widget": False, "jdbc": False}
1869
+ _hash_raw_args = True
1870
+
1871
+ @property
1872
+ def name(self) -> str:
1873
+ return self.text("this") or "?"
1874
+
1875
+
1876
+ class Null(Expression, Condition):
1877
+ arg_types = {}
1878
+
1879
+ @property
1880
+ def name(self) -> str:
1881
+ return "NULL"
1882
+
1883
+ def to_py(self) -> t.Literal[None]:
1884
+ return None
1885
+
1886
+
1887
+ class Boolean(Expression, Condition):
1888
+ is_primitive = True
1889
+
1890
+ def to_py(self) -> bool:
1891
+ return self.this
1892
+
1893
+
1894
+ class Dot(Expression, Binary):
1895
+ @property
1896
+ def is_star(self) -> bool:
1897
+ return self.expression.is_star
1898
+
1899
+ @property
1900
+ def name(self) -> str:
1901
+ return self.expression.name
1902
+
1903
+ @property
1904
+ def output_name(self) -> str:
1905
+ return self.name
1906
+
1907
+ @classmethod
1908
+ def build(cls, expressions: Sequence[Expr]) -> Dot:
1909
+ """Build a Dot object with a sequence of expressions."""
1910
+ if len(expressions) < 2:
1911
+ raise ValueError("Dot requires >= 2 expressions.")
1912
+
1913
+ return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))
1914
+
1915
+ @property
1916
+ def parts(self) -> list[Expr]:
1917
+ """Return the parts of a table / column in order catalog, db, table."""
1918
+ this, *parts = self.flatten()
1919
+
1920
+ parts.reverse()
1921
+
1922
+ for arg in COLUMN_PARTS:
1923
+ part = this.args.get(arg)
1924
+
1925
+ if isinstance(part, Expr):
1926
+ parts.append(part)
1927
+
1928
+ parts.reverse()
1929
+ return parts
1930
+
1931
+
1932
+ class Kwarg(Expression, Binary):
1933
+ """Kwarg in special functions like func(kwarg => y)."""
1934
+
1935
+
1936
+ class Alias(Expression):
1937
+ arg_types = {"this": True, "alias": False}
1938
+
1939
+ @property
1940
+ def output_name(self) -> str:
1941
+ return self.alias
1942
+
1943
+
1944
+ class PivotAlias(Alias):
1945
+ pass
1946
+
1947
+
1948
+ class PivotAny(Expression):
1949
+ arg_types = {"this": False}
1950
+
1951
+
1952
+ class Aliases(Expression):
1953
+ arg_types = {"this": True, "expressions": True}
1954
+
1955
+ @property
1956
+ def aliases(self) -> list[Expr]:
1957
+ return self.expressions
1958
+
1959
+
1960
+ class Bracket(Expression, Condition):
1961
+ # https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#array_subscript_operator
1962
+ arg_types = {
1963
+ "this": True,
1964
+ "expressions": True,
1965
+ "offset": False,
1966
+ "safe": False,
1967
+ "returns_list_for_maps": False,
1968
+ "json_access": False,
1969
+ }
1970
+
1971
+ @property
1972
+ def output_name(self) -> str:
1973
+ if len(self.expressions) == 1:
1974
+ return self.expressions[0].output_name
1975
+
1976
+ return super().output_name
1977
+
1978
+
1979
+ class ForIn(Expression):
1980
+ arg_types = {"this": True, "expression": True}
1981
+
1982
+
1983
+ class IgnoreNulls(Expression):
1984
+ pass
1985
+
1986
+
1987
+ class RespectNulls(Expression):
1988
+ pass
1989
+
1990
+
1991
+ class HavingMax(Expression):
1992
+ arg_types = {"this": True, "expression": True, "max": True}
1993
+
1994
+
1995
+ class SafeFunc(Expression, Func):
1996
+ pass
1997
+
1998
+
1999
+ class Typeof(Expression, Func):
2000
+ pass
2001
+
2002
+
2003
+ class ParameterizedAgg(Expression, AggFunc):
2004
+ arg_types = {"this": True, "expressions": True, "params": True}
2005
+ _hash_raw_args = True
2006
+
2007
+
2008
+ class Anonymous(Expression, Func):
2009
+ arg_types = {"this": True, "expressions": False}
2010
+ is_var_len_args = True
2011
+
2012
+ @property
2013
+ def name(self) -> str:
2014
+ return self.this if isinstance(self.this, str) else self.this.name
2015
+
2016
+
2017
+ class AnonymousAggFunc(Expression, AggFunc):
2018
+ arg_types = {"this": True, "expressions": False}
2019
+ is_var_len_args = True
2020
+ _hash_raw_args = True
2021
+
2022
+
2023
+ class CombinedAggFunc(AnonymousAggFunc):
2024
+ arg_types = {"this": True, "expressions": False}
2025
+
2026
+
2027
+ class CombinedParameterizedAgg(ParameterizedAgg):
2028
+ arg_types = {"this": True, "expressions": True, "params": True}
2029
+
2030
+
2031
+ class HashAgg(Expression, AggFunc):
2032
+ arg_types = {"this": True, "expressions": False}
2033
+ is_var_len_args = True
2034
+
2035
+
2036
+ class Hll(Expression, AggFunc):
2037
+ arg_types = {"this": True, "expressions": False}
2038
+ is_var_len_args = True
2039
+
2040
+
2041
+ class ApproxDistinct(Expression, AggFunc):
2042
+ arg_types = {"this": True, "accuracy": False}
2043
+ _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
2044
+
2045
+
2046
+ class Slice(Expression):
2047
+ arg_types = {"this": False, "expression": False, "step": False}
2048
+
2049
+
2050
+ @trait
2051
+ class TimeUnit(Expr):
2052
+ """Automatically converts unit arg into a var."""
2053
+
2054
+ UNABBREVIATED_UNIT_NAME: t.ClassVar[dict[str, str]] = {
2055
+ "D": "DAY",
2056
+ "H": "HOUR",
2057
+ "M": "MINUTE",
2058
+ "MS": "MILLISECOND",
2059
+ "NS": "NANOSECOND",
2060
+ "Q": "QUARTER",
2061
+ "S": "SECOND",
2062
+ "US": "MICROSECOND",
2063
+ "W": "WEEK",
2064
+ "Y": "YEAR",
2065
+ }
2066
+
2067
+ VAR_LIKE: t.ClassVar[tuple[Type[Expr], ...]] = (Column, Literal, Var)
2068
+
2069
+ def __init__(self, **args: object) -> None:
2070
+ super().__init__(**args)
2071
+
2072
+ unit = self.args.get("unit")
2073
+ if (
2074
+ unit
2075
+ and type(unit) in TimeUnit.VAR_LIKE
2076
+ and not (isinstance(unit, Column) and len(unit.parts) != 1)
2077
+ ):
2078
+ unit = Var(this=(self.UNABBREVIATED_UNIT_NAME.get(unit.name) or unit.name).upper())
2079
+ self.args["unit"] = unit
2080
+ self._set_parent("unit", unit)
2081
+ elif type(unit).__name__ == "Week":
2082
+ unit.set("this", Var(this=unit.this.name.upper())) # type: ignore[union-attr]
2083
+
2084
+ @property
2085
+ def unit(self) -> Expr | None:
2086
+ return self.args.get("unit")
2087
+
2088
+
2089
+ class _TimeUnit(Expression, TimeUnit):
2090
+ """Automatically converts unit arg into a var."""
2091
+
2092
+ arg_types = {"unit": False}
2093
+
2094
+
2095
+ @trait
2096
+ class IntervalOp(TimeUnit):
2097
+ def interval(self) -> Interval:
2098
+ from sqlglot.expressions.datatypes import Interval
2099
+
2100
+ expr = self.expression
2101
+ return Interval(
2102
+ this=expr.copy() if expr is not None else None,
2103
+ unit=self.unit.copy() if self.unit else None,
2104
+ )
2105
+
2106
+
2107
+ class Filter(Expression):
2108
+ arg_types = {"this": True, "expression": True}
2109
+
2110
+
2111
+ class Check(Expression):
2112
+ pass
2113
+
2114
+
2115
+ class Ordered(Expression):
2116
+ arg_types = {"this": True, "desc": False, "nulls_first": True, "with_fill": False}
2117
+
2118
+ @property
2119
+ def name(self) -> str:
2120
+ return self.this.name
2121
+
2122
+
2123
+ class Add(Expression, Binary):
2124
+ pass
2125
+
2126
+
2127
+ class BitwiseAnd(Expression, Binary):
2128
+ arg_types = {"this": True, "expression": True, "padside": False}
2129
+
2130
+
2131
+ class BitwiseLeftShift(Expression, Binary):
2132
+ arg_types = {"this": True, "expression": True, "requires_int128": False}
2133
+
2134
+
2135
+ class BitwiseOr(Expression, Binary):
2136
+ arg_types = {"this": True, "expression": True, "padside": False}
2137
+
2138
+
2139
+ class BitwiseRightShift(Expression, Binary):
2140
+ arg_types = {"this": True, "expression": True, "requires_int128": False}
2141
+
2142
+
2143
+ class BitwiseXor(Expression, Binary):
2144
+ arg_types = {"this": True, "expression": True, "padside": False}
2145
+
2146
+
2147
+ class Div(Expression, Binary):
2148
+ arg_types = {"this": True, "expression": True, "typed": False, "safe": False}
2149
+
2150
+
2151
+ class Overlaps(Expression, Binary, Predicate):
2152
+ pass
2153
+
2154
+
2155
+ class ExtendsLeft(Expression, Binary, Predicate):
2156
+ pass
2157
+
2158
+
2159
+ class ExtendsRight(Expression, Binary, Predicate):
2160
+ pass
2161
+
2162
+
2163
+ class DPipe(Expression, Binary):
2164
+ arg_types = {"this": True, "expression": True, "safe": False}
2165
+
2166
+
2167
+ class EQ(Expression, Binary, Predicate):
2168
+ pass
2169
+
2170
+
2171
+ class NullSafeEQ(Expression, Binary, Predicate):
2172
+ pass
2173
+
2174
+
2175
+ class NullSafeNEQ(Expression, Binary, Predicate):
2176
+ pass
2177
+
2178
+
2179
+ class PropertyEQ(Expression, Binary):
2180
+ pass
2181
+
2182
+
2183
+ class Distance(Expression, Binary):
2184
+ pass
2185
+
2186
+
2187
+ class DistanceNd(Expression, Binary):
2188
+ pass
2189
+
2190
+
2191
+ class Escape(Expression, Binary):
2192
+ pass
2193
+
2194
+
2195
+ class Glob(Expression, Binary, Predicate):
2196
+ pass
2197
+
2198
+
2199
+ class GT(Expression, Binary, Predicate):
2200
+ pass
2201
+
2202
+
2203
+ class GTE(Expression, Binary, Predicate):
2204
+ pass
2205
+
2206
+
2207
+ class ILike(Expression, Binary, Predicate):
2208
+ arg_types = {"this": True, "expression": True, "negate": False}
2209
+
2210
+
2211
+ class IntDiv(Expression, Binary):
2212
+ pass
2213
+
2214
+
2215
+ class Is(Expression, Binary, Predicate):
2216
+ arg_types = {"this": True, "expression": True, "negate": False}
2217
+
2218
+
2219
+ class Like(Expression, Binary, Predicate):
2220
+ arg_types = {"this": True, "expression": True, "negate": False}
2221
+
2222
+
2223
+ class Match(Expression, Binary, Predicate):
2224
+ arg_types = {"this": True, "expression": True, "kind": False, "analyzer": False}
2225
+
2226
+
2227
+ class LT(Expression, Binary, Predicate):
2228
+ pass
2229
+
2230
+
2231
+ class LTE(Expression, Binary, Predicate):
2232
+ pass
2233
+
2234
+
2235
+ class Mod(Expression, Binary):
2236
+ pass
2237
+
2238
+
2239
+ class Mul(Expression, Binary):
2240
+ pass
2241
+
2242
+
2243
+ class NEQ(Expression, Binary, Predicate):
2244
+ pass
2245
+
2246
+
2247
+ class NestedJSONSelect(Expression, Binary):
2248
+ pass
2249
+
2250
+
2251
+ class Operator(Expression, Binary):
2252
+ arg_types = {"this": True, "operator": True, "expression": True}
2253
+
2254
+
2255
+ class SimilarTo(Expression, Binary, Predicate):
2256
+ pass
2257
+
2258
+
2259
+ class Sub(Expression, Binary):
2260
+ pass
2261
+
2262
+
2263
+ class Adjacent(Expression, Binary, Predicate):
2264
+ pass
2265
+
2266
+
2267
+ class Unary(Expression, Condition):
2268
+ pass
2269
+
2270
+
2271
+ class BitwiseNot(Unary):
2272
+ pass
2273
+
2274
+
2275
+ class Not(Unary):
2276
+ pass
2277
+
2278
+
2279
+ class Paren(Unary):
2280
+ @property
2281
+ def output_name(self) -> str:
2282
+ return self.this.name
2283
+
2284
+
2285
+ class Neg(Unary):
2286
+ def to_py(self) -> int | Decimal:
2287
+ if self.is_number:
2288
+ return self.this.to_py() * -1
2289
+ return super().to_py()
2290
+
2291
+
2292
+ class AtIndex(Expression):
2293
+ arg_types = {"this": True, "expression": True}
2294
+
2295
+
2296
+ class AtTimeZone(Expression):
2297
+ arg_types = {"this": True, "zone": True}
2298
+
2299
+
2300
+ class FromTimeZone(Expression):
2301
+ arg_types = {"this": True, "zone": True}
2302
+
2303
+
2304
+ class FormatPhrase(Expression):
2305
+ """Format override for a column in Teradata.
2306
+ Can be expanded to additional dialects as needed
2307
+
2308
+ https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Types-and-Literals/Data-Type-Formats-and-Format-Phrases/FORMAT
2309
+ """
2310
+
2311
+ arg_types = {"this": True, "format": True}
2312
+
2313
+
2314
+ class Between(Expression, Predicate):
2315
+ arg_types = {"this": True, "low": True, "high": True, "symmetric": False}
2316
+
2317
+
2318
+ class Distinct(Expression):
2319
+ arg_types = {"expressions": False, "on": False}
2320
+
2321
+
2322
+ class In(Expression, Predicate):
2323
+ arg_types = {
2324
+ "this": True,
2325
+ "expressions": False,
2326
+ "query": False,
2327
+ "unnest": False,
2328
+ "field": False,
2329
+ "is_global": False,
2330
+ }
2331
+
2332
+
2333
+ class And(Expression, Connector, Func):
2334
+ pass
2335
+
2336
+
2337
+ class Or(Expression, Connector, Func):
2338
+ pass
2339
+
2340
+
2341
+ class Xor(Expression, Connector, Func):
2342
+ arg_types = {"this": True, "expression": True, "round_input": False}
2343
+
2344
+
2345
+ class Pow(Expression, Binary, Func):
2346
+ _sql_names = ["POWER", "POW"]
2347
+
2348
+
2349
+ class RegexpLike(Expression, Binary, Predicate, Func):
2350
+ arg_types = {"this": True, "expression": True, "flag": False, "full_match": False}
2351
+
2352
+
2353
+ def not_(
2354
+ expression: ExpOrStr,
2355
+ dialect: DialectType = None,
2356
+ copy: bool = True,
2357
+ **opts: Unpack[ParserNoDialectArgs],
2358
+ ) -> Not:
2359
+ """
2360
+ Wrap a condition with a NOT operator.
2361
+
2362
+ Example:
2363
+ >>> not_("this_suit='black'").sql()
2364
+ "NOT this_suit = 'black'"
2365
+
2366
+ Args:
2367
+ expression: the SQL code string to parse.
2368
+ If an Expr instance is passed, this is used as-is.
2369
+ dialect: the dialect used to parse the input expression.
2370
+ copy: whether to copy the expression or not.
2371
+ **opts: other options to use to parse the input expressions.
2372
+
2373
+ Returns:
2374
+ The new condition.
2375
+ """
2376
+ this = condition(
2377
+ expression,
2378
+ dialect=dialect,
2379
+ copy=copy,
2380
+ **opts,
2381
+ )
2382
+ return Not(this=_wrap(this, Connector))
2383
+
2384
+
2385
+ def _lazy_unnest(**kwargs: object) -> Expr:
2386
+ from sqlglot.expressions.array import Unnest
2387
+
2388
+ return Unnest(**kwargs)
2389
+
2390
+
2391
+ def convert(value: t.Any, copy: bool = False) -> Expr:
2392
+ """Convert a python value into an expression object.
2393
+
2394
+ Raises an error if a conversion is not possible.
2395
+
2396
+ Args:
2397
+ value: A python object.
2398
+ copy: Whether to copy `value` (only applies to Exprs and collections).
2399
+
2400
+ Returns:
2401
+ The equivalent expression object.
2402
+ """
2403
+ if isinstance(value, Expr):
2404
+ return maybe_copy(value, copy)
2405
+ if isinstance(value, str):
2406
+ return Literal.string(value)
2407
+ if isinstance(value, bool):
2408
+ return Boolean(this=value)
2409
+ if value is None or (isinstance(value, float) and math.isnan(value)):
2410
+ return Null()
2411
+ if isinstance(value, numbers.Number):
2412
+ return Literal.number(value)
2413
+ if isinstance(value, bytes):
2414
+ from sqlglot.expressions.query import HexString as _HexString
2415
+
2416
+ return _HexString(this=value.hex())
2417
+ if isinstance(value, datetime.datetime):
2418
+ datetime_literal = Literal.string(value.isoformat(sep=" "))
2419
+
2420
+ tz = None
2421
+ if value.tzinfo:
2422
+ # this works for zoneinfo.ZoneInfo, pytz.timezone and datetime.datetime.utc to return IANA timezone names like "America/Los_Angeles"
2423
+ # instead of abbreviations like "PDT". This is for consistency with other timezone handling functions in SQLGlot
2424
+ tz = Literal.string(str(value.tzinfo))
2425
+
2426
+ from sqlglot.expressions.temporal import TimeStrToTime as _TimeStrToTime
2427
+
2428
+ return _TimeStrToTime(this=datetime_literal, zone=tz)
2429
+ if isinstance(value, datetime.date):
2430
+ date_literal = Literal.string(value.strftime("%Y-%m-%d"))
2431
+ from sqlglot.expressions.temporal import DateStrToDate as _DateStrToDate
2432
+
2433
+ return _DateStrToDate(this=date_literal)
2434
+ if isinstance(value, datetime.time):
2435
+ time_literal = Literal.string(value.isoformat())
2436
+ from sqlglot.expressions.temporal import TsOrDsToTime as _TsOrDsToTime
2437
+
2438
+ return _TsOrDsToTime(this=time_literal)
2439
+ if isinstance(value, tuple):
2440
+ if hasattr(value, "_fields"):
2441
+ from sqlglot.expressions.array import Struct as _Struct
2442
+
2443
+ return _Struct(
2444
+ expressions=[
2445
+ PropertyEQ(
2446
+ this=to_identifier(k), expression=convert(getattr(value, k), copy=copy)
2447
+ )
2448
+ for k in value._fields
2449
+ ]
2450
+ )
2451
+ from sqlglot.expressions.query import Tuple as _Tuple
2452
+
2453
+ return _Tuple(expressions=[convert(v, copy=copy) for v in value])
2454
+ if isinstance(value, list):
2455
+ from sqlglot.expressions.array import Array as _Array
2456
+
2457
+ return _Array(expressions=[convert(v, copy=copy) for v in value])
2458
+ if isinstance(value, dict):
2459
+ from sqlglot.expressions.array import Array as _Array
2460
+ from sqlglot.expressions.array import Map as _Map
2461
+
2462
+ return _Map(
2463
+ keys=_Array(expressions=[convert(k, copy=copy) for k in value]),
2464
+ values=_Array(expressions=[convert(v, copy=copy) for v in value.values()]),
2465
+ )
2466
+ if hasattr(value, "__dict__"):
2467
+ from sqlglot.expressions.array import Struct as _Struct
2468
+
2469
+ return _Struct(
2470
+ expressions=[
2471
+ PropertyEQ(this=to_identifier(k), expression=convert(v, copy=copy))
2472
+ for k, v in value.__dict__.items()
2473
+ ]
2474
+ )
2475
+ raise ValueError(f"Cannot convert {value}")
2476
+
2477
+
2478
+ QUERY_MODIFIERS = {
2479
+ "match": False,
2480
+ "laterals": False,
2481
+ "joins": False,
2482
+ "connect": False,
2483
+ "pivots": False,
2484
+ "prewhere": False,
2485
+ "where": False,
2486
+ "group": False,
2487
+ "having": False,
2488
+ "qualify": False,
2489
+ "windows": False,
2490
+ "distribute": False,
2491
+ "sort": False,
2492
+ "cluster": False,
2493
+ "order": False,
2494
+ "limit": False,
2495
+ "offset": False,
2496
+ "locks": False,
2497
+ "sample": False,
2498
+ "settings": False,
2499
+ "format": False,
2500
+ "options": False,
2501
+ "for_": False,
2502
+ }
2503
+
2504
+
2505
+ TIMESTAMP_PARTS = {
2506
+ "year": False,
2507
+ "month": False,
2508
+ "day": False,
2509
+ "hour": False,
2510
+ "min": False,
2511
+ "sec": False,
2512
+ "nano": False,
2513
+ }
2514
+
2515
+
2516
+ @t.overload
2517
+ def maybe_parse(
2518
+ sql_or_expression: int | str,
2519
+ *,
2520
+ into: Type[E],
2521
+ dialect: DialectType = None,
2522
+ prefix: str | None = None,
2523
+ copy: bool = False,
2524
+ **opts: Unpack[ParserNoDialectArgs],
2525
+ ) -> E: ...
2526
+
2527
+
2528
+ @t.overload
2529
+ def maybe_parse(
2530
+ sql_or_expression: int | str | E,
2531
+ *,
2532
+ into: IntoType | None = None,
2533
+ dialect: DialectType = None,
2534
+ prefix: str | None = None,
2535
+ copy: bool = False,
2536
+ **opts: Unpack[ParserNoDialectArgs],
2537
+ ) -> E: ...
2538
+
2539
+
2540
+ def maybe_parse(
2541
+ sql_or_expression: ExpOrStr,
2542
+ *,
2543
+ into: IntoType | None = None,
2544
+ dialect: DialectType = None,
2545
+ prefix: str | None = None,
2546
+ copy: bool = False,
2547
+ **opts: Unpack[ParserNoDialectArgs],
2548
+ ) -> Expr:
2549
+ """Gracefully handle a possible string or expression.
2550
+
2551
+ Example:
2552
+ >>> maybe_parse("1")
2553
+ Literal(this=1, is_string=False)
2554
+ >>> maybe_parse(to_identifier("x"))
2555
+ Identifier(this=x, quoted=False)
2556
+
2557
+ Args:
2558
+ sql_or_expression: the SQL code string or an expression
2559
+ into: the SQLGlot Expr to parse into
2560
+ dialect: the dialect used to parse the input expressions (in the case that an
2561
+ input expression is a SQL string).
2562
+ prefix: a string to prefix the sql with before it gets parsed
2563
+ (automatically includes a space)
2564
+ copy: whether to copy the expression.
2565
+ **opts: other options to use to parse the input expressions (again, in the case
2566
+ that an input expression is a SQL string).
2567
+
2568
+ Returns:
2569
+ Expr: the parsed or given expression.
2570
+ """
2571
+ if isinstance(sql_or_expression, Expr):
2572
+ if copy:
2573
+ return sql_or_expression.copy()
2574
+ return sql_or_expression
2575
+
2576
+ if sql_or_expression is None:
2577
+ raise ParseError("SQL cannot be None")
2578
+
2579
+ import sqlglot
2580
+
2581
+ sql = str(sql_or_expression)
2582
+ if prefix:
2583
+ sql = f"{prefix} {sql}"
2584
+
2585
+ return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
2586
+
2587
+
2588
+ @t.overload
2589
+ def maybe_copy(instance: None, copy: bool = True) -> None: ...
2590
+
2591
+
2592
+ @t.overload
2593
+ def maybe_copy(instance: E, copy: bool = True) -> E: ...
2594
+
2595
+
2596
+ def maybe_copy(instance, copy=True):
2597
+ return instance.copy() if copy and instance else instance
2598
+
2599
+
2600
+ def _to_s(node: t.Any, verbose: bool = False, level: int = 0, repr_str: bool = False) -> str:
2601
+ """Generate a textual representation of an Expr tree"""
2602
+ indent = "\n" + (" " * (level + 1))
2603
+ delim = f",{indent}"
2604
+
2605
+ if isinstance(node, Expr):
2606
+ args = {k: v for k, v in node.args.items() if (v is not None and v != []) or verbose}
2607
+
2608
+ if (node.type or verbose) and not node.is_data_type:
2609
+ args["_type"] = node.type
2610
+ if node.comments or verbose:
2611
+ args["_comments"] = node.comments
2612
+
2613
+ if verbose:
2614
+ args["_id"] = id(node)
2615
+
2616
+ # Inline leaves for a more compact representation
2617
+ if node.is_leaf():
2618
+ indent = ""
2619
+ delim = ", "
2620
+
2621
+ repr_str = node.is_string or (isinstance(node, Identifier) and node.quoted)
2622
+ items = delim.join(
2623
+ [f"{k}={_to_s(v, verbose, level + 1, repr_str=repr_str)}" for k, v in args.items()]
2624
+ )
2625
+ return f"{node.__class__.__name__}({indent}{items})"
2626
+
2627
+ if isinstance(node, list):
2628
+ items = delim.join(_to_s(i, verbose, level + 1) for i in node)
2629
+ items = f"{indent}{items}" if items else ""
2630
+ return f"[{items}]"
2631
+
2632
+ # We use the representation of the string to avoid stripping out important whitespace
2633
+ if repr_str and isinstance(node, str):
2634
+ node = repr(node)
2635
+
2636
+ # Indent multiline strings to match the current level
2637
+ return indent.join(textwrap.dedent(str(node).strip("\n")).splitlines())
2638
+
2639
+
2640
+ def _is_wrong_expression(expression, into):
2641
+ return isinstance(expression, Expr) and not isinstance(expression, into)
2642
+
2643
+
2644
+ def _apply_builder(
2645
+ expression: ExpOrStr,
2646
+ instance: E,
2647
+ arg: str,
2648
+ copy: bool = True,
2649
+ prefix: str | None = None,
2650
+ into: Type[Expr] | None = None,
2651
+ dialect: DialectType = None,
2652
+ into_arg="this",
2653
+ **opts: Unpack[ParserNoDialectArgs],
2654
+ ) -> E:
2655
+ if _is_wrong_expression(expression, into) and into is not None:
2656
+ expression = into(**{into_arg: expression})
2657
+ instance = maybe_copy(instance, copy)
2658
+ expression = maybe_parse(
2659
+ sql_or_expression=expression,
2660
+ prefix=prefix,
2661
+ into=into,
2662
+ dialect=dialect,
2663
+ **opts,
2664
+ )
2665
+ instance.set(arg, expression)
2666
+ return instance
2667
+
2668
+
2669
+ def _apply_child_list_builder(
2670
+ *expressions: ExpOrStr | None,
2671
+ instance: E,
2672
+ arg: str,
2673
+ append: bool = True,
2674
+ copy: bool = True,
2675
+ prefix: str | None = None,
2676
+ into: Type[Expr] | None = None,
2677
+ dialect: DialectType = None,
2678
+ properties: MutableMapping[str, object] | None = None,
2679
+ **opts: Unpack[ParserNoDialectArgs],
2680
+ ) -> E:
2681
+ instance = maybe_copy(instance, copy)
2682
+ parsed = []
2683
+ properties = {} if properties is None else properties
2684
+
2685
+ for expression in expressions:
2686
+ if expression is not None:
2687
+ if _is_wrong_expression(expression, into) and into is not None:
2688
+ expression = into(expressions=[expression])
2689
+
2690
+ expression = maybe_parse(
2691
+ expression,
2692
+ into=into,
2693
+ dialect=dialect,
2694
+ prefix=prefix,
2695
+ **opts,
2696
+ )
2697
+ for k, v in expression.args.items():
2698
+ if k == "expressions":
2699
+ parsed.extend(v)
2700
+ else:
2701
+ properties[k] = v
2702
+
2703
+ existing = instance.args.get(arg)
2704
+ if append and existing:
2705
+ parsed = existing.expressions + parsed
2706
+ if into is None:
2707
+ raise ValueError("`into` is required to use `_apply_child_list_builder`")
2708
+ child = into(expressions=parsed)
2709
+ for k, v in properties.items():
2710
+ child.set(k, v)
2711
+ instance.set(arg, child)
2712
+
2713
+ return instance
2714
+
2715
+
2716
+ def _apply_list_builder(
2717
+ *expressions: ExpOrStr | None,
2718
+ instance: E,
2719
+ arg: str,
2720
+ append: bool = True,
2721
+ copy: bool = True,
2722
+ prefix: str | None = None,
2723
+ into: Type[Expr] | None = None,
2724
+ dialect: DialectType = None,
2725
+ **opts: Unpack[ParserNoDialectArgs],
2726
+ ) -> E:
2727
+ inst = maybe_copy(instance, copy)
2728
+
2729
+ parsed = [
2730
+ maybe_parse(
2731
+ sql_or_expression=expression,
2732
+ into=into,
2733
+ prefix=prefix,
2734
+ dialect=dialect,
2735
+ **opts,
2736
+ )
2737
+ for expression in expressions
2738
+ if expression is not None
2739
+ ]
2740
+
2741
+ existing_expressions = inst.args.get(arg)
2742
+ if append and existing_expressions:
2743
+ parsed = existing_expressions + parsed
2744
+
2745
+ inst.set(arg, parsed)
2746
+ return inst
2747
+
2748
+
2749
+ def _apply_conjunction_builder(
2750
+ *expressions: ExpOrStr | None,
2751
+ instance: E,
2752
+ arg: str,
2753
+ into: Type[Expr] | None = None,
2754
+ append: bool = True,
2755
+ copy: bool = True,
2756
+ dialect: DialectType = None,
2757
+ **opts: Unpack[ParserNoDialectArgs],
2758
+ ) -> E:
2759
+ filtered = [exp for exp in expressions if exp is not None and exp != ""]
2760
+ if not filtered:
2761
+ return instance
2762
+
2763
+ inst = maybe_copy(instance, copy)
2764
+
2765
+ existing = inst.args.get(arg)
2766
+ if append and existing is not None:
2767
+ filtered = [existing.this if into else existing] + filtered
2768
+
2769
+ node = and_(*filtered, dialect=dialect, copy=copy, **opts)
2770
+
2771
+ inst.set(arg, into(this=node) if into else node)
2772
+ return inst
2773
+
2774
+
2775
+ def _combine(
2776
+ expressions: Sequence[ExpOrStr | None],
2777
+ operator: Type[Expr],
2778
+ dialect: DialectType = None,
2779
+ copy: bool = True,
2780
+ wrap: bool = True,
2781
+ **opts: Unpack[ParserNoDialectArgs],
2782
+ ) -> Expr:
2783
+ conditions = [
2784
+ condition(expression, dialect=dialect, copy=copy, **opts)
2785
+ for expression in expressions
2786
+ if expression is not None
2787
+ ]
2788
+
2789
+ this, *rest = conditions
2790
+ if rest and wrap:
2791
+ this = _wrap(this, Connector)
2792
+ for expression in rest:
2793
+ this = operator(this=this, expression=_wrap(expression, Connector) if wrap else expression)
2794
+
2795
+ return this
2796
+
2797
+
2798
+ @t.overload
2799
+ def _wrap(expression: None, kind: Type[Expr]) -> None: ...
2800
+
2801
+
2802
+ @t.overload
2803
+ def _wrap(expression: E, kind: Type[Expr]) -> E | Paren: ...
2804
+
2805
+
2806
+ def _wrap(expression: E | None, kind: Type[Expr]) -> E | None | Paren:
2807
+ return Paren(this=expression) if isinstance(expression, kind) else expression
2808
+
2809
+
2810
+ def _apply_set_operation(
2811
+ *expressions: ExpOrStr,
2812
+ set_operation: Type,
2813
+ distinct: bool = True,
2814
+ dialect: DialectType = None,
2815
+ copy: bool = True,
2816
+ **opts: Unpack[ParserNoDialectArgs],
2817
+ ) -> t.Any:
2818
+ return reduce(
2819
+ lambda x, y: set_operation(this=x, expression=y, distinct=distinct, **opts),
2820
+ (maybe_parse(e, dialect=dialect, copy=copy, **opts) for e in expressions),
2821
+ )
2822
+
2823
+
2824
+ SAFE_IDENTIFIER_RE: t.Pattern[str] = re.compile(r"^[_a-zA-Z][\w]*$")
2825
+
2826
+
2827
+ @t.overload
2828
+ def to_identifier(name: None, quoted: bool | None = None, copy: bool = True) -> None: ...
2829
+
2830
+
2831
+ @t.overload
2832
+ def to_identifier(
2833
+ name: int | str | Identifier, quoted: bool | None = None, copy: bool = True
2834
+ ) -> Identifier: ...
2835
+
2836
+
2837
+ def to_identifier(name, quoted=None, copy=True):
2838
+ """Builds an identifier.
2839
+
2840
+ Args:
2841
+ name: The name to turn into an identifier.
2842
+ quoted: Whether to force quote the identifier.
2843
+ copy: Whether to copy name if it's an Identifier.
2844
+
2845
+ Returns:
2846
+ The identifier ast node.
2847
+ """
2848
+
2849
+ if name is None:
2850
+ return None
2851
+
2852
+ if isinstance(name, Identifier):
2853
+ identifier = maybe_copy(name, copy)
2854
+ elif isinstance(name, str):
2855
+ identifier = Identifier(
2856
+ this=name,
2857
+ quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
2858
+ )
2859
+ else:
2860
+ raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
2861
+ return identifier
2862
+
2863
+
2864
+ def condition(
2865
+ expression: ExpOrStr,
2866
+ dialect: DialectType = None,
2867
+ copy: bool = True,
2868
+ **opts: Unpack[ParserNoDialectArgs],
2869
+ ) -> Expr:
2870
+ """
2871
+ Initialize a logical condition expression.
2872
+
2873
+ Example:
2874
+ >>> condition("x=1").sql()
2875
+ 'x = 1'
2876
+
2877
+ This is helpful for composing larger logical syntax trees:
2878
+ >>> where = condition("x=1")
2879
+ >>> where = where.and_("y=1")
2880
+ >>> where.sql()
2881
+ 'x = 1 AND y = 1'
2882
+
2883
+ Args:
2884
+ *expression: the SQL code string to parse.
2885
+ If an Expr instance is passed, this is used as-is.
2886
+ dialect: the dialect used to parse the input expression (in the case that the
2887
+ input expression is a SQL string).
2888
+ copy: Whether to copy `expression` (only applies to expressions).
2889
+ **opts: other options to use to parse the input expressions (again, in the case
2890
+ that the input expression is a SQL string).
2891
+
2892
+ Returns:
2893
+ The new Condition instance
2894
+ """
2895
+ return maybe_parse(
2896
+ expression,
2897
+ into=Condition,
2898
+ dialect=dialect,
2899
+ copy=copy,
2900
+ **opts,
2901
+ )
2902
+
2903
+
2904
+ def and_(
2905
+ *expressions: ExpOrStr | None,
2906
+ dialect: DialectType = None,
2907
+ copy: bool = True,
2908
+ wrap: bool = True,
2909
+ **opts: Unpack[ParserNoDialectArgs],
2910
+ ) -> Condition:
2911
+ """
2912
+ Combine multiple conditions with an AND logical operator.
2913
+
2914
+ Example:
2915
+ >>> and_("x=1", and_("y=1", "z=1")).sql()
2916
+ 'x = 1 AND (y = 1 AND z = 1)'
2917
+
2918
+ Args:
2919
+ *expressions: the SQL code strings to parse.
2920
+ If an Expr instance is passed, this is used as-is.
2921
+ dialect: the dialect used to parse the input expression.
2922
+ copy: whether to copy `expressions` (only applies to Exprs).
2923
+ wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
2924
+ precedence issues, but can be turned off when the produced AST is too deep and
2925
+ causes recursion-related issues.
2926
+ **opts: other options to use to parse the input expressions.
2927
+
2928
+ Returns:
2929
+ The new condition
2930
+ """
2931
+ return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, wrap=wrap, **opts))
2932
+
2933
+
2934
+ def or_(
2935
+ *expressions: ExpOrStr | None,
2936
+ dialect: DialectType = None,
2937
+ copy: bool = True,
2938
+ wrap: bool = True,
2939
+ **opts: Unpack[ParserNoDialectArgs],
2940
+ ) -> Condition:
2941
+ """
2942
+ Combine multiple conditions with an OR logical operator.
2943
+
2944
+ Example:
2945
+ >>> or_("x=1", or_("y=1", "z=1")).sql()
2946
+ 'x = 1 OR (y = 1 OR z = 1)'
2947
+
2948
+ Args:
2949
+ *expressions: the SQL code strings to parse.
2950
+ If an Expr instance is passed, this is used as-is.
2951
+ dialect: the dialect used to parse the input expression.
2952
+ copy: whether to copy `expressions` (only applies to Exprs).
2953
+ wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
2954
+ precedence issues, but can be turned off when the produced AST is too deep and
2955
+ causes recursion-related issues.
2956
+ **opts: other options to use to parse the input expressions.
2957
+
2958
+ Returns:
2959
+ The new condition
2960
+ """
2961
+ return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, wrap=wrap, **opts))
2962
+
2963
+
2964
+ def xor(
2965
+ *expressions: ExpOrStr | None,
2966
+ dialect: DialectType = None,
2967
+ copy: bool = True,
2968
+ wrap: bool = True,
2969
+ **opts: Unpack[ParserNoDialectArgs],
2970
+ ) -> Condition:
2971
+ """
2972
+ Combine multiple conditions with an XOR logical operator.
2973
+
2974
+ Example:
2975
+ >>> xor("x=1", xor("y=1", "z=1")).sql()
2976
+ 'x = 1 XOR (y = 1 XOR z = 1)'
2977
+
2978
+ Args:
2979
+ *expressions: the SQL code strings to parse.
2980
+ If an Expr instance is passed, this is used as-is.
2981
+ dialect: the dialect used to parse the input expression.
2982
+ copy: whether to copy `expressions` (only applies to Exprs).
2983
+ wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
2984
+ precedence issues, but can be turned off when the produced AST is too deep and
2985
+ causes recursion-related issues.
2986
+ **opts: other options to use to parse the input expressions.
2987
+
2988
+ Returns:
2989
+ The new condition
2990
+ """
2991
+ return t.cast(Condition, _combine(expressions, Xor, dialect, copy=copy, wrap=wrap, **opts))
2992
+
2993
+
2994
+ def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
2995
+ """
2996
+ Wrap an expression in parentheses.
2997
+
2998
+ Example:
2999
+ >>> paren("5 + 3").sql()
3000
+ '(5 + 3)'
3001
+
3002
+ Args:
3003
+ expression: the SQL code string to parse.
3004
+ If an Expr instance is passed, this is used as-is.
3005
+ copy: whether to copy the expression or not.
3006
+
3007
+ Returns:
3008
+ The wrapped expression.
3009
+ """
3010
+ return Paren(this=maybe_parse(expression, copy=copy))
3011
+
3012
+
3013
+ def alias_(
3014
+ expression: ExpOrStr,
3015
+ alias: str | Identifier | None,
3016
+ table: bool | Sequence[str | Identifier] = False,
3017
+ quoted: bool | None = None,
3018
+ dialect: DialectType = None,
3019
+ copy: bool = True,
3020
+ **opts: Unpack[ParserNoDialectArgs],
3021
+ ) -> Expr:
3022
+ """Create an Alias expression.
3023
+
3024
+ Example:
3025
+ >>> alias_('foo', 'bar').sql()
3026
+ 'foo AS bar'
3027
+
3028
+ >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
3029
+ '(SELECT 1, 2) AS bar(a, b)'
3030
+
3031
+ Args:
3032
+ expression: the SQL code strings to parse.
3033
+ If an Expr instance is passed, this is used as-is.
3034
+ alias: the alias name to use. If the name has
3035
+ special characters it is quoted.
3036
+ table: Whether to create a table alias, can also be a list of columns.
3037
+ quoted: whether to quote the alias
3038
+ dialect: the dialect used to parse the input expression.
3039
+ copy: Whether to copy the expression.
3040
+ **opts: other options to use to parse the input expressions.
3041
+
3042
+ Returns:
3043
+ Alias: the aliased expression
3044
+ """
3045
+ exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
3046
+ alias = to_identifier(alias, quoted=quoted)
3047
+
3048
+ if table:
3049
+ from sqlglot.expressions.query import TableAlias as _TableAlias
3050
+
3051
+ table_alias = _TableAlias(this=alias)
3052
+ exp.set("alias", table_alias)
3053
+
3054
+ if not isinstance(table, bool):
3055
+ for column in table:
3056
+ table_alias.append("columns", to_identifier(column, quoted=quoted))
3057
+
3058
+ return exp
3059
+
3060
+ # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
3061
+ # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
3062
+ # for the complete Window expression.
3063
+ #
3064
+ # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
3065
+
3066
+ if "alias" in exp.arg_types and type(exp).__name__ != "Window":
3067
+ exp.set("alias", alias)
3068
+ return exp
3069
+ return Alias(this=exp, alias=alias)
3070
+
3071
+
3072
+ @t.overload
3073
+ def column(
3074
+ col: str | Expr,
3075
+ table: str | Identifier | None = None,
3076
+ db: str | Identifier | None = None,
3077
+ catalog: str | Identifier | None = None,
3078
+ *,
3079
+ fields: Collection[str | Identifier],
3080
+ quoted: bool | None = None,
3081
+ copy: bool = True,
3082
+ ) -> Dot:
3083
+ pass
3084
+
3085
+
3086
+ @t.overload
3087
+ def column(
3088
+ col: str | Expr,
3089
+ table: str | Identifier | None = None,
3090
+ db: str | Identifier | None = None,
3091
+ catalog: str | Identifier | None = None,
3092
+ *,
3093
+ fields: t.Literal[None] = None,
3094
+ quoted: bool | None = None,
3095
+ copy: bool = True,
3096
+ ) -> Column:
3097
+ pass
3098
+
3099
+
3100
+ def column(
3101
+ col,
3102
+ table=None,
3103
+ db=None,
3104
+ catalog=None,
3105
+ *,
3106
+ fields=None,
3107
+ quoted=None,
3108
+ copy: bool = True,
3109
+ ):
3110
+ """
3111
+ Build a Column.
3112
+
3113
+ Args:
3114
+ col: Column name or expression.
3115
+ table: Table name.
3116
+ db: Database name.
3117
+ catalog: Catalog name.
3118
+ fields: Additional fields using dots.
3119
+ quoted: Whether to force quotes on the column's identifiers.
3120
+ copy: Whether to copy expressions if passed in.
3121
+
3122
+ Returns:
3123
+ The new Column instance.
3124
+ """
3125
+ col = maybe_copy(col, copy) if isinstance(col, Expr) else to_identifier(col, quoted=quoted)
3126
+
3127
+ this: Column | Dot = Column(
3128
+ this=col,
3129
+ table=to_identifier(table, quoted=quoted, copy=copy),
3130
+ db=to_identifier(db, quoted=quoted, copy=copy),
3131
+ catalog=to_identifier(catalog, quoted=quoted, copy=copy),
3132
+ )
3133
+
3134
+ if fields:
3135
+ this = Dot.build(
3136
+ (this, *(to_identifier(field, quoted=quoted, copy=copy) for field in fields))
3137
+ )
3138
+ return this
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/datatypes.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions datatypes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typing as t
6
+ from enum import auto
7
+
8
+ from sqlglot.helper import AutoName
9
+ from sqlglot.errors import ErrorLevel, ParseError
10
+ from sqlglot.expressions.core import (
11
+ Expr,
12
+ Expression,
13
+ _TimeUnit,
14
+ Identifier,
15
+ Dot,
16
+ maybe_copy,
17
+ )
18
+ from builtins import type as Type
19
+
20
+ if t.TYPE_CHECKING:
21
+ from sqlglot._typing import DataTypeArgs
22
+ from sqlglot.dialects.dialect import DialectType
23
+ from typing_extensions import Self, Unpack
24
+
25
+
26
+ class DataTypeParam(Expression):
27
+ arg_types = {"this": True, "expression": False}
28
+
29
+ @property
30
+ def this(self) -> Expr:
31
+ return self.args["this"]
32
+
33
+ @property
34
+ def name(self) -> str:
35
+ return self.this.name
36
+
37
+
38
+ class DType(AutoName):
39
+ ARRAY = auto()
40
+ AGGREGATEFUNCTION = auto()
41
+ SIMPLEAGGREGATEFUNCTION = auto()
42
+ BIGDECIMAL = auto()
43
+ BIGINT = auto()
44
+ BIGNUM = auto()
45
+ BIGSERIAL = auto()
46
+ BINARY = auto()
47
+ BIT = auto()
48
+ BLOB = auto()
49
+ BOOLEAN = auto()
50
+ BPCHAR = auto()
51
+ CHAR = auto()
52
+ CHARACTER_SET = auto()
53
+ DATE = auto()
54
+ DATE32 = auto()
55
+ DATEMULTIRANGE = auto()
56
+ DATERANGE = auto()
57
+ DATETIME = auto()
58
+ DATETIME2 = auto()
59
+ DATETIME64 = auto()
60
+ DECIMAL = auto()
61
+ DECIMAL32 = auto()
62
+ DECIMAL64 = auto()
63
+ DECIMAL128 = auto()
64
+ DECIMAL256 = auto()
65
+ DECFLOAT = auto()
66
+ DOUBLE = auto()
67
+ DYNAMIC = auto()
68
+ ENUM = auto()
69
+ ENUM8 = auto()
70
+ ENUM16 = auto()
71
+ FILE = auto()
72
+ FIXEDSTRING = auto()
73
+ FLOAT = auto()
74
+ GEOGRAPHY = auto()
75
+ GEOGRAPHYPOINT = auto()
76
+ GEOMETRY = auto()
77
+ POINT = auto()
78
+ RING = auto()
79
+ LINESTRING = auto()
80
+ MULTILINESTRING = auto()
81
+ POLYGON = auto()
82
+ MULTIPOLYGON = auto()
83
+ HLLSKETCH = auto()
84
+ HSTORE = auto()
85
+ IMAGE = auto()
86
+ INET = auto()
87
+ INT = auto()
88
+ INT128 = auto()
89
+ INT256 = auto()
90
+ INT4MULTIRANGE = auto()
91
+ INT4RANGE = auto()
92
+ INT8MULTIRANGE = auto()
93
+ INT8RANGE = auto()
94
+ INTERVAL = auto()
95
+ IPADDRESS = auto()
96
+ IPPREFIX = auto()
97
+ IPV4 = auto()
98
+ IPV6 = auto()
99
+ JSON = auto()
100
+ JSONB = auto()
101
+ LIST = auto()
102
+ LONGBLOB = auto()
103
+ LONGTEXT = auto()
104
+ LOWCARDINALITY = auto()
105
+ MAP = auto()
106
+ MEDIUMBLOB = auto()
107
+ MEDIUMINT = auto()
108
+ MEDIUMTEXT = auto()
109
+ MONEY = auto()
110
+ NAME = auto()
111
+ NCHAR = auto()
112
+ NESTED = auto()
113
+ NOTHING = auto()
114
+ NULL = auto()
115
+ NUMMULTIRANGE = auto()
116
+ NUMRANGE = auto()
117
+ NVARCHAR = auto()
118
+ OBJECT = auto()
119
+ RANGE = auto()
120
+ ROWVERSION = auto()
121
+ SERIAL = auto()
122
+ SET = auto()
123
+ SMALLDATETIME = auto()
124
+ SMALLINT = auto()
125
+ SMALLMONEY = auto()
126
+ SMALLSERIAL = auto()
127
+ STRUCT = auto()
128
+ SUPER = auto()
129
+ TEXT = auto()
130
+ TINYBLOB = auto()
131
+ TINYTEXT = auto()
132
+ TIME = auto()
133
+ TIMETZ = auto()
134
+ TIME_NS = auto()
135
+ TIMESTAMP = auto()
136
+ TIMESTAMPNTZ = auto()
137
+ TIMESTAMPLTZ = auto()
138
+ TIMESTAMPTZ = auto()
139
+ TIMESTAMP_S = auto()
140
+ TIMESTAMP_MS = auto()
141
+ TIMESTAMP_NS = auto()
142
+ TINYINT = auto()
143
+ TSMULTIRANGE = auto()
144
+ TSRANGE = auto()
145
+ TSTZMULTIRANGE = auto()
146
+ TSTZRANGE = auto()
147
+ UBIGINT = auto()
148
+ UINT = auto()
149
+ UINT128 = auto()
150
+ UINT256 = auto()
151
+ UMEDIUMINT = auto()
152
+ UDECIMAL = auto()
153
+ UDOUBLE = auto()
154
+ UNION = auto()
155
+ UNKNOWN = auto() # Sentinel value, useful for type annotation
156
+ USERDEFINED = "USER-DEFINED"
157
+ USMALLINT = auto()
158
+ UTINYINT = auto()
159
+ UUID = auto()
160
+ VARBINARY = auto()
161
+ VARCHAR = auto()
162
+ VARIANT = auto()
163
+ VECTOR = auto()
164
+ XML = auto()
165
+ YEAR = auto()
166
+ TDIGEST = auto()
167
+
168
+ def into_expr(self, **kwargs: object) -> DataType:
169
+ """Converts this `DType` into a `DataType` instance.
170
+
171
+ Args:
172
+ **kwargs (object): additional arguments to pass in the constructor of DataType.
173
+ Returns:
174
+ DataType: the resulting `DataType` instance.
175
+ """
176
+ return DataType(this=self).set_kwargs(kwargs)
177
+
178
+
179
+ class DataType(Expression):
180
+ arg_types = {
181
+ "this": True,
182
+ "expressions": False,
183
+ "nested": False,
184
+ "values": False,
185
+ "kind": False,
186
+ "nullable": False,
187
+ "collate": False,
188
+ }
189
+
190
+ is_data_type: t.ClassVar[bool] = True
191
+
192
+ Type: t.ClassVar[Type[DType]] = DType
193
+
194
+ STRUCT_TYPES: t.ClassVar[set[DType]] = {
195
+ DType.FILE,
196
+ DType.NESTED,
197
+ DType.OBJECT,
198
+ DType.STRUCT,
199
+ DType.UNION,
200
+ }
201
+
202
+ ARRAY_TYPES: t.ClassVar[set[DType]] = {
203
+ DType.ARRAY,
204
+ DType.LIST,
205
+ }
206
+
207
+ NESTED_TYPES: t.ClassVar[set[DType]] = {
208
+ DType.FILE,
209
+ DType.NESTED,
210
+ DType.OBJECT,
211
+ DType.STRUCT,
212
+ DType.UNION,
213
+ DType.ARRAY,
214
+ DType.LIST,
215
+ DType.MAP,
216
+ }
217
+
218
+ TEXT_TYPES: t.ClassVar[set[DType]] = {
219
+ DType.CHAR,
220
+ DType.NCHAR,
221
+ DType.NVARCHAR,
222
+ DType.TEXT,
223
+ DType.TINYTEXT,
224
+ DType.MEDIUMTEXT,
225
+ DType.LONGTEXT,
226
+ DType.VARCHAR,
227
+ DType.NAME,
228
+ }
229
+
230
+ BINARY_TYPES: t.ClassVar[set[DType]] = {
231
+ DType.BINARY,
232
+ DType.VARBINARY,
233
+ DType.TINYBLOB,
234
+ DType.BLOB,
235
+ DType.MEDIUMBLOB,
236
+ DType.LONGBLOB,
237
+ }
238
+
239
+ SIGNED_INTEGER_TYPES: t.ClassVar[set[DType]] = {
240
+ DType.BIGINT,
241
+ DType.INT,
242
+ DType.INT128,
243
+ DType.INT256,
244
+ DType.MEDIUMINT,
245
+ DType.SMALLINT,
246
+ DType.TINYINT,
247
+ }
248
+
249
+ UNSIGNED_INTEGER_TYPES: t.ClassVar[set[DType]] = {
250
+ DType.UBIGINT,
251
+ DType.UINT,
252
+ DType.UINT128,
253
+ DType.UINT256,
254
+ DType.UMEDIUMINT,
255
+ DType.USMALLINT,
256
+ DType.UTINYINT,
257
+ }
258
+
259
+ INTEGER_TYPES: t.ClassVar[set[DType]] = {
260
+ DType.BIGINT,
261
+ DType.INT,
262
+ DType.INT128,
263
+ DType.INT256,
264
+ DType.MEDIUMINT,
265
+ DType.SMALLINT,
266
+ DType.TINYINT,
267
+ DType.UBIGINT,
268
+ DType.UINT,
269
+ DType.UINT128,
270
+ DType.UINT256,
271
+ DType.UMEDIUMINT,
272
+ DType.USMALLINT,
273
+ DType.UTINYINT,
274
+ DType.BIT,
275
+ }
276
+
277
+ FLOAT_TYPES: t.ClassVar[set[DType]] = {
278
+ DType.DOUBLE,
279
+ DType.FLOAT,
280
+ }
281
+
282
+ REAL_TYPES: t.ClassVar[set[DType]] = {
283
+ DType.DOUBLE,
284
+ DType.FLOAT,
285
+ DType.BIGDECIMAL,
286
+ DType.DECIMAL,
287
+ DType.DECIMAL32,
288
+ DType.DECIMAL64,
289
+ DType.DECIMAL128,
290
+ DType.DECIMAL256,
291
+ DType.DECFLOAT,
292
+ DType.MONEY,
293
+ DType.SMALLMONEY,
294
+ DType.UDECIMAL,
295
+ DType.UDOUBLE,
296
+ }
297
+
298
+ NUMERIC_TYPES: t.ClassVar[set[DType]] = {
299
+ DType.BIGINT,
300
+ DType.INT,
301
+ DType.INT128,
302
+ DType.INT256,
303
+ DType.MEDIUMINT,
304
+ DType.SMALLINT,
305
+ DType.TINYINT,
306
+ DType.UBIGINT,
307
+ DType.UINT,
308
+ DType.UINT128,
309
+ DType.UINT256,
310
+ DType.UMEDIUMINT,
311
+ DType.USMALLINT,
312
+ DType.UTINYINT,
313
+ DType.BIT,
314
+ DType.DOUBLE,
315
+ DType.FLOAT,
316
+ DType.BIGDECIMAL,
317
+ DType.DECIMAL,
318
+ DType.DECIMAL32,
319
+ DType.DECIMAL64,
320
+ DType.DECIMAL128,
321
+ DType.DECIMAL256,
322
+ DType.DECFLOAT,
323
+ DType.MONEY,
324
+ DType.SMALLMONEY,
325
+ DType.UDECIMAL,
326
+ DType.UDOUBLE,
327
+ }
328
+
329
+ TEMPORAL_TYPES: t.ClassVar[set[DType]] = {
330
+ DType.DATE,
331
+ DType.DATE32,
332
+ DType.DATETIME,
333
+ DType.DATETIME2,
334
+ DType.DATETIME64,
335
+ DType.SMALLDATETIME,
336
+ DType.TIME,
337
+ DType.TIMESTAMP,
338
+ DType.TIMESTAMPNTZ,
339
+ DType.TIMESTAMPLTZ,
340
+ DType.TIMESTAMPTZ,
341
+ DType.TIMESTAMP_MS,
342
+ DType.TIMESTAMP_NS,
343
+ DType.TIMESTAMP_S,
344
+ DType.TIMETZ,
345
+ }
346
+
347
+ @classmethod
348
+ def build(
349
+ cls,
350
+ dtype: DATA_TYPE,
351
+ dialect: DialectType = None,
352
+ udt: bool = False,
353
+ copy: bool = True,
354
+ **kwargs: Unpack[DataTypeArgs],
355
+ ) -> Self:
356
+ """
357
+ Constructs a DataType object.
358
+
359
+ Args:
360
+ dtype: the data type of interest.
361
+ dialect: the dialect to use for parsing `dtype`, in case it's a string.
362
+ udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
363
+ DataType, thus creating a user-defined type.
364
+ copy: whether to copy the data type.
365
+ kwargs: additional arguments to pass in the constructor of DataType.
366
+
367
+ Returns:
368
+ The constructed DataType object.
369
+ """
370
+ if isinstance(dtype, str):
371
+ return cls.from_str(dtype, dialect, udt, **kwargs)
372
+ elif isinstance(dtype, DType):
373
+ data_type_exp = cls(this=dtype)
374
+ if kwargs:
375
+ for k, v in kwargs.items():
376
+ data_type_exp.set(k, v)
377
+ return data_type_exp
378
+ elif isinstance(dtype, (Identifier, Dot)) and udt:
379
+ return cls(this=DType.USERDEFINED, kind=dtype, **kwargs)
380
+ elif isinstance(dtype, cls):
381
+ return maybe_copy(dtype, copy)
382
+ else:
383
+ raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DType")
384
+
385
+ @classmethod
386
+ def from_str(
387
+ cls,
388
+ dtype: str,
389
+ dialect: DialectType = None,
390
+ udt: bool = False,
391
+ **kwargs: Unpack[DataTypeArgs],
392
+ ) -> Self:
393
+ """
394
+ Constructs a `DataType` object from a `str` representation.
395
+
396
+ Args:
397
+ dtype: the data type of interest.
398
+ dialect: the dialect to use for parsing `dtype`.
399
+ udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
400
+ `DataType`, thus creating a user-defined type.
401
+ kwargs: additional arguments to pass in the constructor of `DataType`.
402
+
403
+ Returns:
404
+ The constructed `DataType` object.
405
+ """
406
+ from sqlglot import parse_one
407
+
408
+ if dtype.upper() == "UNKNOWN":
409
+ return cls(this=DType.UNKNOWN, **kwargs)
410
+ try:
411
+ return parse_one(
412
+ dtype, read=dialect, into=cls, error_level=ErrorLevel.IGNORE
413
+ ).set_kwargs(kwargs)
414
+ except ParseError:
415
+ if udt:
416
+ return cls(this=DType.USERDEFINED, kind=dtype, **kwargs)
417
+ raise
418
+
419
+ def is_type(self, *dtypes: DATA_TYPE, check_nullable: bool = False) -> bool:
420
+ """
421
+ Checks whether this DataType matches one of the provided data types. Nested types or precision
422
+ will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
423
+
424
+ Args:
425
+ dtypes: the data types to compare this DataType to.
426
+ check_nullable: whether to take the NULLABLE type constructor into account for the comparison.
427
+ If false, it means that NULLABLE<INT> is equivalent to INT.
428
+
429
+ Returns:
430
+ True, if and only if there is a type in `dtypes` which is equal to this DataType.
431
+ """
432
+ self_is_nullable: bool | None = self.args.get("nullable")
433
+ for dtype in dtypes:
434
+ other_type = DataType.build(dtype, copy=False, udt=True)
435
+ other_is_nullable: bool | None = other_type.args.get("nullable")
436
+ if (
437
+ other_type.expressions
438
+ or (check_nullable and (self_is_nullable or other_is_nullable))
439
+ or self.this == DType.USERDEFINED
440
+ or other_type.this == DType.USERDEFINED
441
+ ):
442
+ matches = self == other_type
443
+ else:
444
+ matches = self.this == other_type.this
445
+
446
+ if matches:
447
+ return True
448
+ return False
449
+
450
+
451
+ class PseudoType(DataType):
452
+ arg_types = {"this": True}
453
+
454
+
455
+ class ObjectIdentifier(DataType):
456
+ arg_types = {"this": True}
457
+
458
+
459
+ class IntervalSpan(DataType):
460
+ arg_types = {"this": True, "expression": True}
461
+
462
+
463
+ class Interval(_TimeUnit):
464
+ arg_types = {"this": False, "unit": False}
465
+
466
+
467
+ DATA_TYPE = t.Union[str, Identifier, Dot, DataType, DType]
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/ddl.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions DDL."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typing as t
6
+
7
+ from sqlglot.helper import trait
8
+ from sqlglot.expressions.core import Expression, Expr, Func
9
+ from sqlglot.expressions.query import Query, Selectable
10
+
11
+ if t.TYPE_CHECKING:
12
+ from sqlglot.expressions.query import CTE
13
+
14
+
15
+ @trait
16
+ class DDL(Selectable):
17
+ @property
18
+ def ctes(self) -> list[CTE]:
19
+ """Returns a list of all the CTEs attached to this statement."""
20
+ with_ = self.args.get("with_")
21
+ return with_.expressions if with_ else []
22
+
23
+ @property
24
+ def selects(self) -> list[Expr]:
25
+ """If this statement contains a query (e.g. a CTAS), this returns the query's projections."""
26
+ expression = self.expression
27
+ return expression.selects if isinstance(expression, Query) else []
28
+
29
+ @property
30
+ def named_selects(self) -> list[str]:
31
+ """
32
+ If this statement contains a query (e.g. a CTAS), this returns the output
33
+ names of the query's projections.
34
+ """
35
+ expression = self.expression
36
+ return expression.named_selects if isinstance(expression, Query) else []
37
+
38
+
39
+ class Create(Expression, DDL):
40
+ arg_types = {
41
+ "with_": False,
42
+ "this": True,
43
+ "kind": True,
44
+ "expression": False,
45
+ "exists": False,
46
+ "properties": False,
47
+ "replace": False,
48
+ "refresh": False,
49
+ "unique": False,
50
+ "indexes": False,
51
+ "no_schema_binding": False,
52
+ "begin": False,
53
+ "clone": False,
54
+ "concurrently": False,
55
+ "clustered": False,
56
+ }
57
+
58
+ @property
59
+ def kind(self) -> str | None:
60
+ kind = self.args.get("kind")
61
+ return kind and kind.upper()
62
+
63
+
64
+ class SequenceProperties(Expression):
65
+ arg_types = {
66
+ "increment": False,
67
+ "minvalue": False,
68
+ "maxvalue": False,
69
+ "cache": False,
70
+ "start": False,
71
+ "owned": False,
72
+ "options": False,
73
+ }
74
+
75
+
76
+ class TriggerProperties(Expression):
77
+ arg_types = {
78
+ "table": True,
79
+ "timing": True,
80
+ "events": True,
81
+ "execute": True,
82
+ "constraint": False,
83
+ "referenced_table": False,
84
+ "deferrable": False,
85
+ "initially": False,
86
+ "referencing": False,
87
+ "for_each": False,
88
+ "when": False,
89
+ }
90
+
91
+
92
+ class TriggerExecute(Expression):
93
+ pass
94
+
95
+
96
+ class TriggerEvent(Expression):
97
+ arg_types = {"this": True, "columns": False}
98
+
99
+
100
+ class TriggerReferencing(Expression):
101
+ arg_types = {"old": False, "new": False}
102
+
103
+
104
+ class TruncateTable(Expression):
105
+ arg_types = {
106
+ "expressions": True,
107
+ "is_database": False,
108
+ "exists": False,
109
+ "only": False,
110
+ "cluster": False,
111
+ "identity": False,
112
+ "option": False,
113
+ "partition": False,
114
+ }
115
+
116
+
117
+ class Clone(Expression):
118
+ arg_types = {"this": True, "shallow": False, "copy": False}
119
+
120
+
121
+ class Describe(Expression):
122
+ arg_types = {
123
+ "this": True,
124
+ "style": False,
125
+ "kind": False,
126
+ "properties": False,
127
+ "expressions": False,
128
+ "partition": False,
129
+ "format": False,
130
+ "as_json": False,
131
+ }
132
+
133
+
134
+ class Attach(Expression):
135
+ arg_types = {"this": True, "exists": False, "expressions": False}
136
+
137
+
138
+ class Detach(Expression):
139
+ arg_types = {
140
+ "this": True,
141
+ "kind": False,
142
+ "exists": False,
143
+ "cluster": False,
144
+ "permanent": False,
145
+ "sync": False,
146
+ }
147
+
148
+
149
+ class Install(Expression):
150
+ arg_types = {"this": True, "from_": False, "force": False}
151
+
152
+
153
+ class Summarize(Expression):
154
+ arg_types = {"this": True, "table": False}
155
+
156
+
157
+ class Kill(Expression):
158
+ arg_types = {"this": True, "kind": False}
159
+
160
+
161
+ class Pragma(Expression):
162
+ pass
163
+
164
+
165
+ class Declare(Expression):
166
+ arg_types = {"expressions": True, "replace": False}
167
+
168
+
169
+ class DeclareItem(Expression):
170
+ arg_types = {"this": True, "kind": False, "default": False}
171
+
172
+
173
+ class Set(Expression):
174
+ arg_types = {"expressions": False, "unset": False, "tag": False}
175
+
176
+
177
+ class Heredoc(Expression):
178
+ arg_types = {"this": True, "tag": False}
179
+ _hash_raw_args = True
180
+
181
+
182
+ class SetItem(Expression):
183
+ arg_types = {
184
+ "this": False,
185
+ "expressions": False,
186
+ "kind": False,
187
+ "collate": False, # MySQL SET NAMES statement
188
+ "global_": False,
189
+ }
190
+
191
+
192
+ class Show(Expression):
193
+ arg_types = {
194
+ "this": True,
195
+ "history": False,
196
+ "terse": False,
197
+ "target": False,
198
+ "offset": False,
199
+ "starts_with": False,
200
+ "limit": False,
201
+ "from_": False,
202
+ "like": False,
203
+ "where": False,
204
+ "db": False,
205
+ "scope": False,
206
+ "scope_kind": False,
207
+ "full": False,
208
+ "mutex": False,
209
+ "query": False,
210
+ "channel": False,
211
+ "global_": False,
212
+ "log": False,
213
+ "position": False,
214
+ "types": False,
215
+ "privileges": False,
216
+ "for_table": False,
217
+ "for_group": False,
218
+ "for_user": False,
219
+ "for_role": False,
220
+ "into_outfile": False,
221
+ "json": False,
222
+ "iceberg": False,
223
+ }
224
+
225
+
226
+ class UserDefinedFunction(Expression):
227
+ arg_types = {"this": True, "expressions": False, "wrapped": False}
228
+
229
+
230
+ class MacroOverloads(Expression):
231
+ arg_types = {"expressions": True}
232
+
233
+
234
+ class MacroOverload(Expression):
235
+ arg_types = {"this": True, "expressions": False, "is_table": False}
236
+
237
+
238
+ class CharacterSet(Expression):
239
+ arg_types = {"this": True, "default": False}
240
+
241
+
242
+ class AlterColumn(Expression):
243
+ arg_types = {
244
+ "this": True,
245
+ "dtype": False,
246
+ "collate": False,
247
+ "using": False,
248
+ "default": False,
249
+ "drop": False,
250
+ "comment": False,
251
+ "allow_null": False,
252
+ "visible": False,
253
+ "rename_to": False,
254
+ "exists": False,
255
+ }
256
+
257
+
258
+ class ModifyColumn(Expression):
259
+ arg_types = {"this": True, "rename_from": False}
260
+
261
+
262
+ class AlterIndex(Expression):
263
+ arg_types = {"this": True, "visible": True}
264
+
265
+
266
+ class AlterDistStyle(Expression):
267
+ pass
268
+
269
+
270
+ class AlterSortKey(Expression):
271
+ arg_types = {"this": False, "expressions": False, "compound": False}
272
+
273
+
274
+ class AlterSet(Expression):
275
+ arg_types = {
276
+ "expressions": False,
277
+ "option": False,
278
+ "tablespace": False,
279
+ "access_method": False,
280
+ "file_format": False,
281
+ "copy_options": False,
282
+ "tag": False,
283
+ "location": False,
284
+ "serde": False,
285
+ }
286
+
287
+
288
+ class RenameColumn(Expression):
289
+ arg_types = {"this": True, "to": True, "exists": False}
290
+
291
+
292
+ class AlterRename(Expression):
293
+ pass
294
+
295
+
296
+ class RenameIndex(Expression):
297
+ arg_types = {"this": True, "to": True}
298
+
299
+
300
+ class AlterModifySqlSecurity(Expression):
301
+ arg_types = {"expressions": True}
302
+
303
+
304
+ class SwapTable(Expression):
305
+ pass
306
+
307
+
308
+ class Comment(Expression):
309
+ arg_types = {
310
+ "this": True,
311
+ "kind": True,
312
+ "expression": True,
313
+ "exists": False,
314
+ "materialized": False,
315
+ }
316
+
317
+
318
+ class Comprehension(Expression):
319
+ arg_types = {
320
+ "this": True,
321
+ "expression": True,
322
+ "position": False,
323
+ "iterator": True,
324
+ "condition": False,
325
+ }
326
+
327
+
328
+ class MergeTreeTTLAction(Expression):
329
+ arg_types = {
330
+ "this": True,
331
+ "delete": False,
332
+ "recompress": False,
333
+ "to_disk": False,
334
+ "to_volume": False,
335
+ }
336
+
337
+
338
+ class MergeTreeTTL(Expression):
339
+ arg_types = {
340
+ "expressions": True,
341
+ "where": False,
342
+ "group": False,
343
+ "aggregates": False,
344
+ }
345
+
346
+
347
+ class Drop(Expression):
348
+ arg_types = {
349
+ "kind": False,
350
+ "tables": False,
351
+ "expressions": False,
352
+ "exists": False,
353
+ "temporary": False,
354
+ "materialized": False,
355
+ "cascade": False,
356
+ "restrict": False,
357
+ "constraints": False,
358
+ "purge": False,
359
+ "cluster": False,
360
+ "concurrently": False,
361
+ "sync": False,
362
+ "iceberg": False,
363
+ "force": False,
364
+ }
365
+
366
+ @property
367
+ def kind(self) -> str | None:
368
+ kind = self.args.get("kind")
369
+ return kind and kind.upper()
370
+
371
+
372
+ class DropPrimaryKey(Expression):
373
+ arg_types = {}
374
+
375
+
376
+ class Undrop(Expression):
377
+ arg_types = {"this": True, "kind": True, "rename": False}
378
+
379
+ @property
380
+ def kind(self) -> str:
381
+ return self.args["kind"].upper()
382
+
383
+
384
+ class Command(Expression):
385
+ arg_types = {"this": True, "expression": False}
386
+ _hash_raw_args = True
387
+
388
+
389
+ class Transaction(Expression):
390
+ arg_types = {"this": False, "modes": False, "mark": False}
391
+
392
+
393
+ class Commit(Expression):
394
+ arg_types = {"chain": False, "this": False, "durability": False}
395
+
396
+
397
+ class Rollback(Expression):
398
+ arg_types = {"savepoint": False, "this": False}
399
+
400
+
401
+ class Alter(Expression):
402
+ arg_types = {
403
+ "this": False,
404
+ "kind": True,
405
+ "actions": False,
406
+ "exists": False,
407
+ "only": False,
408
+ "options": False,
409
+ "cluster": False,
410
+ "not_valid": False,
411
+ "check": False,
412
+ "cascade": False,
413
+ "iceberg": False,
414
+ }
415
+
416
+ @property
417
+ def kind(self) -> str | None:
418
+ kind = self.args.get("kind")
419
+ return kind and kind.upper()
420
+
421
+ @property
422
+ def actions(self) -> list[Expr]:
423
+ return self.args.get("actions") or []
424
+
425
+
426
+ class AlterSession(Expression):
427
+ arg_types = {"expressions": True, "unset": False}
428
+
429
+
430
+ class Use(Expression):
431
+ arg_types = {"this": False, "expressions": False, "kind": False}
432
+
433
+
434
+ class NextValueFor(Expression, Func):
435
+ arg_types = {"this": True, "order": False}
436
+
437
+
438
+ class Execute(Expression):
439
+ arg_types = {"this": True, "expressions": False, "return_status": False}
440
+
441
+ @property
442
+ def name(self) -> str:
443
+ return self.this.name
444
+
445
+
446
+ class ExecuteSql(Execute):
447
+ pass
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/dml.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions DML."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typing as t
6
+
7
+ from sqlglot.helper import trait
8
+ from sqlglot.expressions.core import (
9
+ Expr,
10
+ Expression,
11
+ _apply_builder,
12
+ _apply_list_builder,
13
+ maybe_copy,
14
+ _apply_conjunction_builder,
15
+ )
16
+ from sqlglot.expressions.ddl import DDL
17
+ from sqlglot.expressions.query import (
18
+ Table,
19
+ Where,
20
+ From,
21
+ _apply_cte_builder,
22
+ )
23
+
24
+ if t.TYPE_CHECKING:
25
+ from typing_extensions import Self, Unpack
26
+ from sqlglot.dialects.dialect import DialectType
27
+ from sqlglot.expressions.core import ExpOrStr
28
+ from sqlglot._typing import ParserNoDialectArgs
29
+
30
+
31
+ @trait
32
+ class DML(Expr):
33
+ """Trait for data manipulation language statements."""
34
+
35
+ def returning(
36
+ self,
37
+ expression: ExpOrStr,
38
+ dialect: DialectType = None,
39
+ copy: bool = True,
40
+ **opts: Unpack[ParserNoDialectArgs],
41
+ ) -> Self:
42
+ """
43
+ Set the RETURNING expression. Not supported by all dialects.
44
+
45
+ Example:
46
+ >>> Delete().delete("tbl").returning("*", dialect="postgres").sql()
47
+ 'DELETE FROM tbl RETURNING *'
48
+
49
+ Args:
50
+ expression: the SQL code strings to parse.
51
+ If an `Expr` instance is passed, it will be used as-is.
52
+ dialect: the dialect used to parse the input expressions.
53
+ copy: if `False`, modify this expression instance in-place.
54
+ opts: other options to use to parse the input expressions.
55
+
56
+ Returns:
57
+ Delete: the modified expression.
58
+ """
59
+ return _apply_builder(
60
+ expression=expression,
61
+ instance=self,
62
+ arg="returning",
63
+ prefix="RETURNING",
64
+ dialect=dialect,
65
+ copy=copy,
66
+ into=Returning,
67
+ **opts,
68
+ )
69
+
70
+
71
+ class Delete(Expression, DML):
72
+ arg_types = {
73
+ "with_": False,
74
+ "this": False,
75
+ "using": False,
76
+ "where": False,
77
+ "returning": False,
78
+ "order": False,
79
+ "limit": False,
80
+ "tables": False, # Multiple-Table Syntax (MySQL)
81
+ "cluster": False, # Clickhouse
82
+ "hint": False,
83
+ }
84
+
85
+ def delete(
86
+ self,
87
+ table: ExpOrStr,
88
+ dialect: DialectType = None,
89
+ copy: bool = True,
90
+ **opts: Unpack[ParserNoDialectArgs],
91
+ ) -> Delete:
92
+ """
93
+ Create a DELETE expression or replace the table on an existing DELETE expression.
94
+
95
+ Example:
96
+ >>> Delete().delete("tbl").sql()
97
+ 'DELETE FROM tbl'
98
+
99
+ Args:
100
+ table: the table from which to delete.
101
+ dialect: the dialect used to parse the input expression.
102
+ copy: if `False`, modify this expression instance in-place.
103
+ opts: other options to use to parse the input expressions.
104
+
105
+ Returns:
106
+ Delete: the modified expression.
107
+ """
108
+ return _apply_builder(
109
+ expression=table,
110
+ instance=self,
111
+ arg="this",
112
+ dialect=dialect,
113
+ into=Table,
114
+ copy=copy,
115
+ **opts,
116
+ )
117
+
118
+ def where(
119
+ self,
120
+ *expressions: ExpOrStr | None,
121
+ append: bool = True,
122
+ dialect: DialectType = None,
123
+ copy: bool = True,
124
+ **opts: Unpack[ParserNoDialectArgs],
125
+ ) -> Delete:
126
+ """
127
+ Append to or set the WHERE expressions.
128
+
129
+ Example:
130
+ >>> Delete().delete("tbl").where("x = 'a' OR x < 'b'").sql()
131
+ "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
132
+
133
+ Args:
134
+ *expressions: the SQL code strings to parse.
135
+ If an `Expr` instance is passed, it will be used as-is.
136
+ Multiple expressions are combined with an AND operator.
137
+ append: if `True`, AND the new expressions to any existing expression.
138
+ Otherwise, this resets the expression.
139
+ dialect: the dialect used to parse the input expressions.
140
+ copy: if `False`, modify this expression instance in-place.
141
+ opts: other options to use to parse the input expressions.
142
+
143
+ Returns:
144
+ Delete: the modified expression.
145
+ """
146
+ return _apply_conjunction_builder(
147
+ *expressions,
148
+ instance=self,
149
+ arg="where",
150
+ append=append,
151
+ into=Where,
152
+ dialect=dialect,
153
+ copy=copy,
154
+ **opts,
155
+ )
156
+
157
+
158
+ class Export(Expression):
159
+ arg_types = {"this": True, "connection": False, "options": True}
160
+
161
+
162
+ class CopyParameter(Expression):
163
+ arg_types = {"this": True, "expression": False, "expressions": False}
164
+
165
+
166
+ class Copy(Expression, DML):
167
+ arg_types = {
168
+ "this": True,
169
+ "kind": True,
170
+ "files": False,
171
+ "credentials": False,
172
+ "format": False,
173
+ "params": False,
174
+ }
175
+
176
+
177
+ class Credentials(Expression):
178
+ arg_types = {
179
+ "credentials": False,
180
+ "encryption": False,
181
+ "storage": False,
182
+ "iam_role": False,
183
+ "region": False,
184
+ }
185
+
186
+
187
+ class Directory(Expression):
188
+ arg_types = {"this": True, "local": False, "row_format": False}
189
+
190
+
191
+ class DirectoryStage(Expression):
192
+ pass
193
+
194
+
195
+ class Insert(Expression, DDL, DML):
196
+ arg_types = {
197
+ "hint": False,
198
+ "with_": False,
199
+ "is_function": False,
200
+ "this": False,
201
+ "expression": False,
202
+ "conflict": False,
203
+ "returning": False,
204
+ "overwrite": False,
205
+ "exists": False,
206
+ "alternative": False,
207
+ "where": False,
208
+ "ignore": False,
209
+ "by_name": False,
210
+ "stored": False,
211
+ "partition": False,
212
+ "settings": False,
213
+ "source": False,
214
+ "default": False,
215
+ "using": False,
216
+ }
217
+
218
+ def with_(
219
+ self,
220
+ alias: ExpOrStr,
221
+ as_: ExpOrStr,
222
+ recursive: bool | None = None,
223
+ materialized: bool | None = None,
224
+ append: bool = True,
225
+ dialect: DialectType = None,
226
+ copy: bool = True,
227
+ **opts: Unpack[ParserNoDialectArgs],
228
+ ) -> Insert:
229
+ """
230
+ Append to or set the common table expressions.
231
+
232
+ Example:
233
+ >>> import sqlglot
234
+ >>> sqlglot.parse_one("INSERT INTO t SELECT x FROM cte").with_("cte", as_="SELECT * FROM tbl").sql()
235
+ 'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
236
+
237
+ Args:
238
+ alias: the SQL code string to parse as the table name.
239
+ If an `Expr` instance is passed, this is used as-is.
240
+ as_: the SQL code string to parse as the table expression.
241
+ If an `Expr` instance is passed, it will be used as-is.
242
+ recursive: set the RECURSIVE part of the expression. Defaults to `False`.
243
+ materialized: set the MATERIALIZED part of the expression.
244
+ append: if `True`, add to any existing expressions.
245
+ Otherwise, this resets the expressions.
246
+ dialect: the dialect used to parse the input expression.
247
+ copy: if `False`, modify this expression instance in-place.
248
+ opts: other options to use to parse the input expressions.
249
+
250
+ Returns:
251
+ The modified expression.
252
+ """
253
+ return _apply_cte_builder(
254
+ self,
255
+ alias,
256
+ as_,
257
+ recursive=recursive,
258
+ materialized=materialized,
259
+ append=append,
260
+ dialect=dialect,
261
+ copy=copy,
262
+ **opts,
263
+ )
264
+
265
+
266
+ class OnConflict(Expression):
267
+ arg_types = {
268
+ "duplicate": False,
269
+ "expressions": False,
270
+ "action": False,
271
+ "conflict_keys": False,
272
+ "index_predicate": False,
273
+ "constraint": False,
274
+ "where": False,
275
+ }
276
+
277
+
278
+ class Returning(Expression):
279
+ arg_types = {"expressions": True, "into": False}
280
+
281
+
282
+ class LoadData(Expression):
283
+ arg_types = {
284
+ "this": True,
285
+ "local": False,
286
+ "overwrite": False,
287
+ "temp": False,
288
+ "inpath": False,
289
+ "files": False,
290
+ "partition": False,
291
+ "input_format": False,
292
+ "serde": False,
293
+ }
294
+
295
+
296
+ class Update(Expression, DML):
297
+ arg_types = {
298
+ "with_": False,
299
+ "this": False,
300
+ "expressions": False,
301
+ "from_": False,
302
+ "where": False,
303
+ "returning": False,
304
+ "order": False,
305
+ "limit": False,
306
+ "options": False,
307
+ "hint": False,
308
+ }
309
+
310
+ def table(
311
+ self,
312
+ expression: ExpOrStr,
313
+ dialect: DialectType = None,
314
+ copy: bool = True,
315
+ **opts: Unpack[ParserNoDialectArgs],
316
+ ) -> Update:
317
+ """
318
+ Set the table to update.
319
+
320
+ Example:
321
+ >>> Update().table("my_table").set_("x = 1").sql()
322
+ 'UPDATE my_table SET x = 1'
323
+
324
+ Args:
325
+ expression : the SQL code strings to parse.
326
+ If a `Table` instance is passed, this is used as-is.
327
+ If another `Expr` instance is passed, it will be wrapped in a `Table`.
328
+ dialect: the dialect used to parse the input expression.
329
+ copy: if `False`, modify this expression instance in-place.
330
+ opts: other options to use to parse the input expressions.
331
+
332
+ Returns:
333
+ The modified Update expression.
334
+ """
335
+ return _apply_builder(
336
+ expression=expression,
337
+ instance=self,
338
+ arg="this",
339
+ into=Table,
340
+ prefix=None,
341
+ dialect=dialect,
342
+ copy=copy,
343
+ **opts,
344
+ )
345
+
346
+ def set_(
347
+ self,
348
+ *expressions: ExpOrStr,
349
+ append: bool = True,
350
+ dialect: DialectType = None,
351
+ copy: bool = True,
352
+ **opts: Unpack[ParserNoDialectArgs],
353
+ ) -> Update:
354
+ """
355
+ Append to or set the SET expressions.
356
+
357
+ Example:
358
+ >>> Update().table("my_table").set_("x = 1").sql()
359
+ 'UPDATE my_table SET x = 1'
360
+
361
+ Args:
362
+ *expressions: the SQL code strings to parse.
363
+ If `Expr` instance(s) are passed, they will be used as-is.
364
+ Multiple expressions are combined with a comma.
365
+ append: if `True`, add the new expressions to any existing SET expressions.
366
+ Otherwise, this resets the expressions.
367
+ dialect: the dialect used to parse the input expressions.
368
+ copy: if `False`, modify this expression instance in-place.
369
+ opts: other options to use to parse the input expressions.
370
+ """
371
+ return _apply_list_builder(
372
+ *expressions,
373
+ instance=self,
374
+ arg="expressions",
375
+ append=append,
376
+ into=Expr,
377
+ prefix=None,
378
+ dialect=dialect,
379
+ copy=copy,
380
+ **opts,
381
+ )
382
+
383
+ def where(
384
+ self,
385
+ *expressions: ExpOrStr | None,
386
+ append: bool = True,
387
+ dialect: DialectType = None,
388
+ copy: bool = True,
389
+ **opts: Unpack[ParserNoDialectArgs],
390
+ ) -> Update:
391
+ """
392
+ Append to or set the WHERE expressions.
393
+
394
+ Example:
395
+ >>> Update().table("tbl").set_("x = 1").where("x = 'a' OR x < 'b'").sql()
396
+ "UPDATE tbl SET x = 1 WHERE x = 'a' OR x < 'b'"
397
+
398
+ Args:
399
+ *expressions: the SQL code strings to parse.
400
+ If an `Expr` instance is passed, it will be used as-is.
401
+ Multiple expressions are combined with an AND operator.
402
+ append: if `True`, AND the new expressions to any existing expression.
403
+ Otherwise, this resets the expression.
404
+ dialect: the dialect used to parse the input expressions.
405
+ copy: if `False`, modify this expression instance in-place.
406
+ opts: other options to use to parse the input expressions.
407
+
408
+ Returns:
409
+ Update: the modified expression.
410
+ """
411
+ return _apply_conjunction_builder(
412
+ *expressions,
413
+ instance=self,
414
+ arg="where",
415
+ append=append,
416
+ into=Where,
417
+ dialect=dialect,
418
+ copy=copy,
419
+ **opts,
420
+ )
421
+
422
+ def from_(
423
+ self,
424
+ expression: ExpOrStr | None = None,
425
+ dialect: DialectType = None,
426
+ copy: bool = True,
427
+ **opts: Unpack[ParserNoDialectArgs],
428
+ ) -> Update:
429
+ """
430
+ Set the FROM expression.
431
+
432
+ Example:
433
+ >>> Update().table("my_table").set_("x = 1").from_("baz").sql()
434
+ 'UPDATE my_table SET x = 1 FROM baz'
435
+
436
+ Args:
437
+ expression : the SQL code strings to parse.
438
+ If a `From` instance is passed, this is used as-is.
439
+ If another `Expr` instance is passed, it will be wrapped in a `From`.
440
+ If nothing is passed in then a from is not applied to the expression
441
+ dialect: the dialect used to parse the input expression.
442
+ copy: if `False`, modify this expression instance in-place.
443
+ opts: other options to use to parse the input expressions.
444
+
445
+ Returns:
446
+ The modified Update expression.
447
+ """
448
+ if not expression:
449
+ return maybe_copy(self, copy)
450
+
451
+ return _apply_builder(
452
+ expression=expression,
453
+ instance=self,
454
+ arg="from_",
455
+ into=From,
456
+ prefix="FROM",
457
+ dialect=dialect,
458
+ copy=copy,
459
+ **opts,
460
+ )
461
+
462
+ def with_(
463
+ self,
464
+ alias: ExpOrStr,
465
+ as_: ExpOrStr,
466
+ recursive: bool | None = None,
467
+ materialized: bool | None = None,
468
+ append: bool = True,
469
+ dialect: DialectType = None,
470
+ copy: bool = True,
471
+ **opts: Unpack[ParserNoDialectArgs],
472
+ ) -> Update:
473
+ """
474
+ Append to or set the common table expressions.
475
+
476
+ Example:
477
+ >>> Update().table("my_table").set_("x = 1").from_("baz").with_("baz", "SELECT id FROM foo").sql()
478
+ 'WITH baz AS (SELECT id FROM foo) UPDATE my_table SET x = 1 FROM baz'
479
+
480
+ Args:
481
+ alias: the SQL code string to parse as the table name.
482
+ If an `Expr` instance is passed, this is used as-is.
483
+ as_: the SQL code string to parse as the table expression.
484
+ If an `Expr` instance is passed, it will be used as-is.
485
+ recursive: set the RECURSIVE part of the expression. Defaults to `False`.
486
+ materialized: set the MATERIALIZED part of the expression.
487
+ append: if `True`, add to any existing expressions.
488
+ Otherwise, this resets the expressions.
489
+ dialect: the dialect used to parse the input expression.
490
+ copy: if `False`, modify this expression instance in-place.
491
+ opts: other options to use to parse the input expressions.
492
+
493
+ Returns:
494
+ The modified expression.
495
+ """
496
+ return _apply_cte_builder(
497
+ self,
498
+ alias,
499
+ as_,
500
+ recursive=recursive,
501
+ materialized=materialized,
502
+ append=append,
503
+ dialect=dialect,
504
+ copy=copy,
505
+ **opts,
506
+ )
507
+
508
+
509
+ class Merge(Expression, DML):
510
+ arg_types = {
511
+ "this": True,
512
+ "using": True,
513
+ "on": False,
514
+ "using_cond": False,
515
+ "whens": True,
516
+ "with_": False,
517
+ "returning": False,
518
+ }
519
+
520
+
521
+ class When(Expression):
522
+ arg_types = {"matched": True, "source": False, "condition": False, "then": True}
523
+
524
+
525
+ class Whens(Expression):
526
+ """Wraps around one or more WHEN [NOT] MATCHED [...] clauses."""
527
+
528
+ arg_types = {"expressions": True}
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/functions.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typing as t
6
+
7
+ from sqlglot.expressions.core import (
8
+ Expression,
9
+ Func,
10
+ Binary,
11
+ SubqueryPredicate,
12
+ ExpOrStr,
13
+ maybe_parse,
14
+ maybe_copy,
15
+ )
16
+
17
+ # Re-export from focused submodules (backward compatibility)
18
+ from sqlglot.expressions.math import * # noqa: F401,F403
19
+ from sqlglot.expressions.string import * # noqa: F401,F403
20
+ from sqlglot.expressions.temporal import * # noqa: F401,F403
21
+ from sqlglot.expressions.aggregate import * # noqa: F401,F403
22
+ from sqlglot.expressions.array import * # noqa: F401,F403
23
+ from sqlglot.expressions.json import * # noqa: F401,F403
24
+
25
+ if t.TYPE_CHECKING:
26
+ from sqlglot.expressions.datatypes import DataType, DATA_TYPE
27
+ from typing_extensions import Unpack
28
+ from sqlglot._typing import ParserArgs
29
+
30
+
31
+ # Cast / type conversion
32
+
33
+
34
+ class Cast(Expression, Func):
35
+ is_cast: t.ClassVar[bool] = True
36
+ arg_types = {
37
+ "this": True,
38
+ "to": True,
39
+ "format": False,
40
+ "safe": False,
41
+ "action": False,
42
+ "default": False,
43
+ }
44
+
45
+ @property
46
+ def name(self) -> str:
47
+ return self.this.name
48
+
49
+ @property
50
+ def to(self) -> DataType:
51
+ return self.args["to"]
52
+
53
+ @property
54
+ def output_name(self) -> str:
55
+ return self.name
56
+
57
+ def is_type(self, *dtypes: DATA_TYPE) -> bool:
58
+ """
59
+ Checks whether this Cast's DataType matches one of the provided data types. Nested types
60
+ like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
61
+ array<int> != array<float>.
62
+
63
+ Args:
64
+ dtypes: the data types to compare this Cast's DataType to.
65
+
66
+ Returns:
67
+ True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
68
+ """
69
+ return self.to.is_type(*dtypes)
70
+
71
+
72
+ class TryCast(Cast):
73
+ arg_types = {
74
+ **Cast.arg_types,
75
+ "requires_string": False,
76
+ "null_on_text_overflow": False,
77
+ "probe_date_format": False,
78
+ }
79
+
80
+
81
+ class JSONCast(Cast):
82
+ pass
83
+
84
+
85
+ class CastToStrType(Expression, Func):
86
+ arg_types = {"this": True, "to": True}
87
+
88
+
89
+ class Convert(Expression, Func):
90
+ arg_types = {"this": True, "expression": True, "style": False, "safe": False}
91
+
92
+
93
+ # Conditional
94
+
95
+
96
+ class If(Expression, Func):
97
+ arg_types = {"this": True, "true": True, "false": False}
98
+ _sql_names = ["IF", "IIF"]
99
+
100
+
101
+ class Case(Expression, Func):
102
+ arg_types = {"this": False, "ifs": True, "default": False}
103
+
104
+ def when(
105
+ self,
106
+ condition: ExpOrStr,
107
+ then: ExpOrStr,
108
+ copy: bool = True,
109
+ **opts: Unpack[ParserArgs],
110
+ ) -> Case:
111
+ instance = maybe_copy(self, copy)
112
+ instance.append(
113
+ "ifs",
114
+ If(
115
+ this=maybe_parse(condition, copy=copy, **opts),
116
+ true=maybe_parse(then, copy=copy, **opts),
117
+ ),
118
+ )
119
+ return instance
120
+
121
+ def else_(self, condition: ExpOrStr, copy: bool = True, **opts: Unpack[ParserArgs]) -> Case:
122
+ instance = maybe_copy(self, copy)
123
+ instance.set("default", maybe_parse(condition, copy=copy, **opts))
124
+ return instance
125
+
126
+
127
+ class Coalesce(Expression, Func):
128
+ arg_types = {"this": True, "expressions": False, "is_nvl": False, "is_null": False}
129
+ is_var_len_args = True
130
+ _sql_names = ["COALESCE", "IFNULL", "NVL"]
131
+
132
+
133
+ class DecodeCase(Expression, Func):
134
+ arg_types = {"expressions": True}
135
+ is_var_len_args = True
136
+
137
+
138
+ class EqualNull(Expression, Func):
139
+ arg_types = {"this": True, "expression": True}
140
+
141
+
142
+ class Greatest(Expression, Func):
143
+ arg_types = {"this": True, "expressions": False, "ignore_nulls": True}
144
+ is_var_len_args = True
145
+
146
+
147
+ class Least(Expression, Func):
148
+ arg_types = {"this": True, "expressions": False, "ignore_nulls": True}
149
+ is_var_len_args = True
150
+
151
+
152
+ class Nullif(Expression, Func):
153
+ arg_types = {"this": True, "expression": True}
154
+
155
+
156
+ class ObjectTransform(Expression, Func):
157
+ arg_types = {"this": True, "keep": False, "set_": False}
158
+
159
+
160
+ class Nvl2(Expression, Func):
161
+ arg_types = {"this": True, "true": True, "false": False}
162
+
163
+
164
+ class Try(Expression, Func):
165
+ pass
166
+
167
+
168
+ # Predicates / misc functions
169
+
170
+
171
+ class Collate(Expression, Binary, Func):
172
+ pass
173
+
174
+
175
+ class Collation(Expression, Func):
176
+ pass
177
+
178
+
179
+ class ConnectByRoot(Expression, Func):
180
+ pass
181
+
182
+
183
+ class CheckXml(Expression, Func):
184
+ arg_types = {"this": True, "disable_auto_convert": False}
185
+
186
+
187
+ class Exists(Expression, Func, SubqueryPredicate):
188
+ arg_types = {"this": True, "expression": False}
189
+
190
+
191
+ # Type coercions / lax types
192
+
193
+
194
+ class Float64(Expression, Func):
195
+ arg_types = {"this": True, "expression": False}
196
+
197
+
198
+ class Int64(Expression, Func):
199
+ pass
200
+
201
+
202
+ class IsArray(Expression, Func):
203
+ pass
204
+
205
+
206
+ class IsNullValue(Expression, Func):
207
+ pass
208
+
209
+
210
+ class LaxBool(Expression, Func):
211
+ pass
212
+
213
+
214
+ class LaxFloat64(Expression, Func):
215
+ pass
216
+
217
+
218
+ class LaxInt64(Expression, Func):
219
+ pass
220
+
221
+
222
+ class LaxString(Expression, Func):
223
+ pass
224
+
225
+
226
+ class ToBoolean(Expression, Func):
227
+ arg_types = {"this": True, "safe": False}
228
+
229
+
230
+ class ToVariant(Expression, Func):
231
+ pass
232
+
233
+
234
+ # Session / context functions
235
+
236
+
237
+ class CurrentAccount(Expression, Func):
238
+ arg_types = {}
239
+
240
+
241
+ class CurrentAccountName(Expression, Func):
242
+ arg_types = {}
243
+
244
+
245
+ class CurrentAvailableRoles(Expression, Func):
246
+ arg_types = {}
247
+
248
+
249
+ class CurrentCatalog(Expression, Func):
250
+ arg_types = {}
251
+
252
+
253
+ class CurrentClient(Expression, Func):
254
+ arg_types = {}
255
+
256
+
257
+ class CurrentDatabase(Expression, Func):
258
+ arg_types = {}
259
+
260
+
261
+ class CurrentIpAddress(Expression, Func):
262
+ arg_types = {}
263
+
264
+
265
+ class CurrentOrganizationName(Expression, Func):
266
+ arg_types = {}
267
+
268
+
269
+ class CurrentOrganizationUser(Expression, Func):
270
+ arg_types = {}
271
+
272
+
273
+ class CurrentRegion(Expression, Func):
274
+ arg_types = {}
275
+
276
+
277
+ class CurrentRole(Expression, Func):
278
+ arg_types = {}
279
+
280
+
281
+ class CurrentRoleType(Expression, Func):
282
+ arg_types = {}
283
+
284
+
285
+ class CurrentSchema(Expression, Func):
286
+ arg_types = {"this": False}
287
+
288
+
289
+ class CurrentSchemas(Expression, Func):
290
+ arg_types = {"this": False}
291
+
292
+
293
+ class CurrentSecondaryRoles(Expression, Func):
294
+ arg_types = {}
295
+
296
+
297
+ class CurrentSession(Expression, Func):
298
+ arg_types = {}
299
+
300
+
301
+ class CurrentStatement(Expression, Func):
302
+ arg_types = {}
303
+
304
+
305
+ class CurrentTransaction(Expression, Func):
306
+ arg_types = {}
307
+
308
+
309
+ class CurrentUser(Expression, Func):
310
+ arg_types = {"this": False}
311
+
312
+
313
+ class CurrentUserId(Expression, Func):
314
+ arg_types = {}
315
+
316
+
317
+ class CurrentVersion(Expression, Func):
318
+ arg_types = {}
319
+
320
+
321
+ class CurrentWarehouse(Expression, Func):
322
+ arg_types = {}
323
+
324
+
325
+ class SessionUser(Expression, Func):
326
+ arg_types = {}
327
+
328
+
329
+ # ML / AI
330
+
331
+
332
+ class AIClassify(Expression, Func):
333
+ arg_types = {"this": True, "categories": True, "config": False}
334
+ _sql_names = ["AI_CLASSIFY"]
335
+
336
+
337
+ class AIEmbed(Expression, Func):
338
+ arg_types = {"expressions": True}
339
+ is_var_len_args = True
340
+ _sql_names = ["AI_EMBED"]
341
+
342
+
343
+ class AISimilarity(Expression, Func):
344
+ arg_types = {"expressions": True}
345
+ is_var_len_args = True
346
+ _sql_names = ["AI_SIMILARITY"]
347
+
348
+
349
+ class AIGenerate(Expression, Func):
350
+ arg_types = {"expressions": True}
351
+ is_var_len_args = True
352
+ _sql_names = ["AI_GENERATE"]
353
+
354
+
355
+ class FeaturesAtTime(Expression, Func):
356
+ arg_types = {"this": True, "time": False, "num_rows": False, "ignore_feature_nulls": False}
357
+
358
+
359
+ class GenerateEmbedding(Expression, Func):
360
+ arg_types = {"this": True, "expression": True, "params_struct": False, "is_text": False}
361
+
362
+
363
+ class GenerateText(Expression, Func):
364
+ arg_types = {"this": True, "expression": False, "params_struct": False}
365
+
366
+
367
+ class GenerateTable(Expression, Func):
368
+ arg_types = {"this": True, "expression": False, "params_struct": False}
369
+
370
+
371
+ class GenerateBool(Expression, Func):
372
+ arg_types = {"this": True, "expression": False, "params_struct": False}
373
+
374
+
375
+ class GenerateInt(Expression, Func):
376
+ arg_types = {"this": True, "expression": False, "params_struct": False}
377
+
378
+
379
+ class GenerateDouble(Expression, Func):
380
+ arg_types = {"this": True, "expression": False, "params_struct": False}
381
+
382
+
383
+ class MLForecast(Expression, Func):
384
+ arg_types = {"this": True, "expression": False, "params_struct": False}
385
+
386
+
387
+ class AIForecast(Expression, Func):
388
+ arg_types = {
389
+ "this": True,
390
+ "data_col": False,
391
+ "timestamp_col": False,
392
+ "model": False,
393
+ "id_cols": False,
394
+ "horizon": False,
395
+ "forecast_end_timestamp": False,
396
+ "confidence_level": False,
397
+ "output_historical_time_series": False,
398
+ "context_window": False,
399
+ }
400
+
401
+
402
+ class MLTranslate(Expression, Func):
403
+ arg_types = {"this": True, "expression": True, "params_struct": True}
404
+
405
+
406
+ class Predict(Expression, Func):
407
+ arg_types = {"this": True, "expression": True, "params_struct": False}
408
+
409
+
410
+ class VectorSearch(Expression, Func):
411
+ arg_types = {
412
+ "this": True,
413
+ "column_to_search": True,
414
+ "query_table": True,
415
+ "query_column_to_search": False,
416
+ "top_k": False,
417
+ "distance_type": False,
418
+ "options": False,
419
+ }
420
+
421
+
422
+ # Data reading
423
+
424
+
425
+ class ReadCSV(Expression, Func):
426
+ _sql_names = ["READ_CSV"]
427
+ is_var_len_args = True
428
+ arg_types = {"this": True, "expressions": False}
429
+
430
+
431
+ class ReadParquet(Expression, Func):
432
+ is_var_len_args = True
433
+ arg_types = {"expressions": True}
434
+
435
+
436
+ # XML
437
+
438
+
439
+ class XMLElement(Expression, Func):
440
+ _sql_names = ["XMLELEMENT"]
441
+ arg_types = {"this": True, "expressions": False, "evalname": False}
442
+
443
+
444
+ class GetIgnoreCase(Expression, Func):
445
+ arg_types = {"this": True, "expression": True}
446
+
447
+
448
+ class XMLGet(Expression, Func):
449
+ _sql_names = ["XMLGET"]
450
+ arg_types = {"this": True, "expression": True, "instance": False}
451
+
452
+
453
+ class XMLTable(Expression, Func):
454
+ arg_types = {
455
+ "this": True,
456
+ "namespaces": False,
457
+ "passing": False,
458
+ "columns": False,
459
+ "by_ref": False,
460
+ }
461
+
462
+
463
+ # Network / domain
464
+
465
+
466
+ class Host(Expression, Func):
467
+ pass
468
+
469
+
470
+ class NetFunc(Expression, Func):
471
+ pass
472
+
473
+
474
+ class ParseIp(Expression, Func):
475
+ arg_types = {"this": True, "type": True, "permissive": False}
476
+
477
+
478
+ class RegDomain(Expression, Func):
479
+ pass
480
+
481
+
482
+ # Misc utility
483
+
484
+
485
+ class Columns(Expression, Func):
486
+ arg_types = {"this": True, "unpack": False}
487
+
488
+
489
+ class Normal(Expression, Func):
490
+ arg_types = {"this": True, "stddev": True, "gen": True}
491
+
492
+
493
+ class Rand(Expression, Func):
494
+ _sql_names = ["RAND", "RANDOM"]
495
+ arg_types = {"this": False, "lower": False, "upper": False}
496
+
497
+
498
+ class Randn(Expression, Func):
499
+ arg_types = {"this": False}
500
+
501
+
502
+ class Randstr(Expression, Func):
503
+ arg_types = {"this": True, "generator": False}
504
+
505
+
506
+ class RangeBucket(Expression, Func):
507
+ arg_types = {"this": True, "expression": True}
508
+
509
+
510
+ class RangeN(Expression, Func):
511
+ arg_types = {"this": True, "expressions": True, "each": False}
512
+
513
+
514
+ class Seq1(Expression, Func):
515
+ arg_types = {"this": False}
516
+
517
+
518
+ class Seq2(Expression, Func):
519
+ arg_types = {"this": False}
520
+
521
+
522
+ class Seq4(Expression, Func):
523
+ arg_types = {"this": False}
524
+
525
+
526
+ class Seq8(Expression, Func):
527
+ arg_types = {"this": False}
528
+
529
+
530
+ class Uniform(Expression, Func):
531
+ arg_types = {"this": True, "expression": True, "gen": False, "seed": False}
532
+
533
+
534
+ class Uuid(Expression, Func):
535
+ _sql_names = ["UUID", "GEN_RANDOM_UUID", "GENERATE_UUID", "UUID_STRING"]
536
+
537
+ arg_types = {"this": False, "name": False, "is_string": False}
538
+
539
+
540
+ class WeekStart(Expression, Func):
541
+ pass
542
+
543
+
544
+ class WidthBucket(Expression, Func):
545
+ arg_types = {
546
+ "this": True,
547
+ "min_value": False,
548
+ "max_value": False,
549
+ "num_buckets": False,
550
+ "threshold": False,
551
+ }
552
+
553
+
554
+ class Zipf(Expression, Func):
555
+ arg_types = {"this": True, "elementcount": True, "gen": True}
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/json.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions - JSON functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlglot.expressions.core import Expression, Func, AggFunc, Binary, Predicate
6
+
7
+
8
+ class CheckJson(Expression, Func):
9
+ arg_types = {"this": True}
10
+
11
+
12
+ class JSONArray(Expression, Func):
13
+ arg_types = {
14
+ "expressions": False,
15
+ "null_handling": False,
16
+ "return_type": False,
17
+ "strict": False,
18
+ }
19
+ is_var_len_args = True
20
+
21
+
22
+ class JSONArrayAgg(Expression, AggFunc):
23
+ arg_types = {
24
+ "this": True,
25
+ "order": False,
26
+ "null_handling": False,
27
+ "return_type": False,
28
+ "strict": False,
29
+ }
30
+
31
+
32
+ class JSONArrayAppend(Expression, Func):
33
+ arg_types = {"this": True, "expressions": True}
34
+ is_var_len_args = True
35
+ _sql_names = ["JSON_ARRAY_APPEND"]
36
+
37
+
38
+ class JSONArrayContains(Expression, Binary, Predicate, Func):
39
+ arg_types = {"this": True, "expression": True, "json_type": False}
40
+ _sql_names = ["JSON_ARRAY_CONTAINS"]
41
+
42
+
43
+ class JSONArrayInsert(Expression, Func):
44
+ arg_types = {"this": True, "expressions": True}
45
+ is_var_len_args = True
46
+ _sql_names = ["JSON_ARRAY_INSERT"]
47
+
48
+
49
+ class JSONBContains(Expression, Binary, Predicate, Func):
50
+ _sql_names = ["JSONB_CONTAINS"]
51
+
52
+
53
+ class JSONBContainsAllTopKeys(Expression, Binary, Predicate, Func):
54
+ pass
55
+
56
+
57
+ class JSONBContainsTopKey(Expression, Binary, Predicate, Func):
58
+ pass
59
+
60
+
61
+ class JSONBContainsAnyTopKeys(Expression, Binary, Predicate, Func):
62
+ pass
63
+
64
+
65
+ class JSONBDeleteAtPath(Expression, Binary, Func):
66
+ pass
67
+
68
+
69
+ class JSONBPathExists(Expression, Binary, Predicate, Func):
70
+ pass
71
+
72
+
73
+ class JSONBExists(Expression, Func):
74
+ arg_types = {"this": True, "path": True}
75
+ _sql_names = ["JSONB_EXISTS"]
76
+
77
+
78
+ class JSONBExtract(Expression, Binary, Func):
79
+ _sql_names = ["JSONB_EXTRACT"]
80
+
81
+
82
+ class JSONBExtractScalar(Expression, Binary, Func):
83
+ arg_types = {"this": True, "expression": True, "json_type": False}
84
+ _sql_names = ["JSONB_EXTRACT_SCALAR"]
85
+
86
+
87
+ class JSONBObjectAgg(Expression, AggFunc):
88
+ arg_types = {"this": True, "expression": True}
89
+
90
+
91
+ class JSONBool(Expression, Func):
92
+ pass
93
+
94
+
95
+ class JSONExists(Expression, Func):
96
+ arg_types = {
97
+ "this": True,
98
+ "path": True,
99
+ "passing": False,
100
+ "on_condition": False,
101
+ "from_dcolonqmark": False,
102
+ }
103
+ _hash_raw_args = True
104
+
105
+
106
+ class JSONExtract(Expression, Binary, Func):
107
+ arg_types = {
108
+ "this": True,
109
+ "expression": True,
110
+ "only_json_types": False,
111
+ "expressions": False,
112
+ "variant_extract": False,
113
+ "json_query": False,
114
+ "option": False,
115
+ "quote": False,
116
+ "on_condition": False,
117
+ "requires_json": False,
118
+ "emits": False,
119
+ }
120
+ _sql_names = ["JSON_EXTRACT"]
121
+ is_var_len_args = True
122
+
123
+ @property
124
+ def output_name(self) -> str:
125
+ return self.expression.output_name if not self.expressions else ""
126
+
127
+
128
+ class JSONExtractArray(Expression, Func):
129
+ arg_types = {"this": True, "expression": False}
130
+ _sql_names = ["JSON_EXTRACT_ARRAY"]
131
+
132
+
133
+ class JSONExtractScalar(Expression, Binary, Func):
134
+ arg_types = {
135
+ "this": True,
136
+ "expression": True,
137
+ "only_json_types": False,
138
+ "expressions": False,
139
+ "json_type": False,
140
+ "scalar_only": False,
141
+ "json_subtype": False,
142
+ }
143
+ _sql_names = ["JSON_EXTRACT_SCALAR"]
144
+ is_var_len_args = True
145
+
146
+ @property
147
+ def output_name(self) -> str:
148
+ return self.expression.output_name
149
+
150
+
151
+ class JSONFormat(Expression, Func):
152
+ arg_types = {"this": False, "options": False, "is_json": False, "to_json": False}
153
+ _sql_names = ["JSON_FORMAT"]
154
+
155
+
156
+ class JSONKeys(Expression, Func):
157
+ arg_types = {"this": True, "expression": False, "expressions": False}
158
+ is_var_len_args = True
159
+ _sql_names = ["JSON_KEYS"]
160
+
161
+
162
+ class JSONKeysAtDepth(Expression, Func):
163
+ arg_types = {"this": True, "expression": False, "mode": False}
164
+
165
+
166
+ class JSONObject(Expression, Func):
167
+ arg_types = {
168
+ "expressions": False,
169
+ "null_handling": False,
170
+ "unique_keys": False,
171
+ "return_type": False,
172
+ "encoding": False,
173
+ }
174
+
175
+
176
+ class JSONObjectAgg(Expression, AggFunc):
177
+ arg_types = {
178
+ "expressions": False,
179
+ "null_handling": False,
180
+ "unique_keys": False,
181
+ "return_type": False,
182
+ "encoding": False,
183
+ }
184
+
185
+
186
+ class JSONRemove(Expression, Func):
187
+ arg_types = {"this": True, "expressions": True}
188
+ is_var_len_args = True
189
+ _sql_names = ["JSON_REMOVE"]
190
+
191
+
192
+ class JSONSet(Expression, Func):
193
+ arg_types = {"this": True, "expressions": True}
194
+ is_var_len_args = True
195
+ _sql_names = ["JSON_SET"]
196
+
197
+
198
+ class JSONStripNulls(Expression, Func):
199
+ arg_types = {
200
+ "this": True,
201
+ "expression": False,
202
+ "include_arrays": False,
203
+ "remove_empty": False,
204
+ }
205
+ _sql_names = ["JSON_STRIP_NULLS"]
206
+
207
+
208
+ class StripNullValue(Expression, Func):
209
+ pass
210
+
211
+
212
+ class JSONTable(Expression, Func):
213
+ arg_types = {
214
+ "this": True,
215
+ "schema": True,
216
+ "path": False,
217
+ "error_handling": False,
218
+ "empty_handling": False,
219
+ }
220
+
221
+
222
+ class JSONType(Expression, Func):
223
+ arg_types = {"this": True, "expression": False}
224
+ _sql_names = ["JSON_TYPE"]
225
+
226
+
227
+ class ObjectId(Expression, Func):
228
+ arg_types = {"this": True, "expression": False}
229
+
230
+
231
+ class ObjectInsert(Expression, Func):
232
+ arg_types = {
233
+ "this": True,
234
+ "key": True,
235
+ "value": True,
236
+ "update_flag": False,
237
+ }
238
+
239
+
240
+ class OpenJSON(Expression, Func):
241
+ arg_types = {"this": True, "path": False, "expressions": False}
242
+
243
+
244
+ class FromJson(Expression, Func):
245
+ arg_types = {"this": True, "expression": True, "options": False}
246
+
247
+
248
+ class ParseJSON(Expression, Func):
249
+ # BigQuery, Snowflake have PARSE_JSON, Presto has JSON_PARSE
250
+ # Snowflake also has TRY_PARSE_JSON, which is represented using `safe`
251
+ _sql_names = ["PARSE_JSON", "JSON_PARSE"]
252
+ arg_types = {"this": True, "expression": False, "safe": False, "is_literal": False}
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/math.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions - math, trigonometry, and bitwise functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlglot.expressions.core import Expression, Func, AggFunc
6
+
7
+
8
+ # Trigonometric
9
+
10
+
11
+ class Acos(Expression, Func):
12
+ pass
13
+
14
+
15
+ class Acosh(Expression, Func):
16
+ pass
17
+
18
+
19
+ class Asin(Expression, Func):
20
+ pass
21
+
22
+
23
+ class Asinh(Expression, Func):
24
+ pass
25
+
26
+
27
+ class Atan(Expression, Func):
28
+ arg_types = {"this": True, "expression": False}
29
+
30
+
31
+ class Atanh(Expression, Func):
32
+ pass
33
+
34
+
35
+ class Atan2(Expression, Func):
36
+ arg_types = {"this": True, "expression": True}
37
+
38
+
39
+ class Cos(Expression, Func):
40
+ pass
41
+
42
+
43
+ class Cosh(Expression, Func):
44
+ pass
45
+
46
+
47
+ class Cot(Expression, Func):
48
+ pass
49
+
50
+
51
+ class Coth(Expression, Func):
52
+ pass
53
+
54
+
55
+ class Csc(Expression, Func):
56
+ pass
57
+
58
+
59
+ class Csch(Expression, Func):
60
+ pass
61
+
62
+
63
+ class Degrees(Expression, Func):
64
+ pass
65
+
66
+
67
+ class Radians(Expression, Func):
68
+ pass
69
+
70
+
71
+ class Sec(Expression, Func):
72
+ pass
73
+
74
+
75
+ class Sech(Expression, Func):
76
+ pass
77
+
78
+
79
+ class Sin(Expression, Func):
80
+ pass
81
+
82
+
83
+ class Sinh(Expression, Func):
84
+ pass
85
+
86
+
87
+ class Tan(Expression, Func):
88
+ pass
89
+
90
+
91
+ class Tanh(Expression, Func):
92
+ pass
93
+
94
+
95
+ # Geometric distance / similarity
96
+
97
+
98
+ class CosineDistance(Expression, Func):
99
+ arg_types = {"this": True, "expression": True}
100
+
101
+
102
+ class DotProduct(Expression, Func):
103
+ arg_types = {"this": True, "expression": True}
104
+
105
+
106
+ class EuclideanDistance(Expression, Func):
107
+ arg_types = {"this": True, "expression": True}
108
+
109
+
110
+ class JarowinklerSimilarity(Expression, Func):
111
+ arg_types = {
112
+ "this": True,
113
+ "expression": True,
114
+ "case_insensitive": False,
115
+ "integer_scale": False,
116
+ }
117
+
118
+
119
+ class ManhattanDistance(Expression, Func):
120
+ arg_types = {"this": True, "expression": True}
121
+
122
+
123
+ # Basic arithmetic / math
124
+
125
+
126
+ class Abs(Expression, Func):
127
+ pass
128
+
129
+
130
+ class Cbrt(Expression, Func):
131
+ pass
132
+
133
+
134
+ class Ceil(Expression, Func):
135
+ arg_types = {"this": True, "decimals": False, "to": False}
136
+ _sql_names = ["CEIL", "CEILING"]
137
+
138
+
139
+ class Exp(Expression, Func):
140
+ pass
141
+
142
+
143
+ class Factorial(Expression, Func):
144
+ pass
145
+
146
+
147
+ class Floor(Expression, Func):
148
+ arg_types = {"this": True, "decimals": False, "to": False}
149
+
150
+
151
+ class IsInf(Expression, Func):
152
+ _sql_names = ["IS_INF", "ISINF"]
153
+
154
+
155
+ class IsNan(Expression, Func):
156
+ _sql_names = ["IS_NAN", "ISNAN"]
157
+
158
+
159
+ class Ln(Expression, Func):
160
+ pass
161
+
162
+
163
+ class Log(Expression, Func):
164
+ arg_types = {"this": True, "expression": False}
165
+
166
+
167
+ class Negative(Expression, Func):
168
+ pass
169
+
170
+
171
+ class Nanvl(Expression, Func):
172
+ arg_types = {"this": True, "expression": True}
173
+
174
+
175
+ class Pi(Expression, Func):
176
+ arg_types = {}
177
+
178
+
179
+ class Rint(Expression, Func):
180
+ pass
181
+
182
+
183
+ class Round(Expression, Func):
184
+ arg_types = {
185
+ "this": True,
186
+ "decimals": False,
187
+ "truncate": False,
188
+ "casts_non_integer_decimals": False,
189
+ }
190
+
191
+
192
+ class Sign(Expression, Func):
193
+ _sql_names = ["SIGN", "SIGNUM"]
194
+
195
+
196
+ class Sqrt(Expression, Func):
197
+ pass
198
+
199
+
200
+ class Trunc(Expression, Func):
201
+ arg_types = {"this": True, "decimals": False, "fractions_supported": False}
202
+ _sql_names = ["TRUNC", "TRUNCATE"]
203
+
204
+
205
+ # Safe arithmetic
206
+
207
+
208
+ class SafeAdd(Expression, Func):
209
+ arg_types = {"this": True, "expression": True}
210
+
211
+
212
+ class SafeDivide(Expression, Func):
213
+ arg_types = {"this": True, "expression": True}
214
+
215
+
216
+ class SafeMultiply(Expression, Func):
217
+ arg_types = {"this": True, "expression": True}
218
+
219
+
220
+ class SafeNegate(Expression, Func):
221
+ pass
222
+
223
+
224
+ class SafeSubtract(Expression, Func):
225
+ arg_types = {"this": True, "expression": True}
226
+
227
+
228
+ # Bitwise
229
+
230
+
231
+ class BitwiseAndAgg(Expression, AggFunc):
232
+ pass
233
+
234
+
235
+ class BitwiseCount(Expression, Func):
236
+ pass
237
+
238
+
239
+ class BitwiseOrAgg(Expression, AggFunc):
240
+ pass
241
+
242
+
243
+ class BitwiseXorAgg(Expression, AggFunc):
244
+ pass
245
+
246
+
247
+ class BitmapBitPosition(Expression, Func):
248
+ pass
249
+
250
+
251
+ class BitmapBucketNumber(Expression, Func):
252
+ pass
253
+
254
+
255
+ class BitmapConstructAgg(Expression, AggFunc):
256
+ pass
257
+
258
+
259
+ class BitmapCount(Expression, Func):
260
+ pass
261
+
262
+
263
+ class BitmapOrAgg(Expression, AggFunc):
264
+ pass
265
+
266
+
267
+ class Booland(Expression, Func):
268
+ arg_types = {"this": True, "expression": True, "round_input": False}
269
+
270
+
271
+ class Boolnot(Expression, Func):
272
+ arg_types = {"this": True, "round_input": False}
273
+
274
+
275
+ class Boolor(Expression, Func):
276
+ arg_types = {"this": True, "expression": True, "round_input": False}
277
+
278
+
279
+ class BoolxorAgg(Expression, AggFunc):
280
+ pass
281
+
282
+
283
+ class Getbit(Expression, Func):
284
+ _sql_names = ["GETBIT", "GET_BIT"]
285
+ # zero_is_msb means the most significant bit is indexed 0
286
+ arg_types = {"this": True, "expression": True, "zero_is_msb": False}
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/properties.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions properties."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typing as t
6
+ from enum import auto
7
+
8
+ from sqlglot.expressions.core import ColumnConstraintKind, Expression, Literal, convert
9
+ from sqlglot.helper import AutoName
10
+
11
+
12
+ class Property(Expression):
13
+ arg_types = {"this": True, "value": True}
14
+
15
+
16
+ class GrantPrivilege(Expression):
17
+ arg_types = {"this": True, "expressions": False}
18
+
19
+
20
+ class GrantPrincipal(Expression):
21
+ arg_types = {"this": True, "kind": False}
22
+
23
+
24
+ class AllowedValuesProperty(Expression):
25
+ arg_types = {"expressions": True}
26
+
27
+
28
+ class AggregateKeyProperty(Property):
29
+ arg_types = {"expressions": True}
30
+
31
+
32
+ class AlgorithmProperty(Property):
33
+ arg_types = {"this": True}
34
+
35
+
36
+ class ApiProperty(Property):
37
+ arg_types = {}
38
+
39
+
40
+ class ApplicationProperty(Property):
41
+ arg_types = {}
42
+
43
+
44
+ class AutoIncrementProperty(Property):
45
+ arg_types = {"this": True}
46
+
47
+
48
+ class AutoRefreshProperty(Property):
49
+ arg_types = {
50
+ "this": False,
51
+ "cadence": False,
52
+ "offset": False,
53
+ "randomize": False,
54
+ "expressions": False,
55
+ "settings": False,
56
+ "append": False,
57
+ }
58
+
59
+
60
+ class BackupProperty(Property):
61
+ arg_types = {"this": True}
62
+
63
+
64
+ class BuildProperty(Property):
65
+ arg_types = {"this": True}
66
+
67
+
68
+ class BlockCompressionProperty(Property):
69
+ arg_types = {
70
+ "autotemp": False,
71
+ "always": False,
72
+ "default": False,
73
+ "manual": False,
74
+ "never": False,
75
+ }
76
+
77
+
78
+ class CalledOnNullInputProperty(Property):
79
+ arg_types = {}
80
+
81
+
82
+ class CatalogProperty(Property):
83
+ arg_types = {}
84
+
85
+
86
+ class CharacterSetProperty(Property):
87
+ arg_types = {"this": True, "default": True}
88
+
89
+
90
+ class ChecksumProperty(Property):
91
+ arg_types = {"on": False, "default": False}
92
+
93
+
94
+ class ClusterProperty(Property):
95
+ arg_types = {"this": False, "expressions": False}
96
+
97
+
98
+ class CollateProperty(Property):
99
+ arg_types = {"this": True, "default": False}
100
+
101
+
102
+ class ComputeProperty(Property):
103
+ arg_types = {}
104
+
105
+
106
+ class CopyGrantsProperty(Property):
107
+ arg_types = {}
108
+
109
+
110
+ class DataBlocksizeProperty(Property):
111
+ arg_types = {
112
+ "size": False,
113
+ "units": False,
114
+ "minimum": False,
115
+ "maximum": False,
116
+ "default": False,
117
+ }
118
+
119
+
120
+ class DataDeletionProperty(Property):
121
+ arg_types = {"on": True, "filter_column": False, "retention_period": False}
122
+
123
+
124
+ class DatabaseProperty(Property):
125
+ arg_types = {}
126
+
127
+
128
+ class DefinerProperty(Property):
129
+ arg_types = {"this": True}
130
+ _hash_raw_args = True
131
+
132
+
133
+ class DistKeyProperty(Property):
134
+ arg_types = {"this": True}
135
+
136
+
137
+ class DistributedByProperty(Property):
138
+ arg_types = {"expressions": False, "kind": True, "buckets": False, "order": False}
139
+
140
+
141
+ class DistStyleProperty(Property):
142
+ arg_types = {"this": True}
143
+
144
+
145
+ class DuplicateKeyProperty(Property):
146
+ arg_types = {"expressions": True}
147
+
148
+
149
+ class EngineProperty(Property):
150
+ arg_types = {"this": True}
151
+
152
+
153
+ class UuidProperty(Property):
154
+ arg_types = {"this": True}
155
+
156
+
157
+ class HeapProperty(Property):
158
+ arg_types = {}
159
+
160
+
161
+ class HybridProperty(Property):
162
+ arg_types = {}
163
+
164
+
165
+ class HandlerProperty(Property):
166
+ arg_types = {"this": True}
167
+
168
+
169
+ class ParameterStyleProperty(Property):
170
+ arg_types = {"this": True}
171
+
172
+
173
+ class ToTableProperty(Property):
174
+ arg_types = {"this": True}
175
+
176
+
177
+ class ExecuteAsProperty(Property):
178
+ arg_types = {"this": True}
179
+
180
+
181
+ class ExternalProperty(Property):
182
+ arg_types = {"this": False}
183
+
184
+
185
+ class FallbackProperty(Property):
186
+ arg_types = {"no": True, "protection": False}
187
+
188
+
189
+ class FileFormatProperty(Property):
190
+ arg_types = {"this": False, "expressions": False, "hive_format": False}
191
+
192
+
193
+ class CredentialsProperty(Property):
194
+ arg_types = {"expressions": True}
195
+
196
+
197
+ class FreespaceProperty(Property):
198
+ arg_types = {"this": True, "percent": False}
199
+
200
+
201
+ class GlobalProperty(Property):
202
+ arg_types = {}
203
+
204
+
205
+ class IcebergProperty(Property):
206
+ arg_types = {}
207
+
208
+
209
+ class InheritsProperty(Property):
210
+ arg_types = {"expressions": True}
211
+
212
+
213
+ class InputModelProperty(Property):
214
+ arg_types = {"this": True}
215
+
216
+
217
+ class OutputModelProperty(Property):
218
+ arg_types = {"this": True}
219
+
220
+
221
+ class IsolatedLoadingProperty(Property):
222
+ arg_types = {"no": False, "concurrent": False, "target": False}
223
+
224
+
225
+ class JournalProperty(Property):
226
+ arg_types = {
227
+ "no": False,
228
+ "dual": False,
229
+ "before": False,
230
+ "local": False,
231
+ "after": False,
232
+ }
233
+
234
+
235
+ class LanguageProperty(Property):
236
+ arg_types = {"this": True}
237
+
238
+
239
+ class EnviromentProperty(Property):
240
+ arg_types = {"expressions": True}
241
+
242
+
243
+ class ClusteredByProperty(Property):
244
+ arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
245
+
246
+
247
+ class DictProperty(Property):
248
+ arg_types = {"this": True, "kind": True, "settings": False}
249
+
250
+
251
+ class DictSubProperty(Property):
252
+ pass
253
+
254
+
255
+ class DictRange(Property):
256
+ arg_types = {"this": True, "min": True, "max": True}
257
+
258
+
259
+ class DynamicProperty(Property):
260
+ arg_types = {}
261
+
262
+
263
+ class OnCluster(Property):
264
+ arg_types = {"this": True}
265
+
266
+
267
+ class EmptyProperty(Property):
268
+ arg_types = {}
269
+
270
+
271
+ class LikeProperty(Property):
272
+ arg_types = {"this": True, "expressions": False}
273
+
274
+
275
+ class LocationProperty(Property):
276
+ arg_types = {"this": True}
277
+
278
+
279
+ class LockProperty(Property):
280
+ arg_types = {"this": True}
281
+
282
+
283
+ class LockingProperty(Property):
284
+ arg_types = {
285
+ "this": False,
286
+ "kind": True,
287
+ "for_or_in": False,
288
+ "lock_type": True,
289
+ "override": False,
290
+ }
291
+
292
+
293
+ class LogProperty(Property):
294
+ arg_types = {"no": True}
295
+
296
+
297
+ class MaskingProperty(Property):
298
+ arg_types = {}
299
+
300
+
301
+ class MaterializedProperty(Property):
302
+ arg_types = {"this": False}
303
+
304
+
305
+ class MergeBlockRatioProperty(Property):
306
+ arg_types = {"this": False, "no": False, "default": False, "percent": False}
307
+
308
+
309
+ class ModuleProperty(Property):
310
+ arg_types = {"this": True, "expressions": False}
311
+
312
+
313
+ class NetworkProperty(Property):
314
+ arg_types = {}
315
+
316
+
317
+ class NoPrimaryIndexProperty(Property):
318
+ arg_types = {}
319
+
320
+
321
+ class OnProperty(Property):
322
+ arg_types = {"this": True}
323
+
324
+
325
+ class OnCommitProperty(Property):
326
+ arg_types = {"delete": False}
327
+
328
+
329
+ class PartitionedByProperty(Property):
330
+ arg_types = {"this": True}
331
+
332
+
333
+ class PartitionedByBucket(Property):
334
+ arg_types = {"this": True, "expression": True}
335
+
336
+
337
+ class PartitionByTruncate(Property):
338
+ arg_types = {"this": True, "expression": True}
339
+
340
+
341
+ class PartitionByRangeProperty(Property):
342
+ arg_types = {"partition_expressions": True, "create_expressions": True}
343
+
344
+
345
+ class PartitionByRangePropertyDynamic(Expression):
346
+ arg_types = {"this": False, "start": True, "end": True, "every": True}
347
+
348
+
349
+ class RollupProperty(Property):
350
+ arg_types = {"expressions": True}
351
+
352
+
353
+ class RollupIndex(Expression):
354
+ arg_types = {"this": True, "expressions": True, "from_index": False, "properties": False}
355
+
356
+
357
+ class RowAccessProperty(Property):
358
+ arg_types = {"this": False, "expressions": False}
359
+
360
+
361
+ class PartitionByListProperty(Property):
362
+ arg_types = {"partition_expressions": True, "create_expressions": True}
363
+
364
+
365
+ class PartitionList(Expression):
366
+ arg_types = {"this": True, "expressions": True}
367
+
368
+
369
+ class RefreshTriggerProperty(Property):
370
+ arg_types = {
371
+ "method": False,
372
+ "kind": False,
373
+ "every": False,
374
+ "unit": False,
375
+ "starts": False,
376
+ }
377
+
378
+
379
+ class UniqueKeyProperty(Property):
380
+ arg_types = {"expressions": True}
381
+
382
+
383
+ class PartitionBoundSpec(Expression):
384
+ # this -> IN / MODULUS, expression -> REMAINDER, from_expressions -> FROM (...), to_expressions -> TO (...)
385
+ arg_types = {
386
+ "this": False,
387
+ "expression": False,
388
+ "from_expressions": False,
389
+ "to_expressions": False,
390
+ }
391
+
392
+
393
+ class PartitionedOfProperty(Property):
394
+ # this -> parent_table (schema), expression -> FOR VALUES ... / DEFAULT
395
+ arg_types = {"this": True, "expression": True}
396
+
397
+
398
+ class PhysicalProperty(Property):
399
+ arg_types = {"this": True, "value": False}
400
+
401
+
402
+ class StreamingTableProperty(Property):
403
+ arg_types = {}
404
+
405
+
406
+ class RemoteWithConnectionModelProperty(Property):
407
+ arg_types = {"this": True}
408
+
409
+
410
+ class ReturnsProperty(Property):
411
+ arg_types = {"this": False, "is_table": False, "table": False, "null": False}
412
+
413
+
414
+ class StrictProperty(Property):
415
+ arg_types = {}
416
+
417
+
418
+ class RowFormatProperty(Property):
419
+ arg_types = {"this": True}
420
+
421
+
422
+ class RowFormatDelimitedProperty(Property):
423
+ # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
424
+ arg_types = {
425
+ "fields": False,
426
+ "escaped": False,
427
+ "collection_items": False,
428
+ "map_keys": False,
429
+ "lines": False,
430
+ "null": False,
431
+ "serde": False,
432
+ }
433
+
434
+
435
+ class RowFormatSerdeProperty(Property):
436
+ arg_types = {"this": True, "serde_properties": False}
437
+
438
+
439
+ class QueryTransform(Expression):
440
+ arg_types = {
441
+ "expressions": True,
442
+ "command_script": True,
443
+ "schema": False,
444
+ "row_format_before": False,
445
+ "record_writer": False,
446
+ "row_format_after": False,
447
+ "record_reader": False,
448
+ }
449
+
450
+
451
+ class SampleProperty(Property):
452
+ arg_types = {"this": True}
453
+
454
+
455
+ class SchemaCommentProperty(Property):
456
+ arg_types = {"this": True}
457
+
458
+
459
+ class SemanticView(Expression):
460
+ arg_types = {
461
+ "this": True,
462
+ "metrics": False,
463
+ "dimensions": False,
464
+ "facts": False,
465
+ "where": False,
466
+ }
467
+
468
+
469
+ class SerdeProperties(Property):
470
+ arg_types = {"expressions": True, "with_": False}
471
+
472
+
473
+ class SetProperty(Property):
474
+ arg_types = {"multi": True}
475
+
476
+
477
+ class SharingProperty(Property):
478
+ arg_types = {"this": False}
479
+
480
+
481
+ class SetConfigProperty(Property):
482
+ arg_types = {"this": True}
483
+
484
+
485
+ class SettingsProperty(Property):
486
+ arg_types = {"expressions": True}
487
+
488
+
489
+ class SortKeyProperty(Property):
490
+ arg_types = {"this": True, "compound": False}
491
+
492
+
493
+ class SqlReadWriteProperty(Property):
494
+ arg_types = {"this": True}
495
+
496
+
497
+ class SqlSecurityProperty(Property):
498
+ arg_types = {"this": True}
499
+
500
+
501
+ class StabilityProperty(Property):
502
+ arg_types = {"this": True}
503
+
504
+
505
+ class StorageHandlerProperty(Property):
506
+ arg_types = {"this": True}
507
+
508
+
509
+ class StorageProperty(Property):
510
+ arg_types = {"expressions": True}
511
+
512
+
513
+ class UsingProperty(Property):
514
+ # kind: JAR, FILE, or ARCHIVE; this: the resource path (string literal)
515
+ arg_types = {"this": True, "kind": True}
516
+
517
+
518
+ class TemporaryProperty(Property):
519
+ arg_types = {"this": False}
520
+
521
+
522
+ class VirtualProperty(Property):
523
+ arg_types = {}
524
+
525
+
526
+ class SecureProperty(Property):
527
+ arg_types = {}
528
+
529
+
530
+ class SecurityIntegrationProperty(Property):
531
+ arg_types = {}
532
+
533
+
534
+ class Tags(Property, ColumnConstraintKind):
535
+ arg_types = {"expressions": True}
536
+
537
+
538
+ class TableSpaceProperty(Property):
539
+ arg_types = {"this": True}
540
+
541
+
542
+ class PropertiesLocation(AutoName):
543
+ POST_CREATE = auto()
544
+ POST_NAME = auto()
545
+ POST_SCHEMA = auto()
546
+ POST_WITH = auto()
547
+ POST_ALIAS = auto()
548
+ POST_EXPRESSION = auto()
549
+ POST_INDEX = auto()
550
+ UNSUPPORTED = auto()
551
+
552
+
553
+ class TransformModelProperty(Property):
554
+ arg_types = {"expressions": True}
555
+
556
+
557
+ class TransientProperty(Property):
558
+ arg_types = {"this": False}
559
+
560
+
561
+ class UnloggedProperty(Property):
562
+ arg_types = {}
563
+
564
+
565
+ class UsingTemplateProperty(Property):
566
+ arg_types = {"this": True}
567
+
568
+
569
+ class ViewAttributeProperty(Property):
570
+ arg_types = {"this": True}
571
+
572
+
573
+ class VolatileProperty(Property):
574
+ arg_types = {"this": False}
575
+
576
+
577
+ class WithDataProperty(Property):
578
+ arg_types = {"no": True, "statistics": False}
579
+
580
+
581
+ class WithJournalTableProperty(Property):
582
+ arg_types = {"this": True}
583
+
584
+
585
+ class WithSchemaBindingProperty(Property):
586
+ arg_types = {"this": True}
587
+
588
+
589
+ class WithSystemVersioningProperty(Property):
590
+ arg_types = {
591
+ "on": False,
592
+ "this": False,
593
+ "data_consistency": False,
594
+ "retention_period": False,
595
+ "with_": True,
596
+ }
597
+
598
+
599
+ class WithProcedureOptions(Property):
600
+ arg_types = {"expressions": True}
601
+
602
+
603
+ class EncodeProperty(Property):
604
+ arg_types = {"this": True, "properties": False, "key": False}
605
+
606
+
607
+ class IncludeProperty(Property):
608
+ arg_types = {"this": True, "alias": False, "column_def": False}
609
+
610
+
611
+ class ForceProperty(Property):
612
+ arg_types = {}
613
+
614
+
615
+ class Properties(Expression):
616
+ arg_types = {"expressions": True}
617
+
618
+ NAME_TO_PROPERTY: t.ClassVar[dict[str, type[Property]]] = {
619
+ "ALGORITHM": AlgorithmProperty,
620
+ "AUTO_INCREMENT": AutoIncrementProperty,
621
+ "CHARACTER SET": CharacterSetProperty,
622
+ "CLUSTERED_BY": ClusteredByProperty,
623
+ "COLLATE": CollateProperty,
624
+ "COMMENT": SchemaCommentProperty,
625
+ "CREDENTIALS": CredentialsProperty,
626
+ "DEFINER": DefinerProperty,
627
+ "DISTKEY": DistKeyProperty,
628
+ "DISTRIBUTED_BY": DistributedByProperty,
629
+ "DISTSTYLE": DistStyleProperty,
630
+ "ENGINE": EngineProperty,
631
+ "EXECUTE AS": ExecuteAsProperty,
632
+ "FORMAT": FileFormatProperty,
633
+ "LANGUAGE": LanguageProperty,
634
+ "LOCATION": LocationProperty,
635
+ "LOCK": LockProperty,
636
+ "PARTITIONED_BY": PartitionedByProperty,
637
+ "RETURNS": ReturnsProperty,
638
+ "ROW_FORMAT": RowFormatProperty,
639
+ "SORTKEY": SortKeyProperty,
640
+ "ENCODE": EncodeProperty,
641
+ "INCLUDE": IncludeProperty,
642
+ }
643
+
644
+ PROPERTY_TO_NAME: t.ClassVar[dict[type[Property], str]] = {
645
+ v: k for k, v in NAME_TO_PROPERTY.items()
646
+ }
647
+
648
+ # CREATE property locations
649
+ # Form: schema specified
650
+ # create [POST_CREATE]
651
+ # table a [POST_NAME]
652
+ # (b int) [POST_SCHEMA]
653
+ # with ([POST_WITH])
654
+ # index (b) [POST_INDEX]
655
+ #
656
+ # Form: alias selection
657
+ # create [POST_CREATE]
658
+ # table a [POST_NAME]
659
+ # as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
660
+ # index (c) [POST_INDEX]
661
+ Location: t.ClassVar[type[PropertiesLocation]] = PropertiesLocation
662
+
663
+ @classmethod
664
+ def from_dict(cls, properties_dict: dict) -> Properties:
665
+ expressions = []
666
+ for key, value in properties_dict.items():
667
+ property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
668
+ if property_cls:
669
+ expressions.append(property_cls(this=convert(value)))
670
+ else:
671
+ expressions.append(Property(this=Literal.string(key), value=convert(value)))
672
+
673
+ return cls(expressions=expressions)
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/query.py ADDED
@@ -0,0 +1,2329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions query."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typing as t
6
+
7
+ from sqlglot.errors import ParseError
8
+ from sqlglot.helper import trait, ensure_list
9
+ from sqlglot.expressions.core import (
10
+ Aliases,
11
+ Column,
12
+ Condition,
13
+ Distinct,
14
+ Dot,
15
+ DynamicIdentifier,
16
+ Expr,
17
+ Expression,
18
+ Func,
19
+ Hint,
20
+ Identifier,
21
+ In,
22
+ Var,
23
+ _apply_builder,
24
+ _apply_child_list_builder,
25
+ _apply_list_builder,
26
+ _apply_conjunction_builder,
27
+ _apply_set_operation,
28
+ ExpOrStr,
29
+ QUERY_MODIFIERS,
30
+ maybe_parse,
31
+ maybe_copy,
32
+ to_identifier,
33
+ convert,
34
+ and_,
35
+ alias_,
36
+ column,
37
+ )
38
+
39
+ if t.TYPE_CHECKING:
40
+ from sqlglot.dialects.dialect import DialectType
41
+ from sqlglot.expressions.datatypes import DataType
42
+ from sqlglot.expressions.constraints import ColumnConstraint
43
+ from sqlglot.expressions.ddl import Create
44
+ from sqlglot.expressions.array import Unnest
45
+ from sqlglot._typing import E, ParserArgs, ParserNoDialectArgs
46
+ from typing_extensions import Unpack
47
+
48
+ S = t.TypeVar("S", bound="SetOperation")
49
+ Q = t.TypeVar("Q", bound="Query")
50
+
51
+
52
+ def _apply_cte_builder(
53
+ instance: E,
54
+ alias: ExpOrStr,
55
+ as_: ExpOrStr,
56
+ recursive: bool | None = None,
57
+ materialized: bool | None = None,
58
+ append: bool = True,
59
+ dialect: DialectType = None,
60
+ copy: bool = True,
61
+ scalar: bool | None = None,
62
+ **opts: Unpack[ParserNoDialectArgs],
63
+ ) -> E:
64
+ alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
65
+ as_expression = maybe_parse(as_, dialect=dialect, copy=copy, **opts)
66
+ if scalar and not isinstance(as_expression, Subquery):
67
+ # scalar CTE must be wrapped in a subquery
68
+ as_expression = Subquery(this=as_expression)
69
+ cte = CTE(this=as_expression, alias=alias_expression, materialized=materialized, scalar=scalar)
70
+ return _apply_child_list_builder(
71
+ cte,
72
+ instance=instance,
73
+ arg="with_",
74
+ append=append,
75
+ copy=copy,
76
+ into=With,
77
+ properties={"recursive": recursive} if recursive else {},
78
+ )
79
+
80
+
81
+ @trait
82
+ class Selectable(Expr):
83
+ @property
84
+ def selects(self) -> list[Expr]:
85
+ raise NotImplementedError("Subclasses must implement selects")
86
+
87
+ @property
88
+ def named_selects(self) -> list[str]:
89
+ return _named_selects(self)
90
+
91
+
92
+ def _named_selects(self: Expr) -> list[str]:
93
+ selectable = t.cast(Selectable, self)
94
+ return [select.output_name for select in selectable.selects]
95
+
96
+
97
+ @trait
98
+ class DerivedTable(Selectable):
99
+ @property
100
+ def selects(self) -> list[Expr]:
101
+ this = self.this
102
+ return this.selects if isinstance(this, Query) else []
103
+
104
+
105
+ @trait
106
+ class UDTF(DerivedTable):
107
+ @property
108
+ def selects(self) -> list[Expr]:
109
+ alias = self.args.get("alias")
110
+ return alias.columns if alias else []
111
+
112
+
113
+ @trait
114
+ class Query(Selectable):
115
+ """Trait for any SELECT/UNION/etc. query expression."""
116
+
117
+ @property
118
+ def ctes(self) -> list[CTE]:
119
+ with_ = self.args.get("with_")
120
+ return with_.expressions if with_ else []
121
+
122
+ def select(
123
+ self: Q,
124
+ *expressions: ExpOrStr | None,
125
+ append: bool = True,
126
+ dialect: DialectType = None,
127
+ copy: bool = True,
128
+ **opts: Unpack[ParserNoDialectArgs],
129
+ ) -> Q:
130
+ raise NotImplementedError("Query objects must implement `select`")
131
+
132
+ def subquery(self, alias: ExpOrStr | None = None, copy: bool = True) -> Subquery:
133
+ """
134
+ Returns a `Subquery` that wraps around this query.
135
+
136
+ Example:
137
+ >>> subquery = Select().select("x").from_("tbl").subquery()
138
+ >>> Select().select("x").from_(subquery).sql()
139
+ 'SELECT x FROM (SELECT x FROM tbl)'
140
+
141
+ Args:
142
+ alias: an optional alias for the subquery.
143
+ copy: if `False`, modify this expression instance in-place.
144
+ """
145
+ instance = maybe_copy(self, copy)
146
+ if not isinstance(alias, Expr):
147
+ alias = TableAlias(this=to_identifier(alias)) if alias else None
148
+
149
+ return Subquery(this=instance, alias=alias)
150
+
151
+ def limit(
152
+ self: Q,
153
+ expression: ExpOrStr | int,
154
+ dialect: DialectType = None,
155
+ copy: bool = True,
156
+ **opts: Unpack[ParserNoDialectArgs],
157
+ ) -> Q:
158
+ """
159
+ Adds a LIMIT clause to this query.
160
+
161
+ Example:
162
+ >>> Select().select("1").union(Select().select("1")).limit(1).sql()
163
+ 'SELECT 1 UNION SELECT 1 LIMIT 1'
164
+
165
+ Args:
166
+ expression: the SQL code string to parse.
167
+ This can also be an integer.
168
+ If a `Limit` instance is passed, it will be used as-is.
169
+ If another `Expr` instance is passed, it will be wrapped in a `Limit`.
170
+ dialect: the dialect used to parse the input expression.
171
+ copy: if `False`, modify this expression instance in-place.
172
+ opts: other options to use to parse the input expressions.
173
+
174
+ Returns:
175
+ A limited Select expression.
176
+ """
177
+ return _apply_builder(
178
+ expression=expression,
179
+ instance=self,
180
+ arg="limit",
181
+ into=Limit,
182
+ prefix="LIMIT",
183
+ dialect=dialect,
184
+ copy=copy,
185
+ into_arg="expression",
186
+ **opts,
187
+ )
188
+
189
+ def offset(
190
+ self: Q,
191
+ expression: ExpOrStr | int,
192
+ dialect: DialectType = None,
193
+ copy: bool = True,
194
+ **opts: Unpack[ParserNoDialectArgs],
195
+ ) -> Q:
196
+ """
197
+ Set the OFFSET expression.
198
+
199
+ Example:
200
+ >>> Select().from_("tbl").select("x").offset(10).sql()
201
+ 'SELECT x FROM tbl OFFSET 10'
202
+
203
+ Args:
204
+ expression: the SQL code string to parse.
205
+ This can also be an integer.
206
+ If a `Offset` instance is passed, this is used as-is.
207
+ If another `Expr` instance is passed, it will be wrapped in a `Offset`.
208
+ dialect: the dialect used to parse the input expression.
209
+ copy: if `False`, modify this expression instance in-place.
210
+ opts: other options to use to parse the input expressions.
211
+
212
+ Returns:
213
+ The modified Select expression.
214
+ """
215
+ return _apply_builder(
216
+ expression=expression,
217
+ instance=self,
218
+ arg="offset",
219
+ into=Offset,
220
+ prefix="OFFSET",
221
+ dialect=dialect,
222
+ copy=copy,
223
+ into_arg="expression",
224
+ **opts,
225
+ )
226
+
227
+ def order_by(
228
+ self: Q,
229
+ *expressions: ExpOrStr | None,
230
+ append: bool = True,
231
+ dialect: DialectType = None,
232
+ copy: bool = True,
233
+ **opts: Unpack[ParserNoDialectArgs],
234
+ ) -> Q:
235
+ """
236
+ Set the ORDER BY expression.
237
+
238
+ Example:
239
+ >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
240
+ 'SELECT x FROM tbl ORDER BY x DESC'
241
+
242
+ Args:
243
+ *expressions: the SQL code strings to parse.
244
+ If a `Group` instance is passed, this is used as-is.
245
+ If another `Expr` instance is passed, it will be wrapped in a `Order`.
246
+ append: if `True`, add to any existing expressions.
247
+ Otherwise, this flattens all the `Order` expression into a single expression.
248
+ dialect: the dialect used to parse the input expression.
249
+ copy: if `False`, modify this expression instance in-place.
250
+ opts: other options to use to parse the input expressions.
251
+
252
+ Returns:
253
+ The modified Select expression.
254
+ """
255
+ return _apply_child_list_builder(
256
+ *expressions,
257
+ instance=self,
258
+ arg="order",
259
+ append=append,
260
+ copy=copy,
261
+ prefix="ORDER BY",
262
+ into=Order,
263
+ dialect=dialect,
264
+ **opts,
265
+ )
266
+
267
+ def where(
268
+ self: Q,
269
+ *expressions: ExpOrStr | None,
270
+ append: bool = True,
271
+ dialect: DialectType = None,
272
+ copy: bool = True,
273
+ **opts: Unpack[ParserNoDialectArgs],
274
+ ) -> Q:
275
+ """
276
+ Append to or set the WHERE expressions.
277
+
278
+ Examples:
279
+ >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
280
+ "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
281
+
282
+ Args:
283
+ *expressions: the SQL code strings to parse.
284
+ If an `Expr` instance is passed, it will be used as-is.
285
+ Multiple expressions are combined with an AND operator.
286
+ append: if `True`, AND the new expressions to any existing expression.
287
+ Otherwise, this resets the expression.
288
+ dialect: the dialect used to parse the input expressions.
289
+ copy: if `False`, modify this expression instance in-place.
290
+ opts: other options to use to parse the input expressions.
291
+
292
+ Returns:
293
+ The modified expression.
294
+ """
295
+ return _apply_conjunction_builder(
296
+ *[expr.this if isinstance(expr, Where) else expr for expr in expressions],
297
+ instance=self,
298
+ arg="where",
299
+ append=append,
300
+ into=Where,
301
+ dialect=dialect,
302
+ copy=copy,
303
+ **opts,
304
+ )
305
+
306
+ def with_(
307
+ self: Q,
308
+ alias: ExpOrStr,
309
+ as_: ExpOrStr,
310
+ recursive: bool | None = None,
311
+ materialized: bool | None = None,
312
+ append: bool = True,
313
+ dialect: DialectType = None,
314
+ copy: bool = True,
315
+ scalar: bool | None = None,
316
+ **opts: Unpack[ParserNoDialectArgs],
317
+ ) -> Q:
318
+ """
319
+ Append to or set the common table expressions.
320
+
321
+ Example:
322
+ >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
323
+ 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
324
+
325
+ Args:
326
+ alias: the SQL code string to parse as the table name.
327
+ If an `Expr` instance is passed, this is used as-is.
328
+ as_: the SQL code string to parse as the table expression.
329
+ If an `Expr` instance is passed, it will be used as-is.
330
+ recursive: set the RECURSIVE part of the expression. Defaults to `False`.
331
+ materialized: set the MATERIALIZED part of the expression.
332
+ append: if `True`, add to any existing expressions.
333
+ Otherwise, this resets the expressions.
334
+ dialect: the dialect used to parse the input expression.
335
+ copy: if `False`, modify this expression instance in-place.
336
+ scalar: if `True`, this is a scalar common table expression.
337
+ opts: other options to use to parse the input expressions.
338
+
339
+ Returns:
340
+ The modified expression.
341
+ """
342
+ return _apply_cte_builder(
343
+ self,
344
+ alias,
345
+ as_,
346
+ recursive=recursive,
347
+ materialized=materialized,
348
+ append=append,
349
+ dialect=dialect,
350
+ copy=copy,
351
+ scalar=scalar,
352
+ **opts,
353
+ )
354
+
355
+ def union(
356
+ self,
357
+ *expressions: ExpOrStr,
358
+ distinct: bool = True,
359
+ dialect: DialectType = None,
360
+ copy: bool = True,
361
+ **opts: Unpack[ParserNoDialectArgs],
362
+ ) -> Union:
363
+ """
364
+ Builds a UNION expression.
365
+
366
+ Example:
367
+ >>> import sqlglot
368
+ >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
369
+ 'SELECT * FROM foo UNION SELECT * FROM bla'
370
+
371
+ Args:
372
+ expressions: the SQL code strings.
373
+ If `Expr` instances are passed, they will be used as-is.
374
+ distinct: set the DISTINCT flag if and only if this is true.
375
+ dialect: the dialect used to parse the input expression.
376
+ opts: other options to use to parse the input expressions.
377
+
378
+ Returns:
379
+ The new Union expression.
380
+ """
381
+ return union(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
382
+
383
+ def intersect(
384
+ self,
385
+ *expressions: ExpOrStr,
386
+ distinct: bool = True,
387
+ dialect: DialectType = None,
388
+ copy: bool = True,
389
+ **opts: Unpack[ParserNoDialectArgs],
390
+ ) -> Intersect:
391
+ """
392
+ Builds an INTERSECT expression.
393
+
394
+ Example:
395
+ >>> import sqlglot
396
+ >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
397
+ 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
398
+
399
+ Args:
400
+ expressions: the SQL code strings.
401
+ If `Expr` instances are passed, they will be used as-is.
402
+ distinct: set the DISTINCT flag if and only if this is true.
403
+ dialect: the dialect used to parse the input expression.
404
+ opts: other options to use to parse the input expressions.
405
+
406
+ Returns:
407
+ The new Intersect expression.
408
+ """
409
+ return intersect(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
410
+
411
+ def except_(
412
+ self,
413
+ *expressions: ExpOrStr,
414
+ distinct: bool = True,
415
+ dialect: DialectType = None,
416
+ copy: bool = True,
417
+ **opts: Unpack[ParserNoDialectArgs],
418
+ ) -> Except:
419
+ """
420
+ Builds an EXCEPT expression.
421
+
422
+ Example:
423
+ >>> import sqlglot
424
+ >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
425
+ 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
426
+
427
+ Args:
428
+ expressions: the SQL code strings.
429
+ If `Expr` instance are passed, they will be used as-is.
430
+ distinct: set the DISTINCT flag if and only if this is true.
431
+ dialect: the dialect used to parse the input expression.
432
+ opts: other options to use to parse the input expressions.
433
+
434
+ Returns:
435
+ The new Except expression.
436
+ """
437
+ return except_(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
438
+
439
+
440
+ class QueryBand(Expression):
441
+ arg_types = {"this": True, "scope": False, "update": False}
442
+
443
+
444
+ class RecursiveWithSearch(Expression):
445
+ arg_types = {
446
+ "kind": True,
447
+ "this": True,
448
+ "expression": True,
449
+ "to": False,
450
+ "default": False,
451
+ "using": False,
452
+ }
453
+
454
+
455
+ class With(Expression):
456
+ arg_types = {
457
+ "expressions": False,
458
+ "recursive": False,
459
+ "search": False,
460
+ "cycle": False,
461
+ "udfs": False,
462
+ }
463
+
464
+ @property
465
+ def recursive(self) -> bool:
466
+ return bool(self.args.get("recursive"))
467
+
468
+
469
+ class CTE(Expression, DerivedTable):
470
+ arg_types = {
471
+ "this": True,
472
+ "alias": True,
473
+ "scalar": False,
474
+ "materialized": False,
475
+ "key_expressions": False,
476
+ }
477
+
478
+
479
+ class ProjectionDef(Expression):
480
+ arg_types = {"this": True, "expression": True}
481
+
482
+
483
+ class TableAlias(Expression):
484
+ arg_types = {"this": False, "columns": False}
485
+
486
+ @property
487
+ def columns(self) -> list[t.Any]:
488
+ return self.args.get("columns") or []
489
+
490
+
491
+ class BitString(Expression, Condition):
492
+ is_primitive = True
493
+
494
+
495
+ class HexString(Expression, Condition):
496
+ arg_types = {"this": True, "is_integer": False}
497
+ is_primitive = True
498
+
499
+
500
+ class ByteString(Expression, Condition):
501
+ arg_types = {"this": True, "is_bytes": False}
502
+ is_primitive = True
503
+ _hash_raw_args = True
504
+
505
+
506
+ class RawString(Expression, Condition):
507
+ is_primitive = True
508
+ _hash_raw_args = True
509
+
510
+
511
+ class UnicodeString(Expression, Condition):
512
+ arg_types = {"this": True, "escape": False}
513
+ _hash_raw_args = True
514
+
515
+
516
+ class ColumnPosition(Expression):
517
+ arg_types = {"this": False, "position": True}
518
+
519
+
520
+ class ColumnDef(Expression):
521
+ arg_types = {
522
+ "this": True,
523
+ "kind": False,
524
+ "constraints": False,
525
+ "exists": False,
526
+ "position": False,
527
+ "default": False,
528
+ "output": False,
529
+ }
530
+
531
+ @property
532
+ def constraints(self) -> list[ColumnConstraint]:
533
+ return self.args.get("constraints") or []
534
+
535
+ @property
536
+ def kind(self) -> DataType | None:
537
+ return self.args.get("kind")
538
+
539
+
540
+ class Changes(Expression):
541
+ arg_types = {"information": True, "at_before": False, "end": False}
542
+
543
+
544
+ class Connect(Expression):
545
+ arg_types = {"start": False, "connect": True, "nocycle": False}
546
+
547
+
548
+ class Prior(Expression):
549
+ pass
550
+
551
+
552
+ class Into(Expression):
553
+ arg_types = {
554
+ "this": False,
555
+ "temporary": False,
556
+ "unlogged": False,
557
+ "bulk_collect": False,
558
+ "expressions": False,
559
+ }
560
+
561
+
562
+ class From(Expression):
563
+ @property
564
+ def name(self) -> str:
565
+ return self.this.name
566
+
567
+ @property
568
+ def alias_or_name(self) -> str:
569
+ return self.this.alias_or_name
570
+
571
+
572
+ class Having(Expression):
573
+ pass
574
+
575
+
576
+ class Index(Expression):
577
+ arg_types = {
578
+ "this": False,
579
+ "table": False,
580
+ "unique": False,
581
+ "primary": False,
582
+ "amp": False, # teradata
583
+ "params": False,
584
+ }
585
+
586
+
587
+ class ConditionalInsert(Expression):
588
+ arg_types = {"this": True, "expression": False, "else_": False}
589
+
590
+
591
+ class MultitableInserts(Expression):
592
+ arg_types = {"with_": False, "expressions": True, "kind": False, "source": True}
593
+
594
+
595
+ class OnCondition(Expression):
596
+ arg_types = {"error": False, "empty": False, "null": False}
597
+
598
+
599
+ class Introducer(Expression):
600
+ arg_types = {"this": True, "expression": True}
601
+
602
+
603
+ class National(Expression):
604
+ is_primitive = True
605
+ _hash_raw_args = True
606
+
607
+
608
+ class Partition(Expression):
609
+ arg_types = {"expressions": True, "subpartition": False}
610
+
611
+
612
+ class PartitionRange(Expression):
613
+ arg_types = {"this": True, "expression": False, "expressions": False}
614
+
615
+
616
+ class PartitionId(Expression):
617
+ pass
618
+
619
+
620
+ class Fetch(Expression):
621
+ arg_types = {
622
+ "direction": False,
623
+ "count": False,
624
+ "limit_options": False,
625
+ }
626
+
627
+
628
+ class Grant(Expression):
629
+ arg_types = {
630
+ "privileges": True,
631
+ "kind": False,
632
+ "securable": True,
633
+ "principals": True,
634
+ "grant_option": False,
635
+ }
636
+
637
+
638
+ class Revoke(Expression):
639
+ arg_types = {**Grant.arg_types, "cascade": False}
640
+
641
+
642
+ class Group(Expression):
643
+ arg_types = {
644
+ "expressions": False,
645
+ "grouping_sets": False,
646
+ "cube": False,
647
+ "rollup": False,
648
+ "totals": False,
649
+ "all": False,
650
+ }
651
+
652
+
653
+ class Cube(Expression):
654
+ arg_types = {"expressions": False}
655
+
656
+
657
+ class Rollup(Expression):
658
+ arg_types = {"expressions": False}
659
+
660
+
661
+ class GroupingSets(Expression):
662
+ arg_types = {"expressions": True}
663
+
664
+
665
+ class Lambda(Expression):
666
+ arg_types = {"this": True, "expressions": True}
667
+
668
+
669
+ class Limit(Expression):
670
+ arg_types = {
671
+ "this": False,
672
+ "expression": True,
673
+ "offset": False,
674
+ "limit_options": False,
675
+ "expressions": False,
676
+ }
677
+
678
+ @property
679
+ def is_limit_all(self) -> bool:
680
+ limit_expression = self.args.get("expression")
681
+ return isinstance(limit_expression, Var) and limit_expression.name.upper() == "ALL"
682
+
683
+
684
+ class LimitOptions(Expression):
685
+ arg_types = {
686
+ "percent": False,
687
+ "rows": False,
688
+ "with_ties": False,
689
+ }
690
+
691
+
692
+ class Join(Expression):
693
+ arg_types = {
694
+ "this": True,
695
+ "on": False,
696
+ "side": False,
697
+ "kind": False,
698
+ "using": False,
699
+ "method": False,
700
+ "global_": False,
701
+ "hint": False,
702
+ "match_condition": False, # Snowflake
703
+ "directed": False, # Snowflake
704
+ "expressions": False,
705
+ "pivots": False,
706
+ }
707
+
708
+ @property
709
+ def method(self) -> str:
710
+ return self.text("method").upper()
711
+
712
+ @property
713
+ def kind(self) -> str:
714
+ return self.text("kind").upper()
715
+
716
+ @property
717
+ def side(self) -> str:
718
+ return self.text("side").upper()
719
+
720
+ @property
721
+ def hint(self) -> str:
722
+ return self.text("hint").upper()
723
+
724
+ @property
725
+ def alias_or_name(self) -> str:
726
+ return self.this.alias_or_name
727
+
728
+ @property
729
+ def is_semi_or_anti_join(self) -> bool:
730
+ return self.kind in ("SEMI", "ANTI")
731
+
732
+ def on(
733
+ self,
734
+ *expressions: ExpOrStr | None,
735
+ append: bool = True,
736
+ dialect: DialectType = None,
737
+ copy: bool = True,
738
+ **opts: Unpack[ParserNoDialectArgs],
739
+ ) -> Join:
740
+ """
741
+ Append to or set the ON expressions.
742
+
743
+ Example:
744
+ >>> import sqlglot
745
+ >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
746
+ 'JOIN x ON y = 1'
747
+
748
+ Args:
749
+ *expressions: the SQL code strings to parse.
750
+ If an `Expr` instance is passed, it will be used as-is.
751
+ Multiple expressions are combined with an AND operator.
752
+ append: if `True`, AND the new expressions to any existing expression.
753
+ Otherwise, this resets the expression.
754
+ dialect: the dialect used to parse the input expressions.
755
+ copy: if `False`, modify this expression instance in-place.
756
+ opts: other options to use to parse the input expressions.
757
+
758
+ Returns:
759
+ The modified Join expression.
760
+ """
761
+ join = _apply_conjunction_builder(
762
+ *expressions,
763
+ instance=self,
764
+ arg="on",
765
+ append=append,
766
+ dialect=dialect,
767
+ copy=copy,
768
+ **opts,
769
+ )
770
+
771
+ if join.kind == "CROSS":
772
+ join.set("kind", None)
773
+
774
+ return join
775
+
776
+ def using(
777
+ self,
778
+ *expressions: ExpOrStr | None,
779
+ append: bool = True,
780
+ dialect: DialectType = None,
781
+ copy: bool = True,
782
+ **opts: Unpack[ParserNoDialectArgs],
783
+ ) -> Join:
784
+ """
785
+ Append to or set the USING expressions.
786
+
787
+ Example:
788
+ >>> import sqlglot
789
+ >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
790
+ 'JOIN x USING (foo, bla)'
791
+
792
+ Args:
793
+ *expressions: the SQL code strings to parse.
794
+ If an `Expr` instance is passed, it will be used as-is.
795
+ append: if `True`, concatenate the new expressions to the existing "using" list.
796
+ Otherwise, this resets the expression.
797
+ dialect: the dialect used to parse the input expressions.
798
+ copy: if `False`, modify this expression instance in-place.
799
+ opts: other options to use to parse the input expressions.
800
+
801
+ Returns:
802
+ The modified Join expression.
803
+ """
804
+ join = _apply_list_builder(
805
+ *expressions,
806
+ instance=self,
807
+ arg="using",
808
+ append=append,
809
+ dialect=dialect,
810
+ copy=copy,
811
+ **opts,
812
+ )
813
+
814
+ if join.kind == "CROSS":
815
+ join.set("kind", None)
816
+
817
+ return join
818
+
819
+
820
+ class Lateral(Expression, UDTF):
821
+ arg_types = {
822
+ "this": True,
823
+ "view": False,
824
+ "outer": False,
825
+ "alias": False,
826
+ "cross_apply": False, # True -> CROSS APPLY, False -> OUTER APPLY
827
+ "ordinality": False,
828
+ }
829
+
830
+ @property
831
+ def selects(self) -> list[Expr]:
832
+ from sqlglot.expressions.array import Unnest
833
+
834
+ columns = super().selects
835
+
836
+ # UNNEST ... WITH ORDINALITY stores the ordinality column's name in Unnest.offset
837
+ offset = self.this.args.get("offset") if isinstance(self.this, Unnest) else None
838
+ if isinstance(offset, Identifier):
839
+ columns = columns + [offset]
840
+
841
+ return columns
842
+
843
+
844
+ class TableFromRows(Expression, UDTF):
845
+ arg_types = {
846
+ "this": True,
847
+ "alias": False,
848
+ "joins": False,
849
+ "pivots": False,
850
+ "sample": False,
851
+ }
852
+
853
+
854
+ class MatchRecognizeMeasure(Expression):
855
+ arg_types = {
856
+ "this": True,
857
+ "window_frame": False,
858
+ }
859
+
860
+
861
+ class MatchRecognize(Expression):
862
+ arg_types = {
863
+ "partition_by": False,
864
+ "order": False,
865
+ "measures": False,
866
+ "rows": False,
867
+ "after": False,
868
+ "pattern": False,
869
+ "define": False,
870
+ "alias": False,
871
+ }
872
+
873
+
874
+ class Final(Expression):
875
+ pass
876
+
877
+
878
+ class Offset(Expression):
879
+ arg_types = {"this": False, "expression": True, "expressions": False}
880
+
881
+
882
+ class Order(Expression):
883
+ arg_types = {"this": False, "expressions": True, "siblings": False}
884
+
885
+
886
+ class WithFill(Expression):
887
+ arg_types = {
888
+ "from_": False,
889
+ "to": False,
890
+ "step": False,
891
+ "interpolate": False,
892
+ }
893
+
894
+
895
+ class SkipJSONColumn(Expression):
896
+ arg_types = {"regexp": False, "expression": True}
897
+
898
+
899
+ class Cluster(Expression):
900
+ arg_types = {"expressions": True}
901
+
902
+
903
+ class Distribute(Order):
904
+ pass
905
+
906
+
907
+ class Sort(Order):
908
+ pass
909
+
910
+
911
+ class Qualify(Expression):
912
+ pass
913
+
914
+
915
+ class InputOutputFormat(Expression):
916
+ arg_types = {"input_format": False, "output_format": False}
917
+
918
+
919
+ class Return(Expression):
920
+ pass
921
+
922
+
923
+ class Tuple(Expression):
924
+ arg_types = {"expressions": False}
925
+
926
+ def isin(
927
+ self,
928
+ *expressions: t.Any,
929
+ query: ExpOrStr | None = None,
930
+ unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
931
+ copy: bool = True,
932
+ **opts: Unpack[ParserArgs],
933
+ ) -> In:
934
+ return In(
935
+ this=maybe_copy(self, copy),
936
+ expressions=[convert(e, copy=copy) for e in expressions],
937
+ query=maybe_parse(query, copy=copy, **opts) if query else None,
938
+ unnest=(
939
+ Unnest(
940
+ expressions=[
941
+ maybe_parse(e, copy=copy, **opts)
942
+ for e in t.cast(list[ExpOrStr], ensure_list(unnest))
943
+ ]
944
+ )
945
+ if unnest
946
+ else None
947
+ ),
948
+ )
949
+
950
+
951
+ class QueryOption(Expression):
952
+ arg_types = {"this": True, "expression": False}
953
+
954
+
955
+ # FOR { XML | JSON } query modifier; `kind` is the discriminant ("XML" or "JSON").
956
+ class ForClause(Expression):
957
+ arg_types = {"kind": True, "expressions": False}
958
+
959
+
960
+ class WithTableHint(Expression):
961
+ arg_types = {"expressions": True}
962
+
963
+
964
+ class IndexTableHint(Expression):
965
+ arg_types = {"this": True, "expressions": False, "target": False}
966
+
967
+
968
+ class HistoricalData(Expression):
969
+ arg_types = {"this": True, "kind": True, "expression": True}
970
+
971
+
972
+ class Put(Expression):
973
+ arg_types = {"this": True, "target": True, "properties": False}
974
+
975
+
976
+ class Get(Expression):
977
+ arg_types = {"this": True, "target": True, "properties": False}
978
+
979
+
980
+ class ListStage(Expression):
981
+ """Lists files in a Snowflake stage or Git repository clone."""
982
+
983
+ arg_types = {"this": True, "pattern": False}
984
+
985
+
986
+ class Table(Expression, Selectable):
987
+ arg_types = {
988
+ "this": False,
989
+ "alias": False,
990
+ "db": False,
991
+ "catalog": False,
992
+ "laterals": False,
993
+ "joins": False,
994
+ "pivots": False,
995
+ "hints": False,
996
+ "system_time": False,
997
+ "version": False,
998
+ "format": False,
999
+ "pattern": False,
1000
+ "ordinality": False,
1001
+ "when": False,
1002
+ "only": False,
1003
+ "partition": False,
1004
+ "changes": False,
1005
+ "rows_from": False,
1006
+ "sample": False,
1007
+ "indexed": False,
1008
+ }
1009
+
1010
+ @property
1011
+ def name(self) -> str:
1012
+ this = self.this
1013
+ if not this or (isinstance(this, Func) and not isinstance(this, DynamicIdentifier)):
1014
+ return ""
1015
+ return this.name
1016
+
1017
+ @property
1018
+ def db(self) -> str:
1019
+ return self.text("db")
1020
+
1021
+ @property
1022
+ def catalog(self) -> str:
1023
+ return self.text("catalog")
1024
+
1025
+ @property
1026
+ def selects(self) -> list[Expr]:
1027
+ return []
1028
+
1029
+ @property
1030
+ def named_selects(self) -> list[str]:
1031
+ return []
1032
+
1033
+ @property
1034
+ def parts(self) -> list[Expr]:
1035
+ """Return the parts of a table in order catalog, db, table."""
1036
+ parts: list[Expr] = []
1037
+
1038
+ for arg in ("catalog", "db", "this"):
1039
+ part = self.args.get(arg)
1040
+
1041
+ if isinstance(part, Dot):
1042
+ parts.extend(part.flatten())
1043
+ elif isinstance(part, Expr):
1044
+ parts.append(part)
1045
+
1046
+ return parts
1047
+
1048
+ def to_column(self, copy: bool = True) -> Expr:
1049
+ parts = self.parts
1050
+ last_part = parts[-1]
1051
+
1052
+ if isinstance(last_part, Identifier):
1053
+ col: Expr = column(*reversed(parts[0:4]), fields=parts[4:], copy=copy) # type: ignore
1054
+ else:
1055
+ # This branch will be reached if a function or array is wrapped in a `Table`
1056
+ col = last_part
1057
+
1058
+ alias = self.args.get("alias")
1059
+ if alias:
1060
+ col = alias_(col, alias.this, copy=copy)
1061
+
1062
+ return col
1063
+
1064
+
1065
+ def _is_star(expression: Expr) -> bool:
1066
+ stack = [expression]
1067
+ while stack:
1068
+ node = stack.pop()
1069
+ if isinstance(node, SetOperation):
1070
+ stack.append(node.this)
1071
+ stack.append(node.expression)
1072
+ elif isinstance(node, Subquery):
1073
+ stack.append(node.this)
1074
+ elif node.is_star:
1075
+ return True
1076
+ return False
1077
+
1078
+
1079
+ class SetOperation(Expression, Query):
1080
+ arg_types = {
1081
+ "with_": False,
1082
+ "this": True,
1083
+ "expression": True,
1084
+ "distinct": False,
1085
+ "by_name": False,
1086
+ "side": False,
1087
+ "kind": False,
1088
+ "on": False,
1089
+ **QUERY_MODIFIERS,
1090
+ }
1091
+
1092
+ def select(
1093
+ self: S,
1094
+ *expressions: ExpOrStr | None,
1095
+ append: bool = True,
1096
+ dialect: DialectType = None,
1097
+ copy: bool = True,
1098
+ **opts: Unpack[ParserNoDialectArgs],
1099
+ ) -> S:
1100
+ this = maybe_copy(self, copy)
1101
+ this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1102
+ this.expression.unnest().select(
1103
+ *expressions, append=append, dialect=dialect, copy=False, **opts
1104
+ )
1105
+ return this
1106
+
1107
+ @property
1108
+ def named_selects(self) -> list[str]:
1109
+ expr: Expr = self
1110
+ while isinstance(expr, SetOperation):
1111
+ if expr.args.get("by_name"):
1112
+ left = t.cast(Selectable, expr.this.unnest()).named_selects
1113
+ right = t.cast(Selectable, expr.expression.unnest()).named_selects
1114
+ return list(dict.fromkeys(left + right))
1115
+
1116
+ expr = expr.this.unnest()
1117
+ return _named_selects(expr)
1118
+
1119
+ @property
1120
+ def is_star(self) -> bool:
1121
+ return _is_star(self)
1122
+
1123
+ @property
1124
+ def selects(self) -> list[Expr]:
1125
+ expr: Expr = self
1126
+ while isinstance(expr, SetOperation):
1127
+ expr = expr.this.unnest()
1128
+ return getattr(expr, "selects", [])
1129
+
1130
+ @property
1131
+ def left(self) -> Query:
1132
+ return self.this
1133
+
1134
+ @property
1135
+ def right(self) -> Query:
1136
+ return self.expression
1137
+
1138
+ @property
1139
+ def kind(self) -> str:
1140
+ return self.text("kind").upper()
1141
+
1142
+ @property
1143
+ def side(self) -> str:
1144
+ return self.text("side").upper()
1145
+
1146
+
1147
+ class Union(SetOperation):
1148
+ pass
1149
+
1150
+
1151
+ class Except(SetOperation):
1152
+ pass
1153
+
1154
+
1155
+ class Intersect(SetOperation):
1156
+ pass
1157
+
1158
+
1159
+ class Values(Expression, UDTF):
1160
+ arg_types = {
1161
+ "expressions": True,
1162
+ "alias": False,
1163
+ "order": False,
1164
+ "limit": False,
1165
+ "offset": False,
1166
+ }
1167
+
1168
+
1169
+ class Version(Expression):
1170
+ """
1171
+ Time travel, iceberg, bigquery etc
1172
+ https://trino.io/docs/current/connector/iceberg.html?highlight=snapshot#using-snapshots
1173
+ https://www.databricks.com/blog/2019/02/04/introducing-delta-time-travel-for-large-scale-data-lakes.html
1174
+ https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of
1175
+ https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver16
1176
+ this is either TIMESTAMP or VERSION
1177
+ kind is ("AS OF", "BETWEEN")
1178
+ """
1179
+
1180
+ arg_types = {"this": True, "kind": True, "expression": False}
1181
+
1182
+
1183
+ class Schema(Expression):
1184
+ arg_types = {"this": False, "expressions": False}
1185
+
1186
+
1187
+ class Lock(Expression):
1188
+ arg_types = {"update": True, "expressions": False, "wait": False, "key": False}
1189
+
1190
+
1191
+ class Select(Expression, Query):
1192
+ arg_types = {
1193
+ "with_": False,
1194
+ "kind": False,
1195
+ "expressions": False,
1196
+ "hint": False,
1197
+ "distinct": False,
1198
+ "into": False,
1199
+ "from_": False,
1200
+ "operation_modifiers": False,
1201
+ "exclude": False,
1202
+ **QUERY_MODIFIERS,
1203
+ }
1204
+
1205
+ def from_(
1206
+ self,
1207
+ expression: ExpOrStr,
1208
+ dialect: DialectType = None,
1209
+ copy: bool = True,
1210
+ **opts: Unpack[ParserNoDialectArgs],
1211
+ ) -> Select:
1212
+ """
1213
+ Set the FROM expression.
1214
+
1215
+ Example:
1216
+ >>> Select().from_("tbl").select("x").sql()
1217
+ 'SELECT x FROM tbl'
1218
+
1219
+ Args:
1220
+ expression : the SQL code strings to parse.
1221
+ If a `From` instance is passed, this is used as-is.
1222
+ If another `Expr` instance is passed, it will be wrapped in a `From`.
1223
+ dialect: the dialect used to parse the input expression.
1224
+ copy: if `False`, modify this expression instance in-place.
1225
+ opts: other options to use to parse the input expressions.
1226
+
1227
+ Returns:
1228
+ The modified Select expression.
1229
+ """
1230
+ return _apply_builder(
1231
+ expression=expression,
1232
+ instance=self,
1233
+ arg="from_",
1234
+ into=From,
1235
+ prefix="FROM",
1236
+ dialect=dialect,
1237
+ copy=copy,
1238
+ **opts,
1239
+ )
1240
+
1241
+ def group_by(
1242
+ self,
1243
+ *expressions: ExpOrStr | None,
1244
+ append: bool = True,
1245
+ dialect: DialectType = None,
1246
+ copy: bool = True,
1247
+ **opts: Unpack[ParserNoDialectArgs],
1248
+ ) -> Select:
1249
+ """
1250
+ Set the GROUP BY expression.
1251
+
1252
+ Example:
1253
+ >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
1254
+ 'SELECT x, COUNT(1) FROM tbl GROUP BY x'
1255
+
1256
+ Args:
1257
+ *expressions: the SQL code strings to parse.
1258
+ If a `Group` instance is passed, this is used as-is.
1259
+ If another `Expr` instance is passed, it will be wrapped in a `Group`.
1260
+ If nothing is passed in then a group by is not applied to the expression
1261
+ append: if `True`, add to any existing expressions.
1262
+ Otherwise, this flattens all the `Group` expression into a single expression.
1263
+ dialect: the dialect used to parse the input expression.
1264
+ copy: if `False`, modify this expression instance in-place.
1265
+ opts: other options to use to parse the input expressions.
1266
+
1267
+ Returns:
1268
+ The modified Select expression.
1269
+ """
1270
+ if not expressions:
1271
+ return self if not copy else self.copy()
1272
+
1273
+ return _apply_child_list_builder(
1274
+ *expressions,
1275
+ instance=self,
1276
+ arg="group",
1277
+ append=append,
1278
+ copy=copy,
1279
+ prefix="GROUP BY",
1280
+ into=Group,
1281
+ dialect=dialect,
1282
+ **opts,
1283
+ )
1284
+
1285
+ def sort_by(
1286
+ self,
1287
+ *expressions: ExpOrStr | None,
1288
+ append: bool = True,
1289
+ dialect: DialectType = None,
1290
+ copy: bool = True,
1291
+ **opts: Unpack[ParserNoDialectArgs],
1292
+ ) -> Select:
1293
+ """
1294
+ Set the SORT BY expression.
1295
+
1296
+ Example:
1297
+ >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
1298
+ 'SELECT x FROM tbl SORT BY x DESC'
1299
+
1300
+ Args:
1301
+ *expressions: the SQL code strings to parse.
1302
+ If a `Group` instance is passed, this is used as-is.
1303
+ If another `Expr` instance is passed, it will be wrapped in a `SORT`.
1304
+ append: if `True`, add to any existing expressions.
1305
+ Otherwise, this flattens all the `Order` expression into a single expression.
1306
+ dialect: the dialect used to parse the input expression.
1307
+ copy: if `False`, modify this expression instance in-place.
1308
+ opts: other options to use to parse the input expressions.
1309
+
1310
+ Returns:
1311
+ The modified Select expression.
1312
+ """
1313
+ return _apply_child_list_builder(
1314
+ *expressions,
1315
+ instance=self,
1316
+ arg="sort",
1317
+ append=append,
1318
+ copy=copy,
1319
+ prefix="SORT BY",
1320
+ into=Sort,
1321
+ dialect=dialect,
1322
+ **opts,
1323
+ )
1324
+
1325
+ def cluster_by(
1326
+ self,
1327
+ *expressions: ExpOrStr | None,
1328
+ append: bool = True,
1329
+ dialect: DialectType = None,
1330
+ copy: bool = True,
1331
+ **opts: Unpack[ParserNoDialectArgs],
1332
+ ) -> Select:
1333
+ """
1334
+ Set the CLUSTER BY expression.
1335
+
1336
+ Example:
1337
+ >>> Select().from_("tbl").select("x").cluster_by("x").sql(dialect="hive")
1338
+ 'SELECT x FROM tbl CLUSTER BY x'
1339
+
1340
+ Args:
1341
+ *expressions: the SQL code strings to parse.
1342
+ If a `Group` instance is passed, this is used as-is.
1343
+ If another `Expr` instance is passed, it will be wrapped in a `Cluster`.
1344
+ append: if `True`, add to any existing expressions.
1345
+ Otherwise, this flattens all the `Order` expression into a single expression.
1346
+ dialect: the dialect used to parse the input expression.
1347
+ copy: if `False`, modify this expression instance in-place.
1348
+ opts: other options to use to parse the input expressions.
1349
+
1350
+ Returns:
1351
+ The modified Select expression.
1352
+ """
1353
+ return _apply_child_list_builder(
1354
+ *expressions,
1355
+ instance=self,
1356
+ arg="cluster",
1357
+ append=append,
1358
+ copy=copy,
1359
+ prefix="CLUSTER BY",
1360
+ into=Cluster,
1361
+ dialect=dialect,
1362
+ **opts,
1363
+ )
1364
+
1365
+ def select(
1366
+ self,
1367
+ *expressions: ExpOrStr | None,
1368
+ append: bool = True,
1369
+ dialect: DialectType = None,
1370
+ copy: bool = True,
1371
+ **opts: Unpack[ParserNoDialectArgs],
1372
+ ) -> Select:
1373
+ return _apply_list_builder(
1374
+ *expressions,
1375
+ instance=self,
1376
+ arg="expressions",
1377
+ append=append,
1378
+ dialect=dialect,
1379
+ into=Expr,
1380
+ copy=copy,
1381
+ **opts,
1382
+ )
1383
+
1384
+ def lateral(
1385
+ self,
1386
+ *expressions: ExpOrStr | None,
1387
+ append: bool = True,
1388
+ dialect: DialectType = None,
1389
+ copy: bool = True,
1390
+ **opts: Unpack[ParserNoDialectArgs],
1391
+ ) -> Select:
1392
+ """
1393
+ Append to or set the LATERAL expressions.
1394
+
1395
+ Example:
1396
+ >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
1397
+ 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
1398
+
1399
+ Args:
1400
+ *expressions: the SQL code strings to parse.
1401
+ If an `Expr` instance is passed, it will be used as-is.
1402
+ append: if `True`, add to any existing expressions.
1403
+ Otherwise, this resets the expressions.
1404
+ dialect: the dialect used to parse the input expressions.
1405
+ copy: if `False`, modify this expression instance in-place.
1406
+ opts: other options to use to parse the input expressions.
1407
+
1408
+ Returns:
1409
+ The modified Select expression.
1410
+ """
1411
+ return _apply_list_builder(
1412
+ *expressions,
1413
+ instance=self,
1414
+ arg="laterals",
1415
+ append=append,
1416
+ into=Lateral,
1417
+ prefix="LATERAL VIEW",
1418
+ dialect=dialect,
1419
+ copy=copy,
1420
+ **opts,
1421
+ )
1422
+
1423
+ def join(
1424
+ self,
1425
+ expression: ExpOrStr,
1426
+ on: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None,
1427
+ using: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None,
1428
+ append: bool = True,
1429
+ join_type: str | None = None,
1430
+ join_alias: Identifier | str | None = None,
1431
+ dialect: DialectType = None,
1432
+ copy: bool = True,
1433
+ **opts: Unpack[ParserNoDialectArgs],
1434
+ ) -> Select:
1435
+ """
1436
+ Append to or set the JOIN expressions.
1437
+
1438
+ Example:
1439
+ >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
1440
+ 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
1441
+
1442
+ >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
1443
+ 'SELECT 1 FROM a JOIN b USING (x, y, z)'
1444
+
1445
+ Use `join_type` to change the type of join:
1446
+
1447
+ >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
1448
+ 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
1449
+
1450
+ Args:
1451
+ expression: the SQL code string to parse.
1452
+ If an `Expr` instance is passed, it will be used as-is.
1453
+ on: optionally specify the join "on" criteria as a SQL string.
1454
+ If an `Expr` instance is passed, it will be used as-is.
1455
+ using: optionally specify the join "using" criteria as a SQL string.
1456
+ If an `Expr` instance is passed, it will be used as-is.
1457
+ append: if `True`, add to any existing expressions.
1458
+ Otherwise, this resets the expressions.
1459
+ join_type: if set, alter the parsed join type.
1460
+ join_alias: an optional alias for the joined source.
1461
+ dialect: the dialect used to parse the input expressions.
1462
+ copy: if `False`, modify this expression instance in-place.
1463
+ opts: other options to use to parse the input expressions.
1464
+
1465
+ Returns:
1466
+ Select: the modified expression.
1467
+ """
1468
+ parse_args: ParserArgs = {"dialect": dialect, **opts}
1469
+ try:
1470
+ expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
1471
+ except ParseError:
1472
+ expression = maybe_parse(expression, into=(Join, Expr), **parse_args)
1473
+
1474
+ join = expression if isinstance(expression, Join) else Join(this=expression)
1475
+
1476
+ if isinstance(join.this, Select):
1477
+ join.this.replace(join.this.subquery())
1478
+
1479
+ if join_type:
1480
+ new_join: Join = maybe_parse(f"FROM _ {join_type} JOIN _", **parse_args).find(Join)
1481
+ method = new_join.method
1482
+ side = new_join.side
1483
+ kind = new_join.kind
1484
+
1485
+ if method:
1486
+ join.set("method", method)
1487
+ if side:
1488
+ join.set("side", side)
1489
+ if kind:
1490
+ join.set("kind", kind)
1491
+
1492
+ if on:
1493
+ on_exprs: list[ExpOrStr] = ensure_list(on)
1494
+ on = and_(*on_exprs, dialect=dialect, copy=copy, **opts)
1495
+ join.set("on", on)
1496
+
1497
+ if using:
1498
+ using_exprs: list[ExpOrStr] = ensure_list(using)
1499
+ join = _apply_list_builder(
1500
+ *using_exprs,
1501
+ instance=join,
1502
+ arg="using",
1503
+ append=append,
1504
+ copy=copy,
1505
+ into=Identifier,
1506
+ **opts,
1507
+ )
1508
+
1509
+ if join_alias:
1510
+ join.set("this", alias_(join.this, join_alias, table=True))
1511
+
1512
+ return _apply_list_builder(
1513
+ join,
1514
+ instance=self,
1515
+ arg="joins",
1516
+ append=append,
1517
+ copy=copy,
1518
+ **opts,
1519
+ )
1520
+
1521
+ def having(
1522
+ self,
1523
+ *expressions: ExpOrStr | None,
1524
+ append: bool = True,
1525
+ dialect: DialectType = None,
1526
+ copy: bool = True,
1527
+ **opts: Unpack[ParserNoDialectArgs],
1528
+ ) -> Select:
1529
+ """
1530
+ Append to or set the HAVING expressions.
1531
+
1532
+ Example:
1533
+ >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
1534
+ 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
1535
+
1536
+ Args:
1537
+ *expressions: the SQL code strings to parse.
1538
+ If an `Expr` instance is passed, it will be used as-is.
1539
+ Multiple expressions are combined with an AND operator.
1540
+ append: if `True`, AND the new expressions to any existing expression.
1541
+ Otherwise, this resets the expression.
1542
+ dialect: the dialect used to parse the input expressions.
1543
+ copy: if `False`, modify this expression instance in-place.
1544
+ opts: other options to use to parse the input expressions.
1545
+
1546
+ Returns:
1547
+ The modified Select expression.
1548
+ """
1549
+ return _apply_conjunction_builder(
1550
+ *expressions,
1551
+ instance=self,
1552
+ arg="having",
1553
+ append=append,
1554
+ into=Having,
1555
+ dialect=dialect,
1556
+ copy=copy,
1557
+ **opts,
1558
+ )
1559
+
1560
+ def window(
1561
+ self,
1562
+ *expressions: ExpOrStr | None,
1563
+ append: bool = True,
1564
+ dialect: DialectType = None,
1565
+ copy: bool = True,
1566
+ **opts: Unpack[ParserNoDialectArgs],
1567
+ ) -> Select:
1568
+ return _apply_list_builder(
1569
+ *expressions,
1570
+ instance=self,
1571
+ arg="windows",
1572
+ append=append,
1573
+ into=Window,
1574
+ dialect=dialect,
1575
+ copy=copy,
1576
+ **opts,
1577
+ )
1578
+
1579
+ def qualify(
1580
+ self,
1581
+ *expressions: ExpOrStr | None,
1582
+ append: bool = True,
1583
+ dialect: DialectType = None,
1584
+ copy: bool = True,
1585
+ **opts: Unpack[ParserNoDialectArgs],
1586
+ ) -> Select:
1587
+ return _apply_conjunction_builder(
1588
+ *expressions,
1589
+ instance=self,
1590
+ arg="qualify",
1591
+ append=append,
1592
+ into=Qualify,
1593
+ dialect=dialect,
1594
+ copy=copy,
1595
+ **opts,
1596
+ )
1597
+
1598
+ def distinct(self, *ons: ExpOrStr | None, distinct: bool = True, copy: bool = True) -> Select:
1599
+ """
1600
+ Set the OFFSET expression.
1601
+
1602
+ Example:
1603
+ >>> Select().from_("tbl").select("x").distinct().sql()
1604
+ 'SELECT DISTINCT x FROM tbl'
1605
+
1606
+ Args:
1607
+ ons: the expressions to distinct on
1608
+ distinct: whether the Select should be distinct
1609
+ copy: if `False`, modify this expression instance in-place.
1610
+
1611
+ Returns:
1612
+ Select: the modified expression.
1613
+ """
1614
+ instance = maybe_copy(self, copy)
1615
+ on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
1616
+ instance.set("distinct", Distinct(on=on) if distinct else None)
1617
+ return instance
1618
+
1619
+ def ctas(
1620
+ self,
1621
+ table: ExpOrStr,
1622
+ properties: dict | None = None,
1623
+ dialect: DialectType = None,
1624
+ copy: bool = True,
1625
+ **opts: Unpack[ParserNoDialectArgs],
1626
+ ) -> Create:
1627
+ """
1628
+ Convert this expression to a CREATE TABLE AS statement.
1629
+
1630
+ Example:
1631
+ >>> Select().select("*").from_("tbl").ctas("x").sql()
1632
+ 'CREATE TABLE x AS SELECT * FROM tbl'
1633
+
1634
+ Args:
1635
+ table: the SQL code string to parse as the table name.
1636
+ If another `Expr` instance is passed, it will be used as-is.
1637
+ properties: an optional mapping of table properties
1638
+ dialect: the dialect used to parse the input table.
1639
+ copy: if `False`, modify this expression instance in-place.
1640
+ opts: other options to use to parse the input table.
1641
+
1642
+ Returns:
1643
+ The new Create expression.
1644
+ """
1645
+ instance = maybe_copy(self, copy)
1646
+ table_expression = maybe_parse(table, into=Table, dialect=dialect, **opts)
1647
+
1648
+ properties_expression = None
1649
+ if properties:
1650
+ from sqlglot.expressions.properties import Properties as _Properties
1651
+
1652
+ properties_expression = _Properties.from_dict(properties)
1653
+
1654
+ from sqlglot.expressions.ddl import Create as _Create
1655
+
1656
+ return _Create(
1657
+ this=table_expression,
1658
+ kind="TABLE",
1659
+ expression=instance,
1660
+ properties=properties_expression,
1661
+ )
1662
+
1663
+ def lock(self, update: bool = True, copy: bool = True) -> Select:
1664
+ """
1665
+ Set the locking read mode for this expression.
1666
+
1667
+ Examples:
1668
+ >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
1669
+ "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
1670
+
1671
+ >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
1672
+ "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
1673
+
1674
+ Args:
1675
+ update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
1676
+ copy: if `False`, modify this expression instance in-place.
1677
+
1678
+ Returns:
1679
+ The modified expression.
1680
+ """
1681
+ inst = maybe_copy(self, copy)
1682
+ inst.set("locks", [Lock(update=update)])
1683
+
1684
+ return inst
1685
+
1686
+ def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
1687
+ """
1688
+ Set hints for this expression.
1689
+
1690
+ Examples:
1691
+ >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
1692
+ 'SELECT /*+ BROADCAST(y) */ x FROM tbl'
1693
+
1694
+ Args:
1695
+ hints: The SQL code strings to parse as the hints.
1696
+ If an `Expr` instance is passed, it will be used as-is.
1697
+ dialect: The dialect used to parse the hints.
1698
+ copy: If `False`, modify this expression instance in-place.
1699
+
1700
+ Returns:
1701
+ The modified expression.
1702
+ """
1703
+ inst = maybe_copy(self, copy)
1704
+ inst.set(
1705
+ "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
1706
+ )
1707
+
1708
+ return inst
1709
+
1710
+ @property
1711
+ def named_selects(self) -> list[str]:
1712
+ selects = []
1713
+
1714
+ for e in self.expressions:
1715
+ if e.alias_or_name:
1716
+ selects.append(e.output_name)
1717
+ elif isinstance(e, Aliases):
1718
+ selects.extend([a.name for a in e.aliases])
1719
+ return selects
1720
+
1721
+ @property
1722
+ def is_star(self) -> bool:
1723
+ return any(expression.is_star for expression in self.expressions)
1724
+
1725
+ @property
1726
+ def selects(self) -> list[Expr]:
1727
+ return self.expressions
1728
+
1729
+
1730
+ class Subquery(Expression, DerivedTable, Query):
1731
+ is_subquery: t.ClassVar[bool] = True
1732
+ arg_types = {
1733
+ "this": True,
1734
+ "alias": False,
1735
+ "with_": False,
1736
+ **QUERY_MODIFIERS,
1737
+ }
1738
+
1739
+ def unnest(self) -> Expr:
1740
+ """Returns the first non subquery."""
1741
+ expression: Expr = self
1742
+ while isinstance(expression, Subquery):
1743
+ expression = expression.this
1744
+ return expression
1745
+
1746
+ def unwrap(self) -> Subquery:
1747
+ expression = self
1748
+ while expression.same_parent and expression.is_wrapper:
1749
+ expression = t.cast(Subquery, expression.parent)
1750
+ return expression
1751
+
1752
+ def select(
1753
+ self,
1754
+ *expressions: ExpOrStr | None,
1755
+ append: bool = True,
1756
+ dialect: DialectType = None,
1757
+ copy: bool = True,
1758
+ **opts: Unpack[ParserNoDialectArgs],
1759
+ ) -> Subquery:
1760
+ this = maybe_copy(self, copy)
1761
+ inner = this.unnest()
1762
+ if hasattr(inner, "select"):
1763
+ inner.select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1764
+ return this
1765
+
1766
+ @property
1767
+ def is_wrapper(self) -> bool:
1768
+ """
1769
+ Whether this Subquery acts as a simple wrapper around another expression.
1770
+
1771
+ SELECT * FROM (((SELECT * FROM t)))
1772
+ ^
1773
+ This corresponds to a "wrapper" Subquery node
1774
+ """
1775
+ return all(v is None for k, v in self.args.items() if k != "this")
1776
+
1777
+ @property
1778
+ def is_star(self) -> bool:
1779
+ return _is_star(self)
1780
+
1781
+ @property
1782
+ def output_name(self) -> str:
1783
+ return self.alias
1784
+
1785
+
1786
+ class TableSample(Expression):
1787
+ arg_types = {
1788
+ "expressions": False,
1789
+ "method": False,
1790
+ "bucket_numerator": False,
1791
+ "bucket_denominator": False,
1792
+ "bucket_field": False,
1793
+ "percent": False,
1794
+ "rows": False,
1795
+ "size": False,
1796
+ "seed": False,
1797
+ }
1798
+
1799
+
1800
+ class Tag(Expression):
1801
+ """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
1802
+
1803
+ arg_types = {
1804
+ "this": False,
1805
+ "prefix": False,
1806
+ "postfix": False,
1807
+ }
1808
+
1809
+
1810
+ class Pivot(Expression):
1811
+ arg_types = {
1812
+ "this": False,
1813
+ "alias": False,
1814
+ "expressions": False,
1815
+ "fields": False,
1816
+ "unpivot": False,
1817
+ "using": False,
1818
+ "group": False,
1819
+ "columns": False,
1820
+ "include_nulls": False,
1821
+ "default_on_null": False,
1822
+ "into": False,
1823
+ "with_": False,
1824
+ "identify_pivot_strings": False,
1825
+ "prefixed_pivot_columns": False,
1826
+ "pivot_column_naming": False,
1827
+ "value_columns_first": False,
1828
+ }
1829
+
1830
+ @property
1831
+ def unpivot(self) -> bool:
1832
+ return bool(self.args.get("unpivot"))
1833
+
1834
+ @property
1835
+ def fields(self) -> list[Expr]:
1836
+ return self.args.get("fields", [])
1837
+
1838
+ def output_columns(self, pre_pivot_columns: t.Iterable[str]) -> dict[str, str]:
1839
+ """
1840
+ Returns an ordered map of post-rename output column name -> pre-rename
1841
+ source-side name, in the order the (UN)PIVOT produces them.
1842
+
1843
+ For callers that just want the names, iterate the dict (or call .keys()):
1844
+ >>> from sqlglot import parse_one, exp
1845
+ >>> piv = parse_one("SELECT * FROM t UNPIVOT(val FOR name IN (a, b))").find(exp.Pivot)
1846
+ >>> list(piv.output_columns(["a", "b", "c"]))
1847
+ ['c', 'name', 'val']
1848
+
1849
+ AST shape:
1850
+ PIVOT(SUM(val) FOR name IN ('a', 'b')):
1851
+ expressions: aggregate(s), e.g. [Sum(this=Column(val))]
1852
+ fields: [In(this=Column(name), expressions=[Literal('a'), Literal('b')])]
1853
+ columns: optional explicit output identifiers (e.g. set by Snowflake)
1854
+
1855
+ UNPIVOT(val FOR name IN (a, b)):
1856
+ expressions: value Identifier(s), or Tuple(Identifiers) for multi-value
1857
+ fields: [In(this=Identifier(name), expressions=[Column(a), Column(b)])]
1858
+ For literal-aliased entries (`a AS 'x'`) the IN expressions
1859
+ are wrapped in PivotAlias(this=Column, alias=Literal).
1860
+
1861
+ Args:
1862
+ pre_pivot_columns: Columns visible to the operator before it runs
1863
+ (e.g. the source table or subquery's projections).
1864
+ """
1865
+ if self.unpivot:
1866
+ excluded: set[str] = set()
1867
+ name_columns: list[Identifier] = []
1868
+ for field in self.fields:
1869
+ if not isinstance(field, In):
1870
+ continue
1871
+ if isinstance(field.this, Identifier):
1872
+ name_columns.append(field.this)
1873
+ for e in field.expressions:
1874
+ excluded.update(c.output_name for c in e.find_all(Column))
1875
+ value_columns = [
1876
+ ident
1877
+ for e in self.expressions
1878
+ for ident in (e.expressions if isinstance(e, Tuple) else [e])
1879
+ if isinstance(ident, Identifier)
1880
+ ]
1881
+ # T-SQL emits the value column(s) ahead of the name column, everyone else emits them after it
1882
+ ordered = (
1883
+ value_columns + name_columns
1884
+ if self.args.get("value_columns_first")
1885
+ else name_columns + value_columns
1886
+ )
1887
+ outputs = [i.name for i in ordered]
1888
+ else:
1889
+ excluded = {c.output_name for c in self.find_all(Column)}
1890
+ outputs = [c.output_name for c in self.args.get("columns") or []]
1891
+ if not outputs:
1892
+ outputs = [c.alias_or_name for c in self.expressions]
1893
+
1894
+ if not excluded or not outputs:
1895
+ return {}
1896
+
1897
+ pre_rename = [c for c in pre_pivot_columns if c not in excluded] + outputs
1898
+
1899
+ alias = self.args.get("alias")
1900
+ renames = alias.args.get("columns") if alias else None
1901
+
1902
+ # `PIVOT(...) AS alias(c1, c2, ...)` renames the operator's output columns
1903
+ # positionally from the front (DuckDB, Snowflake): the user's names cover
1904
+ # the leading N output columns, remaining columns keep their auto names.
1905
+ if renames:
1906
+ rename_names = [r.name for r in renames]
1907
+ post_rename = rename_names + pre_rename[len(rename_names) :]
1908
+ else:
1909
+ post_rename = pre_rename
1910
+
1911
+ return dict(zip(post_rename, pre_rename))
1912
+
1913
+
1914
+ class UnpivotColumns(Expression):
1915
+ arg_types = {"this": True, "expressions": True}
1916
+
1917
+
1918
+ class Window(Expression, Condition):
1919
+ arg_types = {
1920
+ "this": True,
1921
+ "partition_by": False,
1922
+ "order": False,
1923
+ "spec": False,
1924
+ "alias": False,
1925
+ "over": False,
1926
+ "first": False,
1927
+ }
1928
+
1929
+
1930
+ class WindowSpec(Expression):
1931
+ arg_types = {
1932
+ "kind": False,
1933
+ "start": False,
1934
+ "start_side": False,
1935
+ "end": False,
1936
+ "end_side": False,
1937
+ "exclude": False,
1938
+ }
1939
+
1940
+
1941
+ class PartitionByExcluding(Expression):
1942
+ arg_types = {"expressions": True}
1943
+
1944
+
1945
+ class PreWhere(Expression):
1946
+ pass
1947
+
1948
+
1949
+ class Where(Expression):
1950
+ pass
1951
+
1952
+
1953
+ class Analyze(Expression):
1954
+ arg_types = {
1955
+ "kind": False,
1956
+ "tables": False,
1957
+ "options": False,
1958
+ "mode": False,
1959
+ "partition": False,
1960
+ "expression": False,
1961
+ "properties": False,
1962
+ }
1963
+
1964
+
1965
+ class AnalyzeStatistics(Expression):
1966
+ arg_types = {
1967
+ "kind": True,
1968
+ "option": False,
1969
+ "this": False,
1970
+ "expressions": False,
1971
+ }
1972
+
1973
+
1974
+ class AnalyzeHistogram(Expression):
1975
+ arg_types = {
1976
+ "this": True,
1977
+ "expressions": True,
1978
+ "expression": False,
1979
+ "update_options": False,
1980
+ }
1981
+
1982
+
1983
+ class AnalyzeSample(Expression):
1984
+ arg_types = {"kind": True, "sample": True}
1985
+
1986
+
1987
+ class AnalyzeListChainedRows(Expression):
1988
+ arg_types = {"expression": False}
1989
+
1990
+
1991
+ class AnalyzeDelete(Expression):
1992
+ arg_types = {"kind": False}
1993
+
1994
+
1995
+ class AnalyzeWith(Expression):
1996
+ arg_types = {"expressions": True}
1997
+
1998
+
1999
+ class AnalyzeValidate(Expression):
2000
+ arg_types = {
2001
+ "kind": True,
2002
+ "this": False,
2003
+ "expression": False,
2004
+ }
2005
+
2006
+
2007
+ class AnalyzeColumns(Expression):
2008
+ pass
2009
+
2010
+
2011
+ class UsingData(Expression):
2012
+ pass
2013
+
2014
+
2015
+ class AddPartition(Expression):
2016
+ arg_types = {"this": True, "exists": False, "location": False}
2017
+
2018
+
2019
+ class AttachOption(Expression):
2020
+ arg_types = {"this": True, "expression": False}
2021
+
2022
+
2023
+ class DropPartition(Expression):
2024
+ arg_types = {"expressions": True, "exists": False}
2025
+
2026
+
2027
+ class ReplaceColumns(Expression):
2028
+ arg_types = {"expressions": True}
2029
+
2030
+
2031
+ class ReplacePartition(Expression):
2032
+ arg_types = {"expression": True, "source": True}
2033
+
2034
+
2035
+ class TranslateCharacters(Expression):
2036
+ arg_types = {"this": True, "expression": True, "with_error": False}
2037
+
2038
+
2039
+ class OverflowTruncateBehavior(Expression):
2040
+ arg_types = {"this": False, "with_count": True}
2041
+
2042
+
2043
+ class JSON(Expression):
2044
+ arg_types = {"this": False, "with_": False, "unique": False}
2045
+
2046
+
2047
+ class JSONPath(Expression):
2048
+ arg_types = {"expressions": True}
2049
+
2050
+ @property
2051
+ def output_name(self) -> str:
2052
+ last_segment = self.expressions[-1].this
2053
+ return last_segment if isinstance(last_segment, str) else ""
2054
+
2055
+
2056
+ class JSONPathPart(Expression):
2057
+ arg_types = {}
2058
+
2059
+
2060
+ class JSONPathFilter(JSONPathPart):
2061
+ arg_types = {"this": True}
2062
+ _hash_raw_args = True
2063
+
2064
+
2065
+ class JSONPathKey(JSONPathPart):
2066
+ arg_types = {"this": True, "quoted": False}
2067
+ _hash_raw_args = True
2068
+
2069
+
2070
+ class JSONPathRecursive(JSONPathPart):
2071
+ arg_types = {"this": False}
2072
+ _hash_raw_args = True
2073
+
2074
+
2075
+ class JSONPathRoot(JSONPathPart):
2076
+ pass
2077
+
2078
+
2079
+ class JSONPathScript(JSONPathPart):
2080
+ arg_types = {"this": True}
2081
+ _hash_raw_args = True
2082
+
2083
+
2084
+ class JSONPathSlice(JSONPathPart):
2085
+ arg_types = {"start": False, "end": False, "step": False}
2086
+
2087
+
2088
+ class JSONPathSelector(JSONPathPart):
2089
+ arg_types = {"this": True}
2090
+
2091
+
2092
+ class JSONPathSubscript(JSONPathPart):
2093
+ arg_types = {"this": True}
2094
+
2095
+
2096
+ class JSONPathUnion(JSONPathPart):
2097
+ arg_types = {"expressions": True}
2098
+ _hash_raw_args = True
2099
+
2100
+
2101
+ class JSONPathWildcard(JSONPathPart):
2102
+ pass
2103
+
2104
+
2105
+ class FormatJson(Expression):
2106
+ pass
2107
+
2108
+
2109
+ class JSONKeyValue(Expression):
2110
+ arg_types = {"this": True, "expression": True}
2111
+
2112
+
2113
+ class JSONColumnDef(Expression):
2114
+ arg_types = {
2115
+ "this": False,
2116
+ "kind": False,
2117
+ "path": False,
2118
+ "nested_schema": False,
2119
+ "ordinality": False,
2120
+ "format_json": False,
2121
+ }
2122
+
2123
+
2124
+ class JSONSchema(Expression):
2125
+ arg_types = {"expressions": True}
2126
+
2127
+
2128
+ class JSONValue(Expression):
2129
+ arg_types = {
2130
+ "this": True,
2131
+ "path": True,
2132
+ "returning": False,
2133
+ "on_condition": False,
2134
+ }
2135
+
2136
+
2137
+ class JSONValueArray(Expression, Func):
2138
+ arg_types = {"this": True, "expression": False}
2139
+
2140
+
2141
+ class OpenJSONColumnDef(Expression):
2142
+ arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
2143
+
2144
+
2145
+ class JSONExtractQuote(Expression):
2146
+ arg_types = {
2147
+ "option": True,
2148
+ "scalar": False,
2149
+ }
2150
+
2151
+
2152
+ class ScopeResolution(Expression):
2153
+ arg_types = {"this": False, "expression": True}
2154
+
2155
+
2156
+ class Stream(Expression):
2157
+ pass
2158
+
2159
+
2160
+ class ModelAttribute(Expression):
2161
+ arg_types = {"this": True, "expression": True}
2162
+
2163
+
2164
+ class XMLNamespace(Expression):
2165
+ pass
2166
+
2167
+
2168
+ class XMLKeyValueOption(Expression):
2169
+ arg_types = {"this": True, "expression": False}
2170
+
2171
+
2172
+ class Semicolon(Expression):
2173
+ arg_types = {}
2174
+
2175
+
2176
+ class TableColumn(Expression):
2177
+ @property
2178
+ def output_name(self) -> str:
2179
+ return self.name
2180
+
2181
+
2182
+ class Variadic(Expression):
2183
+ pass
2184
+
2185
+
2186
+ class StoredProcedure(Expression):
2187
+ arg_types = {"this": True, "expressions": False, "wrapped": False}
2188
+
2189
+
2190
+ class Block(Expression):
2191
+ arg_types = {"expressions": True, "begin": False}
2192
+
2193
+
2194
+ class IfBlock(Expression):
2195
+ arg_types = {"this": True, "true": True, "false": False}
2196
+
2197
+
2198
+ class CaseStatement(Expression):
2199
+ arg_types = {"this": False, "ifs": True, "default": False}
2200
+
2201
+
2202
+ class WhileBlock(Expression):
2203
+ arg_types = {"this": True, "body": True, "label": False}
2204
+
2205
+
2206
+ class LoopBlock(Expression):
2207
+ arg_types = {"body": True, "label": False}
2208
+
2209
+
2210
+ class RepeatBlock(Expression):
2211
+ arg_types = {"body": True, "until": True, "label": False}
2212
+
2213
+
2214
+ class Leave(Expression):
2215
+ pass
2216
+
2217
+
2218
+ class Iterate(Expression):
2219
+ pass
2220
+
2221
+
2222
+ class EndStatement(Expression):
2223
+ arg_types = {}
2224
+
2225
+
2226
+ # https://trino.io/docs/current/udf.html
2227
+ class FunctionSpecification(Expression):
2228
+ arg_types = {
2229
+ "this": True,
2230
+ "characteristics": False,
2231
+ "properties": False,
2232
+ "expression": True,
2233
+ }
2234
+
2235
+
2236
+ UNWRAPPED_QUERIES = (Select, SetOperation)
2237
+
2238
+
2239
+ def union(
2240
+ *expressions: ExpOrStr,
2241
+ distinct: bool = True,
2242
+ dialect: DialectType = None,
2243
+ copy: bool = True,
2244
+ **opts: Unpack[ParserNoDialectArgs],
2245
+ ) -> Union:
2246
+ """
2247
+ Initializes a syntax tree for the `UNION` operation.
2248
+
2249
+ Example:
2250
+ >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
2251
+ 'SELECT * FROM foo UNION SELECT * FROM bla'
2252
+
2253
+ Args:
2254
+ expressions: the SQL code strings, corresponding to the `UNION`'s operands.
2255
+ If `Expr` instances are passed, they will be used as-is.
2256
+ distinct: set the DISTINCT flag if and only if this is true.
2257
+ dialect: the dialect used to parse the input expression.
2258
+ copy: whether to copy the expression.
2259
+ opts: other options to use to parse the input expressions.
2260
+
2261
+ Returns:
2262
+ The new Union instance.
2263
+ """
2264
+ assert len(expressions) >= 2, "At least two expressions are required by `union`."
2265
+ return _apply_set_operation(
2266
+ *expressions, set_operation=Union, distinct=distinct, dialect=dialect, copy=copy, **opts
2267
+ )
2268
+
2269
+
2270
+ def intersect(
2271
+ *expressions: ExpOrStr,
2272
+ distinct: bool = True,
2273
+ dialect: DialectType = None,
2274
+ copy: bool = True,
2275
+ **opts: Unpack[ParserNoDialectArgs],
2276
+ ) -> Intersect:
2277
+ """
2278
+ Initializes a syntax tree for the `INTERSECT` operation.
2279
+
2280
+ Example:
2281
+ >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
2282
+ 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
2283
+
2284
+ Args:
2285
+ expressions: the SQL code strings, corresponding to the `INTERSECT`'s operands.
2286
+ If `Expr` instances are passed, they will be used as-is.
2287
+ distinct: set the DISTINCT flag if and only if this is true.
2288
+ dialect: the dialect used to parse the input expression.
2289
+ copy: whether to copy the expression.
2290
+ opts: other options to use to parse the input expressions.
2291
+
2292
+ Returns:
2293
+ The new Intersect instance.
2294
+ """
2295
+ assert len(expressions) >= 2, "At least two expressions are required by `intersect`."
2296
+ return _apply_set_operation(
2297
+ *expressions, set_operation=Intersect, distinct=distinct, dialect=dialect, copy=copy, **opts
2298
+ )
2299
+
2300
+
2301
+ def except_(
2302
+ *expressions: ExpOrStr,
2303
+ distinct: bool = True,
2304
+ dialect: DialectType = None,
2305
+ copy: bool = True,
2306
+ **opts: Unpack[ParserNoDialectArgs],
2307
+ ) -> Except:
2308
+ """
2309
+ Initializes a syntax tree for the `EXCEPT` operation.
2310
+
2311
+ Example:
2312
+ >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
2313
+ 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
2314
+
2315
+ Args:
2316
+ expressions: the SQL code strings, corresponding to the `EXCEPT`'s operands.
2317
+ If `Expr` instances are passed, they will be used as-is.
2318
+ distinct: set the DISTINCT flag if and only if this is true.
2319
+ dialect: the dialect used to parse the input expression.
2320
+ copy: whether to copy the expression.
2321
+ opts: other options to use to parse the input expressions.
2322
+
2323
+ Returns:
2324
+ The new Except instance.
2325
+ """
2326
+ assert len(expressions) >= 2, "At least two expressions are required by `except_`."
2327
+ return _apply_set_operation(
2328
+ *expressions, set_operation=Except, distinct=distinct, dialect=dialect, copy=copy, **opts
2329
+ )
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/string.py ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions - string, encoding, hashing, and regex functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlglot.expressions.core import Expression, Func, Binary, Predicate
6
+
7
+
8
+ # String basics
9
+
10
+
11
+ class Ascii(Expression, Func):
12
+ pass
13
+
14
+
15
+ class BitLength(Expression, Func):
16
+ pass
17
+
18
+
19
+ class ByteLength(Expression, Func):
20
+ pass
21
+
22
+
23
+ class Chr(Expression, Func):
24
+ arg_types = {"expressions": True, "charset": False}
25
+ is_var_len_args = True
26
+ _sql_names = ["CHR", "CHAR"]
27
+
28
+
29
+ class Concat(Expression, Func):
30
+ arg_types = {"expressions": True, "safe": False, "coalesce": False}
31
+ is_var_len_args = True
32
+
33
+
34
+ class ConcatWs(Concat):
35
+ arg_types = {**Concat.arg_types, "flatten": False}
36
+ _sql_names = ["CONCAT_WS"]
37
+
38
+
39
+ class Contains(Expression, Func):
40
+ arg_types = {"this": True, "expression": True, "json_scope": False}
41
+
42
+
43
+ class Elt(Expression, Func):
44
+ arg_types = {"this": True, "expressions": True}
45
+ is_var_len_args = True
46
+
47
+
48
+ class EndsWith(Expression, Func):
49
+ _sql_names = ["ENDS_WITH", "ENDSWITH"]
50
+ arg_types = {"this": True, "expression": True}
51
+
52
+
53
+ class Format(Expression, Func):
54
+ arg_types = {"this": True, "expressions": False}
55
+ is_var_len_args = True
56
+
57
+
58
+ class Initcap(Expression, Func):
59
+ arg_types = {"this": True, "expression": False}
60
+
61
+
62
+ class IsAscii(Expression, Func):
63
+ pass
64
+
65
+
66
+ class Left(Expression, Func):
67
+ arg_types = {"this": True, "expression": True, "negative_length_returns_empty": False}
68
+
69
+
70
+ class Length(Expression, Func):
71
+ arg_types = {"this": True, "binary": False, "encoding": False}
72
+ _sql_names = ["LENGTH", "LEN", "CHAR_LENGTH", "CHARACTER_LENGTH"]
73
+
74
+
75
+ class Levenshtein(Expression, Func):
76
+ arg_types = {
77
+ "this": True,
78
+ "expression": False,
79
+ "ins_cost": False,
80
+ "del_cost": False,
81
+ "sub_cost": False,
82
+ "max_dist": False,
83
+ }
84
+
85
+
86
+ class Lower(Expression, Func):
87
+ _sql_names = ["LOWER", "LCASE"]
88
+
89
+
90
+ class MatchAgainst(Expression, Func):
91
+ arg_types = {"this": True, "expressions": True, "modifier": False}
92
+
93
+
94
+ class Normalize(Expression, Func):
95
+ arg_types = {"this": True, "form": False, "is_casefold": False}
96
+
97
+
98
+ class NumberToStr(Expression, Func):
99
+ arg_types = {"this": True, "format": True, "culture": False}
100
+
101
+
102
+ class Overlay(Expression, Func):
103
+ arg_types = {"this": True, "expression": True, "from_": True, "for_": False}
104
+
105
+
106
+ class Pad(Expression, Func):
107
+ arg_types = {"this": True, "expression": True, "fill_pattern": False, "is_left": True}
108
+
109
+
110
+ class Repeat(Expression, Func):
111
+ arg_types = {"this": True, "times": True}
112
+
113
+
114
+ class Replace(Expression, Func):
115
+ arg_types = {"this": True, "expression": True, "replacement": False}
116
+
117
+
118
+ class Reverse(Expression, Func):
119
+ pass
120
+
121
+
122
+ class Right(Expression, Func):
123
+ arg_types = {"this": True, "expression": True, "negative_length_returns_empty": False}
124
+
125
+
126
+ class RtrimmedLength(Expression, Func):
127
+ pass
128
+
129
+
130
+ class Search(Expression, Func):
131
+ arg_types = {
132
+ "this": True, # data_to_search / search_data
133
+ "expression": True, # search_query / search_string
134
+ "json_scope": False, # BigQuery: JSON_VALUES | JSON_KEYS | JSON_KEYS_AND_VALUES
135
+ "analyzer": False, # Both: analyzer / ANALYZER
136
+ "analyzer_options": False, # BigQuery: analyzer_options_values
137
+ "search_mode": False, # Snowflake: OR | AND
138
+ }
139
+
140
+
141
+ class SearchIp(Expression, Func):
142
+ arg_types = {"this": True, "expression": True}
143
+
144
+
145
+ class Secret(Expression, Func):
146
+ arg_types = {"this": True, "expression": True}
147
+
148
+
149
+ class Soundex(Expression, Func):
150
+ pass
151
+
152
+
153
+ class SoundexP123(Expression, Func):
154
+ pass
155
+
156
+
157
+ class Space(Expression, Func):
158
+ """
159
+ SPACE(n) → string consisting of n blank characters
160
+ """
161
+
162
+ pass
163
+
164
+
165
+ class Split(Expression, Func):
166
+ arg_types = {
167
+ "this": True,
168
+ "expression": True,
169
+ "limit": False,
170
+ "null_returns_null": False,
171
+ "empty_delimiter_returns_whole": False,
172
+ }
173
+
174
+
175
+ class SplitPart(Expression, Func):
176
+ arg_types = {
177
+ "this": True,
178
+ "delimiter": False,
179
+ "part_index": False,
180
+ "part_index_zero_as_one": False, # usually part_index is 1-based, however Snowflake allows 0 and treats it as 1
181
+ "empty_delimiter_returns_whole": False, # whether the whole input string should be returned if the delimiter string is empty (i.e. Snowflake)
182
+ }
183
+
184
+
185
+ class Strtok(Expression, Func):
186
+ arg_types = {
187
+ "this": True,
188
+ "delimiter": False,
189
+ "part_index": False,
190
+ }
191
+
192
+
193
+ class StartsWith(Expression, Func):
194
+ _sql_names = ["STARTS_WITH", "STARTSWITH"]
195
+ arg_types = {"this": True, "expression": True}
196
+
197
+
198
+ class StrPosition(Expression, Func):
199
+ arg_types = {
200
+ "this": True,
201
+ "substr": True,
202
+ "position": False,
203
+ "occurrence": False,
204
+ "clamp_position": False,
205
+ }
206
+
207
+
208
+ class StrToMap(Expression, Func):
209
+ arg_types = {
210
+ "this": True,
211
+ "pair_delim": False,
212
+ "key_value_delim": False,
213
+ "duplicate_resolution_callback": False,
214
+ }
215
+
216
+
217
+ class String(Expression, Func):
218
+ arg_types = {"this": True, "zone": False}
219
+
220
+
221
+ class Stuff(Expression, Func):
222
+ _sql_names = ["STUFF", "INSERT"]
223
+ arg_types = {"this": True, "start": True, "length": True, "expression": True}
224
+
225
+
226
+ class Substring(Expression, Func):
227
+ _sql_names = ["SUBSTRING", "SUBSTR"]
228
+ arg_types = {"this": True, "start": False, "length": False, "zero_start": False}
229
+
230
+
231
+ class SubstringIndex(Expression, Func):
232
+ """
233
+ SUBSTRING_INDEX(str, delim, count)
234
+
235
+ *count* > 0 → left slice before the *count*-th delimiter
236
+ *count* < 0 → right slice after the |count|-th delimiter
237
+ """
238
+
239
+ arg_types = {"this": True, "delimiter": True, "count": True}
240
+
241
+
242
+ class Translate(Expression, Func):
243
+ arg_types = {"this": True, "from_": True, "to": True}
244
+
245
+
246
+ class Trim(Expression, Func):
247
+ arg_types = {
248
+ "this": True,
249
+ "expression": False,
250
+ "position": False,
251
+ "collation": False,
252
+ }
253
+
254
+
255
+ class Unicode(Expression, Func):
256
+ arg_types = {"this": True, "empty_is_zero": False}
257
+
258
+
259
+ class Upper(Expression, Func):
260
+ _sql_names = ["UPPER", "UCASE"]
261
+
262
+
263
+ class WeightString(Expression, Func):
264
+ arg_types = {"this": True, "to": False}
265
+
266
+
267
+ # Encoding / base conversion
268
+
269
+
270
+ class Base64DecodeBinary(Expression, Func):
271
+ arg_types = {"this": True, "alphabet": False}
272
+
273
+
274
+ class Base64DecodeString(Expression, Func):
275
+ arg_types = {"this": True, "alphabet": False}
276
+
277
+
278
+ class Base64Encode(Expression, Func):
279
+ arg_types = {"this": True, "max_line_length": False, "alphabet": False}
280
+
281
+
282
+ class CodePointsToBytes(Expression, Func):
283
+ pass
284
+
285
+
286
+ class CodePointsToString(Expression, Func):
287
+ pass
288
+
289
+
290
+ class ConvertToCharset(Expression, Func):
291
+ arg_types = {"this": True, "dest": True, "source": False}
292
+
293
+
294
+ class Decode(Expression, Func):
295
+ arg_types = {"this": True, "charset": True, "replace": False}
296
+
297
+
298
+ class Encode(Expression, Func):
299
+ arg_types = {"this": True, "charset": True}
300
+
301
+
302
+ class FromBase(Expression, Func):
303
+ arg_types = {"this": True, "expression": True}
304
+
305
+
306
+ class FromBase32(Expression, Func):
307
+ pass
308
+
309
+
310
+ class FromBase64(Expression, Func):
311
+ pass
312
+
313
+
314
+ class Hex(Expression, Func):
315
+ arg_types = {"this": True, "case": False}
316
+
317
+
318
+ class HexDecodeString(Expression, Func):
319
+ pass
320
+
321
+
322
+ class LowerHex(Hex):
323
+ pass
324
+
325
+
326
+ class SafeConvertBytesToString(Expression, Func):
327
+ pass
328
+
329
+
330
+ class ToBase32(Expression, Func):
331
+ pass
332
+
333
+
334
+ class ToBase64(Expression, Func):
335
+ pass
336
+
337
+
338
+ class ToBinary(Expression, Func):
339
+ arg_types = {"this": True, "format": False, "safe": False}
340
+
341
+
342
+ class ToChar(Expression, Func):
343
+ arg_types = {
344
+ "this": True,
345
+ "format": False,
346
+ "nlsparam": False,
347
+ "is_numeric": False,
348
+ }
349
+
350
+
351
+ class ToCodePoints(Expression, Func):
352
+ pass
353
+
354
+
355
+ class ToDecfloat(Expression, Func):
356
+ arg_types = {
357
+ "this": True,
358
+ "format": False,
359
+ }
360
+
361
+
362
+ class ToDouble(Expression, Func):
363
+ arg_types = {
364
+ "this": True,
365
+ "format": False,
366
+ "safe": False,
367
+ }
368
+
369
+
370
+ class ToFile(Expression, Func):
371
+ arg_types = {
372
+ "this": True,
373
+ "path": False,
374
+ "safe": False,
375
+ }
376
+
377
+
378
+ class ToNumber(Expression, Func):
379
+ arg_types = {
380
+ "this": True,
381
+ "format": False,
382
+ "nlsparam": False,
383
+ "precision": False,
384
+ "scale": False,
385
+ "safe": False,
386
+ "safe_name": False,
387
+ "default": False,
388
+ }
389
+
390
+
391
+ class TryBase64DecodeBinary(Expression, Func):
392
+ arg_types = {"this": True, "alphabet": False}
393
+
394
+
395
+ class TryBase64DecodeString(Expression, Func):
396
+ arg_types = {"this": True, "alphabet": False}
397
+
398
+
399
+ class TryHexDecodeBinary(Expression, Func):
400
+ pass
401
+
402
+
403
+ class TryHexDecodeString(Expression, Func):
404
+ pass
405
+
406
+
407
+ class TryToDecfloat(Expression, Func):
408
+ arg_types = {
409
+ "this": True,
410
+ "format": False,
411
+ }
412
+
413
+
414
+ class Unhex(Expression, Func):
415
+ arg_types = {"this": True, "expression": False}
416
+
417
+
418
+ # Regex
419
+
420
+
421
+ class RegexpCount(Expression, Func):
422
+ arg_types = {
423
+ "this": True,
424
+ "expression": True,
425
+ "position": False,
426
+ "parameters": False,
427
+ }
428
+
429
+
430
+ class RegexpExtract(Expression, Func):
431
+ arg_types = {
432
+ "this": True,
433
+ "expression": True,
434
+ "position": False,
435
+ "occurrence": False,
436
+ "parameters": False,
437
+ "group": False,
438
+ "null_if_pos_overflow": False, # for transpilation target behavior
439
+ }
440
+
441
+
442
+ class RegexpExtractAll(Expression, Func):
443
+ arg_types = {
444
+ "this": True,
445
+ "expression": True,
446
+ "group": False,
447
+ "parameters": False,
448
+ "position": False,
449
+ "occurrence": False,
450
+ }
451
+
452
+
453
+ class RegexpFullMatch(Expression, Binary, Predicate, Func):
454
+ arg_types = {"this": True, "expression": True, "options": False}
455
+
456
+
457
+ class RegexpILike(Expression, Binary, Predicate, Func):
458
+ arg_types = {"this": True, "expression": True, "flag": False}
459
+
460
+
461
+ class RegexpInstr(Expression, Func):
462
+ arg_types = {
463
+ "this": True,
464
+ "expression": True,
465
+ "position": False,
466
+ "occurrence": False,
467
+ "option": False,
468
+ "parameters": False,
469
+ "group": False,
470
+ }
471
+
472
+
473
+ class RegexpReplace(Expression, Func):
474
+ arg_types = {
475
+ "this": True,
476
+ "expression": True,
477
+ "replacement": False,
478
+ "position": False,
479
+ "occurrence": False,
480
+ "modifiers": False,
481
+ "single_replace": False,
482
+ }
483
+
484
+
485
+ class RegexpSplit(Expression, Func):
486
+ # "mode" is Dremio-specific, appended after "limit" for from_arg_list compat
487
+ arg_types = {"this": True, "expression": True, "limit": False, "mode": False}
488
+
489
+
490
+ class RegexpSubstr(Expression, Func):
491
+ arg_types = {
492
+ "this": True,
493
+ "expression": True,
494
+ "position": False,
495
+ "occurrence": False,
496
+ "parameters": False,
497
+ "group": False,
498
+ }
499
+
500
+
501
+ # Hashing / cryptographic
502
+
503
+
504
+ class Compress(Expression, Func):
505
+ arg_types = {"this": True, "method": False}
506
+
507
+
508
+ class Decrypt(Expression, Func):
509
+ arg_types = {
510
+ "this": True,
511
+ "passphrase": True,
512
+ "aad": False,
513
+ "encryption_method": False,
514
+ "safe": False,
515
+ }
516
+
517
+
518
+ class DecryptRaw(Expression, Func):
519
+ arg_types = {
520
+ "this": True,
521
+ "key": True,
522
+ "iv": True,
523
+ "aad": False,
524
+ "encryption_method": False,
525
+ "aead": False,
526
+ "safe": False,
527
+ }
528
+
529
+
530
+ class DecompressBinary(Expression, Func):
531
+ arg_types = {"this": True, "method": True}
532
+
533
+
534
+ class DecompressString(Expression, Func):
535
+ arg_types = {"this": True, "method": True}
536
+
537
+
538
+ class Encrypt(Expression, Func):
539
+ arg_types = {"this": True, "passphrase": True, "aad": False, "encryption_method": False}
540
+
541
+
542
+ class EncryptRaw(Expression, Func):
543
+ arg_types = {"this": True, "key": True, "iv": True, "aad": False, "encryption_method": False}
544
+
545
+
546
+ class CityHash64(Expression, Func):
547
+ arg_types = {"expressions": False}
548
+ is_var_len_args = True
549
+
550
+
551
+ class FarmFingerprint(Expression, Func):
552
+ arg_types = {"expressions": True}
553
+ is_var_len_args = True
554
+ _sql_names = ["FARM_FINGERPRINT", "FARMFINGERPRINT64"]
555
+
556
+
557
+ class MD5(Expression, Func):
558
+ _sql_names = ["MD5"]
559
+
560
+
561
+ class MD5Digest(Expression, Func):
562
+ arg_types = {"this": True, "expressions": False}
563
+ is_var_len_args = True
564
+ _sql_names = ["MD5_DIGEST"]
565
+
566
+
567
+ class MD5NumberLower64(Expression, Func):
568
+ pass
569
+
570
+
571
+ class MD5NumberUpper64(Expression, Func):
572
+ pass
573
+
574
+
575
+ class SHA(Expression, Func):
576
+ _sql_names = ["SHA", "SHA1"]
577
+
578
+
579
+ class SHA1Digest(Expression, Func):
580
+ pass
581
+
582
+
583
+ class SHA2(Expression, Func):
584
+ _sql_names = ["SHA2"]
585
+ arg_types = {"this": True, "length": False}
586
+
587
+
588
+ class SHA2Digest(Expression, Func):
589
+ arg_types = {"this": True, "length": False}
590
+
591
+
592
+ class StandardHash(Expression, Func):
593
+ arg_types = {"this": True, "expression": False}
594
+
595
+
596
+ # Parse
597
+
598
+
599
+ class ParseBignumeric(Expression, Func):
600
+ pass
601
+
602
+
603
+ class ParseNumeric(Expression, Func):
604
+ pass
605
+
606
+
607
+ class ParseUrl(Expression, Func):
608
+ arg_types = {"this": True, "part_to_extract": False, "key": False, "permissive": False}
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/expressions/temporal.py ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sqlglot expressions - date, time, and timestamp functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typing as t
6
+
7
+ from sqlglot.expressions.core import (
8
+ Expression,
9
+ Func,
10
+ TimeUnit,
11
+ IntervalOp,
12
+ Literal,
13
+ Column,
14
+ TIMESTAMP_PARTS,
15
+ )
16
+ from sqlglot.expressions.datatypes import DataType, DType
17
+
18
+ if t.TYPE_CHECKING:
19
+ from sqlglot.expressions.core import Expr, Neg
20
+
21
+
22
+ # Current date/time
23
+
24
+
25
+ class CurrentDate(Expression, Func):
26
+ arg_types = {"this": False}
27
+
28
+
29
+ class CurrentDatetime(Expression, Func):
30
+ arg_types = {"this": False}
31
+
32
+
33
+ class CurrentTime(Expression, Func):
34
+ arg_types = {"this": False}
35
+
36
+
37
+ class CurrentTimestamp(Expression, Func):
38
+ arg_types = {"this": False, "sysdate": False}
39
+
40
+
41
+ class CurrentTimestampLTZ(Expression, Func):
42
+ arg_types = {}
43
+
44
+
45
+ class CurrentTimezone(Expression, Func):
46
+ arg_types = {}
47
+
48
+
49
+ class Localtime(Expression, Func):
50
+ arg_types = {"this": False}
51
+
52
+
53
+ class Localtimestamp(Expression, Func):
54
+ arg_types = {"this": False}
55
+
56
+
57
+ class Systimestamp(Expression, Func):
58
+ arg_types = {"this": False}
59
+
60
+
61
+ class UtcDate(Expression, Func):
62
+ arg_types = {}
63
+
64
+
65
+ class UtcTime(Expression, Func):
66
+ arg_types = {"this": False}
67
+
68
+
69
+ class UtcTimestamp(Expression, Func):
70
+ arg_types = {"this": False}
71
+
72
+
73
+ # Date arithmetic
74
+
75
+
76
+ class AddMonths(Expression, Func):
77
+ arg_types = {"this": True, "expression": True, "preserve_end_of_month": False}
78
+
79
+
80
+ class DateAdd(Expression, Func, IntervalOp):
81
+ arg_types = {"this": True, "expression": True, "unit": False}
82
+
83
+
84
+ class DateBin(Expression, Func, IntervalOp):
85
+ arg_types = {"this": True, "expression": True, "unit": False, "zone": False, "origin": False}
86
+
87
+
88
+ class DateDiff(Expression, Func, TimeUnit):
89
+ _sql_names = ["DATEDIFF", "DATE_DIFF"]
90
+ arg_types = {
91
+ "this": True,
92
+ "expression": True,
93
+ "unit": False,
94
+ "zone": False,
95
+ "big_int": False,
96
+ "date_part_boundary": False,
97
+ }
98
+
99
+
100
+ class DateSub(Expression, Func, IntervalOp):
101
+ arg_types = {"this": True, "expression": True, "unit": False}
102
+
103
+
104
+ class DatetimeAdd(Expression, Func, IntervalOp):
105
+ arg_types = {"this": True, "expression": True, "unit": False}
106
+
107
+
108
+ class DatetimeDiff(Expression, Func, TimeUnit):
109
+ arg_types = {"this": True, "expression": True, "unit": False, "date_part_boundary": False}
110
+
111
+
112
+ class DatetimeSub(Expression, Func, IntervalOp):
113
+ arg_types = {"this": True, "expression": True, "unit": False}
114
+
115
+
116
+ class MonthsBetween(Expression, Func):
117
+ arg_types = {"this": True, "expression": True, "roundoff": False}
118
+
119
+
120
+ class TimeAdd(Expression, Func, TimeUnit):
121
+ arg_types = {"this": True, "expression": True, "unit": False}
122
+
123
+
124
+ class TimeDiff(Expression, Func, TimeUnit):
125
+ arg_types = {"this": True, "expression": True, "unit": False}
126
+
127
+
128
+ class TimeSub(Expression, Func, TimeUnit):
129
+ arg_types = {"this": True, "expression": True, "unit": False}
130
+
131
+
132
+ class TimestampAdd(Expression, Func, TimeUnit):
133
+ arg_types = {"this": True, "expression": True, "unit": False}
134
+
135
+
136
+ class TimestampDiff(Expression, Func, TimeUnit):
137
+ _sql_names = ["TIMESTAMPDIFF", "TIMESTAMP_DIFF"]
138
+ arg_types = {"this": True, "expression": True, "unit": False}
139
+
140
+
141
+ class TimestampSub(Expression, Func, TimeUnit):
142
+ arg_types = {"this": True, "expression": True, "unit": False}
143
+
144
+
145
+ class TsOrDsAdd(Expression, Func, TimeUnit):
146
+ # return_type is used to correctly cast the arguments of this expression when transpiling it
147
+ arg_types = {"this": True, "expression": True, "unit": False, "return_type": False}
148
+
149
+ @property
150
+ def return_type(self) -> DataType:
151
+ return DataType.build(self.args.get("return_type") or DType.DATE)
152
+
153
+
154
+ class TsOrDsDiff(Expression, Func, TimeUnit):
155
+ arg_types = {"this": True, "expression": True, "unit": False}
156
+
157
+
158
+ # Truncation
159
+
160
+
161
+ class DatetimeTrunc(Expression, Func, TimeUnit):
162
+ arg_types = {"this": True, "unit": True, "zone": False}
163
+
164
+
165
+ class DateTrunc(Expression, Func):
166
+ arg_types = {"unit": True, "this": True, "zone": False, "input_type_preserved": False}
167
+
168
+ def __init__(self, **args):
169
+ # Across most dialects it's safe to unabbreviate the unit (e.g. 'Q' -> 'QUARTER') except Oracle
170
+ # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html
171
+ unabbreviate = args.pop("unabbreviate", True)
172
+
173
+ unit = args.get("unit")
174
+ if isinstance(unit, TimeUnit.VAR_LIKE) and not (
175
+ isinstance(unit, Column) and len(unit.parts) != 1
176
+ ):
177
+ unit_name = unit.name.upper()
178
+ if unabbreviate and unit_name in TimeUnit.UNABBREVIATED_UNIT_NAME:
179
+ unit_name = TimeUnit.UNABBREVIATED_UNIT_NAME[unit_name]
180
+
181
+ args["unit"] = Literal.string(unit_name)
182
+
183
+ super().__init__(**args)
184
+
185
+ @property
186
+ def unit(self) -> Expr:
187
+ return self.args["unit"]
188
+
189
+
190
+ class TimestampTrunc(Expression, Func, TimeUnit):
191
+ arg_types = {"this": True, "unit": True, "zone": False, "input_type_preserved": False}
192
+
193
+
194
+ class TimeSlice(Expression, Func, TimeUnit):
195
+ arg_types = {"this": True, "expression": True, "unit": True, "kind": False}
196
+
197
+
198
+ class TimeTrunc(Expression, Func, TimeUnit):
199
+ arg_types = {"this": True, "unit": True, "zone": False}
200
+
201
+
202
+ # Date/time extraction
203
+
204
+
205
+ class Day(Expression, Func):
206
+ pass
207
+
208
+
209
+ class DayOfMonth(Expression, Func):
210
+ _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
211
+
212
+
213
+ class DayOfWeek(Expression, Func):
214
+ _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
215
+
216
+
217
+ class DayOfWeekIso(Expression, Func):
218
+ _sql_names = ["DAYOFWEEK_ISO", "ISODOW"]
219
+
220
+
221
+ class DayOfYear(Expression, Func):
222
+ _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
223
+
224
+
225
+ class Dayname(Expression, Func):
226
+ arg_types = {"this": True, "abbreviated": False}
227
+
228
+
229
+ class Extract(Expression, Func):
230
+ arg_types = {"this": True, "expression": True}
231
+
232
+
233
+ class GetExtract(Expression, Func):
234
+ arg_types = {"this": True, "expression": True}
235
+
236
+
237
+ class Hour(Expression, Func):
238
+ pass
239
+
240
+
241
+ class Minute(Expression, Func):
242
+ pass
243
+
244
+
245
+ class Month(Expression, Func):
246
+ pass
247
+
248
+
249
+ class Monthname(Expression, Func):
250
+ arg_types = {"this": True, "abbreviated": False}
251
+
252
+
253
+ class Quarter(Expression, Func):
254
+ pass
255
+
256
+
257
+ class Second(Expression, Func):
258
+ pass
259
+
260
+
261
+ class ToDays(Expression, Func):
262
+ pass
263
+
264
+
265
+ class Week(Expression, Func):
266
+ arg_types = {"this": True, "mode": False}
267
+
268
+
269
+ class WeekOfYear(Expression, Func):
270
+ _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
271
+
272
+
273
+ class Year(Expression, Func):
274
+ pass
275
+
276
+
277
+ class YearOfWeek(Expression, Func):
278
+ _sql_names = ["YEAR_OF_WEEK", "YEAROFWEEK"]
279
+
280
+
281
+ class YearOfWeekIso(Expression, Func):
282
+ _sql_names = ["YEAR_OF_WEEK_ISO", "YEAROFWEEKISO"]
283
+
284
+
285
+ # Date/time construction
286
+
287
+
288
+ class Date(Expression, Func):
289
+ arg_types = {"this": False, "zone": False, "expressions": False}
290
+ is_var_len_args = True
291
+
292
+
293
+ class DateFromParts(Expression, Func):
294
+ _sql_names = ["DATE_FROM_PARTS", "DATEFROMPARTS"]
295
+ arg_types = {"year": True, "month": False, "day": False, "allow_overflow": False}
296
+
297
+
298
+ class DateFromUnixDate(Expression, Func):
299
+ pass
300
+
301
+
302
+ class Datetime(Expression, Func):
303
+ arg_types = {"this": True, "expression": False}
304
+
305
+
306
+ class GapFill(Expression, Func):
307
+ arg_types = {
308
+ "this": True,
309
+ "ts_column": True,
310
+ "bucket_width": True,
311
+ "partitioning_columns": False,
312
+ "value_columns": False,
313
+ "origin": False,
314
+ "ignore_nulls": False,
315
+ }
316
+
317
+
318
+ class GenerateDateArray(Expression, Func):
319
+ arg_types = {"start": True, "end": True, "step": False}
320
+
321
+
322
+ class GenerateTimestampArray(Expression, Func):
323
+ arg_types = {"start": True, "end": True, "step": True}
324
+
325
+
326
+ class JustifyDays(Expression, Func):
327
+ pass
328
+
329
+
330
+ class JustifyHours(Expression, Func):
331
+ pass
332
+
333
+
334
+ class JustifyInterval(Expression, Func):
335
+ pass
336
+
337
+
338
+ class LastDay(Expression, Func, TimeUnit):
339
+ _sql_names = ["LAST_DAY", "LAST_DAY_OF_MONTH"]
340
+ arg_types = {"this": True, "unit": False}
341
+
342
+
343
+ class MakeInterval(Expression, Func):
344
+ arg_types = {
345
+ "year": False,
346
+ "month": False,
347
+ "week": False,
348
+ "day": False,
349
+ "hour": False,
350
+ "minute": False,
351
+ "second": False,
352
+ }
353
+
354
+
355
+ class NextDay(Expression, Func):
356
+ arg_types = {"this": True, "expression": True}
357
+
358
+
359
+ class PreviousDay(Expression, Func):
360
+ arg_types = {"this": True, "expression": True}
361
+
362
+
363
+ class Time(Expression, Func):
364
+ arg_types = {"this": False, "zone": False}
365
+
366
+
367
+ class TimeFromParts(Expression, Func):
368
+ _sql_names = ["TIME_FROM_PARTS", "TIMEFROMPARTS"]
369
+ arg_types = {
370
+ "hour": True,
371
+ "min": True,
372
+ "sec": True,
373
+ "nano": False,
374
+ "fractions": False,
375
+ "precision": False,
376
+ "overflow": False,
377
+ }
378
+
379
+
380
+ class Timestamp(Expression, Func):
381
+ arg_types = {"this": False, "zone": False, "with_tz": False}
382
+
383
+
384
+ class TimestampFromParts(Expression, Func):
385
+ _sql_names = ["TIMESTAMP_FROM_PARTS", "TIMESTAMPFROMPARTS"]
386
+ arg_types = {
387
+ **TIMESTAMP_PARTS,
388
+ "zone": False,
389
+ "milli": False,
390
+ "this": False,
391
+ "expression": False,
392
+ }
393
+
394
+
395
+ class TimestampLtzFromParts(Expression, Func):
396
+ _sql_names = ["TIMESTAMP_LTZ_FROM_PARTS", "TIMESTAMPLTZFROMPARTS"]
397
+ arg_types = TIMESTAMP_PARTS.copy()
398
+
399
+
400
+ class TimestampTzFromParts(Expression, Func):
401
+ _sql_names = ["TIMESTAMP_TZ_FROM_PARTS", "TIMESTAMPTZFROMPARTS"]
402
+ arg_types = {
403
+ **TIMESTAMP_PARTS,
404
+ "zone": False,
405
+ }
406
+
407
+
408
+ # Date/time conversion
409
+
410
+
411
+ class ConvertTimezone(Expression, Func):
412
+ arg_types = {
413
+ "source_tz": False,
414
+ "target_tz": True,
415
+ "timestamp": True,
416
+ "options": False,
417
+ }
418
+
419
+
420
+ class DateStrToDate(Expression, Func):
421
+ pass
422
+
423
+
424
+ class DateToDateStr(Expression, Func):
425
+ pass
426
+
427
+
428
+ class DateToDi(Expression, Func):
429
+ pass
430
+
431
+
432
+ class DiToDate(Expression, Func):
433
+ pass
434
+
435
+
436
+ class FromISO8601Timestamp(Expression, Func):
437
+ _sql_names = ["FROM_ISO8601_TIMESTAMP"]
438
+
439
+
440
+ class FromISO8601Date(Expression, Func):
441
+ _sql_names = ["FROM_ISO8601_DATE"]
442
+
443
+
444
+ class FromISO8601TimestampNanos(Expression, Func):
445
+ _sql_names = ["FROM_ISO8601_TIMESTAMP_NANOS"]
446
+
447
+
448
+ class ParseDatetime(Expression, Func):
449
+ arg_types = {"this": True, "format": False, "zone": False, "default_year": False}
450
+
451
+
452
+ class ParseTime(Expression, Func):
453
+ arg_types = {"this": True, "format": True}
454
+
455
+
456
+ class StrToDate(Expression, Func):
457
+ arg_types = {"this": True, "format": False, "safe": False, "default_year": False}
458
+
459
+
460
+ class StrToTime(Expression, Func):
461
+ arg_types = {
462
+ "this": True,
463
+ "format": True,
464
+ "zone": False,
465
+ "safe": False,
466
+ "target_type": False,
467
+ "default_year": False,
468
+ }
469
+
470
+
471
+ class StrToUnix(Expression, Func):
472
+ arg_types = {"this": False, "format": False}
473
+
474
+
475
+ class TimeStrToDate(Expression, Func):
476
+ pass
477
+
478
+
479
+ class TimeStrToTime(Expression, Func):
480
+ arg_types = {"this": True, "zone": False}
481
+
482
+
483
+ class TimeStrToUnix(Expression, Func):
484
+ pass
485
+
486
+
487
+ class TimeToStr(Expression, Func):
488
+ arg_types = {"this": True, "format": True, "culture": False, "zone": False}
489
+
490
+
491
+ class TimeToTimeStr(Expression, Func):
492
+ pass
493
+
494
+
495
+ class TimeToUnix(Expression, Func):
496
+ pass
497
+
498
+
499
+ class TsOrDiToDi(Expression, Func):
500
+ pass
501
+
502
+
503
+ class TsOrDsToDate(Expression, Func):
504
+ arg_types = {"this": True, "format": False, "safe": False, "default_date": False}
505
+
506
+
507
+ class TsOrDsToDateStr(Expression, Func):
508
+ pass
509
+
510
+
511
+ class TsOrDsToDatetime(Expression, Func):
512
+ pass
513
+
514
+
515
+ class TsOrDsToTime(Expression, Func):
516
+ arg_types = {"this": True, "format": False, "safe": False}
517
+
518
+
519
+ class TsOrDsToTimestamp(Expression, Func):
520
+ pass
521
+
522
+
523
+ class UnixDate(Expression, Func):
524
+ pass
525
+
526
+
527
+ class UnixMicros(Expression, Func):
528
+ pass
529
+
530
+
531
+ class UnixMillis(Expression, Func):
532
+ pass
533
+
534
+
535
+ class UnixSeconds(Expression, Func):
536
+ pass
537
+
538
+
539
+ class UnixToStr(Expression, Func):
540
+ arg_types = {"this": True, "format": False}
541
+
542
+
543
+ class UnixToTime(Expression, Func):
544
+ arg_types = {
545
+ "this": True,
546
+ "scale": False,
547
+ "zone": False,
548
+ "hours": False,
549
+ "minutes": False,
550
+ "format": False,
551
+ "target_type": False,
552
+ }
553
+
554
+ SECONDS: t.ClassVar[Literal | Neg] = Literal.number(0)
555
+ DECIS: t.ClassVar[Literal | Neg] = Literal.number(1)
556
+ CENTIS: t.ClassVar[Literal | Neg] = Literal.number(2)
557
+ MILLIS: t.ClassVar[Literal | Neg] = Literal.number(3)
558
+ DECIMILLIS: t.ClassVar[Literal | Neg] = Literal.number(4)
559
+ CENTIMILLIS: t.ClassVar[Literal | Neg] = Literal.number(5)
560
+ MICROS: t.ClassVar[Literal | Neg] = Literal.number(6)
561
+ DECIMICROS: t.ClassVar[Literal | Neg] = Literal.number(7)
562
+ CENTIMICROS: t.ClassVar[Literal | Neg] = Literal.number(8)
563
+ NANOS: t.ClassVar[Literal | Neg] = Literal.number(9)
564
+
565
+
566
+ class UnixToTimeStr(Expression, Func):
567
+ pass
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generator.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/__init__.py ADDED
File without changes
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/athena.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing as t
4
+
5
+ from sqlglot import exp, generator
6
+ from sqlglot.generators.hive import HiveGenerator
7
+ from sqlglot.generators.trino import TrinoGenerator
8
+
9
+
10
+ def _is_iceberg_table(properties: exp.Properties) -> bool:
11
+ for p in properties.expressions:
12
+ if isinstance(p, exp.Property) and p.name == "table_type":
13
+ return p.text("value").lower() == "iceberg"
14
+
15
+ return False
16
+
17
+
18
+ def _location_property_sql(self: AthenaTrinoGenerator, e: exp.LocationProperty) -> str:
19
+ # If table_type='iceberg', the LocationProperty is called 'location'
20
+ # Otherwise, it's called 'external_location'
21
+ # ref: https://docs.aws.amazon.com/athena/latest/ug/create-table-as.html
22
+
23
+ prop_name = "external_location"
24
+
25
+ if isinstance(e.parent, exp.Properties):
26
+ if _is_iceberg_table(e.parent):
27
+ prop_name = "location"
28
+
29
+ return f"{prop_name}={self.sql(e, 'this')}"
30
+
31
+
32
+ def _partitioned_by_property_sql(self: AthenaTrinoGenerator, e: exp.PartitionedByProperty) -> str:
33
+ # If table_type='iceberg' then the table property for partitioning is called 'partitioning'
34
+ # If table_type='hive' it's called 'partitioned_by'
35
+ # ref: https://docs.aws.amazon.com/athena/latest/ug/create-table-as.html#ctas-table-properties
36
+
37
+ prop_name = "partitioned_by"
38
+
39
+ if isinstance(e.parent, exp.Properties):
40
+ if _is_iceberg_table(e.parent):
41
+ prop_name = "partitioning"
42
+
43
+ return f"{prop_name}={self.sql(e, 'this')}"
44
+
45
+
46
+ def _generate_as_hive(expression: exp.Expr) -> bool:
47
+ if isinstance(expression, exp.Create):
48
+ if expression.kind == "TABLE":
49
+ properties = expression.args.get("properties")
50
+
51
+ # CREATE EXTERNAL TABLE is Hive
52
+ if properties and properties.find(exp.ExternalProperty):
53
+ return True
54
+
55
+ # Any CREATE TABLE other than CREATE TABLE ... As <query> is Hive
56
+ if not isinstance(expression.expression, exp.Query):
57
+ # CTAS with a leading USING EXTERNAL FUNCTION clause is Trino
58
+ return not (
59
+ isinstance(expression.expression, exp.Command)
60
+ and expression.expression.text("this").upper() == "USING"
61
+ )
62
+ else:
63
+ # CREATE VIEW is Trino, but CREATE SCHEMA, CREATE DATABASE, etc, is Hive
64
+ return expression.kind != "VIEW"
65
+ elif isinstance(expression, (exp.Alter, exp.Drop, exp.Describe, exp.Show)):
66
+ if isinstance(expression, exp.Drop) and expression.kind == "VIEW":
67
+ # DROP VIEW is Trino, because CREATE VIEW is as well
68
+ return False
69
+
70
+ # Everything else, e.g., ALTER statements, is Hive
71
+ return True
72
+
73
+ return False
74
+
75
+
76
+ def _generator_kwargs(
77
+ pretty: bool | int | None,
78
+ identify: str | bool,
79
+ normalize: bool,
80
+ pad: int,
81
+ indent: int,
82
+ normalize_functions: str | bool | None,
83
+ unsupported_level: t.Any,
84
+ max_unsupported: int,
85
+ leading_comma: bool,
86
+ max_text_width: int,
87
+ comments: bool,
88
+ ) -> dict[str, t.Any]:
89
+ kwargs: dict[str, t.Any] = {
90
+ "pretty": pretty,
91
+ "identify": identify,
92
+ "normalize": normalize,
93
+ "pad": pad,
94
+ "indent": indent,
95
+ "normalize_functions": normalize_functions,
96
+ "max_unsupported": max_unsupported,
97
+ "leading_comma": leading_comma,
98
+ "max_text_width": max_text_width,
99
+ "comments": comments,
100
+ }
101
+ if unsupported_level is not None:
102
+ kwargs["unsupported_level"] = unsupported_level
103
+ return kwargs
104
+
105
+
106
+ class _HiveGenerator(HiveGenerator):
107
+ def alter_sql(self, expression: exp.Alter) -> str:
108
+ if isinstance(expression, exp.Alter) and expression.kind == "TABLE":
109
+ if expression.actions and isinstance(expression.actions[0], exp.ColumnDef):
110
+ new_actions = exp.Schema(expressions=expression.actions)
111
+ expression.set("actions", [new_actions])
112
+
113
+ return super().alter_sql(expression)
114
+
115
+
116
+ class AthenaTrinoGenerator(TrinoGenerator):
117
+ PROPERTIES_LOCATION = {
118
+ **TrinoGenerator.PROPERTIES_LOCATION,
119
+ exp.LocationProperty: exp.Properties.Location.POST_WITH,
120
+ }
121
+
122
+ TRANSFORMS = {
123
+ **TrinoGenerator.TRANSFORMS,
124
+ exp.PartitionedByProperty: _partitioned_by_property_sql,
125
+ exp.LocationProperty: _location_property_sql,
126
+ }
127
+
128
+
129
+ class AthenaGenerator(AthenaTrinoGenerator):
130
+ SELECT_KINDS: tuple[str, ...] = ()
131
+ SUPPORTS_DECODE_CASE = False
132
+
133
+ AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
134
+
135
+ __slots__ = ("_hive_generator", "_trino_generator")
136
+
137
+ def __init__(
138
+ self,
139
+ pretty: bool | int | None = None,
140
+ identify: str | bool = False,
141
+ normalize: bool = False,
142
+ pad: int = 2,
143
+ indent: int = 2,
144
+ normalize_functions: str | bool | None = None,
145
+ unsupported_level: t.Any = None,
146
+ max_unsupported: int = 3,
147
+ leading_comma: bool = False,
148
+ max_text_width: int = 80,
149
+ comments: bool = True,
150
+ dialect: t.Any = None,
151
+ hive: t.Any = None,
152
+ trino: t.Any = None,
153
+ ) -> None:
154
+ import sqlglot.dialects.hive as hive_mod
155
+ import sqlglot.dialects.trino as trino_mod
156
+
157
+ hive_dialect = hive or hive_mod.Hive()
158
+ trino_dialect = trino or trino_mod.Trino()
159
+
160
+ kwargs = _generator_kwargs(
161
+ pretty,
162
+ identify,
163
+ normalize,
164
+ pad,
165
+ indent,
166
+ normalize_functions,
167
+ unsupported_level,
168
+ max_unsupported,
169
+ leading_comma,
170
+ max_text_width,
171
+ comments,
172
+ )
173
+
174
+ generator.Generator.__init__(self, dialect=dialect, **kwargs)
175
+ self._hive_generator: generator.Generator = _HiveGenerator(dialect=hive_dialect, **kwargs)
176
+ self._trino_generator: generator.Generator = AthenaTrinoGenerator(
177
+ dialect=trino_dialect, **kwargs
178
+ )
179
+
180
+ def generate(self, expression: exp.Expr, copy: bool = True) -> str:
181
+ if _generate_as_hive(expression):
182
+ return self._hive_generator.generate(expression, copy=copy)
183
+
184
+ return self._trino_generator.generate(expression, copy=copy)
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/bigquery.py ADDED
@@ -0,0 +1,881 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import re
5
+ import typing as t
6
+ from decimal import Decimal
7
+ from fractions import Fraction
8
+
9
+ from sqlglot import exp, generator, transforms
10
+ from sqlglot.dialects.dialect import (
11
+ arg_max_or_min_no_count,
12
+ array_sort_order,
13
+ date_add_interval_sql,
14
+ datestrtodate_sql,
15
+ filter_array_using_unnest,
16
+ generate_series_sql,
17
+ if_sql,
18
+ inline_array_unless_query,
19
+ max_or_greatest,
20
+ min_or_least,
21
+ no_filter_sql,
22
+ no_ilike_sql,
23
+ regexp_replace_sql,
24
+ rename_func,
25
+ sha256_sql,
26
+ timestrtotime_sql,
27
+ ts_or_ds_add_cast,
28
+ unit_to_var,
29
+ strposition_sql,
30
+ groupconcat_sql,
31
+ sha2_digest_sql,
32
+ )
33
+ from sqlglot.generator import unsupported_args
34
+ from sqlglot.helper import seq_get
35
+
36
+ logger = logging.getLogger("sqlglot")
37
+
38
+ JSON_EXTRACT_TYPE = t.Union[exp.JSONExtract, exp.JSONExtractScalar, exp.JSONExtractArray]
39
+
40
+ DQUOTES_ESCAPING_JSON_FUNCTIONS = ("JSON_QUERY", "JSON_VALUE", "JSON_QUERY_ARRAY")
41
+
42
+
43
+ def _derived_table_values_to_unnest(self: BigQueryGenerator, expression: exp.Values) -> str:
44
+ if not expression.find_ancestor(exp.From, exp.Join):
45
+ return self.values_sql(expression)
46
+
47
+ structs = []
48
+ alias = expression.args.get("alias")
49
+ for tup in expression.find_all(exp.Tuple):
50
+ field_aliases = (
51
+ alias.columns
52
+ if alias and alias.columns
53
+ else (f"_c{i}" for i in range(len(tup.expressions)))
54
+ )
55
+ expressions = [
56
+ exp.PropertyEQ(this=exp.to_identifier(name), expression=fld)
57
+ for name, fld in zip(field_aliases, tup.expressions)
58
+ ]
59
+ structs.append(exp.Struct(expressions=expressions))
60
+
61
+ # Due to `UNNEST_COLUMN_ONLY`, it is expected that the table alias be contained in the columns expression
62
+ alias_name_only = exp.TableAlias(columns=[alias.this]) if alias else None
63
+ return self.unnest_sql(
64
+ exp.Unnest(expressions=[exp.array(*structs, copy=False)], alias=alias_name_only)
65
+ )
66
+
67
+
68
+ def _returnsproperty_sql(self: BigQueryGenerator, expression: exp.ReturnsProperty) -> str:
69
+ this = expression.this
70
+ if isinstance(this, exp.Schema):
71
+ this = f"{self.sql(this, 'this')} <{self.expressions(this)}>"
72
+ else:
73
+ this = self.sql(this)
74
+ return f"RETURNS {this}"
75
+
76
+
77
+ def _create_sql(self: BigQueryGenerator, expression: exp.Create) -> str:
78
+ returns = expression.find(exp.ReturnsProperty)
79
+ if expression.kind == "FUNCTION" and returns and returns.args.get("is_table"):
80
+ expression.set("kind", "TABLE FUNCTION")
81
+
82
+ if isinstance(expression.expression, (exp.Subquery, exp.Literal)):
83
+ expression.set("expression", expression.expression.this)
84
+
85
+ return self.create_sql(expression)
86
+
87
+
88
+ # https://issuetracker.google.com/issues/162294746
89
+ # workaround for bigquery bug when grouping by an expression and then ordering
90
+ # WITH x AS (SELECT 1 y)
91
+ # SELECT y + 1 z
92
+ # FROM x
93
+ # GROUP BY x + 1
94
+ # ORDER by z
95
+ def _alias_ordered_group(expression: exp.Expr) -> exp.Expr:
96
+ if isinstance(expression, exp.Select):
97
+ group = expression.args.get("group")
98
+ order = expression.args.get("order")
99
+
100
+ if group and order:
101
+ aliases = {
102
+ select.this: select.args["alias"]
103
+ for select in expression.selects
104
+ if isinstance(select, exp.Alias)
105
+ }
106
+
107
+ for grouped in group.expressions:
108
+ if grouped.is_int:
109
+ continue
110
+ alias = aliases.get(grouped)
111
+ if alias:
112
+ grouped.replace(exp.column(alias))
113
+
114
+ return expression
115
+
116
+
117
+ def _pushdown_cte_column_names(expression: exp.Expr) -> exp.Expr:
118
+ """BigQuery doesn't allow column names when defining a CTE, so we try to push them down."""
119
+ if isinstance(expression, exp.CTE) and expression.alias_column_names:
120
+ cte_query = expression.this
121
+
122
+ if cte_query.is_star:
123
+ logger.warning(
124
+ "Can't push down CTE column names for star queries. Run the query through"
125
+ " the optimizer or use 'qualify' to expand the star projections first."
126
+ )
127
+ return expression
128
+
129
+ column_names = expression.alias_column_names
130
+ expression.args["alias"].set("columns", None)
131
+
132
+ for name, select in zip(column_names, cte_query.selects):
133
+ to_replace = select
134
+
135
+ if isinstance(select, exp.Alias):
136
+ select = select.this
137
+
138
+ # Inner aliases are shadowed by the CTE column names
139
+ to_replace.replace(exp.alias_(select, name))
140
+
141
+ return expression
142
+
143
+
144
+ def _unnest_explode_generate_series(expression: exp.Expr) -> exp.Expr:
145
+ """
146
+ Rewrites exploding GENERATE_SERIES projections into table references, e.g.
147
+
148
+ SELECT GENERATE_SERIES(1, 2) AS x -> SELECT x FROM GENERATE_SERIES(1, 2) AS x
149
+ SELECT y, GENERATE_SERIES(1, 2) AS x FROM t -> SELECT y, x FROM t CROSS JOIN GENERATE_SERIES(1, 2) AS x
150
+
151
+ since BigQuery can't explode in the projection and must unnest it in the FROM clause instead.
152
+ The resulting table reference is unnested downstream by `transforms.unnest_generate_series`.
153
+ """
154
+ if isinstance(expression, exp.Select):
155
+ for projection in expression.selects:
156
+ if isinstance(series := projection.unalias(), exp.ExplodingGenerateSeries):
157
+ column_name = projection.output_name or "_gen_series_value"
158
+
159
+ projection.replace(exp.column(column_name))
160
+ table = exp.Table(
161
+ this=series, alias=exp.TableAlias(this=exp.to_identifier(column_name))
162
+ )
163
+
164
+ if expression.args.get("from_"):
165
+ expression.join(table, copy=False, join_type="CROSS")
166
+ else:
167
+ expression.set("from_", exp.From(this=table))
168
+
169
+ return expression
170
+
171
+
172
+ def _array_contains_sql(self: BigQueryGenerator, expression: exp.ArrayContains) -> str:
173
+ return self.sql(
174
+ exp.Exists(
175
+ this=exp.select("1")
176
+ .from_(exp.Unnest(expressions=[expression.left]).as_("_unnest", table=["_col"]))
177
+ .where(exp.column("_col").eq(expression.right))
178
+ )
179
+ )
180
+
181
+
182
+ def _widen_decimal(expression: exp.Expr) -> exp.Expr:
183
+ # NUMERIC holds at most 29 integer and 9 fractional digits, e.g. DECIMAL(38, 0) needs BIGNUMERIC
184
+ for node in expression.find_all(exp.DataType):
185
+ if node.is_type(exp.DType.DECIMAL) and node.expressions:
186
+ precision, *rest = (param.this for param in node.expressions)
187
+ scale = rest[0] if rest else exp.Literal.number(0)
188
+ if precision.is_int and scale.is_int:
189
+ scale_digits = int(scale.name)
190
+ if int(precision.name) - scale_digits > 29 or scale_digits > 9:
191
+ node.set("this", exp.DType.BIGDECIMAL)
192
+ return expression
193
+
194
+
195
+ def _extract_part(part: str) -> t.Callable[[BigQueryGenerator, exp.Func], str]:
196
+ return lambda self, e: self.sql(exp.func("EXTRACT", exp.var(part), e.this, copy=False))
197
+
198
+
199
+ def _day_of_week_iso_sql(self: BigQueryGenerator, expression: exp.DayOfWeekIso) -> str:
200
+ # DAYOFWEEK is Sunday=1..Saturday=7, ISO is Monday=1..Sunday=7
201
+ template: exp.Expr = exp.maybe_parse("(MOD(EXTRACT(DAYOFWEEK FROM :this) + 5, 7) + 1)")
202
+ return self.sql(exp.replace_placeholders(template, this=expression.this))
203
+
204
+
205
+ def _array_agg_fold_sql(
206
+ self: BigQueryGenerator, expression: exp.ArrayDistinct | exp.ArraySort
207
+ ) -> str:
208
+ distinct = False
209
+ ignore_nulls = False
210
+ sort: exp.ArraySort | None = None
211
+ agg: exp.Expr = expression
212
+ while isinstance(agg, (exp.ArrayDistinct, exp.ArraySort)) and not agg.expression:
213
+ if isinstance(agg, exp.ArrayDistinct):
214
+ distinct = True
215
+ ignore_nulls |= agg.args.get("check_null") is False
216
+ elif sort is None:
217
+ sort = agg
218
+ agg = agg.this
219
+
220
+ order = array_sort_order(sort) if sort else None
221
+
222
+ # An ARRAY_AGG with its own ORDER BY or LIMIT can't take another
223
+ if (
224
+ not isinstance(agg, exp.ArrayAgg)
225
+ or isinstance(agg.this, (exp.Order, exp.Limit))
226
+ or (sort is not None and order is None)
227
+ ):
228
+ self.unsupported(
229
+ f"{expression.sql_name()} is only supported on an ARRAY_AGG without ORDER BY or LIMIT and with a literal order"
230
+ )
231
+ return self.func(expression.sql_name(), expression.this, expression.expression)
232
+
233
+ value = agg.this
234
+ if isinstance(value, exp.Distinct):
235
+ distinct, value = True, value.expressions[0]
236
+
237
+ folded: exp.Expr = exp.Distinct(expressions=[value]) if distinct else value
238
+ if order is not None:
239
+ asc, nulls_first = order
240
+ keys = [exp.Ordered(this=value.copy(), desc=not asc or None, nulls_first=asc)]
241
+
242
+ # Aggregate ORDER BY only puts NULLs first when ascending, so other placements need a key
243
+ if not ignore_nulls and nulls_first is not None and nulls_first != asc:
244
+ if distinct:
245
+ self.unsupported("ARRAY_AGG(DISTINCT) only puts NULLs first when ascending")
246
+ else:
247
+ is_null = value.copy().is_(exp.null())
248
+ keys.insert(
249
+ 0,
250
+ exp.Ordered(
251
+ this=is_null, desc=nulls_first or None, nulls_first=not nulls_first
252
+ ),
253
+ )
254
+ folded = exp.Order(this=folded, expressions=keys)
255
+ agg.set("this", folded)
256
+ if ignore_nulls:
257
+ # All-NULL input yields [], but an empty input still yields NULL.
258
+ agg = exp.If(
259
+ this=exp.Count(this=exp.Star()).eq(0),
260
+ true=exp.null(),
261
+ false=exp.func("COALESCE", exp.IgnoreNulls(this=agg), exp.array()),
262
+ )
263
+ return self.sql(agg)
264
+
265
+
266
+ def _ts_or_ds_add_sql(self: BigQueryGenerator, expression: exp.TsOrDsAdd) -> str:
267
+ return date_add_interval_sql("DATE", "ADD")(self, ts_or_ds_add_cast(expression))
268
+
269
+
270
+ def _ts_or_ds_diff_sql(self: BigQueryGenerator, expression: exp.TsOrDsDiff) -> str:
271
+ expression.this.replace(exp.cast(expression.this, exp.DType.TIMESTAMP))
272
+ expression.expression.replace(exp.cast(expression.expression, exp.DType.TIMESTAMP))
273
+ unit = unit_to_var(expression)
274
+ return self.func("DATE_DIFF", expression.this, expression.expression, unit)
275
+
276
+
277
+ def _unix_to_time_sql(self: BigQueryGenerator, expression: exp.UnixToTime) -> str:
278
+ scale = expression.args.get("scale")
279
+ timestamp = expression.this
280
+
281
+ if scale in (None, exp.UnixToTime.SECONDS):
282
+ return self.func("TIMESTAMP_SECONDS", timestamp)
283
+ if scale == exp.UnixToTime.MILLIS:
284
+ return self.func("TIMESTAMP_MILLIS", timestamp)
285
+ if scale == exp.UnixToTime.MICROS:
286
+ return self.func("TIMESTAMP_MICROS", timestamp)
287
+
288
+ unix_seconds = exp.cast(
289
+ exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)), exp.DType.BIGINT
290
+ )
291
+ return self.func("TIMESTAMP_SECONDS", unix_seconds)
292
+
293
+
294
+ def _str_to_datetime_sql(self: BigQueryGenerator, expression: exp.StrToDate | exp.StrToTime) -> str:
295
+ this = self.sql(expression, "this")
296
+ dtype = "DATE" if isinstance(expression, exp.StrToDate) else "TIMESTAMP"
297
+
298
+ if expression.args.get("safe"):
299
+ fmt = self.format_time(
300
+ expression,
301
+ self.dialect.INVERSE_FORMAT_MAPPING,
302
+ self.dialect.INVERSE_FORMAT_TRIE,
303
+ )
304
+ return f"SAFE_CAST({this} AS {dtype} FORMAT {fmt})"
305
+
306
+ fmt = self.format_time(expression)
307
+ return self.func(f"PARSE_{dtype}", fmt, this, expression.args.get("zone"))
308
+
309
+
310
+ @unsupported_args("ins_cost", "del_cost", "sub_cost")
311
+ def _levenshtein_sql(self: BigQueryGenerator, expression: exp.Levenshtein) -> str:
312
+ max_dist = expression.args.get("max_dist")
313
+ if max_dist:
314
+ max_dist = exp.Kwarg(this=exp.var("max_distance"), expression=max_dist)
315
+
316
+ return self.func("EDIT_DISTANCE", expression.this, expression.expression, max_dist)
317
+
318
+
319
+ def _json_extract_sql(self: BigQueryGenerator, expression: JSON_EXTRACT_TYPE) -> str:
320
+ upper = self.function_name(expression).upper()
321
+
322
+ dquote_escaping = upper in DQUOTES_ESCAPING_JSON_FUNCTIONS
323
+
324
+ if dquote_escaping:
325
+ self._quote_json_path_key_using_brackets = False
326
+
327
+ sql = rename_func(upper)(self, expression)
328
+
329
+ if dquote_escaping:
330
+ self._quote_json_path_key_using_brackets = True
331
+
332
+ return sql
333
+
334
+
335
+ class BigQueryGenerator(generator.Generator):
336
+ TRY_SUPPORTED = False
337
+ SUPPORTS_UESCAPE = False
338
+ SUPPORTS_DECODE_CASE = False
339
+ INTERVAL_ALLOWS_PLURAL_FORM = False
340
+ JOIN_HINTS = False
341
+ QUERY_HINTS = False
342
+ TABLE_HINTS = False
343
+ LIMIT_FETCH = "LIMIT"
344
+ RENAME_TABLE_WITH_DB = False
345
+ NVL2_SUPPORTED = False
346
+ UNNEST_WITH_ORDINALITY = False
347
+ CAST_TO_INT_ROUNDS = True
348
+ COLLATE_IS_FUNC = True
349
+ LIMIT_ONLY_LITERALS = True
350
+ SUPPORTS_TABLE_ALIAS_COLUMNS = False
351
+ SUPPORTS_NAMED_CTE_COLUMNS = False
352
+ UNPIVOT_ALIASES_ARE_IDENTIFIERS = False
353
+ JSON_KEY_VALUE_PAIR_SEP = ","
354
+ NULL_ORDERING_SUPPORTED: bool | None = False
355
+ IGNORE_NULLS_IN_FUNC = True
356
+ JSON_PATH_SINGLE_QUOTE_ESCAPE = True
357
+ CAN_IMPLEMENT_ARRAY_ANY = True
358
+ SUPPORTS_TO_NUMBER = False
359
+ NAMED_PLACEHOLDER_TOKEN = "@"
360
+ HEX_FUNC = "TO_HEX"
361
+ WITH_PROPERTIES_PREFIX = "OPTIONS"
362
+ SUPPORTS_EXPLODING_PROJECTIONS = False
363
+ EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
364
+ SUPPORTS_UNIX_SECONDS = True
365
+ DECLARE_DEFAULT_ASSIGNMENT = "DEFAULT"
366
+
367
+ SAFE_JSON_PATH_KEY_RE = re.compile(r"^[\-\w]*$")
368
+
369
+ WINDOW_FUNCS_WITH_NULL_ORDERING = (
370
+ exp.CumeDist,
371
+ exp.DenseRank,
372
+ exp.FirstValue,
373
+ exp.Lag,
374
+ exp.LastValue,
375
+ exp.Lead,
376
+ exp.NthValue,
377
+ exp.Ntile,
378
+ exp.PercentRank,
379
+ exp.Rank,
380
+ exp.RowNumber,
381
+ )
382
+
383
+ TS_OR_DS_TYPES: t.ClassVar = (
384
+ exp.TsOrDsToDatetime,
385
+ exp.TsOrDsToTimestamp,
386
+ exp.TsOrDsToTime,
387
+ exp.TsOrDsToDate,
388
+ )
389
+
390
+ TRANSFORMS = {
391
+ **generator.Generator.TRANSFORMS,
392
+ exp.AIEmbed: rename_func("EMBED"),
393
+ exp.AIGenerate: rename_func("GENERATE"),
394
+ exp.AISimilarity: rename_func("SIMILARITY"),
395
+ exp.ApproxTopK: rename_func("APPROX_TOP_COUNT"),
396
+ exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"),
397
+ exp.ArgMax: arg_max_or_min_no_count("MAX_BY"),
398
+ exp.ArgMin: arg_max_or_min_no_count("MIN_BY"),
399
+ exp.Array: inline_array_unless_query,
400
+ exp.ArrayContains: _array_contains_sql,
401
+ exp.ArrayDistinct: _array_agg_fold_sql,
402
+ exp.ArraySort: _array_agg_fold_sql,
403
+ exp.ArrayFilter: filter_array_using_unnest,
404
+ exp.ArrayRemove: filter_array_using_unnest,
405
+ exp.BitwiseAndAgg: rename_func("BIT_AND"),
406
+ exp.BitwiseOrAgg: rename_func("BIT_OR"),
407
+ exp.BitwiseXorAgg: rename_func("BIT_XOR"),
408
+ exp.BitwiseCount: rename_func("BIT_COUNT"),
409
+ exp.ByteLength: rename_func("BYTE_LENGTH"),
410
+ exp.Cast: transforms.preprocess(
411
+ [_widen_decimal, transforms.remove_precision_parameterized_types]
412
+ ),
413
+ exp.CollateProperty: lambda self, e: (
414
+ f"DEFAULT COLLATE {self.sql(e, 'this')}"
415
+ if e.args.get("default")
416
+ else f"COLLATE {self.sql(e, 'this')}"
417
+ ),
418
+ exp.Commit: lambda *_: "COMMIT TRANSACTION",
419
+ exp.CountIf: rename_func("COUNTIF"),
420
+ exp.Create: _create_sql,
421
+ exp.CTE: transforms.preprocess([_pushdown_cte_column_names]),
422
+ exp.DateAdd: date_add_interval_sql("DATE", "ADD"),
423
+ exp.DateDiff: lambda self, e: self.func("DATE_DIFF", e.this, e.expression, unit_to_var(e)),
424
+ exp.DateFromParts: rename_func("DATE"),
425
+ exp.DateStrToDate: datestrtodate_sql,
426
+ exp.DateSub: date_add_interval_sql("DATE", "SUB"),
427
+ exp.DatetimeAdd: date_add_interval_sql("DATETIME", "ADD"),
428
+ exp.DatetimeSub: date_add_interval_sql("DATETIME", "SUB"),
429
+ exp.DateFromUnixDate: rename_func("DATE_FROM_UNIX_DATE"),
430
+ exp.Day: _extract_part("DAY"),
431
+ exp.DayOfMonth: _extract_part("DAY"),
432
+ exp.DayOfWeekIso: _day_of_week_iso_sql,
433
+ exp.DayOfYear: _extract_part("DAYOFYEAR"),
434
+ exp.Filter: no_filter_sql,
435
+ exp.FromTimeZone: lambda self, e: self.func(
436
+ "DATETIME", self.func("TIMESTAMP", e.this, e.args.get("zone")), "'UTC'"
437
+ ),
438
+ exp.GenerateSeries: generate_series_sql("GENERATE_ARRAY"),
439
+ exp.GroupConcat: lambda self, e: groupconcat_sql(
440
+ self, e, func_name="STRING_AGG", within_group=False, sep=None
441
+ ),
442
+ exp.Hex: lambda self, e: self.func("UPPER", self.func("TO_HEX", self.sql(e, "this"))),
443
+ exp.HexString: lambda self, e: self.hexstring_sql(e, binary_function_repr="FROM_HEX"),
444
+ exp.Hour: _extract_part("HOUR"),
445
+ exp.If: if_sql(false_value="NULL"),
446
+ exp.ILike: no_ilike_sql,
447
+ exp.IntDiv: rename_func("DIV"),
448
+ exp.Int64: rename_func("INT64"),
449
+ exp.JSONBool: rename_func("BOOL"),
450
+ exp.JSONExtract: _json_extract_sql,
451
+ exp.JSONExtractArray: _json_extract_sql,
452
+ exp.JSONExtractScalar: _json_extract_sql,
453
+ exp.JSONFormat: lambda self, e: self.func(
454
+ "TO_JSON" if e.args.get("to_json") else "TO_JSON_STRING",
455
+ e.this,
456
+ e.args.get("options"),
457
+ ),
458
+ exp.JSONKeysAtDepth: rename_func("JSON_KEYS"),
459
+ exp.JSONValueArray: rename_func("JSON_VALUE_ARRAY"),
460
+ exp.Levenshtein: _levenshtein_sql,
461
+ exp.Max: max_or_greatest,
462
+ exp.MD5: lambda self, e: self.func("TO_HEX", self.func("MD5", e.this)),
463
+ exp.MD5Digest: rename_func("MD5"),
464
+ exp.Min: min_or_least,
465
+ exp.Month: _extract_part("MONTH"),
466
+ exp.Normalize: lambda self, e: self.func(
467
+ "NORMALIZE_AND_CASEFOLD" if e.args.get("is_casefold") else "NORMALIZE",
468
+ e.this,
469
+ e.args.get("form"),
470
+ ),
471
+ exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
472
+ exp.Quarter: _extract_part("QUARTER"),
473
+ exp.RegexpExtract: lambda self, e: self.func(
474
+ "REGEXP_EXTRACT",
475
+ e.this,
476
+ e.expression,
477
+ e.args.get("position"),
478
+ e.args.get("occurrence"),
479
+ ),
480
+ exp.RegexpExtractAll: lambda self, e: self.func("REGEXP_EXTRACT_ALL", e.this, e.expression),
481
+ exp.RegexpReplace: regexp_replace_sql,
482
+ exp.RegexpLike: rename_func("REGEXP_CONTAINS"),
483
+ exp.ReturnsProperty: _returnsproperty_sql,
484
+ exp.Rollback: lambda *_: "ROLLBACK TRANSACTION",
485
+ exp.ParseTime: lambda self, e: self.func("PARSE_TIME", self.format_time(e), e.this),
486
+ exp.ParseDatetime: lambda self, e: self.func("PARSE_DATETIME", self.format_time(e), e.this),
487
+ exp.Select: transforms.preprocess(
488
+ [
489
+ _unnest_explode_generate_series,
490
+ transforms.explode_projection_to_unnest(),
491
+ transforms.unqualify_unnest,
492
+ transforms.eliminate_distinct_on,
493
+ _alias_ordered_group,
494
+ transforms.eliminate_semi_and_anti_joins,
495
+ ]
496
+ ),
497
+ exp.SHA: rename_func("SHA1"),
498
+ exp.SHA2: sha256_sql,
499
+ exp.SHA1Digest: rename_func("SHA1"),
500
+ exp.SHA2Digest: sha2_digest_sql,
501
+ exp.StabilityProperty: lambda self, e: (
502
+ "DETERMINISTIC" if e.name == "IMMUTABLE" else "NOT DETERMINISTIC"
503
+ ),
504
+ exp.String: rename_func("STRING"),
505
+ exp.StrPosition: lambda self, e: strposition_sql(
506
+ self, e, func_name="INSTR", supports_position=True, supports_occurrence=True
507
+ ),
508
+ exp.StrToDate: _str_to_datetime_sql,
509
+ exp.StrToTime: _str_to_datetime_sql,
510
+ exp.SessionUser: lambda *_: "SESSION_USER()",
511
+ exp.Table: transforms.preprocess([transforms.unnest_generate_series]),
512
+ exp.TimeAdd: date_add_interval_sql("TIME", "ADD"),
513
+ exp.TimeFromParts: rename_func("TIME"),
514
+ exp.TimestampFromParts: rename_func("DATETIME"),
515
+ exp.TimeSub: date_add_interval_sql("TIME", "SUB"),
516
+ exp.TimestampAdd: date_add_interval_sql("TIMESTAMP", "ADD"),
517
+ exp.TimestampDiff: rename_func("TIMESTAMP_DIFF"),
518
+ exp.TimestampSub: date_add_interval_sql("TIMESTAMP", "SUB"),
519
+ exp.TimeStrToTime: timestrtotime_sql,
520
+ exp.Transaction: lambda *_: "BEGIN TRANSACTION",
521
+ exp.TsOrDsAdd: _ts_or_ds_add_sql,
522
+ exp.TsOrDsDiff: _ts_or_ds_diff_sql,
523
+ exp.TsOrDsToTime: rename_func("TIME"),
524
+ exp.TsOrDsToDatetime: rename_func("DATETIME"),
525
+ exp.TsOrDsToTimestamp: rename_func("TIMESTAMP"),
526
+ exp.Unhex: rename_func("FROM_HEX"),
527
+ exp.UnixDate: rename_func("UNIX_DATE"),
528
+ exp.UnixToTime: _unix_to_time_sql,
529
+ exp.Uuid: lambda *_: "GENERATE_UUID()",
530
+ exp.Values: _derived_table_values_to_unnest,
531
+ exp.VariancePop: rename_func("VAR_POP"),
532
+ exp.WeekOfYear: _extract_part("ISOWEEK"),
533
+ exp.Year: _extract_part("YEAR"),
534
+ exp.SafeDivide: rename_func("SAFE_DIVIDE"),
535
+ }
536
+
537
+ SUPPORTED_JSON_PATH_PARTS = {
538
+ exp.JSONPathKey,
539
+ exp.JSONPathRoot,
540
+ exp.JSONPathSubscript,
541
+ }
542
+
543
+ TYPE_MAPPING = {
544
+ **generator.Generator.TYPE_MAPPING,
545
+ exp.DType.BIGDECIMAL: "BIGNUMERIC",
546
+ exp.DType.BIGINT: "INT64",
547
+ exp.DType.BINARY: "BYTES",
548
+ exp.DType.BLOB: "BYTES",
549
+ exp.DType.BOOLEAN: "BOOL",
550
+ exp.DType.CHAR: "STRING",
551
+ exp.DType.DECIMAL: "NUMERIC",
552
+ exp.DType.DOUBLE: "FLOAT64",
553
+ exp.DType.FLOAT: "FLOAT64",
554
+ exp.DType.INT: "INT64",
555
+ exp.DType.NCHAR: "STRING",
556
+ exp.DType.NVARCHAR: "STRING",
557
+ exp.DType.SMALLINT: "INT64",
558
+ exp.DType.TEXT: "STRING",
559
+ exp.DType.TIMESTAMP: "DATETIME",
560
+ exp.DType.TIMESTAMPNTZ: "DATETIME",
561
+ exp.DType.TIMESTAMPTZ: "TIMESTAMP",
562
+ exp.DType.TIMESTAMPLTZ: "TIMESTAMP",
563
+ exp.DType.TINYINT: "INT64",
564
+ exp.DType.ROWVERSION: "BYTES",
565
+ exp.DType.UUID: "STRING",
566
+ exp.DType.VARBINARY: "BYTES",
567
+ exp.DType.VARCHAR: "STRING",
568
+ exp.DType.VARIANT: "ANY TYPE",
569
+ }
570
+
571
+ PROPERTIES_LOCATION = {
572
+ **generator.Generator.PROPERTIES_LOCATION,
573
+ exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
574
+ exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
575
+ }
576
+
577
+ # WINDOW comes after QUALIFY
578
+ # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#window_clause
579
+ # BigQuery requires QUALIFY before WINDOW
580
+ AFTER_HAVING_MODIFIER_TRANSFORMS = {
581
+ "qualify": generator.AFTER_HAVING_MODIFIER_TRANSFORMS["qualify"],
582
+ "windows": generator.AFTER_HAVING_MODIFIER_TRANSFORMS["windows"],
583
+ }
584
+
585
+ # from: https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#reserved_keywords
586
+ RESERVED_KEYWORDS = {
587
+ "all",
588
+ "and",
589
+ "any",
590
+ "array",
591
+ "as",
592
+ "asc",
593
+ "assert_rows_modified",
594
+ "at",
595
+ "between",
596
+ "by",
597
+ "case",
598
+ "cast",
599
+ "collate",
600
+ "contains",
601
+ "create",
602
+ "cross",
603
+ "cube",
604
+ "current",
605
+ "default",
606
+ "define",
607
+ "desc",
608
+ "distinct",
609
+ "else",
610
+ "end",
611
+ "enum",
612
+ "escape",
613
+ "except",
614
+ "exclude",
615
+ "exists",
616
+ "extract",
617
+ "false",
618
+ "fetch",
619
+ "following",
620
+ "for",
621
+ "from",
622
+ "full",
623
+ "group",
624
+ "grouping",
625
+ "groups",
626
+ "hash",
627
+ "having",
628
+ "if",
629
+ "ignore",
630
+ "in",
631
+ "inner",
632
+ "intersect",
633
+ "interval",
634
+ "into",
635
+ "is",
636
+ "join",
637
+ "lateral",
638
+ "left",
639
+ "like",
640
+ "limit",
641
+ "lookup",
642
+ "merge",
643
+ "natural",
644
+ "new",
645
+ "no",
646
+ "not",
647
+ "null",
648
+ "nulls",
649
+ "of",
650
+ "on",
651
+ "or",
652
+ "order",
653
+ "outer",
654
+ "over",
655
+ "partition",
656
+ "preceding",
657
+ "proto",
658
+ "qualify",
659
+ "range",
660
+ "recursive",
661
+ "respect",
662
+ "right",
663
+ "rollup",
664
+ "rows",
665
+ "select",
666
+ "set",
667
+ "some",
668
+ "struct",
669
+ "tablesample",
670
+ "then",
671
+ "to",
672
+ "treat",
673
+ "true",
674
+ "unbounded",
675
+ "union",
676
+ "unnest",
677
+ "using",
678
+ "when",
679
+ "where",
680
+ "window",
681
+ "with",
682
+ "within",
683
+ }
684
+
685
+ def frombase_sql(self, expression: exp.FromBase) -> str:
686
+ # Hex is the only base BigQuery can cast from, and the sign goes before the prefix, e.g. -0xff
687
+ if expression.expression.name != "16":
688
+ self.unsupported("FROM_BASE is only supported for base 16")
689
+ return self.function_fallback_sql(expression)
690
+
691
+ prefixed = exp.func(
692
+ "REGEXP_REPLACE",
693
+ expression.this,
694
+ exp.Literal.string("^([+-]?)"),
695
+ exp.Literal.string("\\10x"),
696
+ copy=False,
697
+ )
698
+ return self.sql(exp.cast(prefixed, exp.DType.BIGINT, copy=False))
699
+
700
+ def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str:
701
+ node: exp.Expr = expression
702
+ while node.parent and not isinstance(node.parent, (exp.Window, exp.AggFunc, exp.Select)):
703
+ node = node.parent
704
+ if isinstance(node.parent, exp.Window) and node.arg_key == "this":
705
+ self.unsupported("APPROX_QUANTILES does not support window functions")
706
+ return self.function_fallback_sql(expression)
707
+
708
+ # The k/n quantile is APPROX_QUANTILES(x, n)[k], e.g. 0.95 -> n = 20, k = 19. n is at most
709
+ # 100,000, so the quantile has at most 5 decimal places, and Decimal comparisons are exact
710
+ quantile = expression.args["quantile"]
711
+ weight = expression.args.get("weight")
712
+ value = Decimal(quantile.to_py()) if quantile.is_number else None
713
+ if (
714
+ value is None
715
+ or not 0 <= value <= 1
716
+ or round(value, 5) != value
717
+ or (weight and (not weight.is_number or weight.to_py() != 1))
718
+ ):
719
+ self.unsupported("APPROX_QUANTILE needs a literal quantile and no weight")
720
+ return self.function_fallback_sql(expression)
721
+
722
+ fraction = Fraction(value)
723
+ quantiles = exp.func("APPROX_QUANTILES", expression.this, fraction.denominator, copy=False)
724
+ return self.sql(quantiles[fraction.numerator])
725
+
726
+ def weekstart_sql(self, expression: exp.WeekStart) -> str:
727
+ if expression.this.name.upper() == "SUNDAY":
728
+ # BigQuery specific optimization since WEEK(SUNDAY) == WEEK
729
+ return "WEEK"
730
+
731
+ return self.func("WEEK", expression.this)
732
+
733
+ def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
734
+ unit = expression.unit
735
+ unit_sql = unit.name if unit.is_string else self.sql(unit)
736
+ return self.func("DATE_TRUNC", expression.this, unit_sql, expression.args.get("zone"))
737
+
738
+ def mod_sql(self, expression: exp.Mod) -> str:
739
+ this = expression.this
740
+ expr = expression.expression
741
+ return self.func(
742
+ "MOD",
743
+ this.unnest() if isinstance(this, exp.Paren) else this,
744
+ expr.unnest() if isinstance(expr, exp.Paren) else expr,
745
+ )
746
+
747
+ def column_parts(self, expression: exp.Column) -> str:
748
+ if expression.meta_get("quoted_column"):
749
+ # If a column reference is of the form `dataset.table`.name, we need
750
+ # to preserve the quoted table path, otherwise the reference breaks
751
+ table_parts = ".".join(p.name for p in expression.parts[:-1])
752
+ table_path = self.sql(exp.Identifier(this=table_parts, quoted=True))
753
+ return f"{table_path}.{self.sql(expression, 'this')}"
754
+
755
+ return super().column_parts(expression)
756
+
757
+ def table_parts(self, expression: exp.Table) -> str:
758
+ # Depending on the context, `x.y` may not resolve to the same data source as `x`.`y`, so
759
+ # we need to make sure the correct quoting is used in each case.
760
+ #
761
+ # For example, if there is a CTE x that clashes with a schema name, then the former will
762
+ # return the table y in that schema, whereas the latter will return the CTE's y column:
763
+ #
764
+ # - WITH x AS (SELECT [1, 2] AS y) SELECT * FROM x, `x.y` -> cross join
765
+ # - WITH x AS (SELECT [1, 2] AS y) SELECT * FROM x, `x`.`y` -> implicit unnest
766
+ if expression.meta_get("quoted_table"):
767
+ table_parts = ".".join(p.name for p in expression.parts)
768
+ return self.sql(exp.Identifier(this=table_parts, quoted=True))
769
+
770
+ return super().table_parts(expression)
771
+
772
+ def timetostr_sql(self, expression: exp.TimeToStr) -> str:
773
+ this = expression.this
774
+ if isinstance(this, exp.TsOrDsToDatetime):
775
+ func_name = "FORMAT_DATETIME"
776
+ elif isinstance(this, exp.TsOrDsToTimestamp):
777
+ func_name = "FORMAT_TIMESTAMP"
778
+ elif isinstance(this, exp.TsOrDsToTime):
779
+ func_name = "FORMAT_TIME"
780
+ else:
781
+ func_name = "FORMAT_DATE"
782
+
783
+ time_expr = this if isinstance(this, self.TS_OR_DS_TYPES) else expression
784
+ return self.func(
785
+ func_name, self.format_time(expression), time_expr.this, expression.args.get("zone")
786
+ )
787
+
788
+ def eq_sql(self, expression: exp.EQ) -> str:
789
+ # Operands of = cannot be NULL in BigQuery
790
+ if isinstance(expression.left, exp.Null) or isinstance(expression.right, exp.Null):
791
+ if not isinstance(expression.parent, exp.Update):
792
+ return "NULL"
793
+
794
+ return self.binary(expression, "=")
795
+
796
+ def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
797
+ parent = expression.parent
798
+
799
+ # BigQuery allows CAST(.. AS {STRING|TIMESTAMP} [FORMAT <fmt> [AT TIME ZONE <tz>]]).
800
+ # Only the TIMESTAMP one should use the below conversion, when AT TIME ZONE is included.
801
+ if not isinstance(parent, exp.Cast) or not parent.to.is_type("text"):
802
+ return self.func(
803
+ "TIMESTAMP", self.func("DATETIME", expression.this, expression.args.get("zone"))
804
+ )
805
+
806
+ return super().attimezone_sql(expression)
807
+
808
+ def trycast_sql(self, expression: exp.TryCast) -> str:
809
+ return self.cast_sql(expression, safe_prefix="SAFE_")
810
+
811
+ def bracket_sql(self, expression: exp.Bracket) -> str:
812
+ this = expression.this
813
+ expressions = expression.expressions
814
+
815
+ if len(expressions) == 1 and this and this.is_type(exp.DType.STRUCT):
816
+ arg = expressions[0]
817
+ if arg.type is None:
818
+ from sqlglot.optimizer.annotate_types import annotate_types
819
+
820
+ arg = annotate_types(arg, dialect=self.dialect)
821
+
822
+ if arg.type and arg.type.this in exp.DataType.TEXT_TYPES:
823
+ # BQ doesn't support bracket syntax with string values for structs
824
+ return f"{self.sql(this)}.{arg.name}"
825
+
826
+ expressions_sql = self.expressions(expression, flat=True)
827
+ offset = expression.args.get("offset")
828
+
829
+ if offset == 0:
830
+ expressions_sql = f"OFFSET({expressions_sql})"
831
+ elif offset == 1:
832
+ expressions_sql = f"ORDINAL({expressions_sql})"
833
+ elif offset is not None:
834
+ self.unsupported(f"Unsupported array offset: {offset}")
835
+
836
+ if expression.args.get("safe"):
837
+ expressions_sql = f"SAFE_{expressions_sql}"
838
+
839
+ return f"{self.sql(this)}[{expressions_sql}]"
840
+
841
+ def in_unnest_op(self, expression: exp.Unnest) -> str:
842
+ return self.sql(expression)
843
+
844
+ def version_sql(self, expression: exp.Version) -> str:
845
+ if expression.name == "TIMESTAMP":
846
+ expression.set("this", "SYSTEM_TIME")
847
+ return super().version_sql(expression)
848
+
849
+ def contains_sql(self, expression: exp.Contains) -> str:
850
+ this = expression.this
851
+ expr = expression.expression
852
+
853
+ if isinstance(this, exp.Lower) and isinstance(expr, exp.Lower):
854
+ this = this.this
855
+ expr = expr.this
856
+
857
+ return self.func("CONTAINS_SUBSTR", this, expr, expression.args.get("json_scope"))
858
+
859
+ def parsejson_sql(self, expression: exp.ParseJSON) -> str:
860
+ if expression.args.get("is_literal"):
861
+ return f"JSON {self.sql(expression, 'this')}"
862
+ return super().parsejson_sql(expression)
863
+
864
+ def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
865
+ this = expression.this
866
+
867
+ # This ensures that inline type-annotated ARRAY literals like ARRAY<INT64>[1, 2, 3]
868
+ # are roundtripped unaffected. The inner check excludes ARRAY(SELECT ...) expressions,
869
+ # because they aren't literals and so the above syntax is invalid BigQuery.
870
+ if isinstance(this, exp.Array):
871
+ elem = seq_get(this.expressions, 0)
872
+ if not (elem and elem.find(exp.Query)):
873
+ return f"{self.sql(expression, 'to')}{self.sql(this)}"
874
+
875
+ return super().cast_sql(expression, safe_prefix=safe_prefix)
876
+
877
+ def clusterproperty_sql(self, expression: exp.ClusterProperty) -> str:
878
+ if expression.this:
879
+ self.unsupported(f"Unsupported CLUSTER BY {self.sql(expression, 'this')}")
880
+ return ""
881
+ return self.op_expressions("CLUSTER BY", expression)
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/clickhouse.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import datetime
4
+ import typing as t
5
+
6
+ from sqlglot import exp, generator
7
+ from sqlglot.dialects.dialect import (
8
+ arg_max_or_min_no_count,
9
+ inline_array_sql,
10
+ jarowinkler_similarity,
11
+ json_extract_segments,
12
+ json_path_key_only_name,
13
+ length_or_char_length_sql,
14
+ no_pivot_sql,
15
+ rename_func,
16
+ remove_from_array_using_filter,
17
+ sha256_sql,
18
+ strposition_sql,
19
+ var_map_sql,
20
+ weekstart_unit_to_str,
21
+ unit_to_var,
22
+ trim_sql,
23
+ sha2_digest_sql,
24
+ )
25
+ from sqlglot.generator import unsupported_args
26
+ from sqlglot.helper import is_int
27
+ from collections import defaultdict
28
+
29
+ DATETIME_DELTA = t.Union[exp.DateAdd, exp.DateDiff, exp.DateSub, exp.TimestampSub, exp.TimestampAdd]
30
+
31
+
32
+ def _unix_to_time_sql(self: ClickHouseGenerator, expression: exp.UnixToTime) -> str:
33
+ scale = expression.args.get("scale")
34
+ timestamp = expression.this
35
+
36
+ if scale in (None, exp.UnixToTime.SECONDS):
37
+ return self.func("fromUnixTimestamp", exp.cast(timestamp, exp.DType.BIGINT))
38
+ if scale == exp.UnixToTime.MILLIS:
39
+ return self.func("fromUnixTimestamp64Milli", exp.cast(timestamp, exp.DType.BIGINT))
40
+ if scale == exp.UnixToTime.MICROS:
41
+ return self.func("fromUnixTimestamp64Micro", exp.cast(timestamp, exp.DType.BIGINT))
42
+ if scale == exp.UnixToTime.NANOS:
43
+ return self.func("fromUnixTimestamp64Nano", exp.cast(timestamp, exp.DType.BIGINT))
44
+
45
+ return self.func(
46
+ "fromUnixTimestamp",
47
+ exp.cast(exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)), exp.DType.BIGINT),
48
+ )
49
+
50
+
51
+ def _lower_func(sql: str) -> str:
52
+ index = sql.index("(")
53
+ return sql[:index].lower() + sql[index:]
54
+
55
+
56
+ def _quantile_sql(self: ClickHouseGenerator, expression: exp.Quantile) -> str:
57
+ quantile = expression.args["quantile"]
58
+ args = f"({self.sql(expression, 'this')})"
59
+
60
+ if isinstance(quantile, exp.Array):
61
+ func = self.func("quantiles", *quantile)
62
+ else:
63
+ func = self.func("quantile", quantile)
64
+
65
+ return func + args
66
+
67
+
68
+ def _datetime_delta_sql(name: str) -> t.Callable[[generator.Generator, DATETIME_DELTA], str]:
69
+ def _delta_sql(self: generator.Generator, expression: DATETIME_DELTA) -> str:
70
+ if not expression.unit:
71
+ return rename_func(name)(self, expression)
72
+
73
+ return self.func(
74
+ name,
75
+ unit_to_var(expression),
76
+ expression.expression,
77
+ expression.this,
78
+ expression.args.get("zone"),
79
+ )
80
+
81
+ return _delta_sql
82
+
83
+
84
+ def _timestrtotime_sql(self: ClickHouseGenerator, expression: exp.TimeStrToTime):
85
+ ts = expression.this
86
+
87
+ tz = expression.args.get("zone")
88
+ if tz and isinstance(ts, exp.Literal):
89
+ # Clickhouse will not accept timestamps that include a UTC offset, so we must remove them.
90
+ # The first step to removing is parsing the string with `datetime.datetime.fromisoformat`.
91
+ #
92
+ # In python <3.11, `fromisoformat()` can only parse timestamps of millisecond (3 digit)
93
+ # or microsecond (6 digit) precision. It will error if passed any other number of fractional
94
+ # digits, so we extract the fractional seconds and pad to 6 digits before parsing.
95
+ ts_string = ts.name.strip()
96
+
97
+ # separate [date and time] from [fractional seconds and UTC offset]
98
+ ts_parts = ts_string.split(".")
99
+ if len(ts_parts) == 2:
100
+ # separate fractional seconds and UTC offset
101
+ offset_sep = "+" if "+" in ts_parts[1] else "-"
102
+ ts_frac_parts = ts_parts[1].split(offset_sep)
103
+ num_frac_parts = len(ts_frac_parts)
104
+
105
+ # pad to 6 digits if fractional seconds present
106
+ ts_frac_parts[0] = ts_frac_parts[0].ljust(6, "0")
107
+ ts_string = "".join(
108
+ [
109
+ ts_parts[0], # date and time
110
+ ".",
111
+ ts_frac_parts[0], # fractional seconds
112
+ offset_sep if num_frac_parts > 1 else "",
113
+ ts_frac_parts[1] if num_frac_parts > 1 else "", # utc offset (if present)
114
+ ]
115
+ )
116
+
117
+ # return literal with no timezone, eg turn '2020-01-01 12:13:14-08:00' into '2020-01-01 12:13:14'
118
+ # this is because Clickhouse encodes the timezone as a data type parameter and throws an error if
119
+ # it's part of the timestamp string
120
+ ts_without_tz = (
121
+ datetime.datetime.fromisoformat(ts_string).replace(tzinfo=None).isoformat(sep=" ")
122
+ )
123
+ ts = exp.Literal.string(ts_without_tz)
124
+
125
+ # Non-nullable DateTime64 with microsecond precision
126
+ expressions = [exp.DataTypeParam(this=tz)] if tz else []
127
+ datatype = exp.DType.DATETIME64.into_expr(
128
+ expressions=[exp.DataTypeParam(this=exp.Literal.number(6)), *expressions],
129
+ nullable=False,
130
+ )
131
+
132
+ return self.sql(exp.cast(ts, datatype, dialect=self.dialect))
133
+
134
+
135
+ def _map_sql(self: ClickHouseGenerator, expression: exp.Map | exp.VarMap) -> str:
136
+ if not (expression.parent and expression.parent.arg_key == "settings"):
137
+ return _lower_func(var_map_sql(self, expression))
138
+
139
+ keys = expression.args.get("keys")
140
+ values = expression.args.get("values")
141
+
142
+ if not isinstance(keys, exp.Array) or not isinstance(values, exp.Array):
143
+ self.unsupported("Cannot convert array columns into map.")
144
+ return ""
145
+
146
+ args = []
147
+ for key, value in zip(keys.expressions, values.expressions):
148
+ args.append(f"{self.sql(key)}: {self.sql(value)}")
149
+
150
+ csv_args = ", ".join(args)
151
+
152
+ return f"{{{csv_args}}}"
153
+
154
+
155
+ def _json_cast_sql(self: ClickHouseGenerator, expression: exp.JSONCast) -> str:
156
+ this = self.sql(expression, "this")
157
+ to = expression.to
158
+ to_sql = self.sql(to)
159
+
160
+ if to.expressions:
161
+ to_sql = self.sql(exp.to_identifier(to_sql))
162
+
163
+ return f"{this}.:{to_sql}"
164
+
165
+
166
+ class ClickHouseGenerator(generator.Generator):
167
+ BYTE_STRING_FUNCTION = "unhex"
168
+ SELECT_KINDS: tuple[str, ...] = ()
169
+ TRY_SUPPORTED = False
170
+ SUPPORTS_UESCAPE = False
171
+ SUPPORTS_DECODE_CASE = False
172
+
173
+ AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
174
+
175
+ QUERY_HINTS = False
176
+ STRUCT_DELIMITER = ("(", ")")
177
+ NVL2_SUPPORTED = False
178
+ ALTER_SET_TYPE = "TYPE"
179
+ SUPPORTS_ALTER_COLUMN_IF_EXISTS = True
180
+ TABLESAMPLE_REQUIRES_PARENS = False
181
+ TABLESAMPLE_SIZE_IS_ROWS = False
182
+ TABLESAMPLE_KEYWORDS = "SAMPLE"
183
+ LAST_DAY_SUPPORTS_DATE_PART = False
184
+ CAN_IMPLEMENT_ARRAY_ANY = True
185
+ SUPPORTS_TO_NUMBER = False
186
+ JOIN_HINTS = False
187
+ TABLE_HINTS = False
188
+ GROUPINGS_SEP = ""
189
+ SET_OP_MODIFIERS = False
190
+ SET_OP_LIMITS = True
191
+ ARRAY_SIZE_NAME = "LENGTH"
192
+ WRAP_DERIVED_VALUES = False
193
+ AUTO_REFRESH_BARE_INTERVALS = True
194
+
195
+ STRING_TYPE_MAPPING: t.ClassVar = {
196
+ exp.DType.BLOB: "String",
197
+ exp.DType.CHAR: "String",
198
+ exp.DType.LONGBLOB: "String",
199
+ exp.DType.LONGTEXT: "String",
200
+ exp.DType.MEDIUMBLOB: "String",
201
+ exp.DType.MEDIUMTEXT: "String",
202
+ exp.DType.TINYBLOB: "String",
203
+ exp.DType.TINYTEXT: "String",
204
+ exp.DType.TEXT: "String",
205
+ exp.DType.VARBINARY: "String",
206
+ exp.DType.VARCHAR: "String",
207
+ }
208
+
209
+ SUPPORTED_JSON_PATH_PARTS = {
210
+ exp.JSONPathKey,
211
+ exp.JSONPathRoot,
212
+ exp.JSONPathSubscript,
213
+ }
214
+
215
+ TYPE_MAPPING = {
216
+ **generator.Generator.TYPE_MAPPING,
217
+ exp.DType.BLOB: "String",
218
+ exp.DType.CHAR: "String",
219
+ exp.DType.LONGBLOB: "String",
220
+ exp.DType.LONGTEXT: "String",
221
+ exp.DType.MEDIUMBLOB: "String",
222
+ exp.DType.MEDIUMTEXT: "String",
223
+ exp.DType.TINYBLOB: "String",
224
+ exp.DType.TINYTEXT: "String",
225
+ exp.DType.TEXT: "String",
226
+ exp.DType.VARBINARY: "String",
227
+ exp.DType.VARCHAR: "String",
228
+ exp.DType.ARRAY: "Array",
229
+ exp.DType.BOOLEAN: "Bool",
230
+ exp.DType.BIGINT: "Int64",
231
+ exp.DType.DATE32: "Date32",
232
+ exp.DType.DATETIME: "DateTime",
233
+ exp.DType.DATETIME2: "DateTime",
234
+ exp.DType.SMALLDATETIME: "DateTime",
235
+ exp.DType.DATETIME64: "DateTime64",
236
+ exp.DType.DECIMAL: "Decimal",
237
+ exp.DType.DECIMAL32: "Decimal32",
238
+ exp.DType.DECIMAL64: "Decimal64",
239
+ exp.DType.DECIMAL128: "Decimal128",
240
+ exp.DType.DECIMAL256: "Decimal256",
241
+ exp.DType.TIMESTAMP: "DateTime",
242
+ exp.DType.TIMESTAMPNTZ: "DateTime",
243
+ exp.DType.TIMESTAMPTZ: "DateTime",
244
+ exp.DType.DOUBLE: "Float64",
245
+ exp.DType.ENUM: "Enum",
246
+ exp.DType.ENUM8: "Enum8",
247
+ exp.DType.ENUM16: "Enum16",
248
+ exp.DType.FIXEDSTRING: "FixedString",
249
+ exp.DType.FLOAT: "Float32",
250
+ exp.DType.INT: "Int32",
251
+ exp.DType.MEDIUMINT: "Int32",
252
+ exp.DType.INT128: "Int128",
253
+ exp.DType.INT256: "Int256",
254
+ exp.DType.LOWCARDINALITY: "LowCardinality",
255
+ exp.DType.MAP: "Map",
256
+ exp.DType.NESTED: "Nested",
257
+ exp.DType.NOTHING: "Nothing",
258
+ exp.DType.SMALLINT: "Int16",
259
+ exp.DType.STRUCT: "Tuple",
260
+ exp.DType.TINYINT: "Int8",
261
+ exp.DType.UBIGINT: "UInt64",
262
+ exp.DType.UINT: "UInt32",
263
+ exp.DType.UINT128: "UInt128",
264
+ exp.DType.UINT256: "UInt256",
265
+ exp.DType.USMALLINT: "UInt16",
266
+ exp.DType.UTINYINT: "UInt8",
267
+ exp.DType.IPV4: "IPv4",
268
+ exp.DType.IPV6: "IPv6",
269
+ exp.DType.POINT: "Point",
270
+ exp.DType.RING: "Ring",
271
+ exp.DType.LINESTRING: "LineString",
272
+ exp.DType.MULTILINESTRING: "MultiLineString",
273
+ exp.DType.POLYGON: "Polygon",
274
+ exp.DType.MULTIPOLYGON: "MultiPolygon",
275
+ exp.DType.AGGREGATEFUNCTION: "AggregateFunction",
276
+ exp.DType.SIMPLEAGGREGATEFUNCTION: "SimpleAggregateFunction",
277
+ exp.DType.DYNAMIC: "Dynamic",
278
+ }
279
+
280
+ TRANSFORMS = {
281
+ **{k: v for k, v in generator.Generator.TRANSFORMS.items() if k != exp.AutoRefreshProperty},
282
+ exp.AnyValue: rename_func("any"),
283
+ exp.ApproxDistinct: rename_func("uniq"),
284
+ exp.ArrayDistinct: rename_func("arrayDistinct"),
285
+ exp.ArrayConcat: rename_func("arrayConcat"),
286
+ exp.ArrayContains: rename_func("has"),
287
+ exp.ArrayFilter: lambda self, e: self.func("arrayFilter", e.expression, e.this),
288
+ exp.Transform: lambda self, e: self.func("arrayMap", e.expression, e.this),
289
+ exp.ArrayRemove: remove_from_array_using_filter,
290
+ exp.ArrayReverse: rename_func("arrayReverse"),
291
+ exp.ArraySlice: rename_func("arraySlice"),
292
+ exp.ArraySum: rename_func("arraySum"),
293
+ exp.ArrayMax: rename_func("arrayMax"),
294
+ exp.ArrayMin: rename_func("arrayMin"),
295
+ exp.ArgMax: arg_max_or_min_no_count("argMax"),
296
+ exp.ArgMin: arg_max_or_min_no_count("argMin"),
297
+ exp.Array: inline_array_sql,
298
+ exp.BitwiseAndAgg: rename_func("groupBitAnd"),
299
+ exp.BitwiseOrAgg: rename_func("groupBitOr"),
300
+ exp.BitwiseXorAgg: rename_func("groupBitXor"),
301
+ exp.CityHash64: rename_func("cityHash64"),
302
+ exp.CastToStrType: rename_func("CAST"),
303
+ exp.CurrentDatabase: rename_func("CURRENT_DATABASE"),
304
+ exp.CurrentSchemas: rename_func("CURRENT_SCHEMAS"),
305
+ exp.CountIf: rename_func("countIf"),
306
+ exp.CosineDistance: rename_func("cosineDistance"),
307
+ exp.CompressColumnConstraint: lambda self, e: (
308
+ f"CODEC({self.expressions(e, key='this', flat=True)})"
309
+ ),
310
+ exp.ComputedColumnConstraint: lambda self, e: (
311
+ f"{'MATERIALIZED' if e.args.get('persisted') else 'ALIAS'} {self.sql(e, 'this')}"
312
+ ),
313
+ exp.CurrentDate: lambda self, e: self.func("CURRENT_DATE"),
314
+ exp.CurrentVersion: rename_func("VERSION"),
315
+ exp.DateAdd: _datetime_delta_sql("DATE_ADD"),
316
+ exp.DateDiff: _datetime_delta_sql("DATE_DIFF"),
317
+ exp.DateStrToDate: rename_func("toDate"),
318
+ exp.DateSub: _datetime_delta_sql("DATE_SUB"),
319
+ exp.DayOfMonth: rename_func("toDayOfMonth"),
320
+ exp.DayOfWeekIso: rename_func("toDayOfWeek"),
321
+ exp.DayOfYear: rename_func("toDayOfYear"),
322
+ exp.Explode: rename_func("arrayJoin"),
323
+ exp.FarmFingerprint: rename_func("farmFingerprint64"),
324
+ exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL",
325
+ exp.IsInf: rename_func("isInfinite"),
326
+ exp.IsNan: rename_func("isNaN"),
327
+ exp.JarowinklerSimilarity: jarowinkler_similarity("jaroWinklerSimilarity"),
328
+ exp.JSONCast: _json_cast_sql,
329
+ exp.JSONExtract: json_extract_segments("JSONExtractRaw", quoted_index=False),
330
+ exp.JSONExtractScalar: json_extract_segments("JSONExtractString", quoted_index=False),
331
+ exp.JSONPathKey: json_path_key_only_name,
332
+ exp.JSONPathRoot: lambda *_: "",
333
+ exp.Length: length_or_char_length_sql,
334
+ exp.Map: _map_sql,
335
+ exp.Median: rename_func("median"),
336
+ exp.Nullif: rename_func("nullIf"),
337
+ exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
338
+ exp.Pivot: no_pivot_sql,
339
+ exp.Quantile: _quantile_sql,
340
+ exp.RegexpLike: lambda self, e: self.func("match", e.this, e.expression),
341
+ exp.Rand: rename_func("randCanonical"),
342
+ exp.StartsWith: rename_func("startsWith"),
343
+ exp.Struct: rename_func("tuple"),
344
+ exp.Trunc: rename_func("trunc"),
345
+ exp.EndsWith: rename_func("endsWith"),
346
+ exp.EuclideanDistance: rename_func("L2Distance"),
347
+ exp.StrPosition: lambda self, e: strposition_sql(
348
+ self,
349
+ e,
350
+ func_name="POSITION",
351
+ supports_position=True,
352
+ use_ansi_position=False,
353
+ ),
354
+ exp.TimeToStr: lambda self, e: self.func(
355
+ "formatDateTime",
356
+ e.this.this if isinstance(e.this, exp.TsOrDsToTimestamp) else e.this,
357
+ self.format_time(e),
358
+ e.args.get("zone"),
359
+ ),
360
+ exp.TimeStrToTime: _timestrtotime_sql,
361
+ exp.TimestampAdd: _datetime_delta_sql("TIMESTAMP_ADD"),
362
+ exp.TimestampSub: _datetime_delta_sql("TIMESTAMP_SUB"),
363
+ exp.Typeof: rename_func("toTypeName"),
364
+ exp.VarMap: _map_sql,
365
+ exp.Xor: lambda self, e: self.func("xor", e.this, e.expression),
366
+ exp.MD5Digest: rename_func("MD5"),
367
+ exp.MD5: lambda self, e: self.func("LOWER", self.func("HEX", self.func("MD5", e.this))),
368
+ exp.SHA: rename_func("SHA1"),
369
+ exp.SHA1Digest: rename_func("SHA1"),
370
+ exp.SHA2: sha256_sql,
371
+ exp.SHA2Digest: sha2_digest_sql,
372
+ exp.Split: lambda self, e: self.func(
373
+ "splitByString", e.args.get("expression"), e.this, e.args.get("limit")
374
+ ),
375
+ exp.RegexpSplit: lambda self, e: self.func(
376
+ "splitByRegexp", e.args.get("expression"), e.this, e.args.get("limit")
377
+ ),
378
+ exp.UnixToTime: _unix_to_time_sql,
379
+ exp.Trim: lambda self, e: trim_sql(self, e, default_trim_type="BOTH"),
380
+ exp.Variance: rename_func("varSamp"),
381
+ exp.VariancePop: rename_func("varPop"),
382
+ exp.WeekOfYear: rename_func("toISOWeek"),
383
+ exp.YearOfWeekIso: rename_func("toISOYear"),
384
+ exp.SchemaCommentProperty: lambda self, e: self.naked_property(e),
385
+ exp.Stddev: rename_func("stddevSamp"),
386
+ exp.Chr: rename_func("CHAR"),
387
+ exp.Lag: rename_func("lag"),
388
+ exp.Lead: rename_func("lead"),
389
+ exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")(
390
+ rename_func("editDistance")
391
+ ),
392
+ exp.ParseDatetime: lambda self, e: self.func(
393
+ "parseDateTime", e.this, e.args.get("format"), e.args.get("zone")
394
+ ),
395
+ }
396
+
397
+ PROPERTIES_LOCATION = {
398
+ **generator.Generator.PROPERTIES_LOCATION,
399
+ exp.AutoRefreshProperty: exp.Properties.Location.POST_NAME,
400
+ exp.DefinerProperty: exp.Properties.Location.POST_SCHEMA,
401
+ exp.OnCluster: exp.Properties.Location.POST_NAME,
402
+ exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
403
+ exp.ToTableProperty: exp.Properties.Location.POST_NAME,
404
+ exp.UuidProperty: exp.Properties.Location.POST_NAME,
405
+ exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
406
+ }
407
+
408
+ # There's no list in docs, but it can be found in Clickhouse code
409
+ # see `ClickHouse/src/Parsers/ParserCreate*.cpp`
410
+ ON_CLUSTER_TARGETS: t.ClassVar = {
411
+ "SCHEMA", # Transpiled CREATE SCHEMA may have OnCluster property set
412
+ "DATABASE",
413
+ "TABLE",
414
+ "VIEW",
415
+ "DICTIONARY",
416
+ "INDEX",
417
+ "FUNCTION",
418
+ "NAMED COLLECTION",
419
+ }
420
+
421
+ # https://clickhouse.com/docs/en/sql-reference/data-types/nullable
422
+ NON_NULLABLE_TYPES: t.ClassVar = {
423
+ exp.DType.ARRAY,
424
+ exp.DType.MAP,
425
+ exp.DType.STRUCT,
426
+ exp.DType.POINT,
427
+ exp.DType.RING,
428
+ exp.DType.LINESTRING,
429
+ exp.DType.MULTILINESTRING,
430
+ exp.DType.POLYGON,
431
+ exp.DType.MULTIPOLYGON,
432
+ }
433
+
434
+ @unsupported_args("json_scope")
435
+ def contains_sql(self, expression: exp.Contains) -> str:
436
+ # ClickHouse has no CONTAINS; the comparison needs parentheses inside another operator
437
+ result = exp.StrPosition(this=expression.this, substr=expression.expression) > 0
438
+ if isinstance(expression.parent, exp.Binary) and not isinstance(
439
+ expression.parent, exp.Connector
440
+ ):
441
+ return self.sql(exp.paren(result, copy=False))
442
+ return self.sql(result)
443
+
444
+ def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
445
+ this = expression.this
446
+ separator = expression.args.get("separator")
447
+
448
+ if isinstance(this, exp.Limit) and this.this:
449
+ limit = this
450
+ this = limit.this.pop()
451
+ return self.sql(
452
+ exp.ParameterizedAgg(
453
+ this="groupConcat",
454
+ params=[this],
455
+ expressions=[separator, limit.expression],
456
+ )
457
+ )
458
+
459
+ if separator:
460
+ return self.sql(
461
+ exp.ParameterizedAgg(
462
+ this="groupConcat",
463
+ params=[this],
464
+ expressions=[separator],
465
+ )
466
+ )
467
+
468
+ return self.func("groupConcat", this)
469
+
470
+ def select_sql(self, expression: exp.Select) -> str:
471
+ limit = expression.args.get("limit")
472
+ if isinstance(limit, exp.Fetch) and not expression.args.get("order"):
473
+ count = limit.args.get("count")
474
+ expression.set(
475
+ "limit", exp.Limit(expression=count if count is not None else exp.Literal.number(1))
476
+ )
477
+ return super().select_sql(expression)
478
+
479
+ def offset_sql(self, expression: exp.Offset) -> str:
480
+ offset = super().offset_sql(expression)
481
+
482
+ # OFFSET ... FETCH syntax requires a "ROW" or "ROWS" keyword
483
+ # https://clickhouse.com/docs/sql-reference/statements/select/offset
484
+ parent = expression.parent
485
+ if isinstance(parent, exp.Select) and isinstance(parent.args.get("limit"), exp.Fetch):
486
+ offset = f"{offset} ROWS"
487
+
488
+ return offset
489
+
490
+ def strtodate_sql(self, expression: exp.StrToDate) -> str:
491
+ strtodate_sql = self.function_fallback_sql(expression)
492
+
493
+ if not isinstance(expression.parent, exp.Cast):
494
+ # StrToDate returns DATEs in other dialects (eg. postgres), so
495
+ # this branch aims to improve the transpilation to clickhouse
496
+ return self.cast_sql(exp.cast(expression, "DATE"))
497
+
498
+ return strtodate_sql
499
+
500
+ def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
501
+ this = expression.this
502
+
503
+ if isinstance(this, exp.StrToDate) and expression.to == exp.DType.DATETIME.into_expr():
504
+ return self.sql(this)
505
+
506
+ this = this.unnest()
507
+ if (
508
+ isinstance(this, exp.JSONExtract)
509
+ and this.args.get("requires_json")
510
+ and expression.to.is_type(*exp.DataType.TEXT_TYPES)
511
+ ):
512
+ return self.func("JSONExtract", this, exp.Literal.string("Nullable(String)"))
513
+
514
+ return super().cast_sql(expression, safe_prefix=safe_prefix)
515
+
516
+ def trycast_sql(self, expression: exp.TryCast) -> str:
517
+ dtype = expression.to
518
+ if not dtype.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True):
519
+ # Casting x into Nullable(T) appears to behave similarly to TRY_CAST(x AS T)
520
+ dtype.set("nullable", True)
521
+
522
+ return super().cast_sql(expression)
523
+
524
+ def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
525
+ this = self.json_path_part(expression.this)
526
+ return str(int(this) + 1) if is_int(this) else this
527
+
528
+ def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
529
+ return f"AS {self.sql(expression, 'this')}"
530
+
531
+ def _any_to_has(
532
+ self,
533
+ expression: exp.EQ | exp.NEQ,
534
+ default: t.Callable[[t.Any], str],
535
+ prefix: str = "",
536
+ ) -> str:
537
+ if isinstance(expression.left, exp.Any):
538
+ arr = expression.left
539
+ this = expression.right
540
+ elif isinstance(expression.right, exp.Any):
541
+ arr = expression.right
542
+ this = expression.left
543
+ else:
544
+ return default(expression)
545
+
546
+ return prefix + self.func("has", arr.this.unnest(), this)
547
+
548
+ def eq_sql(self, expression: exp.EQ) -> str:
549
+ return self._any_to_has(expression, super().eq_sql)
550
+
551
+ def neq_sql(self, expression: exp.NEQ) -> str:
552
+ return self._any_to_has(expression, super().neq_sql, "NOT ")
553
+
554
+ def regexpcount_sql(self, expression: exp.RegexpCount) -> str:
555
+ this = expression.this
556
+ pattern = expression.expression
557
+ position = expression.args.get("position")
558
+ parameters = expression.args.get("parameters")
559
+
560
+ if position:
561
+ # SUBSTRING counts bytes in ClickHouse, the position counts characters
562
+ this = self.func("substringUTF8", this, position)
563
+
564
+ if parameters:
565
+ flags = parameters.name if parameters.is_string else ""
566
+ if not parameters.is_string or set(flags) - set("cims"):
567
+ self.unsupported("Only literal 'c', 'i', 'm' and 's' regexp flags are supported")
568
+ # "c" (case-sensitive) is the default, and the last of "c" and "i" wins
569
+ if flags.rfind("c") > flags.rfind("i"):
570
+ flags = flags.replace("i", "")
571
+ flags = "".join(f for f in flags if f in "ims")
572
+ if flags:
573
+ # countMatches has no flags argument, so they are embedded in the pattern
574
+ pattern = self.func("CONCAT", exp.Literal.string(f"(?{flags})"), pattern)
575
+
576
+ return self.func("countMatches", this, pattern)
577
+
578
+ def regexpilike_sql(self, expression: exp.RegexpILike) -> str:
579
+ # Manually add a flag to make the search case-insensitive
580
+ regex = self.func("CONCAT", "'(?i)'", expression.expression)
581
+ return self.func("match", expression.this, regex)
582
+
583
+ def datatype_sql(self, expression: exp.DataType) -> str:
584
+ # String is the standard ClickHouse type, every other variant is just an alias.
585
+ # Additionally, any supplied length parameter will be ignored.
586
+ #
587
+ # https://clickhouse.com/docs/en/sql-reference/data-types/string
588
+ if expression.this in self.STRING_TYPE_MAPPING:
589
+ dtype = "String"
590
+ else:
591
+ dtype = super().datatype_sql(expression)
592
+
593
+ # This section changes the type to `Nullable(...)` if the following conditions hold:
594
+ # - It's marked as nullable - this ensures we won't wrap ClickHouse types with `Nullable`
595
+ # and change their semantics
596
+ # - It's not the key type of a `Map`. This is because ClickHouse enforces the following
597
+ # constraint: "Type of Map key must be a type, that can be represented by integer or
598
+ # String or FixedString (possibly LowCardinality) or UUID or IPv6"
599
+ # - It's not a composite type, e.g. `Nullable(Array(...))` is not a valid type
600
+ parent = expression.parent
601
+ nullable = expression.args.get("nullable")
602
+ if nullable is True or (
603
+ nullable is None
604
+ and not (
605
+ isinstance(parent, exp.DataType)
606
+ and parent.is_type(exp.DType.MAP, check_nullable=True)
607
+ and expression.index in (None, 0)
608
+ )
609
+ and not expression.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True)
610
+ ):
611
+ dtype = f"Nullable({dtype})"
612
+
613
+ return dtype
614
+
615
+ def cte_sql(self, expression: exp.CTE) -> str:
616
+ if expression.args.get("scalar"):
617
+ this = self.sql(expression, "this")
618
+ alias = self.sql(expression, "alias")
619
+ return f"{this} AS {alias}"
620
+
621
+ return super().cte_sql(expression)
622
+
623
+ def after_limit_modifiers(self, expression: exp.Expr) -> list[str]:
624
+ return super().after_limit_modifiers(expression) + [
625
+ (
626
+ self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
627
+ if expression.args.get("settings")
628
+ else ""
629
+ ),
630
+ (
631
+ self.seg("FORMAT ") + self.sql(expression, "format")
632
+ if expression.args.get("format")
633
+ else ""
634
+ ),
635
+ ]
636
+
637
+ def placeholder_sql(self, expression: exp.Placeholder) -> str:
638
+ return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
639
+
640
+ def oncluster_sql(self, expression: exp.OnCluster) -> str:
641
+ return f"ON CLUSTER {self.sql(expression, 'this')}"
642
+
643
+ def _refresh_interval_sql(self, expression: exp.Expr) -> str:
644
+ if isinstance(expression, exp.Add):
645
+ return f"{self._refresh_interval_sql(expression.this)} {self._refresh_interval_sql(expression.expression)}"
646
+ return self.sql(expression.assert_is(exp.Interval))
647
+
648
+ def autorefreshproperty_sql(self, expression: exp.AutoRefreshProperty) -> str:
649
+ cadence = self.sql(expression, "cadence")
650
+ interval = expression.this
651
+ schedule = (
652
+ f" {cadence} {self._refresh_interval_sql(interval)}" if cadence and interval else ""
653
+ )
654
+ offset = expression.args.get("offset")
655
+ offset = f" OFFSET {self._refresh_interval_sql(offset)}" if offset else ""
656
+ randomize = expression.args.get("randomize")
657
+ randomize = f" RANDOMIZE FOR {self._refresh_interval_sql(randomize)}" if randomize else ""
658
+ dependencies = self.expressions(expression, flat=True)
659
+ dependencies = f" DEPENDS ON {dependencies}" if dependencies else ""
660
+ settings = self.sql(expression, "settings")
661
+ settings = f" {settings}" if settings else ""
662
+ append = " APPEND" if expression.args.get("append") else ""
663
+
664
+ return f"REFRESH{schedule}{offset}{randomize}{dependencies}{settings}{append}"
665
+
666
+ def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str:
667
+ if expression.kind in self.ON_CLUSTER_TARGETS and locations.get(
668
+ exp.Properties.Location.POST_NAME
669
+ ):
670
+ this_name = self.sql(
671
+ expression.this if isinstance(expression.this, exp.Schema) else expression,
672
+ "this",
673
+ )
674
+ this_properties = " ".join(
675
+ [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
676
+ )
677
+ this_schema = self.schema_columns_sql(expression.this)
678
+ this_schema = f"{self.sep()}{this_schema}" if this_schema else ""
679
+
680
+ return f"{this_name}{self.sep()}{this_properties}{this_schema}"
681
+
682
+ return super().createable_sql(expression, locations)
683
+
684
+ def create_sql(self, expression: exp.Create) -> str:
685
+ # The comment property comes last in CTAS statements, i.e. after the query
686
+ query = expression.expression
687
+ if isinstance(query, exp.Query):
688
+ comment_prop = expression.find(exp.SchemaCommentProperty)
689
+ if comment_prop:
690
+ comment_prop.pop()
691
+ if not isinstance(query, exp.Subquery):
692
+ query.replace(exp.paren(query))
693
+ else:
694
+ comment_prop = None
695
+
696
+ create_sql = super().create_sql(expression)
697
+
698
+ comment_sql = self.sql(comment_prop)
699
+ comment_sql = f" {comment_sql}" if comment_sql else ""
700
+
701
+ return f"{create_sql}{comment_sql}"
702
+
703
+ def prewhere_sql(self, expression: exp.PreWhere) -> str:
704
+ this = self.indent(self.sql(expression, "this"))
705
+ return f"{self.seg('PREWHERE')}{self.sep()}{this}"
706
+
707
+ def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
708
+ this = self.sql(expression, "this")
709
+ this = f" {this}" if this else ""
710
+ expr = self.sql(expression, "expression")
711
+ expr = f" {expr}" if expr else ""
712
+ index_type = self.sql(expression, "index_type")
713
+ index_type = f" TYPE {index_type}" if index_type else ""
714
+ granularity = self.sql(expression, "granularity")
715
+ granularity = f" GRANULARITY {granularity}" if granularity else ""
716
+
717
+ return f"INDEX{this}{expr}{index_type}{granularity}"
718
+
719
+ def partition_sql(self, expression: exp.Partition) -> str:
720
+ return f"PARTITION {self.expressions(expression, flat=True)}"
721
+
722
+ def partitionid_sql(self, expression: exp.PartitionId) -> str:
723
+ return f"ID {self.sql(expression.this)}"
724
+
725
+ def replacepartition_sql(self, expression: exp.ReplacePartition) -> str:
726
+ return f"REPLACE {self.sql(expression.expression)} FROM {self.sql(expression, 'source')}"
727
+
728
+ def projectiondef_sql(self, expression: exp.ProjectionDef) -> str:
729
+ return f"PROJECTION {self.sql(expression.this)} {self.wrap(expression.expression)}"
730
+
731
+ def nestedjsonselect_sql(self, expression: exp.NestedJSONSelect) -> str:
732
+ return f"{self.sql(expression, 'this')}.^{self.sql(expression, 'expression')}"
733
+
734
+ def is_sql(self, expression: exp.Is) -> str:
735
+ is_sql = super().is_sql(expression)
736
+
737
+ if isinstance(expression.parent, exp.Not):
738
+ # value IS NOT NULL -> NOT (value IS NULL)
739
+ is_sql = self.wrap(is_sql)
740
+
741
+ return is_sql
742
+
743
+ def in_sql(self, expression: exp.In) -> str:
744
+ in_sql = super().in_sql(expression)
745
+
746
+ if isinstance(expression.parent, exp.Not) and expression.args.get("is_global"):
747
+ in_sql = in_sql.replace("GLOBAL IN", "GLOBAL NOT IN", 1)
748
+
749
+ return in_sql
750
+
751
+ def not_sql(self, expression: exp.Not) -> str:
752
+ if isinstance(expression.this, exp.In):
753
+ if expression.this.args.get("is_global"):
754
+ # let `GLOBAL IN` child interpose `NOT`
755
+ return self.sql(expression, "this")
756
+
757
+ expression.set("this", exp.paren(expression.this, copy=False))
758
+
759
+ return super().not_sql(expression)
760
+
761
+ def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
762
+ # If the VALUES clause contains tuples of expressions, we need to treat it
763
+ # as a table since Clickhouse will automatically alias it as such.
764
+ alias = expression.args.get("alias")
765
+
766
+ if alias and alias.args.get("columns") and expression.expressions:
767
+ values = expression.expressions[0].expressions
768
+ values_as_table = any(isinstance(value, exp.Tuple) for value in values)
769
+ else:
770
+ values_as_table = True
771
+
772
+ return super().values_sql(expression, values_as_table=values_as_table)
773
+
774
+ def timestamptrunc_sql(self, expression: exp.DateTrunc | exp.TimestampTrunc) -> str:
775
+ unit = weekstart_unit_to_str(self, expression)
776
+ # https://clickhouse.com/docs/whats-new/changelog/2023#improvement
777
+ if self.dialect.version < (23, 12) and unit and unit.is_string:
778
+ unit = exp.Literal.string(unit.name.lower())
779
+ return self.func("dateTrunc", unit, expression.this, expression.args.get("zone"))
780
+
781
+ def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
782
+ return self.timestamptrunc_sql(expression)
tasks/tasksmith-ff5cea929429/environment/source/sqlglot/generators/databricks.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+
4
+ from sqlglot import exp, transforms
5
+ from sqlglot.dialects.dialect import (
6
+ date_delta_sql,
7
+ timestamptrunc_sql,
8
+ groupconcat_sql,
9
+ )
10
+ from sqlglot.generators.spark import SparkGenerator
11
+
12
+
13
+ class DatabricksGenerator(SparkGenerator):
14
+ TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
15
+ COPY_PARAMS_ARE_WRAPPED = False
16
+ COPY_PARAMS_EQ_REQUIRED = True
17
+ JSON_PATH_SINGLE_QUOTE_ESCAPE = False
18
+ JSON_PATH_KEY_QUOTED_FORCES_BRACKETS = True
19
+ SAFE_JSON_PATH_KEY_RE = exp.SAFE_IDENTIFIER_RE
20
+ QUOTE_JSON_PATH = False
21
+ PARSE_JSON_NAME: str | None = "PARSE_JSON"
22
+
23
+ TRANSFORMS = {
24
+ k: v
25
+ for k, v in {
26
+ **SparkGenerator.TRANSFORMS,
27
+ exp.CurrentVersion: lambda *_: "CURRENT_VERSION()",
28
+ exp.DateAdd: date_delta_sql("DATEADD"),
29
+ exp.DateDiff: date_delta_sql("DATEDIFF"),
30
+ exp.DatetimeAdd: lambda self, e: self.func(
31
+ "TIMESTAMPADD", e.unit, e.expression, e.this
32
+ ),
33
+ exp.DatetimeSub: lambda self, e: self.func(
34
+ "TIMESTAMPADD",
35
+ e.unit,
36
+ exp.Mul(this=e.expression, expression=exp.Literal.number(-1)),
37
+ e.this,
38
+ ),
39
+ exp.DatetimeTrunc: timestamptrunc_sql(),
40
+ exp.GroupConcat: groupconcat_sql,
41
+ exp.Select: transforms.preprocess(
42
+ [
43
+ transforms.eliminate_distinct_on,
44
+ transforms.unnest_to_explode,
45
+ transforms.any_to_exists,
46
+ ]
47
+ ),
48
+ exp.JSONExtract: lambda self, e: f"{self.sql(e, 'this')}:{self.sql(e, 'expression')}",
49
+ exp.JSONPathRoot: lambda self, e: (
50
+ "$" if isinstance(e.parent and e.parent.parent, exp.JSONExtractScalar) else ""
51
+ ),
52
+ exp.ToChar: lambda self, e: (
53
+ self.cast_sql(exp.Cast(this=e.this, to=exp.DataType(this="STRING")))
54
+ if e.args.get("is_numeric")
55
+ else self.function_fallback_sql(e)
56
+ ),
57
+ exp.CurrentCatalog: lambda *_: "CURRENT_CATALOG()",
58
+ exp.RegexpLike: None,
59
+ exp.TryCast: None,
60
+ exp.RegrAvgx: lambda self, e: self._regr_sql(e),
61
+ exp.RegrSxx: lambda self, e: self._regr_sql(e),
62
+ exp.RegrSyy: lambda self, e: self._regr_sql(e),
63
+ }.items()
64
+ if v is not None
65
+ }
66
+
67
+ TYPE_MAPPING = {
68
+ **SparkGenerator.TYPE_MAPPING,
69
+ exp.DType.NULL: "VOID",
70
+ }
71
+
72
+ def create_sql(self, expression: exp.Create) -> str:
73
+ body = expression.expression
74
+ if (
75
+ body
76
+ and not isinstance(body, exp.Return)
77
+ and expression.kind == "FUNCTION"
78
+ and any(p.args.get("is_table") for p in expression.find_all(exp.ReturnsProperty))
79
+ ):
80
+ expression.set("expression", exp.Return(this=body))
81
+ return super().create_sql(expression)
82
+
83
+ def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
84
+ constraint = expression.find(exp.GeneratedAsIdentityColumnConstraint)
85
+ kind = expression.kind
86
+ if (
87
+ constraint
88
+ and isinstance(kind, exp.DataType)
89
+ and kind.this in exp.DataType.INTEGER_TYPES
90
+ ):
91
+ # only BIGINT generated identity constraints are supported
92
+ expression.set("kind", exp.DType.BIGINT.into_expr())
93
+
94
+ return super().columndef_sql(expression, sep)
95
+
96
+ def timeserieskey_sql(self, expression: exp.TimeseriesKey) -> str:
97
+ return f"{self.sql(expression, 'this')} TIMESERIES"
98
+
99
+ def jsonpath_sql(self, expression: exp.JSONPath) -> str:
100
+ path = super().jsonpath_sql(expression)
101
+
102
+ if isinstance(expression.parent, exp.JSONExtractScalar):
103
+ path = self.escape_str(path)
104
+ return f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
105
+
106
+ return path
107
+
108
+ def uniform_sql(self, expression: exp.Uniform) -> str:
109
+ gen = expression.args.get("gen")
110
+ seed = expression.args.get("seed")
111
+
112
+ # From Snowflake UNIFORM(min, max, gen) as RANDOM(), RANDOM(seed), or constant value -> Extract seed
113
+ if gen:
114
+ seed = gen.this
115
+
116
+ return self.func("UNIFORM", expression.this, expression.expression, seed)
117
+
118
+ def _regr_sql(self, expression: exp.RegrAvgx | exp.RegrSxx | exp.RegrSyy) -> str:
119
+ name = expression.sql_name()
120
+ x = expression.expression
121
+ if isinstance(x, exp.Distinct):
122
+ return self.func(name, exp.Distinct(expressions=[expression.this]), *x.expressions)
123
+ return self.func(name, expression.this, x)
124
+
125
+ def clusterproperty_sql(self, expression):
126
+ this = self.sql(expression, "this") or f"({self.expressions(expression, flat=True)})"
127
+ return f"CLUSTER BY {this}"