Edit on GitHub

sqlglot.dialects.presto

  1from __future__ import annotations
  2
  3import typing as t
  4
  5from sqlglot import exp, generator, parser, tokens, transforms
  6from sqlglot.dialects.dialect import (
  7    Dialect,
  8    date_trunc_to_time,
  9    format_time_lambda,
 10    if_sql,
 11    no_ilike_sql,
 12    no_safe_divide_sql,
 13    rename_func,
 14    struct_extract_sql,
 15    timestamptrunc_sql,
 16    timestrtotime_sql,
 17)
 18from sqlglot.dialects.mysql import MySQL
 19from sqlglot.errors import UnsupportedError
 20from sqlglot.helper import seq_get
 21from sqlglot.tokens import TokenType
 22
 23
 24def _approx_distinct_sql(self: generator.Generator, expression: exp.ApproxDistinct) -> str:
 25    accuracy = expression.args.get("accuracy")
 26    accuracy = ", " + self.sql(accuracy) if accuracy else ""
 27    return f"APPROX_DISTINCT({self.sql(expression, 'this')}{accuracy})"
 28
 29
 30def _datatype_sql(self: generator.Generator, expression: exp.DataType) -> str:
 31    sql = self.datatype_sql(expression)
 32    if expression.this == exp.DataType.Type.TIMESTAMPTZ:
 33        sql = f"{sql} WITH TIME ZONE"
 34    return sql
 35
 36
 37def _explode_to_unnest_sql(self: generator.Generator, expression: exp.Lateral) -> str:
 38    if isinstance(expression.this, (exp.Explode, exp.Posexplode)):
 39        return self.sql(
 40            exp.Join(
 41                this=exp.Unnest(
 42                    expressions=[expression.this.this],
 43                    alias=expression.args.get("alias"),
 44                    ordinality=isinstance(expression.this, exp.Posexplode),
 45                ),
 46                kind="cross",
 47            )
 48        )
 49    return self.lateral_sql(expression)
 50
 51
 52def _initcap_sql(self: generator.Generator, expression: exp.Initcap) -> str:
 53    regex = r"(\w)(\w*)"
 54    return f"REGEXP_REPLACE({self.sql(expression, 'this')}, '{regex}', x -> UPPER(x[1]) || LOWER(x[2]))"
 55
 56
 57def _decode_sql(self: generator.Generator, expression: exp.Decode) -> str:
 58    _ensure_utf8(expression.args["charset"])
 59    return self.func("FROM_UTF8", expression.this, expression.args.get("replace"))
 60
 61
 62def _encode_sql(self: generator.Generator, expression: exp.Encode) -> str:
 63    _ensure_utf8(expression.args["charset"])
 64    return f"TO_UTF8({self.sql(expression, 'this')})"
 65
 66
 67def _no_sort_array(self: generator.Generator, expression: exp.SortArray) -> str:
 68    if expression.args.get("asc") == exp.false():
 69        comparator = "(a, b) -> CASE WHEN a < b THEN 1 WHEN a > b THEN -1 ELSE 0 END"
 70    else:
 71        comparator = None
 72    return self.func("ARRAY_SORT", expression.this, comparator)
 73
 74
 75def _schema_sql(self: generator.Generator, expression: exp.Schema) -> str:
 76    if isinstance(expression.parent, exp.Property):
 77        columns = ", ".join(f"'{c.name}'" for c in expression.expressions)
 78        return f"ARRAY[{columns}]"
 79
 80    if expression.parent:
 81        for schema in expression.parent.find_all(exp.Schema):
 82            if isinstance(schema.parent, exp.Property):
 83                expression = expression.copy()
 84                expression.expressions.extend(schema.expressions)
 85
 86    return self.schema_sql(expression)
 87
 88
 89def _quantile_sql(self: generator.Generator, expression: exp.Quantile) -> str:
 90    self.unsupported("Presto does not support exact quantiles")
 91    return f"APPROX_PERCENTILE({self.sql(expression, 'this')}, {self.sql(expression, 'quantile')})"
 92
 93
 94def _str_to_time_sql(
 95    self: generator.Generator, expression: exp.StrToDate | exp.StrToTime | exp.TsOrDsToDate
 96) -> str:
 97    return f"DATE_PARSE({self.sql(expression, 'this')}, {self.format_time(expression)})"
 98
 99
100def _ts_or_ds_to_date_sql(self: generator.Generator, expression: exp.TsOrDsToDate) -> str:
101    time_format = self.format_time(expression)
102    if time_format and time_format not in (Presto.time_format, Presto.date_format):
103        return f"CAST({_str_to_time_sql(self, expression)} AS DATE)"
104    return f"CAST(SUBSTR(CAST({self.sql(expression, 'this')} AS VARCHAR), 1, 10) AS DATE)"
105
106
107def _ts_or_ds_add_sql(self: generator.Generator, expression: exp.TsOrDsAdd) -> str:
108    this = expression.this
109
110    if not isinstance(this, exp.CurrentDate):
111        this = self.func(
112            "DATE_PARSE",
113            self.func(
114                "SUBSTR",
115                this if this.is_string else exp.cast(this, "VARCHAR"),
116                exp.Literal.number(1),
117                exp.Literal.number(10),
118            ),
119            Presto.date_format,
120        )
121
122    return self.func(
123        "DATE_ADD",
124        exp.Literal.string(expression.text("unit") or "day"),
125        expression.expression,
126        this,
127    )
128
129
130def _sequence_sql(self: generator.Generator, expression: exp.GenerateSeries) -> str:
131    start = expression.args["start"]
132    end = expression.args["end"]
133    step = expression.args.get("step", 1)  # Postgres defaults to 1 for generate_series
134
135    target_type = None
136
137    if isinstance(start, exp.Cast):
138        target_type = start.to
139    elif isinstance(end, exp.Cast):
140        target_type = end.to
141
142    if target_type and target_type.this == exp.DataType.Type.TIMESTAMP:
143        to = target_type.copy()
144
145        if target_type is start.to:
146            end = exp.Cast(this=end, to=to)
147        else:
148            start = exp.Cast(this=start, to=to)
149
150    return self.func("SEQUENCE", start, end, step)
151
152
153def _ensure_utf8(charset: exp.Literal) -> None:
154    if charset.name.lower() != "utf-8":
155        raise UnsupportedError(f"Unsupported charset {charset}")
156
157
158def _approx_percentile(args: t.Sequence) -> exp.Expression:
159    if len(args) == 4:
160        return exp.ApproxQuantile(
161            this=seq_get(args, 0),
162            weight=seq_get(args, 1),
163            quantile=seq_get(args, 2),
164            accuracy=seq_get(args, 3),
165        )
166    if len(args) == 3:
167        return exp.ApproxQuantile(
168            this=seq_get(args, 0),
169            quantile=seq_get(args, 1),
170            accuracy=seq_get(args, 2),
171        )
172    return exp.ApproxQuantile.from_arg_list(args)
173
174
175def _from_unixtime(args: t.Sequence) -> exp.Expression:
176    if len(args) == 3:
177        return exp.UnixToTime(
178            this=seq_get(args, 0),
179            hours=seq_get(args, 1),
180            minutes=seq_get(args, 2),
181        )
182    if len(args) == 2:
183        return exp.UnixToTime(
184            this=seq_get(args, 0),
185            zone=seq_get(args, 1),
186        )
187    return exp.UnixToTime.from_arg_list(args)
188
189
190class Presto(Dialect):
191    index_offset = 1
192    null_ordering = "nulls_are_last"
193    time_format = MySQL.time_format  # type: ignore
194    time_mapping = MySQL.time_mapping  # type: ignore
195
196    class Tokenizer(tokens.Tokenizer):
197        KEYWORDS = {
198            **tokens.Tokenizer.KEYWORDS,
199            "START": TokenType.BEGIN,
200            "ROW": TokenType.STRUCT,
201        }
202
203    class Parser(parser.Parser):
204        FUNCTIONS = {
205            **parser.Parser.FUNCTIONS,  # type: ignore
206            "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list,
207            "CARDINALITY": exp.ArraySize.from_arg_list,
208            "CONTAINS": exp.ArrayContains.from_arg_list,
209            "DATE_ADD": lambda args: exp.DateAdd(
210                this=seq_get(args, 2),
211                expression=seq_get(args, 1),
212                unit=seq_get(args, 0),
213            ),
214            "DATE_DIFF": lambda args: exp.DateDiff(
215                this=seq_get(args, 2),
216                expression=seq_get(args, 1),
217                unit=seq_get(args, 0),
218            ),
219            "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"),
220            "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"),
221            "DATE_TRUNC": date_trunc_to_time,
222            "FROM_UNIXTIME": _from_unixtime,
223            "NOW": exp.CurrentTimestamp.from_arg_list,
224            "STRPOS": lambda args: exp.StrPosition(
225                this=seq_get(args, 0),
226                substr=seq_get(args, 1),
227                instance=seq_get(args, 2),
228            ),
229            "TO_UNIXTIME": exp.TimeToUnix.from_arg_list,
230            "APPROX_PERCENTILE": _approx_percentile,
231            "FROM_HEX": exp.Unhex.from_arg_list,
232            "TO_HEX": exp.Hex.from_arg_list,
233            "TO_UTF8": lambda args: exp.Encode(
234                this=seq_get(args, 0), charset=exp.Literal.string("utf-8")
235            ),
236            "FROM_UTF8": lambda args: exp.Decode(
237                this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8")
238            ),
239        }
240        FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy()
241        FUNCTION_PARSERS.pop("TRIM")
242
243    class Generator(generator.Generator):
244        INTERVAL_ALLOWS_PLURAL_FORM = False
245        JOIN_HINTS = False
246        TABLE_HINTS = False
247        STRUCT_DELIMITER = ("(", ")")
248
249        PROPERTIES_LOCATION = {
250            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
251            exp.LocationProperty: exp.Properties.Location.UNSUPPORTED,
252            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
253        }
254
255        TYPE_MAPPING = {
256            **generator.Generator.TYPE_MAPPING,  # type: ignore
257            exp.DataType.Type.INT: "INTEGER",
258            exp.DataType.Type.FLOAT: "REAL",
259            exp.DataType.Type.BINARY: "VARBINARY",
260            exp.DataType.Type.TEXT: "VARCHAR",
261            exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP",
262            exp.DataType.Type.STRUCT: "ROW",
263        }
264
265        TRANSFORMS = {
266            **generator.Generator.TRANSFORMS,  # type: ignore
267            **transforms.UNALIAS_GROUP,  # type: ignore
268            exp.ApproxDistinct: _approx_distinct_sql,
269            exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]",
270            exp.ArrayConcat: rename_func("CONCAT"),
271            exp.ArrayContains: rename_func("CONTAINS"),
272            exp.ArraySize: rename_func("CARDINALITY"),
273            exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
274            exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
275            exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})",
276            exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
277            exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
278            exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
279            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
280            exp.DataType: _datatype_sql,
281            exp.DateAdd: lambda self, e: self.func(
282                "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
283            ),
284            exp.DateDiff: lambda self, e: self.func(
285                "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
286            ),
287            exp.DateStrToDate: lambda self, e: f"CAST(DATE_PARSE({self.sql(e, 'this')}, {Presto.date_format}) AS DATE)",
288            exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.dateint_format}) AS INT)",
289            exp.Decode: _decode_sql,
290            exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.dateint_format}) AS DATE)",
291            exp.Encode: _encode_sql,
292            exp.GenerateSeries: _sequence_sql,
293            exp.Hex: rename_func("TO_HEX"),
294            exp.If: if_sql,
295            exp.ILike: no_ilike_sql,
296            exp.Initcap: _initcap_sql,
297            exp.Lateral: _explode_to_unnest_sql,
298            exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"),
299            exp.LogicalOr: rename_func("BOOL_OR"),
300            exp.LogicalAnd: rename_func("BOOL_AND"),
301            exp.Quantile: _quantile_sql,
302            exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"),
303            exp.SafeDivide: no_safe_divide_sql,
304            exp.Schema: _schema_sql,
305            exp.Select: transforms.preprocess(
306                [transforms.eliminate_qualify, transforms.explode_to_unnest]
307            ),
308            exp.SortArray: _no_sort_array,
309            exp.StrPosition: rename_func("STRPOS"),
310            exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)",
311            exp.StrToTime: _str_to_time_sql,
312            exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))",
313            exp.StructExtract: struct_extract_sql,
314            exp.TableFormatProperty: lambda self, e: f"TABLE_FORMAT='{e.name.upper()}'",
315            exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'",
316            exp.TimestampTrunc: timestamptrunc_sql,
317            exp.TimeStrToDate: timestrtotime_sql,
318            exp.TimeStrToTime: timestrtotime_sql,
319            exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.time_format}))",
320            exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})",
321            exp.TimeToUnix: rename_func("TO_UNIXTIME"),
322            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)",
323            exp.TsOrDsAdd: _ts_or_ds_add_sql,
324            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
325            exp.Unhex: rename_func("FROM_HEX"),
326            exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})",
327            exp.UnixToTime: rename_func("FROM_UNIXTIME"),
328            exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)",
329            exp.VariancePop: rename_func("VAR_POP"),
330        }
331
332        def interval_sql(self, expression: exp.Interval) -> str:
333            unit = self.sql(expression, "unit")
334            if expression.this and unit.lower().startswith("week"):
335                return f"({expression.this.name} * INTERVAL '7' day)"
336            return super().interval_sql(expression)
337
338        def transaction_sql(self, expression: exp.Transaction) -> str:
339            modes = expression.args.get("modes")
340            modes = f" {', '.join(modes)}" if modes else ""
341            return f"START TRANSACTION{modes}"
class Presto(sqlglot.dialects.dialect.Dialect):
191class Presto(Dialect):
192    index_offset = 1
193    null_ordering = "nulls_are_last"
194    time_format = MySQL.time_format  # type: ignore
195    time_mapping = MySQL.time_mapping  # type: ignore
196
197    class Tokenizer(tokens.Tokenizer):
198        KEYWORDS = {
199            **tokens.Tokenizer.KEYWORDS,
200            "START": TokenType.BEGIN,
201            "ROW": TokenType.STRUCT,
202        }
203
204    class Parser(parser.Parser):
205        FUNCTIONS = {
206            **parser.Parser.FUNCTIONS,  # type: ignore
207            "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list,
208            "CARDINALITY": exp.ArraySize.from_arg_list,
209            "CONTAINS": exp.ArrayContains.from_arg_list,
210            "DATE_ADD": lambda args: exp.DateAdd(
211                this=seq_get(args, 2),
212                expression=seq_get(args, 1),
213                unit=seq_get(args, 0),
214            ),
215            "DATE_DIFF": lambda args: exp.DateDiff(
216                this=seq_get(args, 2),
217                expression=seq_get(args, 1),
218                unit=seq_get(args, 0),
219            ),
220            "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"),
221            "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"),
222            "DATE_TRUNC": date_trunc_to_time,
223            "FROM_UNIXTIME": _from_unixtime,
224            "NOW": exp.CurrentTimestamp.from_arg_list,
225            "STRPOS": lambda args: exp.StrPosition(
226                this=seq_get(args, 0),
227                substr=seq_get(args, 1),
228                instance=seq_get(args, 2),
229            ),
230            "TO_UNIXTIME": exp.TimeToUnix.from_arg_list,
231            "APPROX_PERCENTILE": _approx_percentile,
232            "FROM_HEX": exp.Unhex.from_arg_list,
233            "TO_HEX": exp.Hex.from_arg_list,
234            "TO_UTF8": lambda args: exp.Encode(
235                this=seq_get(args, 0), charset=exp.Literal.string("utf-8")
236            ),
237            "FROM_UTF8": lambda args: exp.Decode(
238                this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8")
239            ),
240        }
241        FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy()
242        FUNCTION_PARSERS.pop("TRIM")
243
244    class Generator(generator.Generator):
245        INTERVAL_ALLOWS_PLURAL_FORM = False
246        JOIN_HINTS = False
247        TABLE_HINTS = False
248        STRUCT_DELIMITER = ("(", ")")
249
250        PROPERTIES_LOCATION = {
251            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
252            exp.LocationProperty: exp.Properties.Location.UNSUPPORTED,
253            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
254        }
255
256        TYPE_MAPPING = {
257            **generator.Generator.TYPE_MAPPING,  # type: ignore
258            exp.DataType.Type.INT: "INTEGER",
259            exp.DataType.Type.FLOAT: "REAL",
260            exp.DataType.Type.BINARY: "VARBINARY",
261            exp.DataType.Type.TEXT: "VARCHAR",
262            exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP",
263            exp.DataType.Type.STRUCT: "ROW",
264        }
265
266        TRANSFORMS = {
267            **generator.Generator.TRANSFORMS,  # type: ignore
268            **transforms.UNALIAS_GROUP,  # type: ignore
269            exp.ApproxDistinct: _approx_distinct_sql,
270            exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]",
271            exp.ArrayConcat: rename_func("CONCAT"),
272            exp.ArrayContains: rename_func("CONTAINS"),
273            exp.ArraySize: rename_func("CARDINALITY"),
274            exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
275            exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
276            exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})",
277            exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
278            exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
279            exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
280            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
281            exp.DataType: _datatype_sql,
282            exp.DateAdd: lambda self, e: self.func(
283                "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
284            ),
285            exp.DateDiff: lambda self, e: self.func(
286                "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
287            ),
288            exp.DateStrToDate: lambda self, e: f"CAST(DATE_PARSE({self.sql(e, 'this')}, {Presto.date_format}) AS DATE)",
289            exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.dateint_format}) AS INT)",
290            exp.Decode: _decode_sql,
291            exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.dateint_format}) AS DATE)",
292            exp.Encode: _encode_sql,
293            exp.GenerateSeries: _sequence_sql,
294            exp.Hex: rename_func("TO_HEX"),
295            exp.If: if_sql,
296            exp.ILike: no_ilike_sql,
297            exp.Initcap: _initcap_sql,
298            exp.Lateral: _explode_to_unnest_sql,
299            exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"),
300            exp.LogicalOr: rename_func("BOOL_OR"),
301            exp.LogicalAnd: rename_func("BOOL_AND"),
302            exp.Quantile: _quantile_sql,
303            exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"),
304            exp.SafeDivide: no_safe_divide_sql,
305            exp.Schema: _schema_sql,
306            exp.Select: transforms.preprocess(
307                [transforms.eliminate_qualify, transforms.explode_to_unnest]
308            ),
309            exp.SortArray: _no_sort_array,
310            exp.StrPosition: rename_func("STRPOS"),
311            exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)",
312            exp.StrToTime: _str_to_time_sql,
313            exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))",
314            exp.StructExtract: struct_extract_sql,
315            exp.TableFormatProperty: lambda self, e: f"TABLE_FORMAT='{e.name.upper()}'",
316            exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'",
317            exp.TimestampTrunc: timestamptrunc_sql,
318            exp.TimeStrToDate: timestrtotime_sql,
319            exp.TimeStrToTime: timestrtotime_sql,
320            exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.time_format}))",
321            exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})",
322            exp.TimeToUnix: rename_func("TO_UNIXTIME"),
323            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)",
324            exp.TsOrDsAdd: _ts_or_ds_add_sql,
325            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
326            exp.Unhex: rename_func("FROM_HEX"),
327            exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})",
328            exp.UnixToTime: rename_func("FROM_UNIXTIME"),
329            exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)",
330            exp.VariancePop: rename_func("VAR_POP"),
331        }
332
333        def interval_sql(self, expression: exp.Interval) -> str:
334            unit = self.sql(expression, "unit")
335            if expression.this and unit.lower().startswith("week"):
336                return f"({expression.this.name} * INTERVAL '7' day)"
337            return super().interval_sql(expression)
338
339        def transaction_sql(self, expression: exp.Transaction) -> str:
340            modes = expression.args.get("modes")
341            modes = f" {', '.join(modes)}" if modes else ""
342            return f"START TRANSACTION{modes}"
class Presto.Tokenizer(sqlglot.tokens.Tokenizer):
197    class Tokenizer(tokens.Tokenizer):
198        KEYWORDS = {
199            **tokens.Tokenizer.KEYWORDS,
200            "START": TokenType.BEGIN,
201            "ROW": TokenType.STRUCT,
202        }
class Presto.Parser(sqlglot.parser.Parser):
204    class Parser(parser.Parser):
205        FUNCTIONS = {
206            **parser.Parser.FUNCTIONS,  # type: ignore
207            "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list,
208            "CARDINALITY": exp.ArraySize.from_arg_list,
209            "CONTAINS": exp.ArrayContains.from_arg_list,
210            "DATE_ADD": lambda args: exp.DateAdd(
211                this=seq_get(args, 2),
212                expression=seq_get(args, 1),
213                unit=seq_get(args, 0),
214            ),
215            "DATE_DIFF": lambda args: exp.DateDiff(
216                this=seq_get(args, 2),
217                expression=seq_get(args, 1),
218                unit=seq_get(args, 0),
219            ),
220            "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"),
221            "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"),
222            "DATE_TRUNC": date_trunc_to_time,
223            "FROM_UNIXTIME": _from_unixtime,
224            "NOW": exp.CurrentTimestamp.from_arg_list,
225            "STRPOS": lambda args: exp.StrPosition(
226                this=seq_get(args, 0),
227                substr=seq_get(args, 1),
228                instance=seq_get(args, 2),
229            ),
230            "TO_UNIXTIME": exp.TimeToUnix.from_arg_list,
231            "APPROX_PERCENTILE": _approx_percentile,
232            "FROM_HEX": exp.Unhex.from_arg_list,
233            "TO_HEX": exp.Hex.from_arg_list,
234            "TO_UTF8": lambda args: exp.Encode(
235                this=seq_get(args, 0), charset=exp.Literal.string("utf-8")
236            ),
237            "FROM_UTF8": lambda args: exp.Decode(
238                this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8")
239            ),
240        }
241        FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy()
242        FUNCTION_PARSERS.pop("TRIM")

Parser consumes a list of tokens produced by the sqlglot.tokens.Tokenizer and produces a parsed syntax tree.

Arguments:
  • error_level: the desired error level. Default: ErrorLevel.RAISE
  • error_message_context: determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 50.
  • index_offset: Index offset for arrays eg ARRAY[0] vs ARRAY[1] as the head of a list. Default: 0
  • alias_post_tablesample: If the table alias comes after tablesample. Default: False
  • max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
  • null_ordering: Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
class Presto.Generator(sqlglot.generator.Generator):
244    class Generator(generator.Generator):
245        INTERVAL_ALLOWS_PLURAL_FORM = False
246        JOIN_HINTS = False
247        TABLE_HINTS = False
248        STRUCT_DELIMITER = ("(", ")")
249
250        PROPERTIES_LOCATION = {
251            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
252            exp.LocationProperty: exp.Properties.Location.UNSUPPORTED,
253            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
254        }
255
256        TYPE_MAPPING = {
257            **generator.Generator.TYPE_MAPPING,  # type: ignore
258            exp.DataType.Type.INT: "INTEGER",
259            exp.DataType.Type.FLOAT: "REAL",
260            exp.DataType.Type.BINARY: "VARBINARY",
261            exp.DataType.Type.TEXT: "VARCHAR",
262            exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP",
263            exp.DataType.Type.STRUCT: "ROW",
264        }
265
266        TRANSFORMS = {
267            **generator.Generator.TRANSFORMS,  # type: ignore
268            **transforms.UNALIAS_GROUP,  # type: ignore
269            exp.ApproxDistinct: _approx_distinct_sql,
270            exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]",
271            exp.ArrayConcat: rename_func("CONCAT"),
272            exp.ArrayContains: rename_func("CONTAINS"),
273            exp.ArraySize: rename_func("CARDINALITY"),
274            exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
275            exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
276            exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})",
277            exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
278            exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
279            exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
280            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
281            exp.DataType: _datatype_sql,
282            exp.DateAdd: lambda self, e: self.func(
283                "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
284            ),
285            exp.DateDiff: lambda self, e: self.func(
286                "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
287            ),
288            exp.DateStrToDate: lambda self, e: f"CAST(DATE_PARSE({self.sql(e, 'this')}, {Presto.date_format}) AS DATE)",
289            exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.dateint_format}) AS INT)",
290            exp.Decode: _decode_sql,
291            exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.dateint_format}) AS DATE)",
292            exp.Encode: _encode_sql,
293            exp.GenerateSeries: _sequence_sql,
294            exp.Hex: rename_func("TO_HEX"),
295            exp.If: if_sql,
296            exp.ILike: no_ilike_sql,
297            exp.Initcap: _initcap_sql,
298            exp.Lateral: _explode_to_unnest_sql,
299            exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"),
300            exp.LogicalOr: rename_func("BOOL_OR"),
301            exp.LogicalAnd: rename_func("BOOL_AND"),
302            exp.Quantile: _quantile_sql,
303            exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"),
304            exp.SafeDivide: no_safe_divide_sql,
305            exp.Schema: _schema_sql,
306            exp.Select: transforms.preprocess(
307                [transforms.eliminate_qualify, transforms.explode_to_unnest]
308            ),
309            exp.SortArray: _no_sort_array,
310            exp.StrPosition: rename_func("STRPOS"),
311            exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)",
312            exp.StrToTime: _str_to_time_sql,
313            exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))",
314            exp.StructExtract: struct_extract_sql,
315            exp.TableFormatProperty: lambda self, e: f"TABLE_FORMAT='{e.name.upper()}'",
316            exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'",
317            exp.TimestampTrunc: timestamptrunc_sql,
318            exp.TimeStrToDate: timestrtotime_sql,
319            exp.TimeStrToTime: timestrtotime_sql,
320            exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.time_format}))",
321            exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})",
322            exp.TimeToUnix: rename_func("TO_UNIXTIME"),
323            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)",
324            exp.TsOrDsAdd: _ts_or_ds_add_sql,
325            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
326            exp.Unhex: rename_func("FROM_HEX"),
327            exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})",
328            exp.UnixToTime: rename_func("FROM_UNIXTIME"),
329            exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)",
330            exp.VariancePop: rename_func("VAR_POP"),
331        }
332
333        def interval_sql(self, expression: exp.Interval) -> str:
334            unit = self.sql(expression, "unit")
335            if expression.this and unit.lower().startswith("week"):
336                return f"({expression.this.name} * INTERVAL '7' day)"
337            return super().interval_sql(expression)
338
339        def transaction_sql(self, expression: exp.Transaction) -> str:
340            modes = expression.args.get("modes")
341            modes = f" {', '.join(modes)}" if modes else ""
342            return f"START TRANSACTION{modes}"

Generator interprets the given syntax tree and produces a SQL string as an output.

Arguments:
  • time_mapping (dict): the dictionary of custom time mappings in which the key represents a python time format and the output the target time format
  • time_trie (trie): a trie of the time_mapping keys
  • pretty (bool): if set to True the returned string will be formatted. Default: False.
  • quote_start (str): specifies which starting character to use to delimit quotes. Default: '.
  • quote_end (str): specifies which ending character to use to delimit quotes. Default: '.
  • identifier_start (str): specifies which starting character to use to delimit identifiers. Default: ".
  • identifier_end (str): specifies which ending character to use to delimit identifiers. Default: ".
  • identify (bool | str): 'always': always quote, 'safe': quote identifiers if they don't contain an upcase, True defaults to always.
  • normalize (bool): if set to True all identifiers will lower cased
  • string_escape (str): specifies a string escape character. Default: '.
  • identifier_escape (str): specifies an identifier escape character. Default: ".
  • pad (int): determines padding in a formatted string. Default: 2.
  • indent (int): determines the size of indentation in a formatted string. Default: 4.
  • unnest_column_only (bool): if true unnest table aliases are considered only as column aliases
  • normalize_functions (str): normalize function names, "upper", "lower", or None Default: "upper"
  • alias_post_tablesample (bool): if the table alias comes after tablesample Default: False
  • unsupported_level (ErrorLevel): determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
  • null_ordering (str): Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
  • max_unsupported (int): Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
  • leading_comma (bool): if the the comma is leading or trailing in select statements Default: False
  • max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
  • comments: Whether or not to preserve comments in the output SQL code. Default: True
def interval_sql(self, expression: sqlglot.expressions.Interval) -> str:
333        def interval_sql(self, expression: exp.Interval) -> str:
334            unit = self.sql(expression, "unit")
335            if expression.this and unit.lower().startswith("week"):
336                return f"({expression.this.name} * INTERVAL '7' day)"
337            return super().interval_sql(expression)
def transaction_sql(self, expression: sqlglot.expressions.Transaction) -> str:
339        def transaction_sql(self, expression: exp.Transaction) -> str:
340            modes = expression.args.get("modes")
341            modes = f" {', '.join(modes)}" if modes else ""
342            return f"START TRANSACTION{modes}"
Inherited Members
sqlglot.generator.Generator
Generator
generate
unsupported
sep
seg
pad_comment
maybe_comment
wrap
no_identify
normalize_func
indent
sql
uncache_sql
cache_sql
characterset_sql
column_sql
columnposition_sql
columndef_sql
columnconstraint_sql
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
notnullcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
create_sql
describe_sql
prepend_ctes
with_sql
cte_sql
tablealias_sql
bitstring_sql
hexstring_sql
bytestring_sql
datatype_sql
directory_sql
delete_sql
drop_sql
except_sql
except_op
fetch_sql
filter_sql
hint_sql
index_sql
identifier_sql
inputoutputformat_sql
national_sql
partition_sql
properties_sql
root_properties
properties
with_properties
locate_properties
property_sql
likeproperty_sql
fallbackproperty_sql
journalproperty_sql
freespaceproperty_sql
afterjournalproperty_sql
checksumproperty_sql
mergeblockratioproperty_sql
datablocksizeproperty_sql
blockcompressionproperty_sql
isolatedloadingproperty_sql
lockingproperty_sql
withdataproperty_sql
insert_sql
intersect_sql
intersect_op
introducer_sql
pseudotype_sql
onconflict_sql
returning_sql
rowformatdelimitedproperty_sql
table_sql
tablesample_sql
pivot_sql
tuple_sql
update_sql
values_sql
var_sql
into_sql
from_sql
group_sql
having_sql
join_sql
lambda_sql
lateral_sql
limit_sql
offset_sql
setitem_sql
set_sql
pragma_sql
lock_sql
literal_sql
loaddata_sql
null_sql
boolean_sql
order_sql
cluster_sql
distribute_sql
sort_sql
ordered_sql
matchrecognize_sql
query_modifiers
select_sql
schema_sql
star_sql
structkwarg_sql
parameter_sql
sessionparameter_sql
placeholder_sql
subquery_sql
qualify_sql
union_sql
union_op
unnest_sql
where_sql
window_sql
partition_by_sql
window_spec_sql
withingroup_sql
between_sql
bracket_sql
all_sql
any_sql
exists_sql
case_sql
constraint_sql
extract_sql
trim_sql
concat_sql
check_sql
foreignkey_sql
primarykey_sql
unique_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
jsonobject_sql
in_sql
in_unnest_op
return_sql
reference_sql
anonymous_sql
paren_sql
neg_sql
not_sql
alias_sql
aliases_sql
attimezone_sql
add_sql
and_sql
connector_sql
bitwiseand_sql
bitwiseleftshift_sql
bitwisenot_sql
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
cast_sql
currentdate_sql
collate_sql
command_sql
comment_sql
commit_sql
rollback_sql
altercolumn_sql
renametable_sql
altertable_sql
droppartition_sql
addconstraint_sql
distinct_sql
ignorenulls_sql
respectnulls_sql
intdiv_sql
dpipe_sql
div_sql
overlaps_sql
distance_sql
dot_sql
eq_sql
escape_sql
glob_sql
gt_sql
gte_sql
ilike_sql
ilikeany_sql
is_sql
like_sql
likeany_sql
similarto_sql
lt_sql
lte_sql
mod_sql
mul_sql
neq_sql
nullsafeeq_sql
nullsafeneq_sql
or_sql
slice_sql
sub_sql
trycast_sql
use_sql
binary
function_fallback_sql
func
format_args
text_width
format_time
expressions
op_expressions
naked_property
set_operation
tag_sql
token_sql
userdefinedfunction_sql
joinhint_sql
kwarg_sql
when_sql
merge_sql
tochar_sql