altimate-code 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +1 -5
  3. package/bin/altimate +6 -0
  4. package/bin/altimate-code +6 -0
  5. package/dbt-tools/bin/altimate-dbt +2 -0
  6. package/dbt-tools/dist/altimate_python_packages/altimate_packages/altimate/__init__.py +0 -0
  7. package/dbt-tools/dist/altimate_python_packages/altimate_packages/altimate/fetch_schema.py +35 -0
  8. package/dbt-tools/dist/altimate_python_packages/altimate_packages/altimate/utils.py +353 -0
  9. package/dbt-tools/dist/altimate_python_packages/altimate_packages/altimate/validate_sql.py +114 -0
  10. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/__init__.py +178 -0
  11. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/__main__.py +96 -0
  12. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/_typing.py +17 -0
  13. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/__init__.py +3 -0
  14. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/__init__.py +18 -0
  15. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/_typing.py +18 -0
  16. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/column.py +332 -0
  17. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/dataframe.py +866 -0
  18. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/functions.py +1267 -0
  19. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/group.py +59 -0
  20. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/normalize.py +78 -0
  21. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/operations.py +53 -0
  22. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/readwriter.py +108 -0
  23. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/session.py +190 -0
  24. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/transforms.py +9 -0
  25. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/types.py +212 -0
  26. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/util.py +32 -0
  27. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dataframe/sql/window.py +134 -0
  28. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/__init__.py +118 -0
  29. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/athena.py +166 -0
  30. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/bigquery.py +1331 -0
  31. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/clickhouse.py +1393 -0
  32. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/databricks.py +131 -0
  33. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/dialect.py +1915 -0
  34. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/doris.py +561 -0
  35. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/drill.py +157 -0
  36. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/druid.py +20 -0
  37. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/duckdb.py +1159 -0
  38. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/dune.py +16 -0
  39. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/hive.py +787 -0
  40. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/materialize.py +94 -0
  41. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/mysql.py +1324 -0
  42. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/oracle.py +378 -0
  43. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/postgres.py +778 -0
  44. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/presto.py +788 -0
  45. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/prql.py +203 -0
  46. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/redshift.py +448 -0
  47. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/risingwave.py +78 -0
  48. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/snowflake.py +1464 -0
  49. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/spark.py +202 -0
  50. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/spark2.py +349 -0
  51. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/sqlite.py +320 -0
  52. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/starrocks.py +343 -0
  53. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/tableau.py +61 -0
  54. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/teradata.py +356 -0
  55. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/trino.py +115 -0
  56. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/dialects/tsql.py +1403 -0
  57. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/diff.py +456 -0
  58. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/errors.py +93 -0
  59. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/executor/__init__.py +95 -0
  60. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/executor/context.py +101 -0
  61. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/executor/env.py +246 -0
  62. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/executor/python.py +460 -0
  63. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/executor/table.py +155 -0
  64. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/expressions.py +8870 -0
  65. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/generator.py +4993 -0
  66. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/helper.py +582 -0
  67. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/jsonpath.py +227 -0
  68. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/lineage.py +423 -0
  69. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/__init__.py +11 -0
  70. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/annotate_types.py +589 -0
  71. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/canonicalize.py +222 -0
  72. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/eliminate_ctes.py +43 -0
  73. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/eliminate_joins.py +181 -0
  74. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/eliminate_subqueries.py +189 -0
  75. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/isolate_table_selects.py +50 -0
  76. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/merge_subqueries.py +415 -0
  77. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/normalize.py +200 -0
  78. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/normalize_identifiers.py +64 -0
  79. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/optimize_joins.py +91 -0
  80. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/optimizer.py +94 -0
  81. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/pushdown_predicates.py +222 -0
  82. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/pushdown_projections.py +172 -0
  83. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/qualify.py +104 -0
  84. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/qualify_columns.py +1024 -0
  85. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/qualify_tables.py +155 -0
  86. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/scope.py +904 -0
  87. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/simplify.py +1587 -0
  88. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/optimizer/unnest_subqueries.py +302 -0
  89. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/parser.py +8501 -0
  90. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/planner.py +463 -0
  91. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/schema.py +588 -0
  92. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/serde.py +68 -0
  93. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/time.py +687 -0
  94. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/tokens.py +1520 -0
  95. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/transforms.py +1020 -0
  96. package/dbt-tools/dist/altimate_python_packages/altimate_packages/sqlglot/trie.py +81 -0
  97. package/dbt-tools/dist/altimate_python_packages/dbt_core_integration.py +825 -0
  98. package/dbt-tools/dist/altimate_python_packages/dbt_utils.py +157 -0
  99. package/dbt-tools/dist/index.js +23859 -0
  100. package/package.json +13 -13
  101. package/postinstall.mjs +42 -0
  102. package/skills/altimate-setup/SKILL.md +31 -0
@@ -0,0 +1,1915 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import logging
5
+ import typing as t
6
+ import sys
7
+
8
+ from enum import Enum, auto
9
+ from functools import reduce
10
+
11
+ from sqlglot import exp
12
+ from sqlglot.dialects import DIALECT_MODULE_NAMES
13
+ from sqlglot.errors import ParseError
14
+ from sqlglot.generator import Generator, unsupported_args
15
+ from sqlglot.helper import (
16
+ AutoName,
17
+ flatten,
18
+ is_int,
19
+ seq_get,
20
+ subclasses,
21
+ suggest_closest_match_and_fail,
22
+ to_bool,
23
+ )
24
+ from sqlglot.jsonpath import JSONPathTokenizer, parse as parse_json_path
25
+ from sqlglot.parser import Parser
26
+ from sqlglot.time import TIMEZONES, format_time, subsecond_precision
27
+ from sqlglot.tokens import Token, Tokenizer, TokenType
28
+ from sqlglot.trie import new_trie
29
+
30
+ DATE_ADD_OR_DIFF = t.Union[
31
+ exp.DateAdd,
32
+ exp.DateDiff,
33
+ exp.DateSub,
34
+ exp.TsOrDsAdd,
35
+ exp.TsOrDsDiff,
36
+ ]
37
+ DATE_ADD_OR_SUB = t.Union[exp.DateAdd, exp.TsOrDsAdd, exp.DateSub]
38
+ JSON_EXTRACT_TYPE = t.Union[exp.JSONExtract, exp.JSONExtractScalar]
39
+
40
+
41
+ if t.TYPE_CHECKING:
42
+ from sqlglot._typing import B, E, F
43
+
44
+ from sqlglot.optimizer.annotate_types import TypeAnnotator
45
+
46
+ AnnotatorsType = t.Dict[t.Type[E], t.Callable[[TypeAnnotator, E], E]]
47
+
48
+ logger = logging.getLogger("sqlglot")
49
+
50
+ UNESCAPED_SEQUENCES = {
51
+ "\\a": "\a",
52
+ "\\b": "\b",
53
+ "\\f": "\f",
54
+ "\\n": "\n",
55
+ "\\r": "\r",
56
+ "\\t": "\t",
57
+ "\\v": "\v",
58
+ "\\\\": "\\",
59
+ }
60
+
61
+
62
+ def annotate_with_type_lambda(data_type: exp.DataType.Type) -> t.Callable[[TypeAnnotator, E], E]:
63
+ return lambda self, e: self._annotate_with_type(e, data_type)
64
+
65
+
66
+ class Dialects(str, Enum):
67
+ """Dialects supported by SQLGLot."""
68
+
69
+ DIALECT = ""
70
+
71
+ ATHENA = "athena"
72
+ BIGQUERY = "bigquery"
73
+ CLICKHOUSE = "clickhouse"
74
+ DATABRICKS = "databricks"
75
+ DORIS = "doris"
76
+ DRILL = "drill"
77
+ DRUID = "druid"
78
+ DUCKDB = "duckdb"
79
+ DUNE = "dune"
80
+ HIVE = "hive"
81
+ MATERIALIZE = "materialize"
82
+ MYSQL = "mysql"
83
+ ORACLE = "oracle"
84
+ POSTGRES = "postgres"
85
+ PRESTO = "presto"
86
+ PRQL = "prql"
87
+ REDSHIFT = "redshift"
88
+ RISINGWAVE = "risingwave"
89
+ SNOWFLAKE = "snowflake"
90
+ SPARK = "spark"
91
+ SPARK2 = "spark2"
92
+ SQLITE = "sqlite"
93
+ STARROCKS = "starrocks"
94
+ TABLEAU = "tableau"
95
+ TERADATA = "teradata"
96
+ TRINO = "trino"
97
+ TSQL = "tsql"
98
+
99
+
100
+ class NormalizationStrategy(str, AutoName):
101
+ """Specifies the strategy according to which identifiers should be normalized."""
102
+
103
+ LOWERCASE = auto()
104
+ """Unquoted identifiers are lowercased."""
105
+
106
+ UPPERCASE = auto()
107
+ """Unquoted identifiers are uppercased."""
108
+
109
+ CASE_SENSITIVE = auto()
110
+ """Always case-sensitive, regardless of quotes."""
111
+
112
+ CASE_INSENSITIVE = auto()
113
+ """Always case-insensitive, regardless of quotes."""
114
+
115
+
116
+ class Version(int):
117
+ def __new__(cls, version_str: t.Optional[str], *args, **kwargs):
118
+ if version_str:
119
+ parts = version_str.split(".")
120
+ parts.extend(["0"] * (3 - len(parts)))
121
+ v = int("".join([p.zfill(3) for p in parts]))
122
+ else:
123
+ # No version defined means we should support the latest engine semantics, so
124
+ # the comparison to any specific version should yield that latest is greater
125
+ v = sys.maxsize
126
+
127
+ return super(Version, cls).__new__(cls, v)
128
+
129
+
130
+ class _Dialect(type):
131
+ _classes: t.Dict[str, t.Type[Dialect]] = {}
132
+
133
+ def __eq__(cls, other: t.Any) -> bool:
134
+ if cls is other:
135
+ return True
136
+ if isinstance(other, str):
137
+ return cls is cls.get(other)
138
+ if isinstance(other, Dialect):
139
+ return cls is type(other)
140
+
141
+ return False
142
+
143
+ def __hash__(cls) -> int:
144
+ return hash(cls.__name__.lower())
145
+
146
+ @property
147
+ def classes(cls):
148
+ if len(DIALECT_MODULE_NAMES) != len(cls._classes):
149
+ for key in DIALECT_MODULE_NAMES:
150
+ cls._try_load(key)
151
+
152
+ return cls._classes
153
+
154
+ @classmethod
155
+ def _try_load(cls, key: str | Dialects) -> None:
156
+ if isinstance(key, Dialects):
157
+ key = key.value
158
+
159
+ # This import will lead to a new dialect being loaded, and hence, registered.
160
+ # We check that the key is an actual sqlglot module to avoid blindly importing
161
+ # files. Custom user dialects need to be imported at the top-level package, in
162
+ # order for them to be registered as soon as possible.
163
+ if key in DIALECT_MODULE_NAMES:
164
+ importlib.import_module(f"sqlglot.dialects.{key}")
165
+
166
+ @classmethod
167
+ def __getitem__(cls, key: str) -> t.Type[Dialect]:
168
+ if key not in cls._classes:
169
+ cls._try_load(key)
170
+
171
+ return cls._classes[key]
172
+
173
+ @classmethod
174
+ def get(
175
+ cls, key: str, default: t.Optional[t.Type[Dialect]] = None
176
+ ) -> t.Optional[t.Type[Dialect]]:
177
+ if key not in cls._classes:
178
+ cls._try_load(key)
179
+
180
+ return cls._classes.get(key, default)
181
+
182
+ def __new__(cls, clsname, bases, attrs):
183
+ klass = super().__new__(cls, clsname, bases, attrs)
184
+ enum = Dialects.__members__.get(clsname.upper())
185
+ cls._classes[enum.value if enum is not None else clsname.lower()] = klass
186
+
187
+ klass.TIME_TRIE = new_trie(klass.TIME_MAPPING)
188
+ klass.FORMAT_TRIE = (
189
+ new_trie(klass.FORMAT_MAPPING) if klass.FORMAT_MAPPING else klass.TIME_TRIE
190
+ )
191
+ klass.INVERSE_TIME_MAPPING = {v: k for k, v in klass.TIME_MAPPING.items()}
192
+ klass.INVERSE_TIME_TRIE = new_trie(klass.INVERSE_TIME_MAPPING)
193
+ klass.INVERSE_FORMAT_MAPPING = {v: k for k, v in klass.FORMAT_MAPPING.items()}
194
+ klass.INVERSE_FORMAT_TRIE = new_trie(klass.INVERSE_FORMAT_MAPPING)
195
+
196
+ klass.INVERSE_CREATABLE_KIND_MAPPING = {
197
+ v: k for k, v in klass.CREATABLE_KIND_MAPPING.items()
198
+ }
199
+
200
+ base = seq_get(bases, 0)
201
+ base_tokenizer = (getattr(base, "tokenizer_class", Tokenizer),)
202
+ base_jsonpath_tokenizer = (getattr(base, "jsonpath_tokenizer_class", JSONPathTokenizer),)
203
+ base_parser = (getattr(base, "parser_class", Parser),)
204
+ base_generator = (getattr(base, "generator_class", Generator),)
205
+
206
+ klass.tokenizer_class = klass.__dict__.get(
207
+ "Tokenizer", type("Tokenizer", base_tokenizer, {})
208
+ )
209
+ klass.jsonpath_tokenizer_class = klass.__dict__.get(
210
+ "JSONPathTokenizer", type("JSONPathTokenizer", base_jsonpath_tokenizer, {})
211
+ )
212
+ klass.parser_class = klass.__dict__.get("Parser", type("Parser", base_parser, {}))
213
+ klass.generator_class = klass.__dict__.get(
214
+ "Generator", type("Generator", base_generator, {})
215
+ )
216
+
217
+ klass.QUOTE_START, klass.QUOTE_END = list(klass.tokenizer_class._QUOTES.items())[0]
218
+ klass.IDENTIFIER_START, klass.IDENTIFIER_END = list(
219
+ klass.tokenizer_class._IDENTIFIERS.items()
220
+ )[0]
221
+
222
+ def get_start_end(token_type: TokenType) -> t.Tuple[t.Optional[str], t.Optional[str]]:
223
+ return next(
224
+ (
225
+ (s, e)
226
+ for s, (e, t) in klass.tokenizer_class._FORMAT_STRINGS.items()
227
+ if t == token_type
228
+ ),
229
+ (None, None),
230
+ )
231
+
232
+ klass.BIT_START, klass.BIT_END = get_start_end(TokenType.BIT_STRING)
233
+ klass.HEX_START, klass.HEX_END = get_start_end(TokenType.HEX_STRING)
234
+ klass.BYTE_START, klass.BYTE_END = get_start_end(TokenType.BYTE_STRING)
235
+ klass.UNICODE_START, klass.UNICODE_END = get_start_end(TokenType.UNICODE_STRING)
236
+
237
+ if "\\" in klass.tokenizer_class.STRING_ESCAPES:
238
+ klass.UNESCAPED_SEQUENCES = {
239
+ **UNESCAPED_SEQUENCES,
240
+ **klass.UNESCAPED_SEQUENCES,
241
+ }
242
+
243
+ klass.ESCAPED_SEQUENCES = {v: k for k, v in klass.UNESCAPED_SEQUENCES.items()}
244
+
245
+ klass.SUPPORTS_COLUMN_JOIN_MARKS = "(+)" in klass.tokenizer_class.KEYWORDS
246
+
247
+ if enum not in ("", "bigquery"):
248
+ klass.generator_class.SELECT_KINDS = ()
249
+
250
+ if enum not in ("", "athena", "presto", "trino", "duckdb"):
251
+ klass.generator_class.TRY_SUPPORTED = False
252
+ klass.generator_class.SUPPORTS_UESCAPE = False
253
+
254
+ if enum not in ("", "databricks", "hive", "spark", "spark2"):
255
+ modifier_transforms = klass.generator_class.AFTER_HAVING_MODIFIER_TRANSFORMS.copy()
256
+ for modifier in ("cluster", "distribute", "sort"):
257
+ modifier_transforms.pop(modifier, None)
258
+
259
+ klass.generator_class.AFTER_HAVING_MODIFIER_TRANSFORMS = modifier_transforms
260
+
261
+ if enum not in ("", "doris", "mysql"):
262
+ klass.parser_class.ID_VAR_TOKENS = klass.parser_class.ID_VAR_TOKENS | {
263
+ TokenType.STRAIGHT_JOIN,
264
+ }
265
+ klass.parser_class.TABLE_ALIAS_TOKENS = klass.parser_class.TABLE_ALIAS_TOKENS | {
266
+ TokenType.STRAIGHT_JOIN,
267
+ }
268
+
269
+ if not klass.SUPPORTS_SEMI_ANTI_JOIN:
270
+ klass.parser_class.TABLE_ALIAS_TOKENS = klass.parser_class.TABLE_ALIAS_TOKENS | {
271
+ TokenType.ANTI,
272
+ TokenType.SEMI,
273
+ }
274
+
275
+ return klass
276
+
277
+
278
+ class Dialect(metaclass=_Dialect):
279
+ INDEX_OFFSET = 0
280
+ """The base index offset for arrays."""
281
+
282
+ WEEK_OFFSET = 0
283
+ """First day of the week in DATE_TRUNC(week). Defaults to 0 (Monday). -1 would be Sunday."""
284
+
285
+ UNNEST_COLUMN_ONLY = False
286
+ """Whether `UNNEST` table aliases are treated as column aliases."""
287
+
288
+ ALIAS_POST_TABLESAMPLE = False
289
+ """Whether the table alias comes after tablesample."""
290
+
291
+ TABLESAMPLE_SIZE_IS_PERCENT = False
292
+ """Whether a size in the table sample clause represents percentage."""
293
+
294
+ NORMALIZATION_STRATEGY = NormalizationStrategy.LOWERCASE
295
+ """Specifies the strategy according to which identifiers should be normalized."""
296
+
297
+ IDENTIFIERS_CAN_START_WITH_DIGIT = False
298
+ """Whether an unquoted identifier can start with a digit."""
299
+
300
+ DPIPE_IS_STRING_CONCAT = True
301
+ """Whether the DPIPE token (`||`) is a string concatenation operator."""
302
+
303
+ STRICT_STRING_CONCAT = False
304
+ """Whether `CONCAT`'s arguments must be strings."""
305
+
306
+ SUPPORTS_USER_DEFINED_TYPES = True
307
+ """Whether user-defined data types are supported."""
308
+
309
+ SUPPORTS_SEMI_ANTI_JOIN = True
310
+ """Whether `SEMI` or `ANTI` joins are supported."""
311
+
312
+ SUPPORTS_COLUMN_JOIN_MARKS = False
313
+ """Whether the old-style outer join (+) syntax is supported."""
314
+
315
+ COPY_PARAMS_ARE_CSV = True
316
+ """Separator of COPY statement parameters."""
317
+
318
+ NORMALIZE_FUNCTIONS: bool | str = "upper"
319
+ """
320
+ Determines how function names are going to be normalized.
321
+ Possible values:
322
+ "upper" or True: Convert names to uppercase.
323
+ "lower": Convert names to lowercase.
324
+ False: Disables function name normalization.
325
+ """
326
+
327
+ PRESERVE_ORIGINAL_NAMES: bool = False
328
+ """
329
+ Whether the name of the function should be preserved inside the node's metadata,
330
+ can be useful for roundtripping deprecated vs new functions that share an AST node
331
+ e.g JSON_VALUE vs JSON_EXTRACT_SCALAR in BigQuery
332
+ """
333
+
334
+ LOG_BASE_FIRST: t.Optional[bool] = True
335
+ """
336
+ Whether the base comes first in the `LOG` function.
337
+ Possible values: `True`, `False`, `None` (two arguments are not supported by `LOG`)
338
+ """
339
+
340
+ NULL_ORDERING = "nulls_are_small"
341
+ """
342
+ Default `NULL` ordering method to use if not explicitly set.
343
+ Possible values: `"nulls_are_small"`, `"nulls_are_large"`, `"nulls_are_last"`
344
+ """
345
+
346
+ TYPED_DIVISION = False
347
+ """
348
+ Whether the behavior of `a / b` depends on the types of `a` and `b`.
349
+ False means `a / b` is always float division.
350
+ True means `a / b` is integer division if both `a` and `b` are integers.
351
+ """
352
+
353
+ SAFE_DIVISION = False
354
+ """Whether division by zero throws an error (`False`) or returns NULL (`True`)."""
355
+
356
+ CONCAT_COALESCE = False
357
+ """A `NULL` arg in `CONCAT` yields `NULL` by default, but in some dialects it yields an empty string."""
358
+
359
+ HEX_LOWERCASE = False
360
+ """Whether the `HEX` function returns a lowercase hexadecimal string."""
361
+
362
+ DATE_FORMAT = "'%Y-%m-%d'"
363
+ DATEINT_FORMAT = "'%Y%m%d'"
364
+ TIME_FORMAT = "'%Y-%m-%d %H:%M:%S'"
365
+
366
+ TIME_MAPPING: t.Dict[str, str] = {}
367
+ """Associates this dialect's time formats with their equivalent Python `strftime` formats."""
368
+
369
+ # https://cloud.google.com/bigquery/docs/reference/standard-sql/format-elements#format_model_rules_date_time
370
+ # https://docs.teradata.com/r/Teradata-Database-SQL-Functions-Operators-Expressions-and-Predicates/March-2017/Data-Type-Conversions/Character-to-DATE-Conversion/Forcing-a-FORMAT-on-CAST-for-Converting-Character-to-DATE
371
+ FORMAT_MAPPING: t.Dict[str, str] = {}
372
+ """
373
+ Helper which is used for parsing the special syntax `CAST(x AS DATE FORMAT 'yyyy')`.
374
+ If empty, the corresponding trie will be constructed off of `TIME_MAPPING`.
375
+ """
376
+
377
+ UNESCAPED_SEQUENCES: t.Dict[str, str] = {}
378
+ """Mapping of an escaped sequence (`\\n`) to its unescaped version (`\n`)."""
379
+
380
+ PSEUDOCOLUMNS: t.Set[str] = set()
381
+ """
382
+ Columns that are auto-generated by the engine corresponding to this dialect.
383
+ For example, such columns may be excluded from `SELECT *` queries.
384
+ """
385
+
386
+ PREFER_CTE_ALIAS_COLUMN = False
387
+ """
388
+ Some dialects, such as Snowflake, allow you to reference a CTE column alias in the
389
+ HAVING clause of the CTE. This flag will cause the CTE alias columns to override
390
+ any projection aliases in the subquery.
391
+
392
+ For example,
393
+ WITH y(c) AS (
394
+ SELECT SUM(a) FROM (SELECT 1 a) AS x HAVING c > 0
395
+ ) SELECT c FROM y;
396
+
397
+ will be rewritten as
398
+
399
+ WITH y(c) AS (
400
+ SELECT SUM(a) AS c FROM (SELECT 1 AS a) AS x HAVING c > 0
401
+ ) SELECT c FROM y;
402
+ """
403
+
404
+ COPY_PARAMS_ARE_CSV = True
405
+ """
406
+ Whether COPY statement parameters are separated by comma or whitespace
407
+ """
408
+
409
+ FORCE_EARLY_ALIAS_REF_EXPANSION = False
410
+ """
411
+ Whether alias reference expansion (_expand_alias_refs()) should run before column qualification (_qualify_columns()).
412
+
413
+ For example:
414
+ WITH data AS (
415
+ SELECT
416
+ 1 AS id,
417
+ 2 AS my_id
418
+ )
419
+ SELECT
420
+ id AS my_id
421
+ FROM
422
+ data
423
+ WHERE
424
+ my_id = 1
425
+ GROUP BY
426
+ my_id,
427
+ HAVING
428
+ my_id = 1
429
+
430
+ In most dialects, "my_id" would refer to "data.my_id" across the query, except:
431
+ - BigQuery, which will forward the alias to GROUP BY + HAVING clauses i.e
432
+ it resolves to "WHERE my_id = 1 GROUP BY id HAVING id = 1"
433
+ - Clickhouse, which will forward the alias across the query i.e it resolves
434
+ to "WHERE id = 1 GROUP BY id HAVING id = 1"
435
+ """
436
+
437
+ EXPAND_ALIAS_REFS_EARLY_ONLY_IN_GROUP_BY = False
438
+ """Whether alias reference expansion before qualification should only happen for the GROUP BY clause."""
439
+
440
+ SUPPORTS_ORDER_BY_ALL = False
441
+ """
442
+ Whether ORDER BY ALL is supported (expands to all the selected columns) as in DuckDB, Spark3/Databricks
443
+ """
444
+
445
+ HAS_DISTINCT_ARRAY_CONSTRUCTORS = False
446
+ """
447
+ Whether the ARRAY constructor is context-sensitive, i.e in Redshift ARRAY[1, 2, 3] != ARRAY(1, 2, 3)
448
+ as the former is of type INT[] vs the latter which is SUPER
449
+ """
450
+
451
+ SUPPORTS_FIXED_SIZE_ARRAYS = False
452
+ """
453
+ Whether expressions such as x::INT[5] should be parsed as fixed-size array defs/casts e.g.
454
+ in DuckDB. In dialects which don't support fixed size arrays such as Snowflake, this should
455
+ be interpreted as a subscript/index operator.
456
+ """
457
+
458
+ STRICT_JSON_PATH_SYNTAX = True
459
+ """Whether failing to parse a JSON path expression using the JSONPath dialect will log a warning."""
460
+
461
+ ON_CONDITION_EMPTY_BEFORE_ERROR = True
462
+ """Whether "X ON EMPTY" should come before "X ON ERROR" (for dialects like T-SQL, MySQL, Oracle)."""
463
+
464
+ ARRAY_AGG_INCLUDES_NULLS: t.Optional[bool] = True
465
+ """Whether ArrayAgg needs to filter NULL values."""
466
+
467
+ PROMOTE_TO_INFERRED_DATETIME_TYPE = False
468
+ """
469
+ This flag is used in the optimizer's canonicalize rule and determines whether x will be promoted
470
+ to the literal's type in x::DATE < '2020-01-01 12:05:03' (i.e., DATETIME). When false, the literal
471
+ is cast to x's type to match it instead.
472
+ """
473
+
474
+ SUPPORTS_VALUES_DEFAULT = True
475
+ """Whether the DEFAULT keyword is supported in the VALUES clause."""
476
+
477
+ NUMBERS_CAN_BE_UNDERSCORE_SEPARATED = False
478
+ """Whether number literals can include underscores for better readability"""
479
+
480
+ HEX_STRING_IS_INTEGER_TYPE: bool = False
481
+ """Whether hex strings such as x'CC' evaluate to integer or binary/blob type"""
482
+
483
+ REGEXP_EXTRACT_DEFAULT_GROUP = 0
484
+ """The default value for the capturing group."""
485
+
486
+ SET_OP_DISTINCT_BY_DEFAULT: t.Dict[t.Type[exp.Expression], t.Optional[bool]] = {
487
+ exp.Except: True,
488
+ exp.Intersect: True,
489
+ exp.Union: True,
490
+ }
491
+ """
492
+ Whether a set operation uses DISTINCT by default. This is `None` when either `DISTINCT` or `ALL`
493
+ must be explicitly specified.
494
+ """
495
+
496
+ CREATABLE_KIND_MAPPING: dict[str, str] = {}
497
+ """
498
+ Helper for dialects that use a different name for the same creatable kind. For example, the Clickhouse
499
+ equivalent of CREATE SCHEMA is CREATE DATABASE.
500
+ """
501
+
502
+ # Whether ADD is present for each column added by ALTER TABLE
503
+ ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = True
504
+
505
+ # --- Autofilled ---
506
+
507
+ tokenizer_class = Tokenizer
508
+ jsonpath_tokenizer_class = JSONPathTokenizer
509
+ parser_class = Parser
510
+ generator_class = Generator
511
+
512
+ # A trie of the time_mapping keys
513
+ TIME_TRIE: t.Dict = {}
514
+ FORMAT_TRIE: t.Dict = {}
515
+
516
+ INVERSE_TIME_MAPPING: t.Dict[str, str] = {}
517
+ INVERSE_TIME_TRIE: t.Dict = {}
518
+ INVERSE_FORMAT_MAPPING: t.Dict[str, str] = {}
519
+ INVERSE_FORMAT_TRIE: t.Dict = {}
520
+
521
+ INVERSE_CREATABLE_KIND_MAPPING: dict[str, str] = {}
522
+
523
+ ESCAPED_SEQUENCES: t.Dict[str, str] = {}
524
+
525
+ # Delimiters for string literals and identifiers
526
+ QUOTE_START = "'"
527
+ QUOTE_END = "'"
528
+ IDENTIFIER_START = '"'
529
+ IDENTIFIER_END = '"'
530
+
531
+ # Delimiters for bit, hex, byte and unicode literals
532
+ BIT_START: t.Optional[str] = None
533
+ BIT_END: t.Optional[str] = None
534
+ HEX_START: t.Optional[str] = None
535
+ HEX_END: t.Optional[str] = None
536
+ BYTE_START: t.Optional[str] = None
537
+ BYTE_END: t.Optional[str] = None
538
+ UNICODE_START: t.Optional[str] = None
539
+ UNICODE_END: t.Optional[str] = None
540
+
541
+ DATE_PART_MAPPING = {
542
+ "Y": "YEAR",
543
+ "YY": "YEAR",
544
+ "YYY": "YEAR",
545
+ "YYYY": "YEAR",
546
+ "YR": "YEAR",
547
+ "YEARS": "YEAR",
548
+ "YRS": "YEAR",
549
+ "MM": "MONTH",
550
+ "MON": "MONTH",
551
+ "MONS": "MONTH",
552
+ "MONTHS": "MONTH",
553
+ "D": "DAY",
554
+ "DD": "DAY",
555
+ "DAYS": "DAY",
556
+ "DAYOFMONTH": "DAY",
557
+ "DAY OF WEEK": "DAYOFWEEK",
558
+ "WEEKDAY": "DAYOFWEEK",
559
+ "DOW": "DAYOFWEEK",
560
+ "DW": "DAYOFWEEK",
561
+ "WEEKDAY_ISO": "DAYOFWEEKISO",
562
+ "DOW_ISO": "DAYOFWEEKISO",
563
+ "DW_ISO": "DAYOFWEEKISO",
564
+ "DAY OF YEAR": "DAYOFYEAR",
565
+ "DOY": "DAYOFYEAR",
566
+ "DY": "DAYOFYEAR",
567
+ "W": "WEEK",
568
+ "WK": "WEEK",
569
+ "WEEKOFYEAR": "WEEK",
570
+ "WOY": "WEEK",
571
+ "WY": "WEEK",
572
+ "WEEK_ISO": "WEEKISO",
573
+ "WEEKOFYEARISO": "WEEKISO",
574
+ "WEEKOFYEAR_ISO": "WEEKISO",
575
+ "Q": "QUARTER",
576
+ "QTR": "QUARTER",
577
+ "QTRS": "QUARTER",
578
+ "QUARTERS": "QUARTER",
579
+ "H": "HOUR",
580
+ "HH": "HOUR",
581
+ "HR": "HOUR",
582
+ "HOURS": "HOUR",
583
+ "HRS": "HOUR",
584
+ "M": "MINUTE",
585
+ "MI": "MINUTE",
586
+ "MIN": "MINUTE",
587
+ "MINUTES": "MINUTE",
588
+ "MINS": "MINUTE",
589
+ "S": "SECOND",
590
+ "SEC": "SECOND",
591
+ "SECONDS": "SECOND",
592
+ "SECS": "SECOND",
593
+ "MS": "MILLISECOND",
594
+ "MSEC": "MILLISECOND",
595
+ "MSECS": "MILLISECOND",
596
+ "MSECOND": "MILLISECOND",
597
+ "MSECONDS": "MILLISECOND",
598
+ "MILLISEC": "MILLISECOND",
599
+ "MILLISECS": "MILLISECOND",
600
+ "MILLISECON": "MILLISECOND",
601
+ "MILLISECONDS": "MILLISECOND",
602
+ "US": "MICROSECOND",
603
+ "USEC": "MICROSECOND",
604
+ "USECS": "MICROSECOND",
605
+ "MICROSEC": "MICROSECOND",
606
+ "MICROSECS": "MICROSECOND",
607
+ "USECOND": "MICROSECOND",
608
+ "USECONDS": "MICROSECOND",
609
+ "MICROSECONDS": "MICROSECOND",
610
+ "NS": "NANOSECOND",
611
+ "NSEC": "NANOSECOND",
612
+ "NANOSEC": "NANOSECOND",
613
+ "NSECOND": "NANOSECOND",
614
+ "NSECONDS": "NANOSECOND",
615
+ "NANOSECS": "NANOSECOND",
616
+ "EPOCH_SECOND": "EPOCH",
617
+ "EPOCH_SECONDS": "EPOCH",
618
+ "EPOCH_MILLISECONDS": "EPOCH_MILLISECOND",
619
+ "EPOCH_MICROSECONDS": "EPOCH_MICROSECOND",
620
+ "EPOCH_NANOSECONDS": "EPOCH_NANOSECOND",
621
+ "TZH": "TIMEZONE_HOUR",
622
+ "TZM": "TIMEZONE_MINUTE",
623
+ "DEC": "DECADE",
624
+ "DECS": "DECADE",
625
+ "DECADES": "DECADE",
626
+ "MIL": "MILLENIUM",
627
+ "MILS": "MILLENIUM",
628
+ "MILLENIA": "MILLENIUM",
629
+ "C": "CENTURY",
630
+ "CENT": "CENTURY",
631
+ "CENTS": "CENTURY",
632
+ "CENTURIES": "CENTURY",
633
+ }
634
+
635
+ TYPE_TO_EXPRESSIONS: t.Dict[exp.DataType.Type, t.Set[t.Type[exp.Expression]]] = {
636
+ exp.DataType.Type.BIGINT: {
637
+ exp.ApproxDistinct,
638
+ exp.ArraySize,
639
+ exp.Length,
640
+ },
641
+ exp.DataType.Type.BOOLEAN: {
642
+ exp.Between,
643
+ exp.Boolean,
644
+ exp.In,
645
+ exp.RegexpLike,
646
+ },
647
+ exp.DataType.Type.DATE: {
648
+ exp.CurrentDate,
649
+ exp.Date,
650
+ exp.DateFromParts,
651
+ exp.DateStrToDate,
652
+ exp.DiToDate,
653
+ exp.StrToDate,
654
+ exp.TimeStrToDate,
655
+ exp.TsOrDsToDate,
656
+ },
657
+ exp.DataType.Type.DATETIME: {
658
+ exp.CurrentDatetime,
659
+ exp.Datetime,
660
+ exp.DatetimeAdd,
661
+ exp.DatetimeSub,
662
+ },
663
+ exp.DataType.Type.DOUBLE: {
664
+ exp.ApproxQuantile,
665
+ exp.Avg,
666
+ exp.Exp,
667
+ exp.Ln,
668
+ exp.Log,
669
+ exp.Pow,
670
+ exp.Quantile,
671
+ exp.Round,
672
+ exp.SafeDivide,
673
+ exp.Sqrt,
674
+ exp.Stddev,
675
+ exp.StddevPop,
676
+ exp.StddevSamp,
677
+ exp.ToDouble,
678
+ exp.Variance,
679
+ exp.VariancePop,
680
+ },
681
+ exp.DataType.Type.INT: {
682
+ exp.Ceil,
683
+ exp.DatetimeDiff,
684
+ exp.DateDiff,
685
+ exp.TimestampDiff,
686
+ exp.TimeDiff,
687
+ exp.DateToDi,
688
+ exp.Levenshtein,
689
+ exp.Sign,
690
+ exp.StrPosition,
691
+ exp.TsOrDiToDi,
692
+ },
693
+ exp.DataType.Type.JSON: {
694
+ exp.ParseJSON,
695
+ },
696
+ exp.DataType.Type.TIME: {
697
+ exp.CurrentTime,
698
+ exp.Time,
699
+ exp.TimeAdd,
700
+ exp.TimeSub,
701
+ },
702
+ exp.DataType.Type.TIMESTAMP: {
703
+ exp.CurrentTimestamp,
704
+ exp.StrToTime,
705
+ exp.TimeStrToTime,
706
+ exp.TimestampAdd,
707
+ exp.TimestampSub,
708
+ exp.UnixToTime,
709
+ },
710
+ exp.DataType.Type.TINYINT: {
711
+ exp.Day,
712
+ exp.Month,
713
+ exp.Week,
714
+ exp.Year,
715
+ exp.Quarter,
716
+ },
717
+ exp.DataType.Type.VARCHAR: {
718
+ exp.ArrayConcat,
719
+ exp.Concat,
720
+ exp.ConcatWs,
721
+ exp.DateToDateStr,
722
+ exp.DPipe,
723
+ exp.GroupConcat,
724
+ exp.Initcap,
725
+ exp.Lower,
726
+ exp.Substring,
727
+ exp.String,
728
+ exp.TimeToStr,
729
+ exp.TimeToTimeStr,
730
+ exp.Trim,
731
+ exp.TsOrDsToDateStr,
732
+ exp.UnixToStr,
733
+ exp.UnixToTimeStr,
734
+ exp.Upper,
735
+ },
736
+ }
737
+
738
+ ANNOTATORS: AnnotatorsType = {
739
+ **{
740
+ expr_type: lambda self, e: self._annotate_unary(e)
741
+ for expr_type in subclasses(exp.__name__, (exp.Unary, exp.Alias))
742
+ },
743
+ **{
744
+ expr_type: lambda self, e: self._annotate_binary(e)
745
+ for expr_type in subclasses(exp.__name__, exp.Binary)
746
+ },
747
+ **{
748
+ expr_type: annotate_with_type_lambda(data_type)
749
+ for data_type, expressions in TYPE_TO_EXPRESSIONS.items()
750
+ for expr_type in expressions
751
+ },
752
+ exp.Abs: lambda self, e: self._annotate_by_args(e, "this"),
753
+ exp.Anonymous: lambda self, e: self._annotate_with_type(e, exp.DataType.Type.UNKNOWN),
754
+ exp.Array: lambda self, e: self._annotate_by_args(e, "expressions", array=True),
755
+ exp.ArrayAgg: lambda self, e: self._annotate_by_args(e, "this", array=True),
756
+ exp.ArrayConcat: lambda self, e: self._annotate_by_args(e, "this", "expressions"),
757
+ exp.Bracket: lambda self, e: self._annotate_bracket(e),
758
+ exp.Cast: lambda self, e: self._annotate_with_type(e, e.args["to"]),
759
+ exp.Case: lambda self, e: self._annotate_by_args(e, "default", "ifs"),
760
+ exp.Coalesce: lambda self, e: self._annotate_by_args(e, "this", "expressions"),
761
+ exp.Count: lambda self, e: self._annotate_with_type(
762
+ e, exp.DataType.Type.BIGINT if e.args.get("big_int") else exp.DataType.Type.INT
763
+ ),
764
+ exp.DataType: lambda self, e: self._annotate_with_type(e, e.copy()),
765
+ exp.DateAdd: lambda self, e: self._annotate_timeunit(e),
766
+ exp.DateSub: lambda self, e: self._annotate_timeunit(e),
767
+ exp.DateTrunc: lambda self, e: self._annotate_timeunit(e),
768
+ exp.Distinct: lambda self, e: self._annotate_by_args(e, "expressions"),
769
+ exp.Div: lambda self, e: self._annotate_div(e),
770
+ exp.Dot: lambda self, e: self._annotate_dot(e),
771
+ exp.Explode: lambda self, e: self._annotate_explode(e),
772
+ exp.Extract: lambda self, e: self._annotate_extract(e),
773
+ exp.Filter: lambda self, e: self._annotate_by_args(e, "this"),
774
+ exp.GenerateDateArray: lambda self, e: self._annotate_with_type(
775
+ e, exp.DataType.build("ARRAY<DATE>")
776
+ ),
777
+ exp.GenerateTimestampArray: lambda self, e: self._annotate_with_type(
778
+ e, exp.DataType.build("ARRAY<TIMESTAMP>")
779
+ ),
780
+ exp.Greatest: lambda self, e: self._annotate_by_args(e, "this", "expressions"),
781
+ exp.If: lambda self, e: self._annotate_by_args(e, "true", "false"),
782
+ exp.Interval: lambda self, e: self._annotate_with_type(e, exp.DataType.Type.INTERVAL),
783
+ exp.Least: lambda self, e: self._annotate_by_args(e, "this", "expressions"),
784
+ exp.Literal: lambda self, e: self._annotate_literal(e),
785
+ exp.Map: lambda self, e: self._annotate_map(e),
786
+ exp.Max: lambda self, e: self._annotate_by_args(e, "this", "expressions"),
787
+ exp.Min: lambda self, e: self._annotate_by_args(e, "this", "expressions"),
788
+ exp.Null: lambda self, e: self._annotate_with_type(e, exp.DataType.Type.NULL),
789
+ exp.Nullif: lambda self, e: self._annotate_by_args(e, "this", "expression"),
790
+ exp.PropertyEQ: lambda self, e: self._annotate_by_args(e, "expression"),
791
+ exp.Slice: lambda self, e: self._annotate_with_type(e, exp.DataType.Type.UNKNOWN),
792
+ exp.Struct: lambda self, e: self._annotate_struct(e),
793
+ exp.Sum: lambda self, e: self._annotate_by_args(e, "this", "expressions", promote=True),
794
+ exp.SortArray: lambda self, e: self._annotate_by_args(e, "this"),
795
+ exp.Timestamp: lambda self, e: self._annotate_with_type(
796
+ e,
797
+ exp.DataType.Type.TIMESTAMPTZ if e.args.get("with_tz") else exp.DataType.Type.TIMESTAMP,
798
+ ),
799
+ exp.ToMap: lambda self, e: self._annotate_to_map(e),
800
+ exp.TryCast: lambda self, e: self._annotate_with_type(e, e.args["to"]),
801
+ exp.Unnest: lambda self, e: self._annotate_unnest(e),
802
+ exp.VarMap: lambda self, e: self._annotate_map(e),
803
+ }
804
+
805
+ # Specifies what types a given type can be coerced into
806
+ COERCES_TO: t.Dict[exp.DataType.Type, t.Set[exp.DataType.Type]] = {}
807
+
808
+ # Determines the supported Dialect instance settings
809
+ SUPPORTED_SETTINGS = {
810
+ "normalization_strategy",
811
+ "version",
812
+ }
813
+
814
+ @classmethod
815
+ def get_or_raise(cls, dialect: DialectType) -> Dialect:
816
+ """
817
+ Look up a dialect in the global dialect registry and return it if it exists.
818
+
819
+ Args:
820
+ dialect: The target dialect. If this is a string, it can be optionally followed by
821
+ additional key-value pairs that are separated by commas and are used to specify
822
+ dialect settings, such as whether the dialect's identifiers are case-sensitive.
823
+
824
+ Example:
825
+ >>> dialect = dialect_class = get_or_raise("duckdb")
826
+ >>> dialect = get_or_raise("mysql, normalization_strategy = case_sensitive")
827
+
828
+ Returns:
829
+ The corresponding Dialect instance.
830
+ """
831
+
832
+ if not dialect:
833
+ return cls()
834
+ if isinstance(dialect, _Dialect):
835
+ return dialect()
836
+ if isinstance(dialect, Dialect):
837
+ return dialect
838
+ if isinstance(dialect, str):
839
+ try:
840
+ dialect_name, *kv_strings = dialect.split(",")
841
+ kv_pairs = (kv.split("=") for kv in kv_strings)
842
+ kwargs = {}
843
+ for pair in kv_pairs:
844
+ key = pair[0].strip()
845
+ value: t.Union[bool | str | None] = None
846
+
847
+ if len(pair) == 1:
848
+ # Default initialize standalone settings to True
849
+ value = True
850
+ elif len(pair) == 2:
851
+ value = pair[1].strip()
852
+
853
+ kwargs[key] = to_bool(value)
854
+
855
+ except ValueError:
856
+ raise ValueError(
857
+ f"Invalid dialect format: '{dialect}'. "
858
+ "Please use the correct format: 'dialect [, k1 = v2 [, ...]]'."
859
+ )
860
+
861
+ result = cls.get(dialect_name.strip())
862
+ if not result:
863
+ suggest_closest_match_and_fail("dialect", dialect_name, list(DIALECT_MODULE_NAMES))
864
+
865
+ assert result is not None
866
+ return result(**kwargs)
867
+
868
+ raise ValueError(f"Invalid dialect type for '{dialect}': '{type(dialect)}'.")
869
+
870
+ @classmethod
871
+ def format_time(
872
+ cls, expression: t.Optional[str | exp.Expression]
873
+ ) -> t.Optional[exp.Expression]:
874
+ """Converts a time format in this dialect to its equivalent Python `strftime` format."""
875
+ if isinstance(expression, str):
876
+ return exp.Literal.string(
877
+ # the time formats are quoted
878
+ format_time(expression[1:-1], cls.TIME_MAPPING, cls.TIME_TRIE)
879
+ )
880
+
881
+ if expression and expression.is_string:
882
+ return exp.Literal.string(format_time(expression.this, cls.TIME_MAPPING, cls.TIME_TRIE))
883
+
884
+ return expression
885
+
886
+ def __init__(self, **kwargs) -> None:
887
+ self.version = Version(kwargs.pop("version", None))
888
+
889
+ normalization_strategy = kwargs.pop("normalization_strategy", None)
890
+ if normalization_strategy is None:
891
+ self.normalization_strategy = self.NORMALIZATION_STRATEGY
892
+ else:
893
+ self.normalization_strategy = NormalizationStrategy(normalization_strategy.upper())
894
+
895
+ self.settings = kwargs
896
+
897
+ for unsupported_setting in kwargs.keys() - self.SUPPORTED_SETTINGS:
898
+ suggest_closest_match_and_fail("setting", unsupported_setting, self.SUPPORTED_SETTINGS)
899
+
900
+ def __eq__(self, other: t.Any) -> bool:
901
+ # Does not currently take dialect state into account
902
+ return type(self) == other
903
+
904
+ def __hash__(self) -> int:
905
+ # Does not currently take dialect state into account
906
+ return hash(type(self))
907
+
908
+ def normalize_identifier(self, expression: E) -> E:
909
+ """
910
+ Transforms an identifier in a way that resembles how it'd be resolved by this dialect.
911
+
912
+ For example, an identifier like `FoO` would be resolved as `foo` in Postgres, because it
913
+ lowercases all unquoted identifiers. On the other hand, Snowflake uppercases them, so
914
+ it would resolve it as `FOO`. If it was quoted, it'd need to be treated as case-sensitive,
915
+ and so any normalization would be prohibited in order to avoid "breaking" the identifier.
916
+
917
+ There are also dialects like Spark, which are case-insensitive even when quotes are
918
+ present, and dialects like MySQL, whose resolution rules match those employed by the
919
+ underlying operating system, for example they may always be case-sensitive in Linux.
920
+
921
+ Finally, the normalization behavior of some engines can even be controlled through flags,
922
+ like in Redshift's case, where users can explicitly set enable_case_sensitive_identifier.
923
+
924
+ SQLGlot aims to understand and handle all of these different behaviors gracefully, so
925
+ that it can analyze queries in the optimizer and successfully capture their semantics.
926
+ """
927
+ if (
928
+ isinstance(expression, exp.Identifier)
929
+ and self.normalization_strategy is not NormalizationStrategy.CASE_SENSITIVE
930
+ and (
931
+ not expression.quoted
932
+ or self.normalization_strategy is NormalizationStrategy.CASE_INSENSITIVE
933
+ )
934
+ ):
935
+ expression.set(
936
+ "this",
937
+ (
938
+ expression.this.upper()
939
+ if self.normalization_strategy is NormalizationStrategy.UPPERCASE
940
+ else expression.this.lower()
941
+ ),
942
+ )
943
+
944
+ return expression
945
+
946
+ def case_sensitive(self, text: str) -> bool:
947
+ """Checks if text contains any case sensitive characters, based on the dialect's rules."""
948
+ if self.normalization_strategy is NormalizationStrategy.CASE_INSENSITIVE:
949
+ return False
950
+
951
+ unsafe = (
952
+ str.islower
953
+ if self.normalization_strategy is NormalizationStrategy.UPPERCASE
954
+ else str.isupper
955
+ )
956
+ return any(unsafe(char) for char in text)
957
+
958
+ def can_identify(self, text: str, identify: str | bool = "safe") -> bool:
959
+ """Checks if text can be identified given an identify option.
960
+
961
+ Args:
962
+ text: The text to check.
963
+ identify:
964
+ `"always"` or `True`: Always returns `True`.
965
+ `"safe"`: Only returns `True` if the identifier is case-insensitive.
966
+
967
+ Returns:
968
+ Whether the given text can be identified.
969
+ """
970
+ if identify is True or identify == "always":
971
+ return True
972
+
973
+ if identify == "safe":
974
+ return not self.case_sensitive(text)
975
+
976
+ return False
977
+
978
+ def quote_identifier(self, expression: E, identify: bool = True) -> E:
979
+ """
980
+ Adds quotes to a given identifier.
981
+
982
+ Args:
983
+ expression: The expression of interest. If it's not an `Identifier`, this method is a no-op.
984
+ identify: If set to `False`, the quotes will only be added if the identifier is deemed
985
+ "unsafe", with respect to its characters and this dialect's normalization strategy.
986
+ """
987
+ if isinstance(expression, exp.Identifier) and not isinstance(expression.parent, exp.Func):
988
+ name = expression.this
989
+ expression.set(
990
+ "quoted",
991
+ identify or self.case_sensitive(name) or not exp.SAFE_IDENTIFIER_RE.match(name),
992
+ )
993
+
994
+ return expression
995
+
996
+ def to_json_path(self, path: t.Optional[exp.Expression]) -> t.Optional[exp.Expression]:
997
+ if isinstance(path, exp.Literal):
998
+ path_text = path.name
999
+ if path.is_number:
1000
+ path_text = f"[{path_text}]"
1001
+ try:
1002
+ return parse_json_path(path_text, self)
1003
+ except ParseError as e:
1004
+ if self.STRICT_JSON_PATH_SYNTAX:
1005
+ logger.warning(f"Invalid JSON path syntax. {str(e)}")
1006
+
1007
+ return path
1008
+
1009
+ def parse(self, sql: str, **opts) -> t.List[t.Optional[exp.Expression]]:
1010
+ return self.parser(**opts).parse(self.tokenize(sql), sql)
1011
+
1012
+ def parse_into(
1013
+ self, expression_type: exp.IntoType, sql: str, **opts
1014
+ ) -> t.List[t.Optional[exp.Expression]]:
1015
+ return self.parser(**opts).parse_into(expression_type, self.tokenize(sql), sql)
1016
+
1017
+ def generate(self, expression: exp.Expression, copy: bool = True, **opts) -> str:
1018
+ return self.generator(**opts).generate(expression, copy=copy)
1019
+
1020
+ def transpile(self, sql: str, **opts) -> t.List[str]:
1021
+ return [
1022
+ self.generate(expression, copy=False, **opts) if expression else ""
1023
+ for expression in self.parse(sql)
1024
+ ]
1025
+
1026
+ def tokenize(self, sql: str) -> t.List[Token]:
1027
+ return self.tokenizer.tokenize(sql)
1028
+
1029
+ @property
1030
+ def tokenizer(self) -> Tokenizer:
1031
+ return self.tokenizer_class(dialect=self)
1032
+
1033
+ @property
1034
+ def jsonpath_tokenizer(self) -> JSONPathTokenizer:
1035
+ return self.jsonpath_tokenizer_class(dialect=self)
1036
+
1037
+ def parser(self, **opts) -> Parser:
1038
+ return self.parser_class(dialect=self, **opts)
1039
+
1040
+ def generator(self, **opts) -> Generator:
1041
+ return self.generator_class(dialect=self, **opts)
1042
+
1043
+ def generate_values_aliases(self, expression: exp.Values) -> t.List[exp.Identifier]:
1044
+ return [
1045
+ exp.to_identifier(f"_col_{i}")
1046
+ for i, _ in enumerate(expression.expressions[0].expressions)
1047
+ ]
1048
+
1049
+
1050
+ DialectType = t.Union[str, Dialect, t.Type[Dialect], None]
1051
+
1052
+
1053
+ def rename_func(name: str) -> t.Callable[[Generator, exp.Expression], str]:
1054
+ return lambda self, expression: self.func(name, *flatten(expression.args.values()))
1055
+
1056
+
1057
+ @unsupported_args("accuracy")
1058
+ def approx_count_distinct_sql(self: Generator, expression: exp.ApproxDistinct) -> str:
1059
+ return self.func("APPROX_COUNT_DISTINCT", expression.this)
1060
+
1061
+
1062
+ def if_sql(
1063
+ name: str = "IF", false_value: t.Optional[exp.Expression | str] = None
1064
+ ) -> t.Callable[[Generator, exp.If], str]:
1065
+ def _if_sql(self: Generator, expression: exp.If) -> str:
1066
+ return self.func(
1067
+ name,
1068
+ expression.this,
1069
+ expression.args.get("true"),
1070
+ expression.args.get("false") or false_value,
1071
+ )
1072
+
1073
+ return _if_sql
1074
+
1075
+
1076
+ def arrow_json_extract_sql(self: Generator, expression: JSON_EXTRACT_TYPE) -> str:
1077
+ this = expression.this
1078
+ if self.JSON_TYPE_REQUIRED_FOR_EXTRACTION and isinstance(this, exp.Literal) and this.is_string:
1079
+ this.replace(exp.cast(this, exp.DataType.Type.JSON))
1080
+
1081
+ return self.binary(expression, "->" if isinstance(expression, exp.JSONExtract) else "->>")
1082
+
1083
+
1084
+ def inline_array_sql(self: Generator, expression: exp.Array) -> str:
1085
+ return f"[{self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)}]"
1086
+
1087
+
1088
+ def inline_array_unless_query(self: Generator, expression: exp.Array) -> str:
1089
+ elem = seq_get(expression.expressions, 0)
1090
+ if isinstance(elem, exp.Expression) and elem.find(exp.Query):
1091
+ return self.func("ARRAY", elem)
1092
+ return inline_array_sql(self, expression)
1093
+
1094
+
1095
+ def no_ilike_sql(self: Generator, expression: exp.ILike) -> str:
1096
+ return self.like_sql(
1097
+ exp.Like(
1098
+ this=exp.Lower(this=expression.this), expression=exp.Lower(this=expression.expression)
1099
+ )
1100
+ )
1101
+
1102
+
1103
+ def no_paren_current_date_sql(self: Generator, expression: exp.CurrentDate) -> str:
1104
+ zone = self.sql(expression, "this")
1105
+ return f"CURRENT_DATE AT TIME ZONE {zone}" if zone else "CURRENT_DATE"
1106
+
1107
+
1108
+ def no_recursive_cte_sql(self: Generator, expression: exp.With) -> str:
1109
+ if expression.args.get("recursive"):
1110
+ self.unsupported("Recursive CTEs are unsupported")
1111
+ expression.args["recursive"] = False
1112
+ return self.with_sql(expression)
1113
+
1114
+
1115
+ def no_tablesample_sql(self: Generator, expression: exp.TableSample) -> str:
1116
+ self.unsupported("TABLESAMPLE unsupported")
1117
+ return self.sql(expression.this)
1118
+
1119
+
1120
+ def no_pivot_sql(self: Generator, expression: exp.Pivot) -> str:
1121
+ self.unsupported("PIVOT unsupported")
1122
+ return ""
1123
+
1124
+
1125
+ def no_trycast_sql(self: Generator, expression: exp.TryCast) -> str:
1126
+ return self.cast_sql(expression)
1127
+
1128
+
1129
+ def no_comment_column_constraint_sql(
1130
+ self: Generator, expression: exp.CommentColumnConstraint
1131
+ ) -> str:
1132
+ self.unsupported("CommentColumnConstraint unsupported")
1133
+ return ""
1134
+
1135
+
1136
+ def no_map_from_entries_sql(self: Generator, expression: exp.MapFromEntries) -> str:
1137
+ self.unsupported("MAP_FROM_ENTRIES unsupported")
1138
+ return ""
1139
+
1140
+
1141
+ def property_sql(self: Generator, expression: exp.Property) -> str:
1142
+ return f"{self.property_name(expression, string_key=True)}={self.sql(expression, 'value')}"
1143
+
1144
+
1145
+ def strposition_sql(
1146
+ self: Generator,
1147
+ expression: exp.StrPosition,
1148
+ func_name: str = "STRPOS",
1149
+ supports_position: bool = False,
1150
+ supports_occurrence: bool = False,
1151
+ use_ansi_position: bool = True,
1152
+ ) -> str:
1153
+ string = expression.this
1154
+ substr = expression.args.get("substr")
1155
+ position = expression.args.get("position")
1156
+ occurrence = expression.args.get("occurrence")
1157
+ zero = exp.Literal.number(0)
1158
+ one = exp.Literal.number(1)
1159
+
1160
+ if supports_occurrence and occurrence and supports_position and not position:
1161
+ position = one
1162
+
1163
+ transpile_position = position and not supports_position
1164
+ if transpile_position:
1165
+ string = exp.Substring(this=string, start=position)
1166
+
1167
+ if func_name == "POSITION" and use_ansi_position:
1168
+ func = exp.Anonymous(this=func_name, expressions=[exp.In(this=substr, field=string)])
1169
+ else:
1170
+ args = [substr, string] if func_name in ("LOCATE", "CHARINDEX") else [string, substr]
1171
+ if supports_position:
1172
+ args.append(position)
1173
+ if occurrence:
1174
+ if supports_occurrence:
1175
+ args.append(occurrence)
1176
+ else:
1177
+ self.unsupported(f"{func_name} does not support the occurrence parameter.")
1178
+ func = exp.Anonymous(this=func_name, expressions=args)
1179
+
1180
+ if transpile_position:
1181
+ func_with_offset = exp.Sub(this=func + position, expression=one)
1182
+ func_wrapped = exp.If(this=func.eq(zero), true=zero, false=func_with_offset)
1183
+ return self.sql(func_wrapped)
1184
+
1185
+ return self.sql(func)
1186
+
1187
+
1188
+ def struct_extract_sql(self: Generator, expression: exp.StructExtract) -> str:
1189
+ return (
1190
+ f"{self.sql(expression, 'this')}.{self.sql(exp.to_identifier(expression.expression.name))}"
1191
+ )
1192
+
1193
+
1194
+ def var_map_sql(
1195
+ self: Generator, expression: exp.Map | exp.VarMap, map_func_name: str = "MAP"
1196
+ ) -> str:
1197
+ keys = expression.args.get("keys")
1198
+ values = expression.args.get("values")
1199
+
1200
+ if not isinstance(keys, exp.Array) or not isinstance(values, exp.Array):
1201
+ self.unsupported("Cannot convert array columns into map.")
1202
+ return self.func(map_func_name, keys, values)
1203
+
1204
+ args = []
1205
+ for key, value in zip(keys.expressions, values.expressions):
1206
+ args.append(self.sql(key))
1207
+ args.append(self.sql(value))
1208
+
1209
+ return self.func(map_func_name, *args)
1210
+
1211
+
1212
+ def build_formatted_time(
1213
+ exp_class: t.Type[E], dialect: str, default: t.Optional[bool | str] = None
1214
+ ) -> t.Callable[[t.List], E]:
1215
+ """Helper used for time expressions.
1216
+
1217
+ Args:
1218
+ exp_class: the expression class to instantiate.
1219
+ dialect: target sql dialect.
1220
+ default: the default format, True being time.
1221
+
1222
+ Returns:
1223
+ A callable that can be used to return the appropriately formatted time expression.
1224
+ """
1225
+
1226
+ def _builder(args: t.List):
1227
+ return exp_class(
1228
+ this=seq_get(args, 0),
1229
+ format=Dialect[dialect].format_time(
1230
+ seq_get(args, 1)
1231
+ or (Dialect[dialect].TIME_FORMAT if default is True else default or None)
1232
+ ),
1233
+ )
1234
+
1235
+ return _builder
1236
+
1237
+
1238
+ def time_format(
1239
+ dialect: DialectType = None,
1240
+ ) -> t.Callable[[Generator, exp.UnixToStr | exp.StrToUnix], t.Optional[str]]:
1241
+ def _time_format(self: Generator, expression: exp.UnixToStr | exp.StrToUnix) -> t.Optional[str]:
1242
+ """
1243
+ Returns the time format for a given expression, unless it's equivalent
1244
+ to the default time format of the dialect of interest.
1245
+ """
1246
+ time_format = self.format_time(expression)
1247
+ return time_format if time_format != Dialect.get_or_raise(dialect).TIME_FORMAT else None
1248
+
1249
+ return _time_format
1250
+
1251
+
1252
+ def build_date_delta(
1253
+ exp_class: t.Type[E],
1254
+ unit_mapping: t.Optional[t.Dict[str, str]] = None,
1255
+ default_unit: t.Optional[str] = "DAY",
1256
+ supports_timezone: bool = False,
1257
+ ) -> t.Callable[[t.List], E]:
1258
+ def _builder(args: t.List) -> E:
1259
+ unit_based = len(args) >= 3
1260
+ has_timezone = len(args) == 4
1261
+ this = args[2] if unit_based else seq_get(args, 0)
1262
+ unit = None
1263
+ if unit_based or default_unit:
1264
+ unit = args[0] if unit_based else exp.Literal.string(default_unit)
1265
+ unit = exp.var(unit_mapping.get(unit.name.lower(), unit.name)) if unit_mapping else unit
1266
+ expression = exp_class(this=this, expression=seq_get(args, 1), unit=unit)
1267
+ if supports_timezone and has_timezone:
1268
+ expression.set("zone", args[-1])
1269
+ return expression
1270
+
1271
+ return _builder
1272
+
1273
+
1274
+ def build_date_delta_with_interval(
1275
+ expression_class: t.Type[E],
1276
+ ) -> t.Callable[[t.List], t.Optional[E]]:
1277
+ def _builder(args: t.List) -> t.Optional[E]:
1278
+ if len(args) < 2:
1279
+ return None
1280
+
1281
+ interval = args[1]
1282
+
1283
+ if not isinstance(interval, exp.Interval):
1284
+ raise ParseError(f"INTERVAL expression expected but got '{interval}'")
1285
+
1286
+ return expression_class(this=args[0], expression=interval.this, unit=unit_to_str(interval))
1287
+
1288
+ return _builder
1289
+
1290
+
1291
+ def date_trunc_to_time(args: t.List) -> exp.DateTrunc | exp.TimestampTrunc:
1292
+ unit = seq_get(args, 0)
1293
+ this = seq_get(args, 1)
1294
+
1295
+ if isinstance(this, exp.Cast) and this.is_type("date"):
1296
+ return exp.DateTrunc(unit=unit, this=this)
1297
+ return exp.TimestampTrunc(this=this, unit=unit)
1298
+
1299
+
1300
+ def date_add_interval_sql(
1301
+ data_type: str, kind: str
1302
+ ) -> t.Callable[[Generator, exp.Expression], str]:
1303
+ def func(self: Generator, expression: exp.Expression) -> str:
1304
+ this = self.sql(expression, "this")
1305
+ interval = exp.Interval(this=expression.expression, unit=unit_to_var(expression))
1306
+ return f"{data_type}_{kind}({this}, {self.sql(interval)})"
1307
+
1308
+ return func
1309
+
1310
+
1311
+ def timestamptrunc_sql(zone: bool = False) -> t.Callable[[Generator, exp.TimestampTrunc], str]:
1312
+ def _timestamptrunc_sql(self: Generator, expression: exp.TimestampTrunc) -> str:
1313
+ args = [unit_to_str(expression), expression.this]
1314
+ if zone:
1315
+ args.append(expression.args.get("zone"))
1316
+ return self.func("DATE_TRUNC", *args)
1317
+
1318
+ return _timestamptrunc_sql
1319
+
1320
+
1321
+ def no_timestamp_sql(self: Generator, expression: exp.Timestamp) -> str:
1322
+ zone = expression.args.get("zone")
1323
+ if not zone:
1324
+ from sqlglot.optimizer.annotate_types import annotate_types
1325
+
1326
+ target_type = (
1327
+ annotate_types(expression, dialect=self.dialect).type or exp.DataType.Type.TIMESTAMP
1328
+ )
1329
+ return self.sql(exp.cast(expression.this, target_type))
1330
+ if zone.name.lower() in TIMEZONES:
1331
+ return self.sql(
1332
+ exp.AtTimeZone(
1333
+ this=exp.cast(expression.this, exp.DataType.Type.TIMESTAMP),
1334
+ zone=zone,
1335
+ )
1336
+ )
1337
+ return self.func("TIMESTAMP", expression.this, zone)
1338
+
1339
+
1340
+ def no_time_sql(self: Generator, expression: exp.Time) -> str:
1341
+ # Transpile BQ's TIME(timestamp, zone) to CAST(TIMESTAMPTZ <timestamp> AT TIME ZONE <zone> AS TIME)
1342
+ this = exp.cast(expression.this, exp.DataType.Type.TIMESTAMPTZ)
1343
+ expr = exp.cast(
1344
+ exp.AtTimeZone(this=this, zone=expression.args.get("zone")), exp.DataType.Type.TIME
1345
+ )
1346
+ return self.sql(expr)
1347
+
1348
+
1349
+ def no_datetime_sql(self: Generator, expression: exp.Datetime) -> str:
1350
+ this = expression.this
1351
+ expr = expression.expression
1352
+
1353
+ if expr.name.lower() in TIMEZONES:
1354
+ # Transpile BQ's DATETIME(timestamp, zone) to CAST(TIMESTAMPTZ <timestamp> AT TIME ZONE <zone> AS TIMESTAMP)
1355
+ this = exp.cast(this, exp.DataType.Type.TIMESTAMPTZ)
1356
+ this = exp.cast(exp.AtTimeZone(this=this, zone=expr), exp.DataType.Type.TIMESTAMP)
1357
+ return self.sql(this)
1358
+
1359
+ this = exp.cast(this, exp.DataType.Type.DATE)
1360
+ expr = exp.cast(expr, exp.DataType.Type.TIME)
1361
+
1362
+ return self.sql(exp.cast(exp.Add(this=this, expression=expr), exp.DataType.Type.TIMESTAMP))
1363
+
1364
+
1365
+ def left_to_substring_sql(self: Generator, expression: exp.Left) -> str:
1366
+ return self.sql(
1367
+ exp.Substring(
1368
+ this=expression.this, start=exp.Literal.number(1), length=expression.expression
1369
+ )
1370
+ )
1371
+
1372
+
1373
+ def right_to_substring_sql(self: Generator, expression: exp.Left) -> str:
1374
+ return self.sql(
1375
+ exp.Substring(
1376
+ this=expression.this,
1377
+ start=exp.Length(this=expression.this) - exp.paren(expression.expression - 1),
1378
+ )
1379
+ )
1380
+
1381
+
1382
+ def timestrtotime_sql(
1383
+ self: Generator,
1384
+ expression: exp.TimeStrToTime,
1385
+ include_precision: bool = False,
1386
+ ) -> str:
1387
+ datatype = exp.DataType.build(
1388
+ exp.DataType.Type.TIMESTAMPTZ
1389
+ if expression.args.get("zone")
1390
+ else exp.DataType.Type.TIMESTAMP
1391
+ )
1392
+
1393
+ if isinstance(expression.this, exp.Literal) and include_precision:
1394
+ precision = subsecond_precision(expression.this.name)
1395
+ if precision > 0:
1396
+ datatype = exp.DataType.build(
1397
+ datatype.this, expressions=[exp.DataTypeParam(this=exp.Literal.number(precision))]
1398
+ )
1399
+
1400
+ return self.sql(exp.cast(expression.this, datatype, dialect=self.dialect))
1401
+
1402
+
1403
+ def datestrtodate_sql(self: Generator, expression: exp.DateStrToDate) -> str:
1404
+ return self.sql(exp.cast(expression.this, exp.DataType.Type.DATE))
1405
+
1406
+
1407
+ # Used for Presto and Duckdb which use functions that don't support charset, and assume utf-8
1408
+ def encode_decode_sql(
1409
+ self: Generator, expression: exp.Expression, name: str, replace: bool = True
1410
+ ) -> str:
1411
+ charset = expression.args.get("charset")
1412
+ if charset and charset.name.lower() != "utf-8":
1413
+ self.unsupported(f"Expected utf-8 character set, got {charset}.")
1414
+
1415
+ return self.func(name, expression.this, expression.args.get("replace") if replace else None)
1416
+
1417
+
1418
+ def min_or_least(self: Generator, expression: exp.Min) -> str:
1419
+ name = "LEAST" if expression.expressions else "MIN"
1420
+ return rename_func(name)(self, expression)
1421
+
1422
+
1423
+ def max_or_greatest(self: Generator, expression: exp.Max) -> str:
1424
+ name = "GREATEST" if expression.expressions else "MAX"
1425
+ return rename_func(name)(self, expression)
1426
+
1427
+
1428
+ def count_if_to_sum(self: Generator, expression: exp.CountIf) -> str:
1429
+ cond = expression.this
1430
+
1431
+ if isinstance(expression.this, exp.Distinct):
1432
+ cond = expression.this.expressions[0]
1433
+ self.unsupported("DISTINCT is not supported when converting COUNT_IF to SUM")
1434
+
1435
+ return self.func("sum", exp.func("if", cond, 1, 0))
1436
+
1437
+
1438
+ def trim_sql(self: Generator, expression: exp.Trim, default_trim_type: str = "") -> str:
1439
+ target = self.sql(expression, "this")
1440
+ trim_type = self.sql(expression, "position") or default_trim_type
1441
+ remove_chars = self.sql(expression, "expression")
1442
+ collation = self.sql(expression, "collation")
1443
+
1444
+ # Use TRIM/LTRIM/RTRIM syntax if the expression isn't database-specific
1445
+ if not remove_chars:
1446
+ return self.trim_sql(expression)
1447
+
1448
+ trim_type = f"{trim_type} " if trim_type else ""
1449
+ remove_chars = f"{remove_chars} " if remove_chars else ""
1450
+ from_part = "FROM " if trim_type or remove_chars else ""
1451
+ collation = f" COLLATE {collation}" if collation else ""
1452
+ return f"TRIM({trim_type}{remove_chars}{from_part}{target}{collation})"
1453
+
1454
+
1455
+ def str_to_time_sql(self: Generator, expression: exp.Expression) -> str:
1456
+ return self.func("STRPTIME", expression.this, self.format_time(expression))
1457
+
1458
+
1459
+ def concat_to_dpipe_sql(self: Generator, expression: exp.Concat) -> str:
1460
+ return self.sql(reduce(lambda x, y: exp.DPipe(this=x, expression=y), expression.expressions))
1461
+
1462
+
1463
+ def concat_ws_to_dpipe_sql(self: Generator, expression: exp.ConcatWs) -> str:
1464
+ delim, *rest_args = expression.expressions
1465
+ return self.sql(
1466
+ reduce(
1467
+ lambda x, y: exp.DPipe(this=x, expression=exp.DPipe(this=delim, expression=y)),
1468
+ rest_args,
1469
+ )
1470
+ )
1471
+
1472
+
1473
+ @unsupported_args("position", "occurrence", "parameters")
1474
+ def regexp_extract_sql(
1475
+ self: Generator, expression: exp.RegexpExtract | exp.RegexpExtractAll
1476
+ ) -> str:
1477
+ group = expression.args.get("group")
1478
+
1479
+ # Do not render group if it's the default value for this dialect
1480
+ if group and group.name == str(self.dialect.REGEXP_EXTRACT_DEFAULT_GROUP):
1481
+ group = None
1482
+
1483
+ return self.func(expression.sql_name(), expression.this, expression.expression, group)
1484
+
1485
+
1486
+ @unsupported_args("position", "occurrence", "modifiers")
1487
+ def regexp_replace_sql(self: Generator, expression: exp.RegexpReplace) -> str:
1488
+ return self.func(
1489
+ "REGEXP_REPLACE", expression.this, expression.expression, expression.args["replacement"]
1490
+ )
1491
+
1492
+
1493
+ def pivot_column_names(aggregations: t.List[exp.Expression], dialect: DialectType) -> t.List[str]:
1494
+ names = []
1495
+ for agg in aggregations:
1496
+ if isinstance(agg, exp.Alias):
1497
+ names.append(agg.alias)
1498
+ else:
1499
+ """
1500
+ This case corresponds to aggregations without aliases being used as suffixes
1501
+ (e.g. col_avg(foo)). We need to unquote identifiers because they're going to
1502
+ be quoted in the base parser's `_parse_pivot` method, due to `to_identifier`.
1503
+ Otherwise, we'd end up with `col_avg(`foo`)` (notice the double quotes).
1504
+ """
1505
+ agg_all_unquoted = agg.transform(
1506
+ lambda node: (
1507
+ exp.Identifier(this=node.name, quoted=False)
1508
+ if isinstance(node, exp.Identifier)
1509
+ else node
1510
+ )
1511
+ )
1512
+ names.append(agg_all_unquoted.sql(dialect=dialect, normalize_functions="lower"))
1513
+
1514
+ return names
1515
+
1516
+
1517
+ def binary_from_function(expr_type: t.Type[B]) -> t.Callable[[t.List], B]:
1518
+ return lambda args: expr_type(this=seq_get(args, 0), expression=seq_get(args, 1))
1519
+
1520
+
1521
+ # Used to represent DATE_TRUNC in Doris, Postgres and Starrocks dialects
1522
+ def build_timestamp_trunc(args: t.List) -> exp.TimestampTrunc:
1523
+ return exp.TimestampTrunc(this=seq_get(args, 1), unit=seq_get(args, 0))
1524
+
1525
+
1526
+ def any_value_to_max_sql(self: Generator, expression: exp.AnyValue) -> str:
1527
+ return self.func("MAX", expression.this)
1528
+
1529
+
1530
+ def bool_xor_sql(self: Generator, expression: exp.Xor) -> str:
1531
+ a = self.sql(expression.left)
1532
+ b = self.sql(expression.right)
1533
+ return f"({a} AND (NOT {b})) OR ((NOT {a}) AND {b})"
1534
+
1535
+
1536
+ def is_parse_json(expression: exp.Expression) -> bool:
1537
+ return isinstance(expression, exp.ParseJSON) or (
1538
+ isinstance(expression, exp.Cast) and expression.is_type("json")
1539
+ )
1540
+
1541
+
1542
+ def isnull_to_is_null(args: t.List) -> exp.Expression:
1543
+ return exp.Paren(this=exp.Is(this=seq_get(args, 0), expression=exp.null()))
1544
+
1545
+
1546
+ def generatedasidentitycolumnconstraint_sql(
1547
+ self: Generator, expression: exp.GeneratedAsIdentityColumnConstraint
1548
+ ) -> str:
1549
+ start = self.sql(expression, "start") or "1"
1550
+ increment = self.sql(expression, "increment") or "1"
1551
+ return f"IDENTITY({start}, {increment})"
1552
+
1553
+
1554
+ def arg_max_or_min_no_count(name: str) -> t.Callable[[Generator, exp.ArgMax | exp.ArgMin], str]:
1555
+ @unsupported_args("count")
1556
+ def _arg_max_or_min_sql(self: Generator, expression: exp.ArgMax | exp.ArgMin) -> str:
1557
+ return self.func(name, expression.this, expression.expression)
1558
+
1559
+ return _arg_max_or_min_sql
1560
+
1561
+
1562
+ def ts_or_ds_add_cast(expression: exp.TsOrDsAdd) -> exp.TsOrDsAdd:
1563
+ this = expression.this.copy()
1564
+
1565
+ return_type = expression.return_type
1566
+ if return_type.is_type(exp.DataType.Type.DATE):
1567
+ # If we need to cast to a DATE, we cast to TIMESTAMP first to make sure we
1568
+ # can truncate timestamp strings, because some dialects can't cast them to DATE
1569
+ this = exp.cast(this, exp.DataType.Type.TIMESTAMP)
1570
+
1571
+ expression.this.replace(exp.cast(this, return_type))
1572
+ return expression
1573
+
1574
+
1575
+ def date_delta_sql(name: str, cast: bool = False) -> t.Callable[[Generator, DATE_ADD_OR_DIFF], str]:
1576
+ def _delta_sql(self: Generator, expression: DATE_ADD_OR_DIFF) -> str:
1577
+ if cast and isinstance(expression, exp.TsOrDsAdd):
1578
+ expression = ts_or_ds_add_cast(expression)
1579
+
1580
+ return self.func(
1581
+ name,
1582
+ unit_to_var(expression),
1583
+ expression.expression,
1584
+ expression.this,
1585
+ )
1586
+
1587
+ return _delta_sql
1588
+
1589
+
1590
+ def unit_to_str(expression: exp.Expression, default: str = "DAY") -> t.Optional[exp.Expression]:
1591
+ unit = expression.args.get("unit")
1592
+
1593
+ if isinstance(unit, exp.Placeholder):
1594
+ return unit
1595
+ if unit:
1596
+ return exp.Literal.string(unit.name)
1597
+ return exp.Literal.string(default) if default else None
1598
+
1599
+
1600
+ def unit_to_var(expression: exp.Expression, default: str = "DAY") -> t.Optional[exp.Expression]:
1601
+ unit = expression.args.get("unit")
1602
+
1603
+ if isinstance(unit, (exp.Var, exp.Placeholder)):
1604
+ return unit
1605
+ return exp.Var(this=default) if default else None
1606
+
1607
+
1608
+ @t.overload
1609
+ def map_date_part(part: exp.Expression, dialect: DialectType = Dialect) -> exp.Var:
1610
+ pass
1611
+
1612
+
1613
+ @t.overload
1614
+ def map_date_part(
1615
+ part: t.Optional[exp.Expression], dialect: DialectType = Dialect
1616
+ ) -> t.Optional[exp.Expression]:
1617
+ pass
1618
+
1619
+
1620
+ def map_date_part(part, dialect: DialectType = Dialect):
1621
+ mapped = (
1622
+ Dialect.get_or_raise(dialect).DATE_PART_MAPPING.get(part.name.upper()) if part else None
1623
+ )
1624
+ return exp.var(mapped) if mapped else part
1625
+
1626
+
1627
+ def no_last_day_sql(self: Generator, expression: exp.LastDay) -> str:
1628
+ trunc_curr_date = exp.func("date_trunc", "month", expression.this)
1629
+ plus_one_month = exp.func("date_add", trunc_curr_date, 1, "month")
1630
+ minus_one_day = exp.func("date_sub", plus_one_month, 1, "day")
1631
+
1632
+ return self.sql(exp.cast(minus_one_day, exp.DataType.Type.DATE))
1633
+
1634
+
1635
+ def merge_without_target_sql(self: Generator, expression: exp.Merge) -> str:
1636
+ """Remove table refs from columns in when statements."""
1637
+ alias = expression.this.args.get("alias")
1638
+
1639
+ def normalize(identifier: t.Optional[exp.Identifier]) -> t.Optional[str]:
1640
+ return self.dialect.normalize_identifier(identifier).name if identifier else None
1641
+
1642
+ targets = {normalize(expression.this.this)}
1643
+
1644
+ if alias:
1645
+ targets.add(normalize(alias.this))
1646
+
1647
+ for when in expression.args["whens"].expressions:
1648
+ # only remove the target table names from certain parts of WHEN MATCHED / WHEN NOT MATCHED
1649
+ # they are still valid in the <condition>, the right hand side of each UPDATE and the VALUES part
1650
+ # (not the column list) of the INSERT
1651
+ then: exp.Insert | exp.Update | None = when.args.get("then")
1652
+ if then:
1653
+ if isinstance(then, exp.Update):
1654
+ for equals in then.find_all(exp.EQ):
1655
+ equal_lhs = equals.this
1656
+ if (
1657
+ isinstance(equal_lhs, exp.Column)
1658
+ and normalize(equal_lhs.args.get("table")) in targets
1659
+ ):
1660
+ equal_lhs.replace(exp.column(equal_lhs.this))
1661
+ if isinstance(then, exp.Insert):
1662
+ column_list = then.this
1663
+ if isinstance(column_list, exp.Tuple):
1664
+ for column in column_list.expressions:
1665
+ if normalize(column.args.get("table")) in targets:
1666
+ column.replace(exp.column(column.this))
1667
+
1668
+ return self.merge_sql(expression)
1669
+
1670
+
1671
+ def build_json_extract_path(
1672
+ expr_type: t.Type[F], zero_based_indexing: bool = True, arrow_req_json_type: bool = False
1673
+ ) -> t.Callable[[t.List], F]:
1674
+ def _builder(args: t.List) -> F:
1675
+ segments: t.List[exp.JSONPathPart] = [exp.JSONPathRoot()]
1676
+ for arg in args[1:]:
1677
+ if not isinstance(arg, exp.Literal):
1678
+ # We use the fallback parser because we can't really transpile non-literals safely
1679
+ return expr_type.from_arg_list(args)
1680
+
1681
+ text = arg.name
1682
+ if is_int(text) and (not arrow_req_json_type or not arg.is_string):
1683
+ index = int(text)
1684
+ segments.append(
1685
+ exp.JSONPathSubscript(this=index if zero_based_indexing else index - 1)
1686
+ )
1687
+ else:
1688
+ segments.append(exp.JSONPathKey(this=text))
1689
+
1690
+ # This is done to avoid failing in the expression validator due to the arg count
1691
+ del args[2:]
1692
+ return expr_type(
1693
+ this=seq_get(args, 0),
1694
+ expression=exp.JSONPath(expressions=segments),
1695
+ only_json_types=arrow_req_json_type,
1696
+ )
1697
+
1698
+ return _builder
1699
+
1700
+
1701
+ def json_extract_segments(
1702
+ name: str, quoted_index: bool = True, op: t.Optional[str] = None
1703
+ ) -> t.Callable[[Generator, JSON_EXTRACT_TYPE], str]:
1704
+ def _json_extract_segments(self: Generator, expression: JSON_EXTRACT_TYPE) -> str:
1705
+ path = expression.expression
1706
+ if not isinstance(path, exp.JSONPath):
1707
+ return rename_func(name)(self, expression)
1708
+
1709
+ escape = path.args.get("escape")
1710
+
1711
+ segments = []
1712
+ for segment in path.expressions:
1713
+ path = self.sql(segment)
1714
+ if path:
1715
+ if isinstance(segment, exp.JSONPathPart) and (
1716
+ quoted_index or not isinstance(segment, exp.JSONPathSubscript)
1717
+ ):
1718
+ if escape:
1719
+ path = self.escape_str(path)
1720
+
1721
+ path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
1722
+
1723
+ segments.append(path)
1724
+
1725
+ if op:
1726
+ return f" {op} ".join([self.sql(expression.this), *segments])
1727
+ return self.func(name, expression.this, *segments)
1728
+
1729
+ return _json_extract_segments
1730
+
1731
+
1732
+ def json_path_key_only_name(self: Generator, expression: exp.JSONPathKey) -> str:
1733
+ if isinstance(expression.this, exp.JSONPathWildcard):
1734
+ self.unsupported("Unsupported wildcard in JSONPathKey expression")
1735
+
1736
+ return expression.name
1737
+
1738
+
1739
+ def filter_array_using_unnest(
1740
+ self: Generator, expression: exp.ArrayFilter | exp.ArrayRemove
1741
+ ) -> str:
1742
+ cond = expression.expression
1743
+ if isinstance(cond, exp.Lambda) and len(cond.expressions) == 1:
1744
+ alias = cond.expressions[0]
1745
+ cond = cond.this
1746
+ elif isinstance(cond, exp.Predicate):
1747
+ alias = "_u"
1748
+ elif isinstance(expression, exp.ArrayRemove):
1749
+ alias = "_u"
1750
+ cond = exp.NEQ(this=alias, expression=expression.expression)
1751
+ else:
1752
+ self.unsupported("Unsupported filter condition")
1753
+ return ""
1754
+
1755
+ unnest = exp.Unnest(expressions=[expression.this])
1756
+ filtered = exp.select(alias).from_(exp.alias_(unnest, None, table=[alias])).where(cond)
1757
+ return self.sql(exp.Array(expressions=[filtered]))
1758
+
1759
+
1760
+ def remove_from_array_using_filter(self: Generator, expression: exp.ArrayRemove) -> str:
1761
+ lambda_id = exp.to_identifier("_u")
1762
+ cond = exp.NEQ(this=lambda_id, expression=expression.expression)
1763
+ return self.sql(
1764
+ exp.ArrayFilter(
1765
+ this=expression.this, expression=exp.Lambda(this=cond, expressions=[lambda_id])
1766
+ )
1767
+ )
1768
+
1769
+
1770
+ def to_number_with_nls_param(self: Generator, expression: exp.ToNumber) -> str:
1771
+ return self.func(
1772
+ "TO_NUMBER",
1773
+ expression.this,
1774
+ expression.args.get("format"),
1775
+ expression.args.get("nlsparam"),
1776
+ )
1777
+
1778
+
1779
+ def build_default_decimal_type(
1780
+ precision: t.Optional[int] = None, scale: t.Optional[int] = None
1781
+ ) -> t.Callable[[exp.DataType], exp.DataType]:
1782
+ def _builder(dtype: exp.DataType) -> exp.DataType:
1783
+ if dtype.expressions or precision is None:
1784
+ return dtype
1785
+
1786
+ params = f"{precision}{f', {scale}' if scale is not None else ''}"
1787
+ return exp.DataType.build(f"DECIMAL({params})")
1788
+
1789
+ return _builder
1790
+
1791
+
1792
+ def build_timestamp_from_parts(args: t.List) -> exp.Func:
1793
+ if len(args) == 2:
1794
+ # Other dialects don't have the TIMESTAMP_FROM_PARTS(date, time) concept,
1795
+ # so we parse this into Anonymous for now instead of introducing complexity
1796
+ return exp.Anonymous(this="TIMESTAMP_FROM_PARTS", expressions=args)
1797
+
1798
+ return exp.TimestampFromParts.from_arg_list(args)
1799
+
1800
+
1801
+ def sha256_sql(self: Generator, expression: exp.SHA2) -> str:
1802
+ return self.func(f"SHA{expression.text('length') or '256'}", expression.this)
1803
+
1804
+
1805
+ def sequence_sql(self: Generator, expression: exp.GenerateSeries | exp.GenerateDateArray) -> str:
1806
+ start = expression.args.get("start")
1807
+ end = expression.args.get("end")
1808
+ step = expression.args.get("step")
1809
+
1810
+ if isinstance(start, exp.Cast):
1811
+ target_type = start.to
1812
+ elif isinstance(end, exp.Cast):
1813
+ target_type = end.to
1814
+ else:
1815
+ target_type = None
1816
+
1817
+ if start and end and target_type and target_type.is_type("date", "timestamp"):
1818
+ if isinstance(start, exp.Cast) and target_type is start.to:
1819
+ end = exp.cast(end, target_type)
1820
+ else:
1821
+ start = exp.cast(start, target_type)
1822
+
1823
+ return self.func("SEQUENCE", start, end, step)
1824
+
1825
+
1826
+ def build_regexp_extract(expr_type: t.Type[E]) -> t.Callable[[t.List, Dialect], E]:
1827
+ def _builder(args: t.List, dialect: Dialect) -> E:
1828
+ return expr_type(
1829
+ this=seq_get(args, 0),
1830
+ expression=seq_get(args, 1),
1831
+ group=seq_get(args, 2) or exp.Literal.number(dialect.REGEXP_EXTRACT_DEFAULT_GROUP),
1832
+ parameters=seq_get(args, 3),
1833
+ )
1834
+
1835
+ return _builder
1836
+
1837
+
1838
+ def explode_to_unnest_sql(self: Generator, expression: exp.Lateral) -> str:
1839
+ if isinstance(expression.this, exp.Explode):
1840
+ return self.sql(
1841
+ exp.Join(
1842
+ this=exp.Unnest(
1843
+ expressions=[expression.this.this],
1844
+ alias=expression.args.get("alias"),
1845
+ offset=isinstance(expression.this, exp.Posexplode),
1846
+ ),
1847
+ kind="cross",
1848
+ )
1849
+ )
1850
+ return self.lateral_sql(expression)
1851
+
1852
+
1853
+ def timestampdiff_sql(self: Generator, expression: exp.DatetimeDiff | exp.TimestampDiff) -> str:
1854
+ return self.func("TIMESTAMPDIFF", expression.unit, expression.expression, expression.this)
1855
+
1856
+
1857
+ def no_make_interval_sql(self: Generator, expression: exp.MakeInterval, sep: str = ", ") -> str:
1858
+ args = []
1859
+ for unit, value in expression.args.items():
1860
+ if isinstance(value, exp.Kwarg):
1861
+ value = value.expression
1862
+
1863
+ args.append(f"{value} {unit}")
1864
+
1865
+ return f"INTERVAL '{self.format_args(*args, sep=sep)}'"
1866
+
1867
+
1868
+ def length_or_char_length_sql(self: Generator, expression: exp.Length) -> str:
1869
+ length_func = "LENGTH" if expression.args.get("binary") else "CHAR_LENGTH"
1870
+ return self.func(length_func, expression.this)
1871
+
1872
+
1873
+ def groupconcat_sql(
1874
+ self: Generator,
1875
+ expression: exp.GroupConcat,
1876
+ func_name="LISTAGG",
1877
+ sep: str = ",",
1878
+ within_group: bool = True,
1879
+ on_overflow: bool = False,
1880
+ ) -> str:
1881
+ this = expression.this
1882
+ separator = self.sql(expression.args.get("separator") or exp.Literal.string(sep))
1883
+
1884
+ on_overflow_sql = self.sql(expression, "on_overflow")
1885
+ on_overflow_sql = f" ON OVERFLOW {on_overflow_sql}" if (on_overflow and on_overflow_sql) else ""
1886
+
1887
+ order = this.find(exp.Order)
1888
+
1889
+ if order and order.this:
1890
+ this = order.this.pop()
1891
+
1892
+ args = self.format_args(this, f"{separator}{on_overflow_sql}")
1893
+ listagg: exp.Expression = exp.Anonymous(this=func_name, expressions=[args])
1894
+
1895
+ if order:
1896
+ if within_group:
1897
+ listagg = exp.WithinGroup(this=listagg, expression=order)
1898
+ else:
1899
+ listagg.set("expressions", [f"{args}{self.sql(expression=expression.this)}"])
1900
+
1901
+ return self.sql(listagg)
1902
+
1903
+
1904
+ def build_timetostr_or_tochar(args: t.List, dialect: Dialect) -> exp.TimeToStr | exp.ToChar:
1905
+ this = seq_get(args, 0)
1906
+
1907
+ if this and not this.type:
1908
+ from sqlglot.optimizer.annotate_types import annotate_types
1909
+
1910
+ annotate_types(this, dialect=dialect)
1911
+ if this.is_type(*exp.DataType.TEMPORAL_TYPES):
1912
+ dialect_name = dialect.__class__.__name__.lower()
1913
+ return build_formatted_time(exp.TimeToStr, dialect_name, default=True)(args)
1914
+
1915
+ return exp.ToChar.from_arg_list(args)