sqlglotc 30.32.0__tar.gz → 30.33.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.32.0/sqlglotc.egg-info → sqlglotc-30.33.0}/PKG-INFO +2 -2
  2. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/math.py +1 -0
  3. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/query.py +4 -0
  4. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/string.py +4 -2
  5. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/temporal.py +2 -1
  6. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generator.py +16 -0
  7. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/clickhouse.py +2 -2
  8. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/databricks.py +3 -0
  9. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/duckdb.py +74 -24
  10. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/materialize.py +4 -0
  11. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/postgres.py +7 -0
  12. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/presto.py +14 -1
  13. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/redshift.py +3 -0
  14. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/snowflake.py +3 -0
  15. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/spark.py +7 -1
  16. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/spark2.py +18 -5
  17. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/sqlite.py +11 -3
  18. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/tsql.py +10 -3
  19. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/optimizer/qualify_columns.py +11 -15
  20. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/optimizer/scope.py +4 -0
  21. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parser.py +2 -0
  22. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/clickhouse.py +7 -2
  23. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/databricks.py +23 -0
  24. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/duckdb.py +2 -0
  25. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/presto.py +32 -0
  26. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/snowflake.py +2 -2
  27. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/sqlite.py +9 -0
  28. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/tsql.py +3 -3
  29. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/tokenizer_core.py +1 -0
  30. {sqlglotc-30.32.0 → sqlglotc-30.33.0/sqlglotc.egg-info}/PKG-INFO +2 -2
  31. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglotc.egg-info/requires.txt +1 -1
  32. sqlglotc-30.33.0/sqlglotc.egg-info/scm_version.json +8 -0
  33. sqlglotc-30.32.0/sqlglotc.egg-info/scm_version.json +0 -8
  34. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/MANIFEST.in +0 -0
  35. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/pyproject.toml +0 -0
  36. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/setup.cfg +0 -0
  37. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/setup.py +0 -0
  38. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/anonymize.py +0 -0
  39. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/errors.py +0 -0
  40. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/executor/table.py +0 -0
  41. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/aggregate.py +0 -0
  42. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/array.py +0 -0
  43. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/builders.py +0 -0
  44. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/constraints.py +0 -0
  45. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/core.py +0 -0
  46. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/datatypes.py +0 -0
  47. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/ddl.py +0 -0
  48. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/dml.py +0 -0
  49. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/functions.py +0 -0
  50. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/json.py +0 -0
  51. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/expressions/properties.py +0 -0
  52. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/athena.py +0 -0
  53. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/bigquery.py +0 -0
  54. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/dax.py +0 -0
  55. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/doris.py +0 -0
  56. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/dremio.py +0 -0
  57. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/drill.py +0 -0
  58. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/druid.py +0 -0
  59. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/dune.py +0 -0
  60. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/exasol.py +0 -0
  61. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/fabric.py +0 -0
  62. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/hive.py +0 -0
  63. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/mysql.py +0 -0
  64. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/oracle.py +0 -0
  65. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/prql.py +0 -0
  66. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/python.py +0 -0
  67. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/risingwave.py +0 -0
  68. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/singlestore.py +0 -0
  69. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/solr.py +0 -0
  70. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/starrocks.py +0 -0
  71. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/tableau.py +0 -0
  72. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/teradata.py +0 -0
  73. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/generators/trino.py +0 -0
  74. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/helper.py +0 -0
  75. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/lineage.py +0 -0
  76. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/optimizer/annotate_types.py +0 -0
  77. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/optimizer/canonicalize_internal_names.py +0 -0
  78. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/optimizer/isolate_table_selects.py +0 -0
  79. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/optimizer/normalize_identifiers.py +0 -0
  80. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/optimizer/qualify.py +0 -0
  81. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/optimizer/qualify_tables.py +0 -0
  82. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/optimizer/resolver.py +0 -0
  83. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/optimizer/simplify.py +0 -0
  84. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/athena.py +0 -0
  85. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/base.py +0 -0
  86. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/bigquery.py +0 -0
  87. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/dax.py +0 -0
  88. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/doris.py +0 -0
  89. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/dremio.py +0 -0
  90. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/drill.py +0 -0
  91. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/druid.py +0 -0
  92. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/dune.py +0 -0
  93. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/exasol.py +0 -0
  94. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/fabric.py +0 -0
  95. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/hive.py +0 -0
  96. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/materialize.py +0 -0
  97. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/mysql.py +0 -0
  98. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/oracle.py +0 -0
  99. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/postgres.py +0 -0
  100. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/prql.py +0 -0
  101. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/redshift.py +0 -0
  102. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/risingwave.py +0 -0
  103. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/singlestore.py +0 -0
  104. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/solr.py +0 -0
  105. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/spark.py +0 -0
  106. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/spark2.py +0 -0
  107. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/starrocks.py +0 -0
  108. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/tableau.py +0 -0
  109. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/teradata.py +0 -0
  110. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/parsers/trino.py +0 -0
  111. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/serde.py +0 -0
  112. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/time.py +0 -0
  113. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglot/trie.py +0 -0
  114. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglotc.egg-info/SOURCES.txt +0 -0
  115. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglotc.egg-info/dependency_links.txt +0 -0
  116. {sqlglotc-30.32.0 → sqlglotc-30.33.0}/sqlglotc.egg-info/scm_file_list.json +0 -0
  117. {sqlglotc-30.32.0 → sqlglotc-30.33.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.32.0
3
+ Version: 30.33.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.32.0
10
+ Requires-Dist: sqlglot==30.33.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"
@@ -186,6 +186,7 @@ class Round(Expression, Func):
186
186
  "decimals": False,
187
187
  "truncate": False,
188
188
  "casts_non_integer_decimals": False,
189
+ "negative_decimals_are_zero": False,
189
190
  }
190
191
 
191
192
 
@@ -1975,6 +1975,10 @@ class Where(Expression):
1975
1975
  pass
1976
1976
 
1977
1977
 
1978
+ class Optimize(Expression):
1979
+ pass
1980
+
1981
+
1978
1982
  class Analyze(Expression):
1979
1983
  arg_types = {
1980
1984
  "kind": False,
@@ -51,7 +51,9 @@ class EndsWith(Expression, Func):
51
51
 
52
52
 
53
53
  class Format(Expression, Func):
54
- arg_types = {"this": True, "expressions": False}
54
+ """Formats values using printf syntax, or brace syntax when is_fmt is set."""
55
+
56
+ arg_types = {"this": True, "expressions": False, "is_fmt": False}
55
57
  is_var_len_args = True
56
58
 
57
59
 
@@ -253,7 +255,7 @@ class Trim(Expression, Func):
253
255
 
254
256
 
255
257
  class Unicode(Expression, Func):
256
- arg_types = {"this": True, "empty_is_zero": False}
258
+ arg_types = {"this": True, "empty_is_zero": False, "empty_is_null": False}
257
259
 
258
260
 
259
261
  class Upper(Expression, Func):
@@ -504,7 +504,8 @@ class TimeStrToUnix(Expression, Func):
504
504
 
505
505
 
506
506
  class TimeToStr(Expression, Func):
507
- arg_types = {"this": True, "format": True, "culture": False, "zone": False}
507
+ # joda: parsed from Presto/Trino's FORMAT_DATETIME, which DATE_FORMAT can't always express
508
+ arg_types = {"this": True, "format": True, "culture": False, "zone": False, "joda": False}
508
509
 
509
510
 
510
511
  class TimeToTimeStr(Expression, Func):
@@ -4116,6 +4116,18 @@ class Generator:
4116
4116
 
4117
4117
  return escaped
4118
4118
 
4119
+ def format_sql(self, expression: exp.Format) -> str:
4120
+ if (
4121
+ expression.args.get("is_fmt")
4122
+ and expression.this.is_string
4123
+ and not expression.expressions
4124
+ and not any(c in expression.name for c in "{}")
4125
+ ):
4126
+ return self.sql(expression.this)
4127
+
4128
+ self._warn_unsupported_arg(expression, "is_fmt")
4129
+ return self.function_fallback_sql(expression)
4130
+
4119
4131
  def formatjson_sql(self, expression: exp.FormatJson) -> str:
4120
4132
  return f"{self.sql(expression, 'this')} FORMAT JSON"
4121
4133
 
@@ -4474,6 +4486,10 @@ class Generator:
4474
4486
  def command_sql(self, expression: exp.Command) -> str:
4475
4487
  return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
4476
4488
 
4489
+ def optimize_sql(self, expression: exp.Optimize) -> str:
4490
+ self.unsupported("OPTIMIZE is only supported in Databricks")
4491
+ return f"OPTIMIZE {self.sql(expression, 'this')}"
4492
+
4477
4493
  def comment_sql(self, expression: exp.Comment) -> str:
4478
4494
  this = self.sql(expression, "this")
4479
4495
  kind = expression.args["kind"]
@@ -385,9 +385,9 @@ class ClickHouseGenerator(generator.Generator):
385
385
  exp.Xor: lambda self, e: self.func("xor", e.this, e.expression),
386
386
  exp.MD5Digest: rename_func("MD5"),
387
387
  exp.MD5: lambda self, e: self.func("LOWER", self.func("HEX", self.func("MD5", e.this))),
388
- exp.SHA: rename_func("SHA1"),
388
+ exp.SHA: lambda self, e: self.func("LOWER", self.func("HEX", self.func("SHA1", e.this))),
389
389
  exp.SHA1Digest: rename_func("SHA1"),
390
- exp.SHA2: sha256_sql,
390
+ exp.SHA2: lambda self, e: self.func("LOWER", self.func("HEX", sha256_sql(self, e))),
391
391
  exp.SHA2Digest: sha2_digest_sql,
392
392
  exp.Split: lambda self, e: self.func(
393
393
  "splitByString", e.args.get("expression"), e.this, e.args.get("limit")
@@ -212,3 +212,6 @@ class DatabricksGenerator(SparkGenerator):
212
212
  def clusterproperty_sql(self, expression):
213
213
  this = self.sql(expression, "this") or f"({self.expressions(expression, flat=True)})"
214
214
  return f"CLUSTER BY {this}"
215
+
216
+ def optimize_sql(self, expression: exp.Optimize) -> str:
217
+ return f"OPTIMIZE {self.sql(expression, 'this')}"
@@ -2259,7 +2259,7 @@ class DuckDBGenerator(generator.Generator):
2259
2259
  SUBSTR(h, 1, 8) || '-' ||
2260
2260
  SUBSTR(h, 9, 4) || '-' ||
2261
2261
  '5' || SUBSTR(h, 14, 3) || '-' ||
2262
- FORMAT('{:02x}', CAST('0x' || SUBSTR(h, 17, 2) AS INT) & 63 | 128) || SUBSTR(h, 19, 2) || '-' ||
2262
+ PRINTF('%02x', CAST('0x' || SUBSTR(h, 17, 2) AS INT) & 63 | 128) || SUBSTR(h, 19, 2) || '-' ||
2263
2263
  SUBSTR(h, 21, 12)
2264
2264
  )
2265
2265
  FROM (
@@ -2813,32 +2813,56 @@ class DuckDBGenerator(generator.Generator):
2813
2813
 
2814
2814
  def strposition_sql(self, expression: exp.StrPosition) -> str:
2815
2815
  this = expression.this
2816
- substr = expression.args.get("substr")
2816
+ substr = expression.args["substr"]
2817
2817
  position = expression.args.get("position")
2818
+ clamp_position = expression.args.get("clamp_position")
2819
+
2820
+ if clamp_position and position:
2821
+ position = exp.If(
2822
+ this=exp.LTE(this=position, expression=exp.Literal.number(0)),
2823
+ true=exp.Literal.number(1),
2824
+ false=position.copy(),
2825
+ )
2818
2826
 
2819
2827
  # For BINARY/BLOB: DuckDB's STRPOS doesn't support BLOB types
2820
2828
  if _is_binary(this):
2829
+ haystack: exp.Expr = exp.Hex(this=this)
2830
+ offset: exp.Expr = exp.Literal.number(0)
2831
+ if position:
2832
+ # Bound the arithmetic too: DuckDB may fold unreachable CASE branches.
2833
+ limit = exp.func("COALESCE", exp.ByteLength(this=this), 0) + 1
2834
+ offset = exp.Least(this=position, expressions=[limit], ignore_nulls=True) - 1
2835
+ haystack = exp.Substring(this=haystack, start=offset * 2 + 1)
2836
+
2821
2837
  # Match whole bytes, counting a two-character sentinel as the first byte.
2822
2838
  prefix = exp.RegexpExtract(
2823
- this=exp.DPipe(this=exp.Literal.string("xx"), expression=exp.Hex(this=this)),
2839
+ this=exp.DPipe(this=exp.Literal.string("xx"), expression=haystack),
2824
2840
  expression=exp.DPipe(
2825
2841
  this=exp.Literal.string("^(xx(?:..)*?)"), expression=exp.Hex(this=substr)
2826
2842
  ),
2827
2843
  group=exp.Literal.number(1),
2828
2844
  )
2829
- return self.sql(exp.paren(exp.Length(this=prefix) // 2))
2845
+ result: exp.Expr = exp.paren(exp.Length(this=prefix) // 2)
2846
+ if position:
2847
+ result = (
2848
+ exp.case()
2849
+ .when(
2850
+ exp.or_(
2851
+ this.is_(exp.null()), substr.is_(exp.null()), position.is_(exp.null())
2852
+ ),
2853
+ exp.null(),
2854
+ )
2855
+ .when(
2856
+ position > exp.func("GREATEST", exp.ByteLength(this=this), 1),
2857
+ exp.Literal.number(0),
2858
+ )
2859
+ .else_(exp.func("COALESCE", exp.func("NULLIF", result, 0) + offset, 0))
2860
+ )
2861
+ return self.sql(result)
2830
2862
 
2831
- # For VARCHAR: handle clamp_position
2832
- if expression.args.get("clamp_position") and position:
2863
+ if clamp_position and position:
2833
2864
  expression = expression.copy()
2834
- expression.set(
2835
- "position",
2836
- exp.If(
2837
- this=exp.LTE(this=position, expression=exp.Literal.number(0)),
2838
- true=exp.Literal.number(1),
2839
- false=position.copy(),
2840
- ),
2841
- )
2865
+ expression.set("position", position)
2842
2866
 
2843
2867
  return strposition_sql(self, expression)
2844
2868
 
@@ -2964,6 +2988,9 @@ class DuckDBGenerator(generator.Generator):
2964
2988
  return self.func("JSON", arg)
2965
2989
 
2966
2990
  def unicode_sql(self, expression: exp.Unicode) -> str:
2991
+ if expression.args.get("empty_is_null"):
2992
+ return self.func("NULLIF", self.func("UNICODE", expression.this), "-1")
2993
+
2967
2994
  if expression.args.get("empty_is_zero"):
2968
2995
  return self.sql(
2969
2996
  exp.case()
@@ -3920,13 +3947,13 @@ class DuckDBGenerator(generator.Generator):
3920
3947
  upper = expression.args.get("upper")
3921
3948
 
3922
3949
  if lower and upper:
3923
- # scale DuckDB's [0,1) to the specified range
3924
- range_size = exp.paren(upper - lower)
3925
- scaled = exp.Add(this=lower, expression=exp.func("random") * range_size)
3926
-
3927
- # For now we assume that if bounds are set, return type is BIGINT. Snowflake/Teradata
3928
- result = exp.cast(scaled, exp.DType.BIGINT)
3929
- return self.sql(result)
3950
+ # Build 64 random bits in integer arithmetic to preserve the low bits and
3951
+ # avoid overflow when the inclusive range spans signed BIGINT's limits.
3952
+ random_bits = exp.cast(exp.Floor(this=exp.Rand() * (1 << 32)), exp.DType.INT128)
3953
+ random = random_bits * (1 << 32) + random_bits.copy()
3954
+ lower = exp.cast(lower, exp.DType.INT128)
3955
+ upper = exp.cast(upper, exp.DType.INT128)
3956
+ return self.sql(exp.cast(random % (upper - lower + 1) + lower, exp.DType.BIGINT))
3930
3957
 
3931
3958
  # Default DuckDB behavior - just return RANDOM() as float
3932
3959
  return "RANDOM()"
@@ -4640,10 +4667,22 @@ class DuckDBGenerator(generator.Generator):
4640
4667
  return self.sql(result_expr)
4641
4668
 
4642
4669
  def format_sql(self, expression: exp.Format) -> str:
4643
- if expression.name.lower() == "%s" and len(expression.expressions) == 1:
4644
- return self.func("FORMAT", "'{}'", expression.expressions[0])
4670
+ if expression.args.get("is_fmt"):
4671
+ return self.func("FORMAT", expression.this, *expression.expressions)
4645
4672
 
4646
- return self.function_fallback_sql(expression)
4673
+ fmt = expression.name
4674
+ if expression.this.is_string and fmt == "%S" and len(expression.expressions) == 1:
4675
+ return self.func(
4676
+ "UPPER", self.func("FORMAT", exp.Literal.string("{}"), expression.expressions[0])
4677
+ )
4678
+
4679
+ if expression.this.is_string and "%s" in fmt and "%" not in re.sub(r"%%|%s", "", fmt):
4680
+ # Use brace formatting to support non-string %s arguments, as in PostgreSQL.
4681
+ fmt = fmt.replace("{", "{{").replace("}", "}}")
4682
+ fmt = re.sub(r"%%|%s", lambda m: "%" if m[0] == "%%" else "{}", fmt)
4683
+ return self.func("FORMAT", exp.Literal.string(fmt), *expression.expressions)
4684
+
4685
+ return self.func("PRINTF", expression.this, *expression.expressions)
4647
4686
 
4648
4687
  def hexstring_sql(
4649
4688
  self, expression: exp.HexString, binary_function_repr: str | None = None
@@ -4795,6 +4834,17 @@ class DuckDBGenerator(generator.Generator):
4795
4834
  decimals = expression.args.get("decimals")
4796
4835
  truncate = expression.args.get("truncate")
4797
4836
 
4837
+ if decimals is not None and expression.args.get("negative_decimals_are_zero"):
4838
+ if decimals.is_int:
4839
+ decimals = exp.Literal.number(max(0, decimals.to_py()))
4840
+ else:
4841
+ # DuckDB's DECIMAL overload requires constant precision; SQLite rounds doubles.
4842
+ this = exp.cast(this, exp.DType.DOUBLE)
4843
+ # Preserve NULL precision, which GREATEST(decimals, 0) would replace with 0.
4844
+ decimals = exp.If(
4845
+ this=decimals < 0, true=exp.Literal.number(0), false=decimals.copy()
4846
+ )
4847
+
4798
4848
  # DuckDB requires the scale (decimals) argument to be an INT
4799
4849
  # Some dialects (e.g., Snowflake) allow non-integer scales and cast to an integer internally
4800
4850
  if decimals is not None and expression.args.get("casts_non_integer_decimals"):
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from sqlglot import exp
4
+ from sqlglot.generator import Generator
4
5
  from sqlglot.helper import seq_get
5
6
  from sqlglot.generators.postgres import PostgresGenerator
6
7
 
@@ -34,6 +35,9 @@ class MaterializeGenerator(PostgresGenerator):
34
35
  exp.PrimaryKeyColumnConstraint: lambda self, e: "",
35
36
  }
36
37
 
38
+ def arraysize_sql(self, expression: exp.ArraySize) -> str:
39
+ return Generator.arraysize_sql(self, expression)
40
+
37
41
  def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
38
42
  return self.binary(expression, "=>")
39
43
 
@@ -320,6 +320,13 @@ class PostgresGenerator(generator.Generator):
320
320
 
321
321
  return sql
322
322
 
323
+ def arraysize_sql(self, expression: exp.ArraySize) -> str:
324
+ # ARRAY_LENGTH(arr, 1) returns NULL for an empty array, whereas CARDINALITY returns 0
325
+ if not expression.expression:
326
+ return self.func("CARDINALITY", expression.this)
327
+
328
+ return super().arraysize_sql(expression)
329
+
323
330
  def star_sql(self, expression: exp.Star) -> str:
324
331
  if self.STAR_EXCEPT == "EXCEPT" and expression.args.get("except_"):
325
332
  self.unsupported("PostgreSQL does not support EXCEPT in the SELECT projection")
@@ -420,7 +420,6 @@ class PrestoGenerator(generator.Generator):
420
420
  exp.TimeStrToUnix: lambda self, e: self.func(
421
421
  "TO_UNIXTIME", self.func("DATE_PARSE", e.this, type(self.dialect).TIME_FORMAT)
422
422
  ),
423
- exp.TimeToStr: lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e)),
424
423
  exp.TimeToUnix: rename_func("TO_UNIXTIME"),
425
424
  exp.ToChar: lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e)),
426
425
  exp.TryCast: transforms.preprocess([transforms.epoch_cast_to_ts]),
@@ -591,6 +590,20 @@ class PrestoGenerator(generator.Generator):
591
590
 
592
591
  return self.func("LOWER", self.func("TO_HEX", self.func(f"SHA{length}", self.sql(this))))
593
592
 
593
+ def timetostr_sql(self, expression: exp.TimeToStr) -> str:
594
+ if expression.args.get("joda"):
595
+ from sqlglot.dialects.presto import Presto
596
+
597
+ return self.func(
598
+ "FORMAT_DATETIME",
599
+ expression.this,
600
+ self.format_time(
601
+ expression, Presto.INVERSE_JODA_TIME_MAPPING, Presto.INVERSE_JODA_TIME_TRIE
602
+ ),
603
+ )
604
+
605
+ return self.func("DATE_FORMAT", expression.this, self.format_time(expression))
606
+
594
607
  def strtounix_sql(self, expression: exp.StrToUnix) -> str:
595
608
  # Since `TO_UNIXTIME` requires a `TIMESTAMP`, we need to parse the argument into one.
596
609
  # To do this, we first try to `DATE_PARSE` it, but since this can fail when there's a
@@ -381,6 +381,9 @@ class RedshiftGenerator(PostgresGenerator):
381
381
 
382
382
  return f"SET{exprs}{location}{file_format}"
383
383
 
384
+ def arraysize_sql(self, expression: exp.ArraySize) -> str:
385
+ return Generator.arraysize_sql(self, expression)
386
+
384
387
  def array_sql(self, expression: exp.Array) -> str:
385
388
  if expression.args.get("bracket_notation"):
386
389
  return super().array_sql(expression)
@@ -1123,6 +1123,9 @@ class SnowflakeGenerator(generator.Generator):
1123
1123
  return f"{self.sql(expression, 'this')}!{self.sql(expression, 'expression')}"
1124
1124
 
1125
1125
  def format_sql(self, expression: exp.Format) -> str:
1126
+ if expression.args.get("is_fmt"):
1127
+ return super().format_sql(expression)
1128
+
1126
1129
  if expression.name.lower() == "%s" and len(expression.expressions) == 1:
1127
1130
  return self.func("TO_CHAR", expression.expressions[0])
1128
1131
 
@@ -147,7 +147,13 @@ class SparkGenerator(Spark2Generator):
147
147
  }
148
148
 
149
149
  def dateadd_sql(self, expression: exp.DateAdd | exp.DateSub) -> str:
150
- if expression.text("unit").upper() in ("HOUR", "MINUTE", "SECOND"):
150
+ if expression.text("unit").upper() in (
151
+ "HOUR",
152
+ "MINUTE",
153
+ "SECOND",
154
+ "MILLISECOND",
155
+ "MICROSECOND",
156
+ ):
151
157
  amount = expression.expression
152
158
  return self.func(
153
159
  "TIMESTAMPADD",
@@ -187,7 +187,6 @@ class Spark2Generator(HiveGenerator):
187
187
  # (DAY_OF_WEEK(datetime) % 7) + 1 is equivalent to DAYOFWEEK_ISO(datetime)
188
188
  exp.DayOfWeekIso: lambda self, e: f"(({self.func('DAYOFWEEK', e.this)} % 7) + 1)",
189
189
  exp.DayOfYear: rename_func("DAYOFYEAR"),
190
- exp.Format: rename_func("FORMAT_STRING"),
191
190
  exp.From: transforms.preprocess([_unalias_pivot]),
192
191
  exp.FromTimeZone: lambda self, e: self.func(
193
192
  "TO_UTC_TIMESTAMP", e.this, e.args.get("zone")
@@ -213,9 +212,13 @@ class Spark2Generator(HiveGenerator):
213
212
  transforms.any_to_exists,
214
213
  ]
215
214
  ),
216
- exp.SHA2Digest: lambda self, e: self.func(
215
+ exp.SHA1Digest: lambda self, e: self.func("UNHEX", self.func("SHA", e.this)),
216
+ exp.SHA2: lambda self, e: self.func(
217
217
  "SHA2", e.this, e.args.get("length") or exp.Literal.number(256)
218
218
  ),
219
+ exp.SHA2Digest: lambda self, e: self.func(
220
+ "UNHEX", self.func("SHA2", e.this, e.args.get("length") or exp.Literal.number(256))
221
+ ),
219
222
  exp.StrToDate: _str_to_date,
220
223
  exp.StrToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, self.format_time(e)),
221
224
  exp.TimestampTrunc: timestamptrunc_sql(),
@@ -236,10 +239,20 @@ class Spark2Generator(HiveGenerator):
236
239
  WRAP_DERIVED_VALUES = False
237
240
  CREATE_FUNCTION_RETURN_AS = False
238
241
 
242
+ def format_sql(self, expression: exp.Format) -> str:
243
+ if expression.args.get("is_fmt"):
244
+ return super().format_sql(expression)
245
+
246
+ return self.func("FORMAT_STRING", expression.this, *expression.expressions)
247
+
239
248
  def dateadd_sql(self, expression: exp.DateAdd | exp.DateSub) -> str:
240
- if expression.text("unit").upper() in ("HOUR", "MINUTE", "SECOND") and not (
241
- expression.expression.is_number or expression.expression.is_string
242
- ):
249
+ if expression.text("unit").upper() in (
250
+ "HOUR",
251
+ "MINUTE",
252
+ "SECOND",
253
+ "MILLISECOND",
254
+ "MICROSECOND",
255
+ ) and not (expression.expression.is_number or expression.expression.is_string):
243
256
  self.unsupported("Spark 2 does not support non-literal sub-day date arithmetic")
244
257
 
245
258
  return super().dateadd_sql(expression)
@@ -163,7 +163,7 @@ class SQLiteGenerator(generator.Generator):
163
163
  exp.LogicalOr: rename_func("MAX"),
164
164
  exp.LogicalAnd: rename_func("MIN"),
165
165
  exp.Pivot: no_pivot_sql,
166
- exp.Rand: rename_func("RANDOM"),
166
+ exp.Rand: lambda self, e: self.func("RANDOM", e.this),
167
167
  exp.RegexpLike: lambda self, e: self.binary(e, "REGEXP"),
168
168
  exp.Select: transforms.preprocess(
169
169
  [
@@ -275,6 +275,14 @@ class SQLiteGenerator(generator.Generator):
275
275
  unit = unit or modifier.unit
276
276
  modifier = modifier.this
277
277
 
278
+ if unit and unit.name.upper() == "WEEK":
279
+ modifier = modifier * 7
280
+ unit = exp.var("DAY")
281
+
282
+ # SQLite DATE deliberately returns only a date, so sub-day units would
283
+ # silently drop the time; DATETIME retains it.
284
+ func = "DATETIME" if unit and unit.name.upper() in ("HOUR", "MINUTE", "SECOND") else "DATE"
285
+
278
286
  modifier = modifier.unnest()
279
287
  if (
280
288
  unit
@@ -282,7 +290,7 @@ class SQLiteGenerator(generator.Generator):
282
290
  and not (isinstance(modifier, exp.Neg) and modifier.this.is_number)
283
291
  ):
284
292
  return self.func(
285
- "DATE",
293
+ func,
286
294
  expression.this,
287
295
  exp.DPipe(
288
296
  this=exp.paren(modifier),
@@ -291,7 +299,7 @@ class SQLiteGenerator(generator.Generator):
291
299
  )
292
300
  modifier = modifier.name if modifier.is_string else self.sql(modifier)
293
301
  modifier = f"{modifier} {unit.name}" if unit else modifier
294
- return self.func("DATE", expression.this, exp.Literal.string(modifier))
302
+ return self.func(func, expression.this, exp.Literal.string(modifier))
295
303
 
296
304
  def datesub_sql(self, expression: exp.DateSub) -> str:
297
305
  # SQLite has no DATE_SUB, so add the negated amount instead
@@ -52,6 +52,14 @@ def _format_sql(self: TSQLGenerator, expression: exp.NumberToStr | exp.TimeToStr
52
52
  return self.func("FORMAT", expression.this, fmt_sql, expression.args.get("culture"))
53
53
 
54
54
 
55
+ def _sha2_sql(self: TSQLGenerator, expression: exp.SHA2 | exp.SHA2Digest) -> str:
56
+ return self.func(
57
+ "HASHBYTES",
58
+ exp.Literal.string(f"SHA2_{expression.args.get('length', 256)}"),
59
+ expression.this,
60
+ )
61
+
62
+
55
63
  def _string_agg_sql(self: TSQLGenerator, expression: exp.GroupConcat) -> str:
56
64
  this = expression.this
57
65
  distinct = find_in_scope(expression, exp.Distinct)
@@ -252,9 +260,8 @@ class TSQLGenerator(generator.Generator):
252
260
  exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]),
253
261
  exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
254
262
  exp.SHA1Digest: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
255
- exp.SHA2: lambda self, e: self.func(
256
- "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this
257
- ),
263
+ exp.SHA2: _sha2_sql,
264
+ exp.SHA2Digest: _sha2_sql,
258
265
  exp.TemporaryProperty: lambda self, e: "",
259
266
  exp.TimeStrToTime: _timestrtotime_sql,
260
267
  exp.TimeToStr: _format_sql,
@@ -1163,10 +1163,6 @@ def _expand_stars(
1163
1163
  """Expand stars to lists of column selections"""
1164
1164
 
1165
1165
  new_selections: list[exp.Expr] = []
1166
- except_columns: dict[int, set[str]] = {}
1167
- replace_columns: dict[int, dict[str, exp.Alias]] = {}
1168
- rename_columns: dict[int, dict[str, str]] = {}
1169
- ilike_pattern: str | None = None
1170
1166
 
1171
1167
  dialect = resolver.dialect
1172
1168
 
@@ -1192,6 +1188,10 @@ def _expand_stars(
1192
1188
 
1193
1189
  for expression in scope_expression.selects:
1194
1190
  tables: list[str] = []
1191
+ except_columns: dict[int, set[str]] = {}
1192
+ replace_columns: dict[int, dict[str, exp.Alias]] = {}
1193
+ rename_columns: dict[int, dict[str, exp.Identifier]] = {}
1194
+ ilike_pattern: str | None = None
1195
1195
  is_unqualified_star = isinstance(expression, exp.Star)
1196
1196
  coalesced_columns = set()
1197
1197
 
@@ -1356,19 +1356,15 @@ def _expand_stars(
1356
1356
 
1357
1357
  selection = alias(exp.func("coalesce", *coalesce_args), alias=name, copy=False)
1358
1358
  else:
1359
- alias_ = renamed_columns.get(name, name)
1360
1359
  quoted = name in quoted_columns or (
1361
1360
  # if it has characters that the dialect would have changed, infer that it was quoted.
1362
1361
  isinstance(source, exp.Table) and dialect.case_sensitive(name)
1363
1362
  )
1364
- selection_expr = replaced_columns.get(name) or exp.column(
1365
- name, table=table, quoted=quoted
1366
- )
1367
- selection = (
1368
- alias(selection_expr, alias_, copy=False)
1369
- if alias_ != name
1370
- else selection_expr
1371
- )
1363
+ selection = exp.column(name, table=table, quoted=quoted)
1364
+
1365
+ selection = replaced_columns.get(name) or selection
1366
+ if alias_ := renamed_columns.get(name):
1367
+ selection = alias(selection, alias_)
1372
1368
 
1373
1369
  if name in using_selections and using_selections[name] is None:
1374
1370
  using_selections[name] = selection
@@ -1455,14 +1451,14 @@ def _add_except_columns(expression: exp.Expr, tables, except_columns: dict[int,
1455
1451
 
1456
1452
 
1457
1453
  def _add_rename_columns(
1458
- expression: exp.Expr, tables, rename_columns: dict[int, dict[str, str]]
1454
+ expression: exp.Expr, tables, rename_columns: dict[int, dict[str, exp.Identifier]]
1459
1455
  ) -> None:
1460
1456
  rename = expression.args.get("rename")
1461
1457
 
1462
1458
  if not rename:
1463
1459
  return
1464
1460
 
1465
- columns = {e.this.name: e.alias for e in rename}
1461
+ columns = {e.this.name: e.args["alias"] for e in rename}
1466
1462
 
1467
1463
  for table in tables:
1468
1464
  rename_columns[id(table)] = columns
@@ -400,6 +400,10 @@ class Scope:
400
400
 
401
401
  self._columns = []
402
402
  for column in columns + external_columns:
403
+ # Star RENAME sources are column labels, not references.
404
+ if isinstance(column.parent, exp.Alias) and column.parent.arg_key == "rename":
405
+ continue
406
+
403
407
  ancestor = column.find_ancestor(
404
408
  exp.Select,
405
409
  exp.Qualify,
@@ -817,6 +817,7 @@ class Parser:
817
817
  TokenType.NEXT,
818
818
  TokenType.OFFSET,
819
819
  TokenType.OPERATOR,
820
+ TokenType.OPTIMIZE,
820
821
  TokenType.ORDINALITY,
821
822
  TokenType.OUT,
822
823
  TokenType.OVER,
@@ -949,6 +950,7 @@ class Parser:
949
950
  TokenType.MERGE,
950
951
  TokenType.NEXT,
951
952
  TokenType.OFFSET,
953
+ TokenType.OPTIMIZE,
952
954
  TokenType.PRIMARY_KEY,
953
955
  TokenType.RANGE,
954
956
  TokenType.REPLACE,
@@ -352,8 +352,13 @@ class ClickHouseParser(parser.Parser):
352
352
  "TOMONDAY": _build_timestamp_trunc("WEEK"),
353
353
  "UNIQ": exp.ApproxDistinct.from_arg_list,
354
354
  "MD5": exp.MD5Digest.from_arg_list,
355
- "SHA256": lambda args: exp.SHA2(this=seq_get(args, 0), length=exp.Literal.number(256)),
356
- "SHA512": lambda args: exp.SHA2(this=seq_get(args, 0), length=exp.Literal.number(512)),
355
+ "SHA1": exp.SHA1Digest.from_arg_list,
356
+ "SHA256": lambda args: exp.SHA2Digest(
357
+ this=seq_get(args, 0), length=exp.Literal.number(256)
358
+ ),
359
+ "SHA512": lambda args: exp.SHA2Digest(
360
+ this=seq_get(args, 0), length=exp.Literal.number(512)
361
+ ),
357
362
  "SPLITBYCHAR": _build_split_by_char,
358
363
  "SPLITBYREGEXP": _build_split(exp.RegexpSplit),
359
364
  "SPLITBYSTRING": _build_split(exp.Split),
@@ -13,6 +13,11 @@ class DatabricksParser(SparkParser):
13
13
  COLON_IS_VARIANT_EXTRACT = True
14
14
  COLON_CHAIN_IS_SINGLE_EXTRACT = False
15
15
 
16
+ STATEMENT_PARSERS = {
17
+ **SparkParser.STATEMENT_PARSERS,
18
+ TokenType.OPTIMIZE: lambda self: self._parse_optimize(),
19
+ }
20
+
16
21
  FUNCTIONS = {
17
22
  **SparkParser.FUNCTIONS,
18
23
  "IFF": exp.If.from_arg_list,
@@ -58,6 +63,24 @@ class DatabricksParser(SparkParser):
58
63
  TokenType.QDCOLON,
59
64
  }
60
65
 
66
+ def _parse_optimize(self) -> exp.Optimize | exp.Command:
67
+ start = self._prev
68
+ if len(self._tokens) - self._index in (1, 3, 5):
69
+ tokens = self._tokens[self._index :]
70
+ if all(
71
+ token.token_type in self.ID_VAR_TOKENS
72
+ and (
73
+ token.token_type == TokenType.IDENTIFIER
74
+ or not any(char.isspace() for char in token.text)
75
+ )
76
+ for token in tokens[::2]
77
+ ) and all(token.token_type == TokenType.DOT for token in tokens[1::2]):
78
+ return self.expression(exp.Optimize(this=self._parse_table_parts(schema=True)))
79
+
80
+ command = self._parse_as_command(start)
81
+ command.set("this", start.text.upper())
82
+ return self.expression(command)
83
+
61
84
  def _parse_curdate(self) -> exp.CurrentDate:
62
85
  # CURDATE, an alias for CURRENT_DATE, has optional parentheses
63
86
  if self._match(TokenType.L_PAREN):
@@ -206,6 +206,7 @@ class DuckDBParser(parser.Parser):
206
206
  ),
207
207
  "EPOCH": exp.TimeToUnix.from_arg_list,
208
208
  "EPOCH_MS": lambda args: exp.UnixToTime(this=seq_get(args, 0), scale=exp.UnixToTime.MILLIS),
209
+ "FORMAT": lambda args: exp.Format(this=seq_get(args, 0), expressions=args[1:], is_fmt=True),
209
210
  "FROM_HEX": exp.Unhex.from_arg_list,
210
211
  "GENERATE_SERIES": _build_generate_series(),
211
212
  "GET_CURRENT_TIME": exp.CurrentTime.from_arg_list,
@@ -238,6 +239,7 @@ class DuckDBParser(parser.Parser):
238
239
  "MAKE_DATE": exp.DateFromParts.from_arg_list,
239
240
  "MAKE_TIME": exp.TimeFromParts.from_arg_list,
240
241
  "MAKE_TIMESTAMP": _build_make_timestamp,
242
+ "PRINTF": exp.Format.from_arg_list,
241
243
  "QUANTILE_CONT": exp.PercentileCont.from_arg_list,
242
244
  "QUANTILE_DISC": exp.PercentileDisc.from_arg_list,
243
245
  "RANGE": _build_generate_series(end_exclusive=True),
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import re
3
4
  import typing as t
4
5
 
5
6
  from sqlglot import exp, parser
@@ -12,6 +13,7 @@ from sqlglot.dialects.dialect import (
12
13
  date_trunc_to_time,
13
14
  )
14
15
  from sqlglot.helper import seq_get
16
+ from sqlglot.time import format_time
15
17
  from sqlglot.tokens import TokenType
16
18
 
17
19
  if t.TYPE_CHECKING:
@@ -53,6 +55,34 @@ def _build_from_unixtime(args: list) -> exp.Expr:
53
55
  return exp.UnixToTime.from_arg_list(args)
54
56
 
55
57
 
58
+ # A Joda field is a run of one letter, e.g. yyyy, or seconds with milliseconds
59
+ JODA_FIELD_RE = re.compile(r"ss\.SSS|([A-Za-z])\1*")
60
+
61
+
62
+ def _build_format_datetime(args: list) -> exp.Expr:
63
+ from sqlglot.dialects.presto import Presto
64
+
65
+ fmt = seq_get(args, 1)
66
+
67
+ # Formats with quoted text, a literal % or a field without a mapping are left as is
68
+ if (
69
+ len(args) != 2
70
+ or not (fmt and fmt.is_string and fmt.name)
71
+ or "'" in fmt.name
72
+ or "%" in fmt.name
73
+ or any(f.group(0) not in Presto.JODA_TIME_MAPPING for f in JODA_FIELD_RE.finditer(fmt.name))
74
+ ):
75
+ return exp.Anonymous(this="FORMAT_DATETIME", expressions=args)
76
+
77
+ return exp.TimeToStr(
78
+ this=seq_get(args, 0),
79
+ format=exp.Literal.string(
80
+ format_time(fmt.name, Presto.JODA_TIME_MAPPING, Presto.JODA_TIME_TRIE)
81
+ ),
82
+ joda=True,
83
+ )
84
+
85
+
56
86
  def _build_to_char(args: list, dialect: Dialect) -> exp.TimeToStr:
57
87
  fmt = seq_get(args, 1)
58
88
  if isinstance(fmt, exp.Literal):
@@ -109,6 +139,7 @@ class PrestoParser(parser.Parser):
109
139
  "ELEMENT_AT": lambda args: exp.Bracket(
110
140
  this=seq_get(args, 0), expressions=[seq_get(args, 1)], offset=1, safe=True
111
141
  ),
142
+ "FORMAT_DATETIME": _build_format_datetime,
112
143
  "FROM_HEX": exp.Unhex.from_arg_list,
113
144
  "FROM_UNIXTIME": _build_from_unixtime,
114
145
  "FROM_UTF8": lambda args: exp.Decode(
@@ -146,6 +177,7 @@ class PrestoParser(parser.Parser):
146
177
  this=seq_get(args, 0), charset=exp.Literal.string("utf-8")
147
178
  ),
148
179
  "MD5": exp.MD5Digest.from_arg_list,
180
+ "SHA1": exp.SHA1Digest.from_arg_list,
149
181
  "SHA256": lambda args: exp.SHA2Digest(
150
182
  this=seq_get(args, 0), length=exp.Literal.number(256)
151
183
  ),
@@ -604,8 +604,8 @@ class SnowflakeParser(parser.Parser):
604
604
  "REGEXP_SUBSTR_ALL": _build_regexp_extract(exp.RegexpExtractAll),
605
605
  "RANDOM": lambda args: exp.Rand(
606
606
  this=seq_get(args, 0),
607
- lower=exp.Literal.number(-9223372036854775808.0), # -2^63 as float to avoid overflow
608
- upper=exp.Literal.number(9223372036854775807.0), # 2^63-1 as float
607
+ lower=exp.Literal.number(-9223372036854775808),
608
+ upper=exp.Literal.number(9223372036854775807),
609
609
  ),
610
610
  "REPLACE": build_replace_with_optional_replacement,
611
611
  "RIGHT": lambda args: exp.Right(
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
  import typing as t
4
4
 
5
5
  from sqlglot import exp, parser
6
+ from sqlglot.helper import seq_get
6
7
  from sqlglot.parser import IsPredicatePrecedence, binary_range_parser
7
8
  from sqlglot.tokens import Token, TokenType
8
9
 
@@ -110,9 +111,17 @@ class SQLiteParser(parser.Parser):
110
111
  "JSON_GROUP_OBJECT": lambda args: exp.JSONObjectAgg(expressions=args),
111
112
  "MAX": _build_max,
112
113
  "MIN": _build_min,
114
+ "RANDOM": lambda args: exp.Rand(
115
+ lower=exp.Literal.number(-9223372036854775807),
116
+ upper=exp.Literal.number(9223372036854775807),
117
+ ),
118
+ "ROUND": lambda args: exp.Round(
119
+ this=seq_get(args, 0), decimals=seq_get(args, 1), negative_decimals_are_zero=True
120
+ ),
113
121
  "STRFTIME": _build_strftime,
114
122
  "SQLITE_VERSION": exp.CurrentVersion.from_arg_list,
115
123
  "TIME": lambda args: exp.Anonymous(this="TIME", expressions=args),
124
+ "UNICODE": lambda args: exp.Unicode(this=seq_get(args, 0), empty_is_null=True),
116
125
  }
117
126
 
118
127
  FUNCTION_PARSERS = {
@@ -196,11 +196,11 @@ def _build_hashbytes(args: list) -> exp.Expr:
196
196
  return exp.MD5(this=data)
197
197
  if kind in ("SHA", "SHA1"):
198
198
  args.pop(0)
199
- return exp.SHA(this=data)
199
+ return exp.SHA1Digest(this=data)
200
200
  if kind == "SHA2_256":
201
- return exp.SHA2(this=data, length=exp.Literal.number(256))
201
+ return exp.SHA2Digest(this=data, length=exp.Literal.number(256))
202
202
  if kind == "SHA2_512":
203
- return exp.SHA2(this=data, length=exp.Literal.number(512))
203
+ return exp.SHA2Digest(this=data, length=exp.Literal.number(512))
204
204
 
205
205
  return exp.func("HASHBYTES", *args)
206
206
 
@@ -465,6 +465,7 @@ class TokenType(IntEnum):
465
465
  SINK = auto()
466
466
  SOURCE = auto()
467
467
  ANALYZE = auto()
468
+ OPTIMIZE = auto()
468
469
  NAMESPACE = auto()
469
470
  EXPORT = auto()
470
471
 
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlglotc
3
- Version: 30.32.0
3
+ Version: 30.33.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.32.0
10
+ Requires-Dist: sqlglot==30.33.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"
@@ -1,4 +1,4 @@
1
- sqlglot==30.32.0
1
+ sqlglot==30.33.0
2
2
 
3
3
  [dev]
4
4
  setuptools>=61.0
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "30.33.0",
3
+ "distance": 0,
4
+ "node": "g0936dbe9192a3b57c6e6992acfcb93d4b429c51f",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-11-17"
8
+ }
@@ -1,8 +0,0 @@
1
- {
2
- "tag": "30.32.0",
3
- "distance": 0,
4
- "node": "g798a1d77270da43041b37b4f5166252571f1243f",
5
- "dirty": false,
6
- "branch": "HEAD",
7
- "node_date": "2026-11-16"
8
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes