sqlglotc 30.34.0__tar.gz → 30.35.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 (117) hide show
  1. {sqlglotc-30.34.0/sqlglotc.egg-info → sqlglotc-30.35.0}/PKG-INFO +2 -2
  2. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/array.py +5 -0
  3. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/core.py +4 -0
  4. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/ddl.py +4 -0
  5. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/query.py +4 -0
  6. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generator.py +32 -10
  7. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/athena.py +1 -0
  8. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/bigquery.py +104 -2
  9. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/presto.py +1 -0
  10. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/snowflake.py +2 -1
  11. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/spark.py +0 -5
  12. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/trino.py +1 -0
  13. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/tsql.py +1 -0
  14. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/optimizer/annotate_types.py +15 -5
  15. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/optimizer/qualify_columns.py +65 -2
  16. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/optimizer/scope.py +17 -2
  17. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parser.py +44 -9
  18. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/athena.py +1 -0
  19. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/bigquery.py +22 -14
  20. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/trino.py +28 -0
  21. {sqlglotc-30.34.0 → sqlglotc-30.35.0/sqlglotc.egg-info}/PKG-INFO +2 -2
  22. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglotc.egg-info/requires.txt +1 -1
  23. sqlglotc-30.35.0/sqlglotc.egg-info/scm_version.json +8 -0
  24. sqlglotc-30.34.0/sqlglotc.egg-info/scm_version.json +0 -8
  25. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/MANIFEST.in +0 -0
  26. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/pyproject.toml +0 -0
  27. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/setup.cfg +0 -0
  28. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/setup.py +0 -0
  29. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/anonymize.py +0 -0
  30. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/errors.py +0 -0
  31. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/executor/table.py +0 -0
  32. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/aggregate.py +0 -0
  33. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/builders.py +0 -0
  34. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/constraints.py +0 -0
  35. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/datatypes.py +0 -0
  36. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/dml.py +0 -0
  37. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/functions.py +0 -0
  38. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/json.py +0 -0
  39. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/math.py +0 -0
  40. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/properties.py +0 -0
  41. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/string.py +0 -0
  42. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/expressions/temporal.py +0 -0
  43. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/clickhouse.py +0 -0
  44. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/databricks.py +0 -0
  45. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/dax.py +0 -0
  46. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/doris.py +0 -0
  47. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/dremio.py +0 -0
  48. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/drill.py +0 -0
  49. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/druid.py +0 -0
  50. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/duckdb.py +0 -0
  51. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/dune.py +0 -0
  52. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/exasol.py +0 -0
  53. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/fabric.py +0 -0
  54. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/hive.py +0 -0
  55. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/materialize.py +0 -0
  56. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/mysql.py +0 -0
  57. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/oracle.py +0 -0
  58. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/postgres.py +0 -0
  59. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/prql.py +0 -0
  60. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/python.py +0 -0
  61. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/redshift.py +0 -0
  62. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/risingwave.py +0 -0
  63. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/singlestore.py +0 -0
  64. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/solr.py +0 -0
  65. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/spark2.py +0 -0
  66. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/sqlite.py +0 -0
  67. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/starrocks.py +0 -0
  68. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/tableau.py +0 -0
  69. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/generators/teradata.py +0 -0
  70. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/helper.py +0 -0
  71. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/lineage.py +0 -0
  72. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/optimizer/canonicalize_internal_names.py +0 -0
  73. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/optimizer/isolate_table_selects.py +0 -0
  74. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/optimizer/normalize_identifiers.py +0 -0
  75. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/optimizer/qualify.py +0 -0
  76. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/optimizer/qualify_tables.py +0 -0
  77. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/optimizer/resolver.py +0 -0
  78. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/optimizer/simplify.py +0 -0
  79. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/base.py +0 -0
  80. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/clickhouse.py +0 -0
  81. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/databricks.py +0 -0
  82. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/dax.py +0 -0
  83. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/doris.py +0 -0
  84. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/dremio.py +0 -0
  85. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/drill.py +0 -0
  86. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/druid.py +0 -0
  87. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/duckdb.py +0 -0
  88. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/dune.py +0 -0
  89. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/exasol.py +0 -0
  90. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/fabric.py +0 -0
  91. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/hive.py +0 -0
  92. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/materialize.py +0 -0
  93. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/mysql.py +0 -0
  94. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/oracle.py +0 -0
  95. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/postgres.py +0 -0
  96. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/presto.py +0 -0
  97. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/prql.py +0 -0
  98. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/redshift.py +0 -0
  99. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/risingwave.py +0 -0
  100. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/singlestore.py +0 -0
  101. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/snowflake.py +0 -0
  102. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/solr.py +0 -0
  103. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/spark.py +0 -0
  104. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/spark2.py +0 -0
  105. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/sqlite.py +0 -0
  106. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/starrocks.py +0 -0
  107. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/tableau.py +0 -0
  108. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/teradata.py +0 -0
  109. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/parsers/tsql.py +0 -0
  110. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/serde.py +0 -0
  111. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/time.py +0 -0
  112. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/tokenizer_core.py +0 -0
  113. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglot/trie.py +0 -0
  114. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglotc.egg-info/SOURCES.txt +0 -0
  115. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglotc.egg-info/dependency_links.txt +0 -0
  116. {sqlglotc-30.34.0 → sqlglotc-30.35.0}/sqlglotc.egg-info/scm_file_list.json +0 -0
  117. {sqlglotc-30.34.0 → sqlglotc-30.35.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.34.0
3
+ Version: 30.35.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.34.0
10
+ Requires-Dist: sqlglot==30.35.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"
@@ -405,3 +405,8 @@ class StX(Expression, Func):
405
405
 
406
406
  class StY(Expression, Func):
407
407
  arg_types = {"this": True, "expression": False}
408
+
409
+
410
+ class StGeogPoint(Expression, Func):
411
+ arg_types = {"this": True, "expression": True}
412
+ _sql_names = ["ST_GEOGPOINT"]
@@ -1479,6 +1479,10 @@ class Expression(Expr):
1479
1479
  return between
1480
1480
 
1481
1481
  def is_(self, other: ExpOrStr) -> Is:
1482
+ if isinstance(other, Not) and isinstance(other.this, (Null, Boolean)):
1483
+ predicate = self._binop(Is, other.this)
1484
+ predicate.set("negate", True)
1485
+ return predicate
1482
1486
  return self._binop(Is, other)
1483
1487
 
1484
1488
  def like(self, other: ExpOrStr) -> Like:
@@ -453,3 +453,7 @@ class Execute(Expression):
453
453
 
454
454
  class ExecuteSql(Execute):
455
455
  pass
456
+
457
+
458
+ class ExecuteImmediate(Execute):
459
+ arg_types = {"this": True, "expressions": False}
@@ -850,6 +850,10 @@ class Lateral(Expression, UDTF):
850
850
  return columns
851
851
 
852
852
 
853
+ class TableArgument(Expression):
854
+ """A relation passed to a table function with the TABLE keyword."""
855
+
856
+
853
857
  class TableFromRows(Expression, UDTF):
854
858
  arg_types = {
855
859
  "this": True,
@@ -504,6 +504,7 @@ class Generator:
504
504
  SUPPORTS_SELECT_INTO = False
505
505
 
506
506
  SUPPORTS_OPTIMIZE = False
507
+ SUPPORTS_EXECUTE_IMMEDIATE = True
507
508
 
508
509
  # Whether UNLOGGED tables can be created
509
510
  SUPPORTS_UNLOGGED_TABLES = False
@@ -623,6 +624,7 @@ class Generator:
623
624
  ALTER_SET_WRAPPED = False
624
625
 
625
626
  # Whether to normalize the date parts in EXTRACT(<date_part> FROM <expr>) into a common representation
627
+ # using the dialect's general aliases as a fallback for parts without an EXTRACT-specific mapping.
626
628
  # For instance, to extract the day of week in ISO semantics, one can use ISODOW, DAYOFWEEKISO etc depending on the dialect.
627
629
  # TODO: The normalization should be done by default once we've tested it across all dialects.
628
630
  NORMALIZE_EXTRACT_DATE_PARTS = False
@@ -1031,7 +1033,9 @@ class Generator:
1031
1033
  expression = self.preprocess(expression)
1032
1034
 
1033
1035
  self.unsupported_messages = []
1034
- sql = self.sql(expression).strip()
1036
+ sql = self.sql(expression)
1037
+ # A trailing newline in a raw command can terminate a line comment.
1038
+ sql = sql.lstrip() if isinstance(expression, exp.Command) else sql.strip()
1035
1039
 
1036
1040
  if self.pretty:
1037
1041
  sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
@@ -2661,6 +2665,10 @@ class Generator:
2661
2665
 
2662
2666
  return f"{only}{table}{changes}{partition}{file_format}{pre_alias}{alias}{indexed}{hints}{pivots}{post_alias}{joins}{laterals}{ordinality}"
2663
2667
 
2668
+ def tableargument_sql(self, expression: exp.TableArgument) -> str:
2669
+ table = expression.this
2670
+ return f"TABLE {self.maybe_comment(self.table_parts(table), table)}"
2671
+
2664
2672
  def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
2665
2673
  table = self.func("TABLE", expression.this)
2666
2674
  alias = self.sql(expression, "alias")
@@ -3947,14 +3955,18 @@ class Generator:
3947
3955
  order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
3948
3956
  return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
3949
3957
 
3950
- def extract_sql(self, expression: exp.Extract) -> str:
3951
- import sqlglot.dialects.dialect
3958
+ def extract_date_part(self, part: exp.Expr) -> exp.Expr:
3959
+ mapping = self.dialect.EXTRACT_DATE_PART_MAPPING
3960
+ if self.NORMALIZE_EXTRACT_DATE_PARTS and part.name.upper() not in mapping:
3961
+ mapping = self.dialect.DATE_PART_MAPPING
3962
+ if mapping:
3963
+ import sqlglot.dialects.dialect
3952
3964
 
3953
- this = (
3954
- sqlglot.dialects.dialect.map_date_part(expression.this, self.dialect)
3955
- if self.NORMALIZE_EXTRACT_DATE_PARTS
3956
- else expression.this
3957
- )
3965
+ return sqlglot.dialects.dialect.map_date_part(part, mapping=mapping)
3966
+ return part
3967
+
3968
+ def extract_sql(self, expression: exp.Extract) -> str:
3969
+ this = self.extract_date_part(expression.this)
3958
3970
  if self.EXTRACT_ALLOWS_QUOTES:
3959
3971
  this_sql = self.sql(this)
3960
3972
  elif isinstance(this, exp.WeekStart):
@@ -4498,7 +4510,8 @@ class Generator:
4498
4510
  return self.binary(expression, "COLLATE")
4499
4511
 
4500
4512
  def command_sql(self, expression: exp.Command) -> str:
4501
- return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
4513
+ args = expression.text("expression").lstrip()
4514
+ return f"{self.sql(expression, 'this')} {args}".rstrip(" \t")
4502
4515
 
4503
4516
  def optimize_sql(self, expression: exp.Optimize) -> str:
4504
4517
  if not self.SUPPORTS_OPTIMIZE:
@@ -5967,7 +5980,8 @@ class Generator:
5967
5980
 
5968
5981
  def gapfill_sql(self, expression: exp.GapFill) -> str:
5969
5982
  this = self.sql(expression, "this")
5970
- this = f"TABLE {this}"
5983
+ if isinstance(expression.this, exp.Table):
5984
+ this = f"TABLE {this}"
5971
5985
  return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
5972
5986
 
5973
5987
  def scope_resolution(self, rhs: str, scope_name: str) -> str:
@@ -6884,6 +6898,14 @@ class Generator:
6884
6898
  self.unsupported("Unsupported Execute syntax")
6885
6899
  return ""
6886
6900
 
6901
+ def executeimmediate_sql(self, expression: exp.ExecuteImmediate) -> str:
6902
+ if not self.SUPPORTS_EXECUTE_IMMEDIATE:
6903
+ self.unsupported("EXECUTE IMMEDIATE is not supported")
6904
+ return ""
6905
+ using = self.expressions(expression, flat=True)
6906
+ using = f" USING {using}" if using else ""
6907
+ return f"EXECUTE IMMEDIATE {self.sql(expression, 'this')}{using}"
6908
+
6887
6909
  def altermodifysqlsecurity_sql(self, expression: exp.AlterModifySqlSecurity) -> str:
6888
6910
  props = self.expressions(expression, sep=" ")
6889
6911
  return f"MODIFY {props}"
@@ -114,6 +114,7 @@ class _HiveGenerator(HiveGenerator):
114
114
 
115
115
 
116
116
  class AthenaTrinoGenerator(TrinoGenerator):
117
+ SUPPORTS_EXECUTE_IMMEDIATE = False
117
118
  PROPERTIES_LOCATION = {
118
119
  **TrinoGenerator.PROPERTIES_LOCATION,
119
120
  exp.LocationProperty: exp.Properties.Location.POST_WITH,
@@ -33,6 +33,7 @@ from sqlglot.dialects.dialect import (
33
33
  from sqlglot.errors import ErrorLevel
34
34
  from sqlglot.generator import unsupported_args
35
35
  from sqlglot.helper import seq_get
36
+ from sqlglot.typing import TIMESTAMP_EXPRESSIONS
36
37
 
37
38
  if t.TYPE_CHECKING:
38
39
  from sqlglot.dialects.dialect import DialectType
@@ -43,6 +44,20 @@ JSON_EXTRACT_TYPE = t.Union[exp.JSONExtract, exp.JSONExtractScalar, exp.JSONExtr
43
44
 
44
45
  DQUOTES_ESCAPING_JSON_FUNCTIONS = ("JSON_QUERY", "JSON_VALUE", "JSON_QUERY_ARRAY")
45
46
 
47
+ # BigQuery's DATE_ADD, DATE_SUB, TIMESTAMP_TRUNC, TIMESTAMP_ADD and TIMESTAMP_SUB return their first
48
+ # argument's type, as parentheses do
49
+ FIRST_ARG_TYPED = (
50
+ exp.Paren,
51
+ exp.DateAdd,
52
+ exp.DateSub,
53
+ exp.TimestampTrunc,
54
+ exp.TimestampAdd,
55
+ exp.TimestampSub,
56
+ )
57
+
58
+ # Expressions BigQuery writes as a TIMESTAMP, e.g. AT TIME ZONE as TIMESTAMP(DATETIME(x, zone))
59
+ TIMESTAMP_TYPED = (exp.AtTimeZone, *TIMESTAMP_EXPRESSIONS)
60
+
46
61
 
47
62
  def _derived_table_values_to_unnest(self: BigQueryGenerator, expression: exp.Values) -> str:
48
63
  if not expression.find_ancestor(exp.From, exp.Join):
@@ -118,6 +133,31 @@ def _alias_ordered_group(expression: exp.Expr) -> exp.Expr:
118
133
  return expression
119
134
 
120
135
 
136
+ def _is_value_window(window: exp.Window) -> bool:
137
+ func = window.this
138
+ if isinstance(func, (exp.IgnoreNulls, exp.RespectNulls)):
139
+ func = func.this
140
+ return isinstance(func, (exp.FirstValue, exp.LastValue, exp.NthValue))
141
+
142
+
143
+ def _nondefault_null_order(ordered: exp.Expr) -> bool:
144
+ # BigQuery sorts NULLs first in ascending order and last in descending order.
145
+ return isinstance(ordered, exp.Ordered) and bool(ordered.args.get("nulls_first")) == bool(
146
+ ordered.args.get("desc")
147
+ )
148
+
149
+
150
+ def _inline_value_window_order(window: exp.Window, inherited: exp.Window) -> bool:
151
+ order = inherited.args.get("order") or window.args.get("order")
152
+ spec = window.args.get("spec") or inherited.args.get("spec")
153
+ return bool(
154
+ order
155
+ and _is_value_window(window)
156
+ and (not spec or spec.text("kind").upper() == "RANGE")
157
+ and any(_nondefault_null_order(key) for key in order.expressions)
158
+ )
159
+
160
+
121
161
  def _pushdown_cte_column_names(expression: exp.Expr) -> exp.Expr:
122
162
  """BigQuery doesn't allow column names when defining a CTE, so we try to push them down."""
123
163
  if isinstance(expression, exp.CTE) and expression.alias_column_names:
@@ -469,11 +509,9 @@ class BigQueryGenerator(generator.Generator):
469
509
  exp.CountIf: rename_func("COUNTIF"),
470
510
  exp.Create: _create_sql,
471
511
  exp.CTE: transforms.preprocess([_pushdown_cte_column_names]),
472
- exp.DateAdd: date_add_interval_sql("DATE", "ADD"),
473
512
  exp.DateDiff: lambda self, e: self.func("DATE_DIFF", e.this, e.expression, unit_to_var(e)),
474
513
  exp.DateFromParts: rename_func("DATE"),
475
514
  exp.DateStrToDate: datestrtodate_sql,
476
- exp.DateSub: date_add_interval_sql("DATE", "SUB"),
477
515
  exp.DatetimeAdd: date_add_interval_sql("DATETIME", "ADD"),
478
516
  exp.DatetimeSub: date_add_interval_sql("DATETIME", "SUB"),
479
517
  exp.DateFromUnixDate: rename_func("DATE_FROM_UNIX_DATE"),
@@ -542,6 +580,7 @@ class BigQueryGenerator(generator.Generator):
542
580
  transforms.unqualify_unnest,
543
581
  transforms.eliminate_distinct_on,
544
582
  _alias_ordered_group,
583
+ lambda e: transforms.eliminate_window_clause(e, _inline_value_window_order),
545
584
  transforms.eliminate_semi_and_anti_joins,
546
585
  ]
547
586
  ),
@@ -821,6 +860,32 @@ class BigQueryGenerator(generator.Generator):
821
860
 
822
861
  return self.func("WEEK", expression.this)
823
862
 
863
+ def dateadd_sql(self, expression: exp.DateAdd | exp.DateSub) -> str:
864
+ kind = "SUB" if isinstance(expression, exp.DateSub) else "ADD"
865
+ this = expression.this
866
+ if expression.text("unit") in ("WEEK", "MONTH", "QUARTER", "YEAR"):
867
+ node = this
868
+ while isinstance(node, FIRST_ARG_TYPED):
869
+ node = node.this
870
+ # TIME_STR_TO_TIME is written as CAST(x AS DATETIME) without a zone, whatever its type
871
+ if (
872
+ node.args.get("zone")
873
+ if isinstance(node, exp.TimeStrToTime)
874
+ else isinstance(node, TIMESTAMP_TYPED) or node.is_type(exp.DType.TIMESTAMPTZ)
875
+ ):
876
+ # TIMESTAMP arithmetic only takes units up to DAY, so use the UTC DATETIME instead
877
+ shifted = (exp.DatetimeSub if kind == "SUB" else exp.DatetimeAdd)(
878
+ this=exp.TsOrDsToDatetime(this=this),
879
+ expression=expression.expression,
880
+ unit=expression.unit,
881
+ )
882
+ return self.func("TIMESTAMP", shifted)
883
+
884
+ return date_add_interval_sql("DATE", kind)(self, expression)
885
+
886
+ def datesub_sql(self, expression: exp.DateSub) -> str:
887
+ return self.dateadd_sql(expression)
888
+
824
889
  def datetrunc_sql(self, expression: exp.DateTrunc) -> str:
825
890
  self._warn_unsupported_arg(expression, "century_from_zero")
826
891
  unit = expression.unit
@@ -1002,6 +1067,43 @@ class BigQueryGenerator(generator.Generator):
1002
1067
 
1003
1068
  return super().cast_sql(expression, safe_prefix=safe_prefix)
1004
1069
 
1070
+ def ordered_sql(self, expression: exp.Ordered) -> str:
1071
+ order = expression.parent
1072
+ window = order.parent if isinstance(order, exp.Order) else None
1073
+ if not isinstance(window, exp.Window) or not _nondefault_null_order(expression):
1074
+ return super().ordered_sql(expression)
1075
+
1076
+ # A WINDOW definition can be used with different functions and frames.
1077
+ if isinstance(window.this, exp.Identifier):
1078
+ return super().ordered_sql(expression.copy())
1079
+
1080
+ spec = window.args.get("spec")
1081
+ if not _is_value_window(window) or (spec and spec.text("kind").upper() != "RANGE"):
1082
+ return super().ordered_sql(expression)
1083
+
1084
+ key = expression.this
1085
+ needs_null_key = key not in (window.args.get("partition_by") or [])
1086
+ if spec and any(isinstance(spec.args.get(bound), exp.Expr) for bound in ("start", "end")):
1087
+ # An offset RANGE allows only one key. With finite bounds, NULL keys can
1088
+ # only frame other NULLs, so their position relative to non-NULLs is immaterial.
1089
+ if needs_null_key and any(
1090
+ spec.text(bound).upper() == "UNBOUNDED" for bound in ("start", "end")
1091
+ ):
1092
+ return super().ordered_sql(expression)
1093
+ needs_null_key = False
1094
+
1095
+ desc = expression.args.get("desc")
1096
+ expression = expression.copy()
1097
+ expression.set("nulls_first", not desc)
1098
+ sql = super().ordered_sql(expression)
1099
+ if not needs_null_key:
1100
+ return sql
1101
+
1102
+ if isinstance(key, (exp.Not, exp.Predicate)):
1103
+ key = exp.paren(key)
1104
+ is_null = key.is_(exp.null())
1105
+ return f"{self.sql(is_null)}{' DESC' if desc else ''}, {sql}"
1106
+
1005
1107
  def clusterproperty_sql(self, expression: exp.ClusterProperty) -> str:
1006
1108
  if expression.this:
1007
1109
  self.unsupported(f"Unsupported CLUSTER BY {self.sql(expression, 'this')}")
@@ -266,6 +266,7 @@ def amend_exploded_column_table(expression: exp.Expr) -> exp.Expr:
266
266
 
267
267
  class PrestoGenerator(generator.Generator):
268
268
  SELECT_KINDS = ()
269
+ SUPPORTS_EXECUTE_IMMEDIATE = False
269
270
  SUPPORTS_DECODE_CASE = False
270
271
  SUPPORTS_MULTI_ARG_CHR = False
271
272
  SUPPORTS_TEMPORAL_PRECISION = False
@@ -401,6 +401,7 @@ class SnowflakeGenerator(generator.Generator):
401
401
  EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
402
402
  SUPPORTS_MEDIAN = True
403
403
  ARRAY_SIZE_NAME = "ARRAY_SIZE"
404
+ NORMALIZE_EXTRACT_DATE_PARTS = True
404
405
  SUPPORTS_DECODE_CASE = True
405
406
  ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
406
407
  ALTER_TABLE_ADD_COLUMNS_WRAPPED = False
@@ -485,7 +486,7 @@ class SnowflakeGenerator(generator.Generator):
485
486
  exp.DotProduct: rename_func("VECTOR_INNER_PRODUCT"),
486
487
  exp.Explode: rename_func("FLATTEN"),
487
488
  exp.Extract: lambda self, e: self.func(
488
- "DATE_PART", map_date_part(e.this, self.dialect), e.expression
489
+ "DATE_PART", self.extract_date_part(e.this), e.expression
489
490
  ),
490
491
  exp.Filter: no_filter_sql,
491
492
  exp.CosineDistance: rename_func("VECTOR_COSINE_SIMILARITY"),
@@ -185,11 +185,6 @@ class SparkGenerator(Spark2Generator):
185
185
  def anyvalue_sql(self, expression: exp.AnyValue) -> str:
186
186
  return self.function_fallback_sql(expression)
187
187
 
188
- def extract_sql(self, expression: exp.Extract) -> str:
189
- if expression.name.upper() == "ISODOW":
190
- expression.set("this", exp.var("DOW_ISO"))
191
- return super().extract_sql(expression)
192
-
193
188
  def datediff_sql(self, expression: exp.DateDiff) -> str:
194
189
  end = self.sql(expression, "this")
195
190
  start = self.sql(expression, "expression")
@@ -12,6 +12,7 @@ from sqlglot.generators.presto import PrestoGenerator, amend_exploded_column_tab
12
12
 
13
13
 
14
14
  class TrinoGenerator(PrestoGenerator):
15
+ SUPPORTS_EXECUTE_IMMEDIATE = True
15
16
  SUPPORTS_TEMPORAL_PRECISION = True
16
17
  SUPPORTS_LEFT_JOIN_UNNEST = True
17
18
  EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
@@ -25,6 +25,7 @@ from sqlglot.time import format_time
25
25
  from collections import defaultdict
26
26
 
27
27
  DATE_PART_UNMAPPING = {
28
+ "ISOWEEK": "ISO_WEEK",
28
29
  "WEEKISO": "ISO_WEEK",
29
30
  "DAYOFWEEK": "WEEKDAY",
30
31
  "TIMEZONE_MINUTE": "TZOFFSET",
@@ -867,13 +867,16 @@ class TypeAnnotator:
867
867
 
868
868
  return expression
869
869
 
870
- def _annotate_literal(self, expression: exp.Literal) -> exp.Literal:
870
+ def _annotate_literal(
871
+ self,
872
+ expression: exp.Literal,
873
+ ) -> exp.Literal:
871
874
  if expression.is_string:
872
875
  self._set_type(expression, exp.DType.VARCHAR)
873
876
  elif expression.is_int:
874
- self._set_type(expression, exp.DType.INT)
877
+ self._set_type(expression, self.dialect.int_literal_type(expression))
875
878
  else:
876
- self._set_type(expression, exp.DType.DOUBLE)
879
+ self._set_type(expression, self.dialect.decimal_literal_type(expression.this))
877
880
 
878
881
  expression.meta["nonnull"] = True
879
882
 
@@ -1001,7 +1004,9 @@ class TypeAnnotator:
1001
1004
 
1002
1005
  return expression
1003
1006
 
1004
- def _annotate_div(self, expression: exp.Div) -> exp.Div:
1007
+ def _annotate_div(
1008
+ self, expression: exp.Div, *, coerce_integer_operands: bool = False
1009
+ ) -> exp.Div:
1005
1010
  left, right = expression.left, expression.right
1006
1011
  left_type = left.type.this if left.type else exp.DType.UNKNOWN
1007
1012
  right_type = right.type.this if right.type else exp.DType.UNKNOWN
@@ -1011,7 +1016,12 @@ class TypeAnnotator:
1011
1016
  and left_type in exp.DataType.INTEGER_TYPES
1012
1017
  and right_type in exp.DataType.INTEGER_TYPES
1013
1018
  ):
1014
- self._set_type(expression, exp.DType.BIGINT)
1019
+ self._set_type(
1020
+ expression,
1021
+ self._maybe_coerce(left_type, right_type)
1022
+ if coerce_integer_operands
1023
+ else exp.DType.BIGINT,
1024
+ )
1015
1025
  else:
1016
1026
  self._set_type(expression, self._maybe_coerce(left_type, right_type))
1017
1027
  if expression.type and expression.type.this not in exp.DataType.REAL_TYPES:
@@ -8,6 +8,7 @@ from collections import Counter
8
8
  from sqlglot import alias, exp
9
9
  from sqlglot.dialects.dialect import AliasPrecedence, Dialect, DialectType, UsingColumnOrder
10
10
  from sqlglot.errors import OptimizeError, highlight_sql
11
+ from sqlglot.helper import tsort
11
12
  from sqlglot.optimizer.annotate_types import TypeAnnotator
12
13
  from sqlglot.optimizer.helpers import is_implicit_group_by_all
13
14
  from sqlglot.optimizer.resolver import Resolver
@@ -71,6 +72,8 @@ def qualify_columns(
71
72
  dialect = schema.dialect or Dialect()
72
73
  pseudocolumns = dialect.PSEUDOCOLUMNS
73
74
  convert_dots_early = expand_alias_refs and dialect.PREFER_PROJECTION_ALIASES_IN_DOT_PATHS
75
+ expand_forward = expand_alias_refs and dialect.SUPPORTS_FORWARD_ALIAS_REFS
76
+ prepare_projection_aliases = convert_dots_early or expand_forward
74
77
 
75
78
  # Qualified scopes that still lack types, in traversal order (sources precede dependents)
76
79
  unannotated_scopes: list[Scope] = []
@@ -93,8 +96,11 @@ def qualify_columns(
93
96
 
94
97
  using_column_tables, using_columns = _expand_using(scope, resolver)
95
98
 
96
- if convert_dots_early:
97
- _convert_columns_to_dots(scope, resolver, prefer_projection_aliases=True)
99
+ if prepare_projection_aliases:
100
+ if convert_dots_early:
101
+ _convert_columns_to_dots(scope, resolver, prefer_projection_aliases=True)
102
+ if expand_forward:
103
+ _expand_forward_alias_refs(scope, resolver)
98
104
 
99
105
  if dialect.FORCE_EARLY_ALIAS_REF_EXPANSION and expand_alias_refs:
100
106
  _expand_alias_refs(
@@ -373,6 +379,63 @@ def _expand_using(scope: Scope, resolver: Resolver) -> tuple[dict[str, t.Any], l
373
379
  return column_tables, using_columns
374
380
 
375
381
 
382
+ def _expand_forward_alias_refs(scope: Scope, resolver: Resolver) -> None:
383
+ expression = scope.expression
384
+ if not isinstance(expression, exp.Select) or len(expression.selects) < 2:
385
+ return
386
+
387
+ selects = expression.selects
388
+ aliases = {s.alias: i for i, s in enumerate(selects) if isinstance(s, exp.Alias)}
389
+ if not aliases:
390
+ return
391
+
392
+ references: dict[int, list[tuple[exp.Column, int]]] = {}
393
+ self_references = []
394
+ for i, projection in enumerate(selects):
395
+ for column in walk_in_scope(projection, prune=lambda n: n.is_star):
396
+ if not isinstance(column, exp.Column) or column.table:
397
+ continue
398
+ target = aliases.get(column.name)
399
+ if target is None:
400
+ continue
401
+ if column.name == projection.alias:
402
+ self_references.append(column)
403
+ else:
404
+ references.setdefault(i, []).append((column, target))
405
+
406
+ if not references and not self_references:
407
+ return
408
+
409
+ try:
410
+ order = tsort({i: {target for _, target in columns} for i, columns in references.items()})
411
+ except ValueError as e:
412
+ raise OptimizeError("Cannot expand cyclic projection aliases") from e
413
+
414
+ # In x + 1 AS x, x is the input column. Bind it before copying the expression
415
+ # so the subsequent alias expansion cannot substitute x a second time.
416
+ for column in self_references:
417
+ table = resolver.get_table(column)
418
+ if not table and scope.can_be_correlated and not resolver.has_unknown_sources:
419
+ table = _get_outer_column_table(column, resolver)
420
+ if table:
421
+ column.set("table", table)
422
+
423
+ for i in order:
424
+ projection = selects[i]
425
+ for column, target in references.get(i, ()):
426
+ definition = selects[target].this
427
+ if column is projection.unnest():
428
+ # SELECT x, 1 AS x exposes two columns named x.
429
+ projection.replace(alias(definition, column.this))
430
+ else:
431
+ replacement = column.replace(exp.paren(definition))
432
+ simplified = simplify_parens(replacement, resolver.dialect)
433
+ if simplified is not replacement:
434
+ replacement.replace(simplified)
435
+
436
+ scope.clear_cache()
437
+
438
+
376
439
  def _expand_alias_refs(
377
440
  scope: Scope, resolver: Resolver, dialect: Dialect, expand_only_groupby: bool = False
378
441
  ) -> None:
@@ -87,6 +87,7 @@ class Scope:
87
87
  _derived_tables: list[exp.Subquery]
88
88
  _udtfs: list[exp.UDTF]
89
89
  _tables: list[exp.Table]
90
+ _table_arguments: list[tuple[exp.Table, str | None]]
90
91
  _ordered_sources: list[exp.Expr]
91
92
  _ctes: list[exp.CTE]
92
93
  _subqueries: list[exp.Select | exp.SetOperation]
@@ -145,6 +146,7 @@ class Scope:
145
146
  self._derived_tables = []
146
147
  self._udtfs = []
147
148
  self._tables = []
149
+ self._table_arguments = []
148
150
  self._ordered_sources = []
149
151
  self._ctes = []
150
152
  self._subqueries = []
@@ -183,6 +185,7 @@ class Scope:
183
185
 
184
186
  def _collect(self) -> None:
185
187
  self._tables = []
188
+ self._table_arguments = []
186
189
  self._ordered_sources = []
187
190
  self._ctes = []
188
191
  self._subqueries = []
@@ -222,7 +225,11 @@ class Scope:
222
225
  self._semi_anti_join_tables.add(node.alias_or_name)
223
226
 
224
227
  self._tables.append(node)
225
- self._ordered_sources.append(node)
228
+ if isinstance(node.parent, exp.TableArgument):
229
+ # Hoisting a CTE can rename this node to the name of another visible CTE.
230
+ self._table_arguments.append((node, None if node.db else node.name))
231
+ else:
232
+ self._ordered_sources.append(node)
226
233
  elif isinstance(node, exp.JoinHint):
227
234
  self._join_hints.append(node)
228
235
  elif type(node) is exp.Lateral or (
@@ -467,6 +474,12 @@ class Scope:
467
474
  self._selected_sources = result
468
475
  return self._selected_sources
469
476
 
477
+ def table_argument_sources(self) -> Iterator[tuple[exp.Table, exp.Table | Scope]]:
478
+ """Resolve TABLE arguments against visible CTEs independently of FROM aliases."""
479
+ self._ensure_collected()
480
+ for table, cte_name in self._table_arguments:
481
+ yield table, self.cte_sources.get(cte_name, table) if cte_name is not None else table
482
+
470
483
  @property
471
484
  def references(self) -> list[tuple[str, exp.Selectable]]:
472
485
  if self._references is None:
@@ -661,7 +674,9 @@ class Scope:
661
674
  scope_ref_count: dict[int, int] = defaultdict(int)
662
675
 
663
676
  for scope in self.traverse():
664
- for _, source in scope.selected_sources.values():
677
+ for _, source in itertools.chain(
678
+ scope.selected_sources.values(), scope.table_argument_sources()
679
+ ):
665
680
  scope_ref_count[id(source)] += 1
666
681
 
667
682
  for name in scope._semi_anti_join_tables: