sqlglotc 30.31.0__tar.gz → 30.32.0__tar.gz

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 (118) hide show
  1. {sqlglotc-30.31.0/sqlglotc.egg-info → sqlglotc-30.32.0}/PKG-INFO +2 -2
  2. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/aggregate.py +8 -1
  3. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/array.py +1 -0
  4. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/core.py +18 -2
  5. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/query.py +9 -2
  6. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/string.py +2 -0
  7. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/temporal.py +15 -3
  8. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generator.py +140 -18
  9. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/athena.py +1 -1
  10. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/bigquery.py +54 -4
  11. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/clickhouse.py +24 -3
  12. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/databricks.py +66 -1
  13. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/dremio.py +1 -1
  14. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/drill.py +1 -1
  15. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/druid.py +1 -1
  16. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/duckdb.py +103 -22
  17. sqlglotc-30.32.0/sqlglot/generators/dune.py +16 -0
  18. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/exasol.py +15 -13
  19. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/hive.py +26 -3
  20. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/mysql.py +9 -3
  21. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/oracle.py +16 -2
  22. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/postgres.py +6 -2
  23. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/presto.py +14 -3
  24. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/redshift.py +13 -5
  25. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/singlestore.py +0 -1
  26. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/snowflake.py +20 -6
  27. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/spark.py +12 -0
  28. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/spark2.py +8 -0
  29. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/sqlite.py +14 -2
  30. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/tableau.py +1 -1
  31. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/teradata.py +19 -1
  32. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/trino.py +1 -0
  33. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/tsql.py +23 -2
  34. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/optimizer/annotate_types.py +2 -0
  35. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/optimizer/qualify_columns.py +53 -13
  36. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/optimizer/qualify_tables.py +2 -2
  37. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/optimizer/resolver.py +13 -0
  38. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/optimizer/scope.py +17 -2
  39. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/optimizer/simplify.py +41 -8
  40. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parser.py +57 -16
  41. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/bigquery.py +26 -6
  42. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/clickhouse.py +16 -1
  43. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/duckdb.py +14 -2
  44. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/exasol.py +5 -5
  45. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/hive.py +1 -0
  46. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/mysql.py +6 -0
  47. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/oracle.py +8 -3
  48. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/postgres.py +19 -10
  49. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/presto.py +7 -1
  50. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/snowflake.py +19 -4
  51. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/spark2.py +6 -0
  52. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/sqlite.py +14 -2
  53. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/teradata.py +117 -6
  54. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/tokenizer_core.py +17 -2
  55. {sqlglotc-30.31.0 → sqlglotc-30.32.0/sqlglotc.egg-info}/PKG-INFO +2 -2
  56. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglotc.egg-info/requires.txt +1 -1
  57. sqlglotc-30.32.0/sqlglotc.egg-info/scm_version.json +8 -0
  58. sqlglotc-30.31.0/sqlglot/generators/dune.py +0 -14
  59. sqlglotc-30.31.0/sqlglotc.egg-info/scm_version.json +0 -8
  60. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/MANIFEST.in +0 -0
  61. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/pyproject.toml +0 -0
  62. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/setup.cfg +0 -0
  63. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/setup.py +0 -0
  64. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/anonymize.py +0 -0
  65. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/errors.py +0 -0
  66. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/executor/table.py +0 -0
  67. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/builders.py +0 -0
  68. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/constraints.py +0 -0
  69. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/datatypes.py +0 -0
  70. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/ddl.py +0 -0
  71. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/dml.py +0 -0
  72. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/functions.py +0 -0
  73. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/json.py +0 -0
  74. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/math.py +0 -0
  75. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/expressions/properties.py +0 -0
  76. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/dax.py +0 -0
  77. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/doris.py +0 -0
  78. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/fabric.py +0 -0
  79. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/materialize.py +0 -0
  80. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/prql.py +0 -0
  81. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/python.py +0 -0
  82. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/risingwave.py +0 -0
  83. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/solr.py +0 -0
  84. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/generators/starrocks.py +0 -0
  85. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/helper.py +0 -0
  86. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/lineage.py +0 -0
  87. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/optimizer/canonicalize_internal_names.py +0 -0
  88. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/optimizer/isolate_table_selects.py +0 -0
  89. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/optimizer/normalize_identifiers.py +0 -0
  90. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/optimizer/qualify.py +0 -0
  91. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/athena.py +0 -0
  92. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/base.py +0 -0
  93. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/databricks.py +0 -0
  94. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/dax.py +0 -0
  95. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/doris.py +0 -0
  96. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/dremio.py +0 -0
  97. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/drill.py +0 -0
  98. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/druid.py +0 -0
  99. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/dune.py +0 -0
  100. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/fabric.py +0 -0
  101. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/materialize.py +0 -0
  102. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/prql.py +0 -0
  103. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/redshift.py +0 -0
  104. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/risingwave.py +0 -0
  105. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/singlestore.py +0 -0
  106. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/solr.py +0 -0
  107. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/spark.py +0 -0
  108. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/starrocks.py +0 -0
  109. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/tableau.py +0 -0
  110. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/trino.py +0 -0
  111. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/parsers/tsql.py +0 -0
  112. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/serde.py +0 -0
  113. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/time.py +0 -0
  114. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglot/trie.py +0 -0
  115. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglotc.egg-info/SOURCES.txt +0 -0
  116. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglotc.egg-info/dependency_links.txt +0 -0
  117. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglotc.egg-info/scm_file_list.json +0 -0
  118. {sqlglotc-30.31.0 → sqlglotc-30.32.0}/sqlglotc.egg-info/top_level.txt +0 -0
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlglotc
3
- Version: 30.31.0
3
+ Version: 30.32.0
4
4
  Summary: mypyc-compiled extensions for sqlglot
5
5
  Author-email: Toby Mao <toby.mao@gmail.com>
6
6
  License-Expression: MIT
7
7
  Project-URL: Homepage, https://sqlglot.com/
8
8
  Project-URL: Repository, https://github.com/tobymao/sqlglot
9
9
  Requires-Python: >=3.10
10
- Requires-Dist: sqlglot==30.31.0
10
+ Requires-Dist: sqlglot==30.32.0
11
11
  Provides-Extra: dev
12
12
  Requires-Dist: setuptools>=61.0; extra == "dev"
13
13
  Requires-Dist: setuptools_scm>=10.2; extra == "dev"
@@ -138,7 +138,12 @@ class FirstValue(Expression, AggFunc):
138
138
 
139
139
 
140
140
  class GroupConcat(Expression, AggFunc):
141
- arg_types = {"this": True, "separator": False, "on_overflow": False}
141
+ arg_types = {
142
+ "this": True,
143
+ "separator": False,
144
+ "on_overflow": False,
145
+ "null_separator_is_empty": False,
146
+ }
142
147
 
143
148
 
144
149
  class Grouping(Expression, AggFunc):
@@ -322,6 +327,8 @@ class Sum(Expression, AggFunc):
322
327
 
323
328
 
324
329
  class Variance(Expression, AggFunc):
330
+ # single_value_returns_zero: Oracle's VARIANCE returns 0 instead of NULL for a single value
331
+ arg_types = {"this": True, "single_value_returns_zero": False}
325
332
  _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
326
333
 
327
334
 
@@ -289,6 +289,7 @@ class Unnest(Expression, Func, UDTF):
289
289
  "expressions": True,
290
290
  "alias": False,
291
291
  "offset": False,
292
+ "offset_base": False,
292
293
  "explode_array": False,
293
294
  }
294
295
 
@@ -46,6 +46,7 @@ TABLE_PARTS = ("this", "db", "catalog")
46
46
  COLUMN_PARTS = ("this", "table", "db", "catalog")
47
47
  POSITION_META_KEYS: tuple[str, ...] = ("line", "col", "start", "end")
48
48
  UNITTEST: bool = "unittest" in sys.modules or "pytest" in sys.modules
49
+ _IMMUTABLE_META_TYPES: frozenset[type] = frozenset((int, str, bool, float, type(None)))
49
50
 
50
51
 
51
52
  @trait
@@ -1014,7 +1015,11 @@ class Expression(Expr):
1014
1015
  if node._type is not None:
1015
1016
  copy._type = deepcopy(node._type)
1016
1017
  if node._meta is not None:
1017
- copy._meta = deepcopy(node._meta)
1018
+ # Positions and flags are immutable, so only other values need a deep copy
1019
+ meta = copy._meta = dict(node._meta)
1020
+ for k, v in meta.items():
1021
+ if type(v) not in _IMMUTABLE_META_TYPES:
1022
+ meta[k] = deepcopy(v)
1018
1023
  if node._hash is not None:
1019
1024
  copy._hash = node._hash
1020
1025
 
@@ -2289,6 +2294,10 @@ class Paren(Unary):
2289
2294
  return self.this.name
2290
2295
 
2291
2296
 
2297
+ class Pos(Unary):
2298
+ pass
2299
+
2300
+
2292
2301
  class Neg(Unary):
2293
2302
  def to_py(self) -> int | Decimal:
2294
2303
  if self.is_number:
@@ -2301,7 +2310,8 @@ class AtIndex(Expression):
2301
2310
 
2302
2311
 
2303
2312
  class AtTimeZone(Expression):
2304
- arg_types = {"this": True, "zone": True}
2313
+ # session_zone: a zoneless operand is read in the session time zone (e.g. Presto, Trino)
2314
+ arg_types = {"this": True, "zone": True, "session_zone": False}
2305
2315
 
2306
2316
 
2307
2317
  class FromTimeZone(Expression):
@@ -2340,6 +2350,12 @@ class TeradataTitle(Expression):
2340
2350
  return self.this.output_name
2341
2351
 
2342
2352
 
2353
+ class TeradataNamed(Alias):
2354
+ """A Teradata NAMED alias on a subexpression; projections use ordinary Alias."""
2355
+
2356
+ arg_types = {"this": True, "alias": True}
2357
+
2358
+
2343
2359
  class Between(Expression, Predicate):
2344
2360
  arg_types = {"this": True, "low": True, "high": True, "symmetric": False}
2345
2361
 
@@ -493,7 +493,9 @@ class BitString(Expression, Condition):
493
493
 
494
494
 
495
495
  class HexString(Expression, Condition):
496
- arg_types = {"this": True, "is_integer": False}
496
+ """Encoded hexadecimal data, binary by default or integer/character when flagged."""
497
+
498
+ arg_types = {"this": True, "is_integer": False, "is_character": False}
497
499
  is_primitive = True
498
500
 
499
501
 
@@ -706,6 +708,8 @@ class Join(Expression):
706
708
  "pivots": False,
707
709
  }
708
710
 
711
+ QUALIFIERS: t.ClassVar[tuple[str, ...]] = ("on", "using", "side", "kind", "method", "nearest")
712
+
709
713
  @property
710
714
  def method(self) -> str:
711
715
  return self.text("method").upper()
@@ -1489,7 +1493,10 @@ class Select(Expression, Query):
1489
1493
  except ParseError:
1490
1494
  expression = maybe_parse(expression, into=(Join, Expr), **parse_args)
1491
1495
 
1492
- join = expression if isinstance(expression, Join) else Join(this=expression)
1496
+ join = expression if isinstance(expression, Join) else Join(this=expression, kind="CROSS")
1497
+
1498
+ if join.kind == "CROSS" and (on or using or join_type):
1499
+ join.set("kind", None)
1493
1500
 
1494
1501
  if isinstance(join.this, Select):
1495
1502
  join.this.replace(join.this.subquery())
@@ -438,6 +438,7 @@ class RegexpExtract(Expression, Func):
438
438
  "null_if_pos_overflow": False,
439
439
  "null_if_no_match": False,
440
440
  "empty_if_group_missing": False,
441
+ "inferred_group": False,
441
442
  }
442
443
 
443
444
 
@@ -449,6 +450,7 @@ class RegexpExtractAll(Expression, Func):
449
450
  "parameters": False,
450
451
  "position": False,
451
452
  "occurrence": False,
453
+ "inferred_group": False,
452
454
  }
453
455
 
454
456
 
@@ -135,7 +135,7 @@ class TimestampAdd(Expression, Func, TimeUnit):
135
135
 
136
136
  class TimestampDiff(Expression, Func, TimeUnit):
137
137
  _sql_names = ["TIMESTAMPDIFF", "TIMESTAMP_DIFF"]
138
- arg_types = {"this": True, "expression": True, "unit": False}
138
+ arg_types = {"this": True, "expression": True, "unit": False, "boundary_for_date": False}
139
139
 
140
140
 
141
141
  class TimestampSub(Expression, Func, TimeUnit):
@@ -163,7 +163,13 @@ class DatetimeTrunc(Expression, Func, TimeUnit):
163
163
 
164
164
 
165
165
  class DateTrunc(Expression, Func):
166
- arg_types = {"unit": True, "this": True, "zone": False, "input_type_preserved": False}
166
+ arg_types = {
167
+ "unit": True,
168
+ "this": True,
169
+ "zone": False,
170
+ "input_type_preserved": False,
171
+ "century_from_zero": False,
172
+ }
167
173
 
168
174
  def __init__(self, **args):
169
175
  # Across most dialects it's safe to unabbreviate the unit (e.g. 'Q' -> 'QUARTER') except Oracle
@@ -188,7 +194,13 @@ class DateTrunc(Expression, Func):
188
194
 
189
195
 
190
196
  class TimestampTrunc(Expression, Func, TimeUnit):
191
- arg_types = {"this": True, "unit": True, "zone": False, "input_type_preserved": False}
197
+ arg_types = {
198
+ "this": True,
199
+ "unit": True,
200
+ "zone": False,
201
+ "input_type_preserved": False,
202
+ "century_from_zero": False,
203
+ }
192
204
 
193
205
 
194
206
  class TimeSlice(Expression, Func, TimeUnit):
@@ -48,15 +48,8 @@ def unsupported_args(
48
48
  def decorator(func: GeneratorMethod) -> GeneratorMethod:
49
49
  @wraps(func)
50
50
  def _func(generator: G, expression: E) -> str:
51
- expression_name = expression.__class__.__name__
52
- dialect_name = generator.dialect.__class__.__name__
53
-
54
51
  for arg_name, diagnostic in diagnostic_by_arg.items():
55
- if expression.args.get(arg_name):
56
- diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format(
57
- arg_name, expression_name, dialect_name
58
- )
59
- generator.unsupported(diagnostic)
52
+ generator._warn_unsupported_arg(expression, arg_name, diagnostic)
60
53
 
61
54
  return func(generator, expression)
62
55
 
@@ -310,6 +303,9 @@ class Generator:
310
303
  # Window functions that support NULLS FIRST/LAST
311
304
  WINDOW_FUNCS_WITH_NULL_ORDERING: t.ClassVar[tuple[type[exp.Expression], ...]] = ()
312
305
 
306
+ # Window functions that require an ORDER BY in their window specification
307
+ WINDOW_FUNCS_REQUIRING_ORDER: t.ClassVar[tuple[type[exp.Expression], ...]] = ()
308
+
313
309
  # Whether ignore nulls is inside the agg or outside.
314
310
  # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER
315
311
  IGNORE_NULLS_IN_FUNC = False
@@ -379,6 +375,12 @@ class Generator:
379
375
  # Whether top-k distance/similarity joins are supported
380
376
  SUPPORTS_NEAREST_JOIN = False
381
377
 
378
+ # Whether MATCH_CONDITION in ASOF joins is supported
379
+ SUPPORTS_MATCH_CONDITION = False
380
+
381
+ # Whether ASOF JOIN MATCH_CONDITION should be folded into the ON clause
382
+ MATCH_CONDITION_IN_ON = False
383
+
382
384
  # Whether table hints should be generated
383
385
  TABLE_HINTS = True
384
386
 
@@ -416,7 +418,7 @@ class Generator:
416
418
  NVL2_SUPPORTED = True
417
419
 
418
420
  # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
419
- SELECT_KINDS: tuple[str, ...] = ("STRUCT", "VALUE")
421
+ SELECT_KINDS: t.ClassVar[tuple[str, ...]] = ("STRUCT", "VALUE")
420
422
 
421
423
  # Whether VALUES statements can be used as derived tables.
422
424
  # MySQL 5 and Redshift do not allow this, so when False, it will convert
@@ -626,6 +628,12 @@ class Generator:
626
628
  # The function name of the exp.ArraySize expression
627
629
  ARRAY_SIZE_NAME: str = "ARRAY_LENGTH"
628
630
 
631
+ # Override for sample variance; otherwise use the expression's function name.
632
+ VARIANCE_NAME: str = ""
633
+
634
+ # Whether VARIANCE natively returns zero for a single non-NULL value.
635
+ VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE = False
636
+
629
637
  # The syntax to use when altering the type of a column
630
638
  ALTER_SET_TYPE = "SET DATA TYPE"
631
639
 
@@ -638,6 +646,9 @@ class Generator:
638
646
  # Whether a multi-argument DECODE(...) function is supported. If not, a CASE expression is generated
639
647
  SUPPORTS_DECODE_CASE = True
640
648
 
649
+ # Whether CHR / CHAR accepts multiple code points, e.g. CHAR(72, 105). If not, the calls are concatenated
650
+ SUPPORTS_MULTI_ARG_CHR = True
651
+
641
652
  # Whether SYMMETRIC and ASYMMETRIC flags are supported with BETWEEN expression
642
653
  SUPPORTS_BETWEEN_FLAGS = False
643
654
 
@@ -1053,6 +1064,17 @@ class Generator:
1053
1064
  expression = sqlglot.transforms.move_ctes_to_top_level(expression)
1054
1065
  return expression
1055
1066
 
1067
+ def _warn_unsupported_arg(
1068
+ self, expression: exp.Expr, arg_name: str, diagnostic: str | None = None
1069
+ ) -> None:
1070
+ if expression.args.get(arg_name):
1071
+ self.unsupported(
1072
+ diagnostic
1073
+ or UNSUPPORTED_TEMPLATE.format(
1074
+ arg_name, expression.__class__.__name__, self.dialect.__class__.__name__
1075
+ )
1076
+ )
1077
+
1056
1078
  def unsupported(self, message: str) -> None:
1057
1079
  if self.unsupported_level == ErrorLevel.IMMEDIATE:
1058
1080
  raise UnsupportedError(message)
@@ -1660,6 +1682,11 @@ class Generator:
1660
1682
  def hexstring_sql(
1661
1683
  self, expression: exp.HexString, binary_function_repr: str | None = None
1662
1684
  ) -> str:
1685
+ if expression.args.get("is_character"):
1686
+ self.unsupported("Hexadecimal character literals are only supported in Teradata")
1687
+ this = expression.this.replace("'", "''")
1688
+ return f"'{this}'XC"
1689
+
1663
1690
  this = self.sql(expression, "this")
1664
1691
  is_integer_type = expression.args.get("is_integer")
1665
1692
 
@@ -2703,16 +2730,20 @@ class Generator:
2703
2730
  in_exprs = expression.fields[0].expressions
2704
2731
  step = len(columns) // len(in_exprs)
2705
2732
 
2706
- # Derive the per-value suffix from the first stored column vs the first IN-list value.
2707
- # This correctly handles dialects (e.g. Spark single-agg) that ignore agg aliases.
2708
- first_base = in_exprs[0].sql() if src_identify_pivot_strings else in_exprs[0].alias_or_name
2709
- first_stored = columns[0].name
2733
+ suffix = ""
2734
+ if len(expression.expressions) != 1 or expression.expressions[0].alias:
2735
+ # Derive the per-value suffix from the first stored column vs the first IN-list value.
2736
+ # This correctly handles dialects (e.g. Spark single-agg) that ignore agg aliases.
2737
+ first_base = (
2738
+ in_exprs[0].sql() if src_identify_pivot_strings else in_exprs[0].alias_or_name
2739
+ )
2740
+ first_stored = columns[0].name
2710
2741
 
2711
- # exit if only suffix matches, not prefix. (e.g. BigQuery, which cannot be fixed)
2712
- if not first_stored.startswith(first_base):
2713
- return None
2742
+ # exit if only suffix matches, not prefix. (e.g. BigQuery, which cannot be fixed)
2743
+ if not first_stored.startswith(first_base):
2744
+ return None
2714
2745
 
2715
- suffix = first_stored[len(first_base) :]
2746
+ suffix = first_stored[len(first_base) :]
2716
2747
 
2717
2748
  # Whether the target dialect would append an agg-name suffix for this pivot.
2718
2749
  # Spark single-agg uniquely drops the agg alias entirely.
@@ -3017,6 +3048,17 @@ class Generator:
3017
3048
  return f"PRIOR {self.sql(expression, 'this')}"
3018
3049
 
3019
3050
  def join_sql(self, expression: exp.Join, join_op: str | None = None) -> str:
3051
+ if (
3052
+ match_condition := expression.args.get("match_condition")
3053
+ ) and not self.SUPPORTS_MATCH_CONDITION:
3054
+ if self.MATCH_CONDITION_IN_ON and not expression.args.get("using"):
3055
+ expression = expression.on(match_condition)
3056
+ expression.set("match_condition", None)
3057
+ # Snowflake ASOF joins preserve unmatched left rows.
3058
+ expression.set("side", "LEFT")
3059
+ else:
3060
+ self.unsupported("MATCH_CONDITION is not supported")
3061
+
3020
3062
  if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
3021
3063
  side = None
3022
3064
  else:
@@ -3725,9 +3767,28 @@ class Generator:
3725
3767
  return f"{self.seg('WHERE')}{self.sep()}{this}"
3726
3768
 
3727
3769
  def window_sql(self, expression: exp.Window) -> str:
3770
+ if (
3771
+ isinstance(expression.this, exp.Variance)
3772
+ and expression.this.args.get("single_value_returns_zero")
3773
+ and expression.text("over") != "KEEP"
3774
+ and not self.VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE
3775
+ ):
3776
+ return self.variance_sql(expression.this, window=expression)
3777
+
3728
3778
  this = self.sql(expression, "this")
3729
3779
  partition = self.partition_by_sql(expression)
3730
3780
  order = expression.args.get("order")
3781
+ if not order and self.WINDOW_FUNCS_REQUIRING_ORDER and not expression.args.get("alias"):
3782
+ func = expression.this
3783
+ if isinstance(func, (exp.IgnoreNulls, exp.RespectNulls)):
3784
+ func = func.this
3785
+ if isinstance(func, self.WINDOW_FUNCS_REQUIRING_ORDER):
3786
+ # Without an ordering all rows of a partition are peers, which is
3787
+ # also the case when ordering by the partition keys themselves
3788
+ partition_by = expression.args.get("partition_by")
3789
+ order = exp.Order(
3790
+ expressions=[e.copy() for e in partition_by] if partition_by else [exp.null()]
3791
+ )
3731
3792
  order = self.order_sql(order, flat=True) if order else ""
3732
3793
  spec = self.sql(expression, "spec")
3733
3794
  alias = self.sql(expression, "alias")
@@ -3834,7 +3895,17 @@ class Generator:
3834
3895
  return f"ANY {this}"
3835
3896
 
3836
3897
  def exists_sql(self, expression: exp.Exists) -> str:
3837
- return f"EXISTS{self.wrap(expression)}"
3898
+ predicate = expression.expression
3899
+ if not predicate:
3900
+ return f"EXISTS{self.wrap(expression)}"
3901
+
3902
+ # Spark's EXISTS(array, lambda)
3903
+ if self.CAN_IMPLEMENT_ARRAY_ANY:
3904
+ filtered = exp.ArrayFilter(this=expression.this, expression=predicate)
3905
+ return self.sql(exp.paren(exp.ArraySize(this=filtered).neq(0)))
3906
+
3907
+ self.unsupported("EXISTS with a lambda predicate is unsupported")
3908
+ return self.function_fallback_sql(expression)
3838
3909
 
3839
3910
  def case_sql(self, expression: exp.Case) -> str:
3840
3911
  this = self.sql(expression, "this")
@@ -4059,6 +4130,10 @@ class Generator:
4059
4130
  self.unsupported("Teradata TITLE display headings are not supported")
4060
4131
  return self.sql(expression, "this")
4061
4132
 
4133
+ def teradatanamed_sql(self, expression: exp.TeradataNamed) -> str:
4134
+ self.unsupported("Teradata NAMED on subexpressions is not supported")
4135
+ return self.sql(expression, "this")
4136
+
4062
4137
  def _jsonobject_sql(
4063
4138
  self, expression: exp.JSONObject | exp.JSONObjectAgg, name: str = ""
4064
4139
  ) -> str:
@@ -4237,6 +4312,9 @@ class Generator:
4237
4312
  sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
4238
4313
  return f"({sql}{self.seg(')', sep='')}"
4239
4314
 
4315
+ def pos_sql(self, expression: exp.Pos) -> str:
4316
+ return f"+{self.sql(expression, 'this')}"
4317
+
4240
4318
  def neg_sql(self, expression: exp.Neg) -> str:
4241
4319
  # This makes sure we don't convert "- - 5" to "--5", which is a comment
4242
4320
  this_sql = self.sql(expression, "this")
@@ -6241,6 +6319,36 @@ class Generator:
6241
6319
  self.unsupported("ARRAY_SORT only sorts ascending with NULLs last")
6242
6320
  return self.func("ARRAY_SORT", expression.this, expression.expression)
6243
6321
 
6322
+ def variance_sql(self, expression: exp.Variance, window: exp.Window | None = None) -> str:
6323
+ this = expression.this
6324
+ name = self.VARIANCE_NAME or self.function_name(expression)
6325
+ if not expression.args.get("single_value_returns_zero"):
6326
+ return self.func(name, this)
6327
+
6328
+ node: exp.Expr = expression
6329
+ while node.parent and not isinstance(node.parent, (exp.Window, exp.AggFunc, exp.Select)):
6330
+ node = node.parent
6331
+ if window is None and isinstance(node.parent, exp.Window) and node.arg_key == "this":
6332
+ self.unsupported("VARIANCE returning 0 for a single value is not supported in a window")
6333
+ return self.func(name, this)
6334
+
6335
+ expression.set("single_value_returns_zero", None)
6336
+ count: exp.Expr
6337
+ variance: exp.Expr = expression
6338
+ if window:
6339
+ count = window.copy()
6340
+ count.set("this", exp.Count(this=count.this.this))
6341
+ variance = window
6342
+ else:
6343
+ count = exp.Count(this=this.copy())
6344
+
6345
+ return self.sql(
6346
+ exp.case(count, copy=False)
6347
+ .when(0, exp.null(), copy=False)
6348
+ .when(1, 0, copy=False)
6349
+ .else_(variance, copy=False)
6350
+ )
6351
+
6244
6352
  def arraysize_sql(self, expression: exp.ArraySize) -> str:
6245
6353
  dim = expression.expression
6246
6354
 
@@ -6659,7 +6767,21 @@ class Generator:
6659
6767
 
6660
6768
  return name
6661
6769
 
6770
+ def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
6771
+ self._warn_unsupported_arg(expression, "century_from_zero")
6772
+ unit = expression.unit
6773
+ if unit.is_string and unit.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"):
6774
+ self.unsupported(f"Unexpected interval unit: {unit.name}")
6775
+
6776
+ return self.function_fallback_sql(expression)
6777
+
6662
6778
  def chr_sql(self, expression: exp.Chr, name: str = "CHR") -> str:
6779
+ args = expression.expressions
6780
+ if len(args) > 1 and not self.SUPPORTS_MULTI_ARG_CHR:
6781
+ # CHAR(72, 105) -> CHR(72) || CHR(105)
6782
+ chars: list[exp.Expr] = [exp.Chr(expressions=[arg.copy()]) for arg in args]
6783
+ return self.sql(reduce(lambda x, y: exp.DPipe(this=x, expression=y), chars))
6784
+
6663
6785
  this = self.expressions(expression)
6664
6786
  charset = self.sql(expression, "charset")
6665
6787
  using = f" USING {charset}" if charset else ""
@@ -127,7 +127,7 @@ class AthenaTrinoGenerator(TrinoGenerator):
127
127
 
128
128
 
129
129
  class AthenaGenerator(AthenaTrinoGenerator):
130
- SELECT_KINDS: tuple[str, ...] = ()
130
+ SELECT_KINDS = ()
131
131
  SUPPORTS_DECODE_CASE = False
132
132
 
133
133
  AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
@@ -340,6 +340,7 @@ class BigQueryGenerator(generator.Generator):
340
340
  TRY_SUPPORTED = False
341
341
  SUPPORTS_UESCAPE = False
342
342
  SUPPORTS_DECODE_CASE = False
343
+ SUPPORTS_MULTI_ARG_CHR = False
343
344
  INTERVAL_ALLOWS_PLURAL_FORM = False
344
345
  JOIN_HINTS = False
345
346
  QUERY_HINTS = False
@@ -370,6 +371,17 @@ class BigQueryGenerator(generator.Generator):
370
371
 
371
372
  SAFE_JSON_PATH_KEY_RE = re.compile(r"^[\-\w]*$")
372
373
 
374
+ WINDOW_FUNCS_REQUIRING_ORDER = (
375
+ exp.CumeDist,
376
+ exp.DenseRank,
377
+ exp.FirstValue,
378
+ exp.LastValue,
379
+ exp.NthValue,
380
+ exp.Ntile,
381
+ exp.PercentRank,
382
+ exp.Rank,
383
+ )
384
+
373
385
  WINDOW_FUNCS_WITH_NULL_ORDERING = (
374
386
  exp.CumeDist,
375
387
  exp.DenseRank,
@@ -519,7 +531,9 @@ class BigQueryGenerator(generator.Generator):
519
531
  exp.TimestampFromParts: rename_func("DATETIME"),
520
532
  exp.TimeSub: date_add_interval_sql("TIME", "SUB"),
521
533
  exp.TimestampAdd: date_add_interval_sql("TIMESTAMP", "ADD"),
522
- exp.TimestampDiff: rename_func("TIMESTAMP_DIFF"),
534
+ exp.TimestampDiff: lambda self, e: self.func(
535
+ "TIMESTAMP_DIFF", e.this, e.expression, e.unit
536
+ ),
523
537
  exp.TimestampSub: date_add_interval_sql("TIMESTAMP", "SUB"),
524
538
  exp.TimeStrToTime: timestrtotime_sql,
525
539
  exp.Transaction: lambda *_: "BEGIN TRANSACTION",
@@ -774,7 +788,10 @@ class BigQueryGenerator(generator.Generator):
774
788
  return self.func("WEEK", expression.this)
775
789
 
776
790
  def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
791
+ self._warn_unsupported_arg(expression, "century_from_zero")
777
792
  unit = expression.unit
793
+ if unit.is_string and unit.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"):
794
+ self.unsupported(f"Unexpected interval unit: {unit.name}")
778
795
  unit_sql = unit.name if unit.is_string else self.sql(unit)
779
796
  return self.func("DATE_TRUNC", expression.this, unit_sql, expression.args.get("zone"))
780
797
 
@@ -837,15 +854,48 @@ class BigQueryGenerator(generator.Generator):
837
854
 
838
855
  return self.binary(expression, "=")
839
856
 
857
+ def escape_sql(self, expression: exp.Escape) -> str:
858
+ # BigQuery's LIKE has no ESCAPE clause and always escapes with a backslash, so a literal
859
+ # pattern is rewritten to backslash escapes. UPPER/LOWER around it can't change a
860
+ # caseless escape character, e.g. ^, so those patterns are rewritten too.
861
+ like, char = expression.this.copy(), expression.expression.name
862
+ pattern = like.expression
863
+ if isinstance(pattern, (exp.Upper, exp.Lower)) and char.upper() == char.lower():
864
+ pattern = pattern.this
865
+ e = re.escape(char)
866
+ if not (
867
+ isinstance(like, exp.Like)
868
+ and expression.expression.is_string
869
+ and len(char) == 1
870
+ and pattern.is_string
871
+ and re.fullmatch(f"(?:[^{e}]|{e}[%_{e}])*", pattern.name)
872
+ ):
873
+ return super().escape_sql(expression)
874
+
875
+ # Escaped %, _ and backslash, and unescaped backslash, get a backslash
876
+ pattern.set(
877
+ "this",
878
+ re.sub(
879
+ f"{e}[%_{e}]|\\\\",
880
+ lambda m: "\\" * (m[0][-1] in "%_\\") + m[0][-1],
881
+ pattern.name,
882
+ ),
883
+ )
884
+ return self.sql(like)
885
+
840
886
  def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
841
887
  parent = expression.parent
842
888
 
843
889
  # BigQuery allows CAST(.. AS {STRING|TIMESTAMP} [FORMAT <fmt> [AT TIME ZONE <tz>]]).
844
890
  # Only the TIMESTAMP one should use the below conversion, when AT TIME ZONE is included.
845
891
  if not isinstance(parent, exp.Cast) or not parent.to.is_type("text"):
846
- return self.func(
847
- "TIMESTAMP", self.func("DATETIME", expression.this, expression.args.get("zone"))
848
- )
892
+ this = expression.this
893
+ if expression.args.get("session_zone"):
894
+ # DATETIME(<ts>, <zone>) only accepts a TIMESTAMP and BigQuery reads a DATETIME
895
+ # cast to TIMESTAMP as UTC, so this assumes the source session time zone is UTC
896
+ this = exp.cast(this, exp.DType.TIMESTAMPTZ)
897
+
898
+ return self.func("TIMESTAMP", self.func("DATETIME", this, expression.args.get("zone")))
849
899
 
850
900
  return super().attimezone_sql(expression)
851
901
 
@@ -6,6 +6,7 @@ import typing as t
6
6
  from sqlglot import exp, generator
7
7
  from sqlglot.dialects.dialect import (
8
8
  arg_max_or_min_no_count,
9
+ array_sort_order,
9
10
  inline_array_sql,
10
11
  jarowinkler_similarity,
11
12
  json_extract_segments,
@@ -30,6 +31,19 @@ from collections import defaultdict
30
31
  DATETIME_DELTA = t.Union[exp.DateAdd, exp.DateDiff, exp.DateSub, exp.TimestampSub, exp.TimestampAdd]
31
32
 
32
33
 
34
+ @unsupported_args(("expression", "ClickHouse's arraySort does not support a comparator."))
35
+ def _array_sort_sql(self: ClickHouseGenerator, expression: exp.ArraySort) -> str:
36
+ order = array_sort_order(expression)
37
+ if order is None:
38
+ self.unsupported("arraySort only takes literal orders")
39
+ return self.func("arraySort", expression.this)
40
+
41
+ asc, nulls_first = order
42
+ if nulls_first:
43
+ self.unsupported("arraySort and arrayReverseSort put NULLs last")
44
+ return self.func("arraySort" if asc else "arrayReverseSort", expression.this)
45
+
46
+
33
47
  def _unix_to_time_sql(self: ClickHouseGenerator, expression: exp.UnixToTime) -> str:
34
48
  scale = expression.args.get("scale")
35
49
  timestamp = expression.this
@@ -166,7 +180,7 @@ def _json_cast_sql(self: ClickHouseGenerator, expression: exp.JSONCast) -> str:
166
180
 
167
181
  class ClickHouseGenerator(generator.Generator):
168
182
  BYTE_STRING_FUNCTION = "unhex"
169
- SELECT_KINDS: tuple[str, ...] = ()
183
+ SELECT_KINDS = ()
170
184
  TRY_SUPPORTED = False
171
185
  SUPPORTS_UESCAPE = False
172
186
  SUPPORTS_DECODE_CASE = False
@@ -186,10 +200,12 @@ class ClickHouseGenerator(generator.Generator):
186
200
  SUPPORTS_TO_NUMBER = False
187
201
  JOIN_HINTS = False
188
202
  TABLE_HINTS = False
203
+ MATCH_CONDITION_IN_ON = True
189
204
  GROUPINGS_SEP = ""
190
205
  SET_OP_MODIFIERS = False
191
206
  SET_OP_LIMITS = True
192
207
  ARRAY_SIZE_NAME = "LENGTH"
208
+ VARIANCE_NAME = "varSamp"
193
209
  WRAP_DERIVED_VALUES = False
194
210
  AUTO_REFRESH_BARE_INTERVALS = True
195
211
 
@@ -289,6 +305,7 @@ class ClickHouseGenerator(generator.Generator):
289
305
  exp.Transform: lambda self, e: self.func("arrayMap", e.expression, e.this),
290
306
  exp.ArrayRemove: remove_from_array_using_filter,
291
307
  exp.ArrayReverse: rename_func("arrayReverse"),
308
+ exp.ArraySort: _array_sort_sql,
292
309
  exp.ArraySlice: rename_func("arraySlice"),
293
310
  exp.ArraySum: rename_func("arraySum"),
294
311
  exp.ArrayMax: rename_func("arrayMax"),
@@ -332,6 +349,8 @@ class ClickHouseGenerator(generator.Generator):
332
349
  exp.JSONPathKey: json_path_key_only_name,
333
350
  exp.JSONPathRoot: lambda *_: "",
334
351
  exp.Length: length_or_char_length_sql,
352
+ exp.LogicalAnd: lambda self, e: self.func("minOrNull", e.this.neq(0)),
353
+ exp.LogicalOr: lambda self, e: self.func("maxOrNull", e.this.neq(0)),
335
354
  exp.Map: _map_sql,
336
355
  exp.Median: rename_func("median"),
337
356
  exp.Nullif: rename_func("nullIf"),
@@ -378,7 +397,6 @@ class ClickHouseGenerator(generator.Generator):
378
397
  ),
379
398
  exp.UnixToTime: _unix_to_time_sql,
380
399
  exp.Trim: lambda self, e: trim_sql(self, e, default_trim_type="BOTH"),
381
- exp.Variance: rename_func("varSamp"),
382
400
  exp.VariancePop: rename_func("varPop"),
383
401
  exp.WeekOfYear: rename_func("toISOWeek"),
384
402
  exp.YearOfWeekIso: rename_func("toISOYear"),
@@ -391,7 +409,7 @@ class ClickHouseGenerator(generator.Generator):
391
409
  rename_func("editDistance")
392
410
  ),
393
411
  exp.ParseDatetime: lambda self, e: self.func(
394
- "parseDateTime", e.this, e.args.get("format"), e.args.get("zone")
412
+ "parseDateTime", e.this, self.format_time(e), e.args.get("zone")
395
413
  ),
396
414
  }
397
415
 
@@ -543,6 +561,9 @@ class ClickHouseGenerator(generator.Generator):
543
561
  else:
544
562
  return default(expression)
545
563
 
564
+ if isinstance(arr.this, exp.Query):
565
+ return default(expression)
566
+
546
567
  return prefix + self.func("has", arr.this.unnest(), this)
547
568
 
548
569
  def eq_sql(self, expression: exp.EQ) -> str: