Edit on GitHub

sqlglot.generators.presto

  1from __future__ import annotations
  2
  3import typing as t
  4
  5from sqlglot import exp, generator, transforms
  6from sqlglot.dialects.dialect import (
  7    array_sort_order,
  8    array_slice_to_slice_sql,
  9    bool_xor_sql,
 10    bracket_to_element_at_sql,
 11    datestrtodate_sql,
 12    encode_decode_sql,
 13    if_sql,
 14    left_to_substring_sql,
 15    no_ilike_sql,
 16    no_pivot_sql,
 17    no_timestamp_sql,
 18    regexp_extract_sql,
 19    rename_func,
 20    right_to_substring_sql,
 21    strposition_sql,
 22    struct_extract_sql,
 23    timestamptrunc_sql,
 24    timestrtotime_sql,
 25    ts_or_ds_add_cast,
 26    unit_to_str,
 27    week_unit_to_dow,
 28    sequence_sql,
 29    explode_to_unnest_sql,
 30)
 31from sqlglot.dialects.hive import Hive
 32from sqlglot.generator import unsupported_args
 33from sqlglot.helper import is_float
 34from sqlglot.optimizer.scope import find_all_in_scope
 35from sqlglot.transforms import unqualify_columns
 36
 37DATE_ADD_OR_SUB = t.Union[exp.DateAdd, exp.TimestampAdd, exp.DateSub]
 38
 39
 40def _sha2_digest_sql(self: PrestoGenerator, expression: exp.SHA2Digest) -> str:
 41    length = expression.text("length") or "256"
 42    if length not in ("256", "512"):
 43        self.unsupported(f"SHA{length} is not supported in Presto")
 44
 45    this = expression.this
 46    if this.is_type(*exp.DataType.TEXT_TYPES):
 47        # the native digest takes VARBINARY, so a text-typed argument needs encoding
 48        this = exp.Encode(this=this, charset=exp.Literal.string("utf-8"))
 49
 50    return self.func(f"SHA{length}", this)
 51
 52
 53def _initcap_sql(self: PrestoGenerator, expression: exp.Initcap) -> str:
 54    delimiters = expression.expression
 55    if delimiters and not (
 56        delimiters.is_string and delimiters.this == self.dialect.INITCAP_DEFAULT_DELIMITER_CHARS
 57    ):
 58        self.unsupported("INITCAP does not support custom delimiters")
 59
 60    regex = r"(\w)(\w*)"
 61    return f"REGEXP_REPLACE({self.sql(expression, 'this')}, '{regex}', x -> UPPER(x[1]) || LOWER(x[2]))"
 62
 63
 64def _array_sort_sql(self: PrestoGenerator, expression: exp.ArraySort) -> str:
 65    if expression.expression:
 66        return self.func("ARRAY_SORT", expression.this, expression.expression)
 67
 68    # ARRAY_SORT puts NULLs last, so reversing it sorts descending with NULLs first
 69    asc, nulls_first = array_sort_order(expression) or (True, True)
 70    if nulls_first == asc:
 71        self.unsupported(
 72            "ARRAY_SORT can't sort ascending with NULLs first or descending with NULLs last"
 73        )
 74    sort = self.func("ARRAY_SORT", expression.this)
 75    return sort if asc else self.func("REVERSE", sort)
 76
 77
 78def _schema_sql(self: PrestoGenerator, expression: exp.Schema) -> str:
 79    if isinstance(expression.parent, exp.PartitionedByProperty):
 80        # Any columns in the ARRAY[] string literals should not be quoted
 81        expression.transform(lambda n: n.name if isinstance(n, exp.Identifier) else n, copy=False)
 82
 83        partition_exprs = [
 84            self.sql(c) if isinstance(c, (exp.Func, exp.Property)) else self.sql(c, "this")
 85            for c in expression.expressions
 86        ]
 87        return self.sql(exp.Array(expressions=[exp.Literal.string(c) for c in partition_exprs]))
 88
 89    if expression.parent:
 90        for schema in expression.parent.find_all(exp.Schema):
 91            if schema is expression:
 92                continue
 93
 94            column_defs = schema.find_all(exp.ColumnDef)
 95            if column_defs and isinstance(schema.parent, exp.Property):
 96                expression.expressions.extend(column_defs)
 97
 98    return self.schema_sql(expression)
 99
100
101def _quantile_sql(self: PrestoGenerator, expression: exp.Quantile) -> str:
102    self.unsupported("Presto does not support exact quantiles")
103    return self.func("APPROX_PERCENTILE", expression.this, expression.args.get("quantile"))
104
105
106def _str_to_time_sql(
107    self: PrestoGenerator, expression: exp.StrToDate | exp.StrToTime | exp.TsOrDsToDate
108) -> str:
109    return self.func("DATE_PARSE", expression.this, self.format_time(expression))
110
111
112def _ts_or_ds_to_date_sql(self: PrestoGenerator, expression: exp.TsOrDsToDate) -> str:
113    time_format = self.format_time(expression)
114    dialect_class = type(self.dialect)
115    if time_format and time_format not in (dialect_class.TIME_FORMAT, dialect_class.DATE_FORMAT):
116        return self.sql(exp.cast(_str_to_time_sql(self, expression), exp.DType.DATE))
117    return self.sql(exp.cast(exp.cast(expression.this, exp.DType.TIMESTAMP), exp.DType.DATE))
118
119
120def _ts_or_ds_add_sql(self: PrestoGenerator, expression: exp.TsOrDsAdd) -> str:
121    expression = ts_or_ds_add_cast(expression)
122    unit = unit_to_str(expression)
123    return self.func("DATE_ADD", unit, expression.expression, expression.this)
124
125
126def _ts_or_ds_diff_sql(self: PrestoGenerator, expression: exp.TsOrDsDiff) -> str:
127    this = exp.cast(expression.this, exp.DType.TIMESTAMP)
128    expr = exp.cast(expression.expression, exp.DType.TIMESTAMP)
129    unit = unit_to_str(expression)
130    return self.func("DATE_DIFF", unit, expr, this)
131
132
133def _first_last_sql(self: PrestoGenerator, expression: exp.Func) -> str:
134    """
135    Trino doesn't support FIRST / LAST as functions, but they're valid in the context
136    of MATCH_RECOGNIZE, so we need to preserve them in that case. In all other cases
137    they're converted into an ARBITRARY call.
138
139    Reference: https://trino.io/docs/current/sql/match-recognize.html#logical-navigation-functions
140    """
141    if isinstance(expression.find_ancestor(exp.MatchRecognize, exp.Select), exp.MatchRecognize):
142        return self.function_fallback_sql(expression)
143
144    return rename_func("ARBITRARY")(self, expression)
145
146
147def _unix_to_time_sql(self: PrestoGenerator, expression: exp.UnixToTime) -> str:
148    scale = expression.args.get("scale")
149    timestamp = self.sql(expression, "this")
150    if scale in (None, exp.UnixToTime.SECONDS):
151        return rename_func("FROM_UNIXTIME")(self, expression)
152
153    return f"FROM_UNIXTIME(CAST({timestamp} AS DOUBLE) / POW(10, {scale}))"
154
155
156def _to_int(self: PrestoGenerator, expression: exp.Expr) -> exp.Expr:
157    if not expression.type:
158        from sqlglot.optimizer.annotate_types import annotate_types
159
160        annotate_types(expression, dialect=self.dialect)
161    if expression.type and expression.type.this not in exp.DataType.INTEGER_TYPES:
162        return exp.cast(expression, to=exp.DType.BIGINT)
163    return expression
164
165
166def _date_delta_sql(
167    name: str, negate_interval: bool = False
168) -> t.Callable[[PrestoGenerator, DATE_ADD_OR_SUB], str]:
169    def _delta_sql(self: PrestoGenerator, expression: DATE_ADD_OR_SUB) -> str:
170        interval = _to_int(self, expression.expression)
171        return self.func(
172            name,
173            unit_to_str(expression),
174            interval * (-1) if negate_interval else interval,
175            expression.this,
176        )
177
178    return _delta_sql
179
180
181def _date_diff_sql(
182    self: PrestoGenerator, expression: exp.DateDiff | exp.DatetimeDiff | exp.TimestampDiff
183) -> str:
184    # Presto/Trino only expose date_diff(unit, ts1, ts2); it returns ts2 - ts1, so the
185    # operands are emitted as (expression, this) to preserve `this - expression` semantics.
186    this: exp.Expr = expression.this
187    expr: exp.Expr = expression.expression
188    unit = unit_to_str(expression)
189
190    # DATE_DIFF counts complete units between its operands, whereas dialects that set
191    # date_part_boundary count unit boundary crossings, so the operands are truncated
192    # down to the unit to make the two coincide
193    if unit and expression.args.get("date_part_boundary"):
194        raw_unit = expression.args.get("unit")
195        dow = week_unit_to_dow(raw_unit)
196
197        if dow is not None:
198            unit = exp.Literal.string("WEEK")
199
200            # DATE_TRUNC('WEEK', ...) is Monday-based; shifting both operands by the same
201            # delta realigns it to the requested week start without changing the diff
202            shift_days = 1 if dow == 7 else 1 - dow
203            if shift_days:
204                delta = exp.Interval(this=exp.Literal.string(str(shift_days)), unit=exp.var("DAY"))
205                this = exp.Add(this=this, expression=delta)
206                expr = exp.Add(this=expr, expression=delta.copy())
207
208        if not isinstance(raw_unit, exp.WeekStart) or dow is not None:
209            this = exp.DateTrunc(unit=unit.copy(), this=this)
210            expr = exp.DateTrunc(unit=unit.copy(), this=expr)
211
212    return self.func("DATE_DIFF", unit, expr, this)
213
214
215def _explode_to_unnest_sql(self: PrestoGenerator, expression: exp.Lateral) -> str:
216    explode = expression.this
217    if isinstance(explode, exp.Explode):
218        exploded_type = explode.this.type
219        alias = expression.args.get("alias")
220
221        # This attempts a best-effort transpilation of LATERAL VIEW EXPLODE on a struct array
222        if (
223            isinstance(alias, exp.TableAlias)
224            and isinstance(exploded_type, exp.DataType)
225            and exploded_type.is_type(exp.DType.ARRAY)
226            and exploded_type.expressions
227            and exploded_type.expressions[0].is_type(exp.DType.STRUCT)
228        ):
229            # When unnesting a ROW in Presto, it produces N columns, so we need to fix the alias
230            alias.set("columns", [c.this.copy() for c in exploded_type.expressions[0].expressions])
231    elif isinstance(explode, exp.Inline):
232        explode.replace(exp.Explode(this=explode.this.copy()))
233
234    return explode_to_unnest_sql(
235        self, expression, supports_left_join_unnest=self.SUPPORTS_LEFT_JOIN_UNNEST
236    )
237
238
239def amend_exploded_column_table(expression: exp.Expr) -> exp.Expr:
240    # We check for expression.type because the columns can be amended only if types were inferred
241    if isinstance(expression, exp.Select) and expression.type:
242        for lateral in expression.args.get("laterals") or []:
243            alias = lateral.args.get("alias")
244            if (
245                not isinstance(lateral.this, exp.Explode)
246                or not isinstance(alias, exp.TableAlias)
247                or len(alias.columns) != 1
248            ):
249                continue
250
251            new_table = alias.this
252            old_table = alias.columns[0].name.lower()
253
254            # When transpiling a LATERAL VIEW EXPLODE Spark query, the exploded fields may be qualified
255            # with the struct column, resulting in invalid Presto references that need to be amended
256            for column in find_all_in_scope(expression, exp.Column, include_udtfs=True):
257                if column.db.lower() == old_table:
258                    column.set("table", column.args["db"].pop())
259                elif column.table.lower() == old_table:
260                    column.set("table", new_table.copy())
261                elif column.name.lower() == old_table and isinstance(column.parent, exp.Dot):
262                    column.parent.replace(exp.column(column.parent.expression, table=new_table))
263
264    return expression
265
266
267class PrestoGenerator(generator.Generator):
268    DAYOFWEEK_ZERO_BASED = True
269    SELECT_KINDS = ()
270    SUPPORTS_EXECUTE_IMMEDIATE = False
271    SUPPORTS_DECODE_CASE = False
272    SUPPORTS_MULTI_ARG_CHR = False
273    SUPPORTS_TEMPORAL_PRECISION = False
274    # https://github.com/prestodb/presto/issues/8200
275    SUPPORTS_LEFT_JOIN_UNNEST = False
276
277    AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
278
279    INTERVAL_ALLOWS_PLURAL_FORM = False
280    JOIN_HINTS = False
281    CAST_TO_INT_ROUNDS = True
282    TABLE_HINTS = False
283    QUERY_HINTS = False
284    IS_BOOL_ALLOWED = False
285    TZ_TO_WITH_TIME_ZONE = True
286    NVL2_SUPPORTED = False
287    STRUCT_DELIMITER = ("(", ")")
288    LIMIT_ONLY_LITERALS = True
289    SUPPORTS_SINGLE_ARG_CONCAT = False
290    LIKE_PROPERTY_INSIDE_SCHEMA = True
291    MULTI_ARG_DISTINCT = False
292    SUPPORTS_TO_NUMBER = False
293    HEX_FUNC = "TO_HEX"
294    PARSE_JSON_NAME: str | None = "JSON_PARSE"
295    PAD_FILL_PATTERN_IS_REQUIRED = True
296    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
297    SUPPORTS_MEDIAN = False
298    ARRAY_SIZE_NAME = "CARDINALITY"
299
300    PROPERTIES_LOCATION = {
301        **generator.Generator.PROPERTIES_LOCATION,
302        exp.LocationProperty: exp.Properties.Location.UNSUPPORTED,
303        exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
304    }
305
306    TYPE_MAPPING = {
307        **generator.Generator.TYPE_MAPPING,
308        exp.DType.BINARY: "VARBINARY",
309        exp.DType.BIT: "BOOLEAN",
310        exp.DType.DATETIME: "TIMESTAMP",
311        exp.DType.DATETIME64: "TIMESTAMP",
312        exp.DType.FLOAT: "REAL",
313        exp.DType.HLLSKETCH: "HYPERLOGLOG",
314        exp.DType.INT: "INTEGER",
315        exp.DType.STRUCT: "ROW",
316        exp.DType.TEXT: "VARCHAR",
317        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
318        exp.DType.TIMESTAMPNTZ: "TIMESTAMP",
319        exp.DType.TIMETZ: "TIME",
320    }
321
322    TRANSFORMS = {
323        **generator.Generator.TRANSFORMS,
324        exp.AnyValue: rename_func("ARBITRARY"),
325        exp.ApproxQuantile: lambda self, e: self.func(
326            "APPROX_PERCENTILE",
327            e.this,
328            e.args.get("weight"),
329            e.args.get("quantile"),
330            e.args.get("accuracy"),
331        ),
332        exp.ArgMax: rename_func("MAX_BY"),
333        exp.ArgMin: rename_func("MIN_BY"),
334        exp.Array: transforms.preprocess(
335            [transforms.inherit_struct_field_names],
336            generator=lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]",
337        ),
338        exp.ArrayAny: rename_func("ANY_MATCH"),
339        exp.ArrayConcat: rename_func("CONCAT"),
340        exp.ArrayContains: rename_func("CONTAINS"),
341        exp.ArraySort: _array_sort_sql,
342        exp.ArrayToString: rename_func("ARRAY_JOIN"),
343        exp.ArrayUniqueAgg: rename_func("SET_AGG"),
344        exp.ArraySlice: array_slice_to_slice_sql,
345        exp.AtTimeZone: rename_func("AT_TIMEZONE"),
346        exp.BitwiseAnd: lambda self, e: self.func("BITWISE_AND", e.this, e.expression),
347        exp.BitwiseLeftShift: rename_func("BITWISE_LEFT_SHIFT"),
348        exp.BitwiseNot: lambda self, e: self.func("BITWISE_NOT", e.this),
349        exp.BitwiseOr: lambda self, e: self.func("BITWISE_OR", e.this, e.expression),
350        exp.BitwiseRightShift: rename_func("BITWISE_RIGHT_SHIFT"),
351        exp.BitwiseXor: lambda self, e: self.func("BITWISE_XOR", e.this, e.expression),
352        exp.Cast: transforms.preprocess([transforms.epoch_cast_to_ts]),
353        exp.CurrentTime: lambda *_: "CURRENT_TIME",
354        exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
355        exp.CurrentUser: lambda *_: "CURRENT_USER",
356        exp.DateAdd: _date_delta_sql("DATE_ADD"),
357        exp.DateDiff: _date_diff_sql,
358        exp.DatetimeDiff: _date_diff_sql,
359        exp.TimestampDiff: _date_diff_sql,
360        exp.DateStrToDate: datestrtodate_sql,
361        exp.DateToDi: lambda self, e: (
362            f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {type(self.dialect).DATEINT_FORMAT}) AS INT)"
363        ),
364        exp.DateSub: _date_delta_sql("DATE_ADD", negate_interval=True),
365        exp.DayOfWeekIso: rename_func("DAY_OF_WEEK"),
366        exp.Decode: lambda self, e: encode_decode_sql(self, e, "FROM_UTF8"),
367        exp.DiToDate: lambda self, e: (
368            f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {type(self.dialect).DATEINT_FORMAT}) AS DATE)"
369        ),
370        exp.Encode: lambda self, e: encode_decode_sql(self, e, "TO_UTF8"),
371        exp.FileFormatProperty: lambda self, e: f"format={self.sql(exp.Literal.string(e.name))}",
372        exp.First: _first_last_sql,
373        exp.FromISO8601Date: rename_func("FROM_ISO8601_DATE"),
374        exp.FromISO8601Timestamp: rename_func("FROM_ISO8601_TIMESTAMP"),
375        exp.FromTimeZone: lambda self, e: (
376            f"WITH_TIMEZONE({self.sql(e, 'this')}, {self.sql(e, 'zone')}) AT TIME ZONE 'UTC'"
377        ),
378        exp.GenerateSeries: sequence_sql,
379        exp.GenerateDateArray: sequence_sql,
380        exp.If: if_sql(),
381        exp.ILike: no_ilike_sql,
382        exp.Initcap: _initcap_sql,
383        exp.Last: _first_last_sql,
384        exp.LastDay: lambda self, e: self.func("LAST_DAY_OF_MONTH", e.this),
385        exp.Lateral: _explode_to_unnest_sql,
386        exp.Left: left_to_substring_sql,
387        exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")(
388            rename_func("LEVENSHTEIN_DISTANCE")
389        ),
390        exp.LogicalAnd: rename_func("BOOL_AND"),
391        exp.LogicalOr: rename_func("BOOL_OR"),
392        exp.Pivot: no_pivot_sql,
393        exp.Quantile: _quantile_sql,
394        exp.RegexpExtract: regexp_extract_sql,
395        exp.RegexpExtractAll: regexp_extract_sql,
396        exp.Right: right_to_substring_sql,
397        exp.Schema: _schema_sql,
398        exp.SchemaCommentProperty: lambda self, e: self.naked_property(e),
399        exp.Select: transforms.preprocess(
400            [
401                transforms.eliminate_window_clause,
402                transforms.eliminate_qualify,
403                transforms.eliminate_distinct_on,
404                transforms.explode_projection_to_unnest(1, unnest_map=True),
405                transforms.eliminate_semi_and_anti_joins,
406                amend_exploded_column_table,
407            ]
408        ),
409        exp.SqlSecurityProperty: lambda self, e: f"SECURITY {self.sql(e.this)}",
410        exp.StrPosition: lambda self, e: strposition_sql(self, e, supports_occurrence=True),
411        exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)",
412        exp.StrToMap: rename_func("SPLIT_TO_MAP"),
413        exp.StrToTime: _str_to_time_sql,
414        exp.StructExtract: struct_extract_sql,
415        exp.Table: transforms.preprocess([transforms.unnest_generate_series]),
416        exp.Timestamp: no_timestamp_sql,
417        exp.TimestampAdd: _date_delta_sql("DATE_ADD"),
418        exp.TimestampTrunc: timestamptrunc_sql(),
419        exp.TimeStrToDate: timestrtotime_sql,
420        exp.TimeStrToTime: timestrtotime_sql,
421        exp.TimeStrToUnix: lambda self, e: self.func(
422            "TO_UNIXTIME", self.func("DATE_PARSE", e.this, type(self.dialect).TIME_FORMAT)
423        ),
424        exp.TimeToUnix: rename_func("TO_UNIXTIME"),
425        exp.ToChar: lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e)),
426        exp.TryCast: transforms.preprocess([transforms.epoch_cast_to_ts]),
427        exp.TsOrDiToDi: lambda self, e: (
428            f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)"
429        ),
430        exp.TsOrDsAdd: _ts_or_ds_add_sql,
431        exp.TsOrDsDiff: _ts_or_ds_diff_sql,
432        exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
433        exp.Unhex: rename_func("FROM_HEX"),
434        exp.UnixToStr: lambda self, e: (
435            f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})"
436        ),
437        exp.UnixToTime: _unix_to_time_sql,
438        exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)",
439        exp.VariancePop: rename_func("VAR_POP"),
440        exp.With: transforms.preprocess([transforms.add_recursive_cte_column_names]),
441        exp.WithinGroup: transforms.preprocess([transforms.remove_within_group_for_percentiles]),
442        # Note: Presto's TRUNCATE always returns DOUBLE, even with decimals=0, whereas
443        # most dialects return INT (SQLite also returns REAL, see sqlite.py). This creates
444        # a bidirectional transpilation gap: Presto→Other may change float division to int
445        # division, and vice versa. Modeling precisely would require exp.FloatTrunc or
446        # similar, deemed overengineering for this subtle semantic difference.
447        exp.Trunc: rename_func("TRUNCATE"),
448        exp.Xor: bool_xor_sql,
449        exp.MD5Digest: rename_func("MD5"),
450        exp.SHA: rename_func("SHA1"),
451        exp.SHA1Digest: rename_func("SHA1"),
452        exp.SHA2Digest: _sha2_digest_sql,
453        exp.Substring: rename_func("SUBSTR"),
454    }
455
456    RESERVED_KEYWORDS = {
457        "alter",
458        "and",
459        "as",
460        "between",
461        "by",
462        "case",
463        "cast",
464        "constraint",
465        "create",
466        "cross",
467        "current_time",
468        "current_timestamp",
469        "deallocate",
470        "delete",
471        "describe",
472        "distinct",
473        "drop",
474        "else",
475        "end",
476        "escape",
477        "except",
478        "execute",
479        "exists",
480        "extract",
481        "false",
482        "for",
483        "from",
484        "full",
485        "group",
486        "having",
487        "in",
488        "inner",
489        "insert",
490        "intersect",
491        "into",
492        "is",
493        "join",
494        "left",
495        "like",
496        "natural",
497        "not",
498        "null",
499        "on",
500        "or",
501        "order",
502        "outer",
503        "prepare",
504        "right",
505        "select",
506        "table",
507        "then",
508        "true",
509        "union",
510        "using",
511        "values",
512        "when",
513        "where",
514        "with",
515    }
516
517    def datatype_sql(self, expression: exp.DataType) -> str:
518        if not self.SUPPORTS_TEMPORAL_PRECISION and expression.this in exp.DataType.TEMPORAL_TYPES:
519            if expression.expressions and expression.expressions[0].name != "3":
520                self.unsupported("Presto only supports millisecond precision for temporal types")
521            expression.set("expressions", None)
522        return super().datatype_sql(expression)
523
524    def exists_sql(self, expression: exp.Exists) -> str:
525        if expression.expression:
526            return self.func("ANY_MATCH", expression.this, expression.expression)
527
528        return super().exists_sql(expression)
529
530    def _native_dayofweek_sql(self, expression: exp.DayOfWeek) -> str:
531        # ISO Sunday is 7, so modulo 7 gives Sunday = 0.
532        return self.sql(exp.paren(exp.DayOfWeekIso(this=expression.this) % 7, copy=False))
533
534    def extract_sql(self, expression: exp.Extract) -> str:
535        date_part = expression.name
536
537        if not date_part.startswith("EPOCH"):
538            return super().extract_sql(expression)
539
540        if date_part == "EPOCH_MILLISECOND":
541            scale = 10**3
542        elif date_part == "EPOCH_MICROSECOND":
543            scale = 10**6
544        elif date_part == "EPOCH_NANOSECOND":
545            scale = 10**9
546        else:
547            scale = None
548
549        value = expression.expression
550
551        ts = exp.cast(value, to=exp.DType.TIMESTAMP.into_expr())
552        to_unix: exp.Expr = exp.TimeToUnix(this=ts)
553
554        if scale:
555            to_unix = exp.Mul(this=to_unix, expression=exp.Literal.number(scale))
556
557        return self.sql(to_unix)
558
559    def addmonths_sql(self, expression: exp.AddMonths) -> str:
560        this = expression.this
561        if this.is_string or this.is_type(*exp.DataType.TEXT_TYPES):
562            this = exp.TimeStrToTime(this=this)
563        if expression.is_type(exp.DType.DATE) and not this.is_type(exp.DType.DATE):
564            this = exp.cast(this, exp.DType.DATE)
565
566        added = exp.DateAdd(this=this, expression=expression.expression, unit=exp.var("MONTH"))
567
568        if not expression.args.get("preserve_end_of_month"):
569            return self.sql(added)
570
571        # Shift the original value by whole days to preserve its time of day.
572        eom_shift = exp.DateDiff(
573            this=exp.LastDay(this=added.copy()),
574            expression=exp.cast(this, exp.DType.DATE),
575            unit=exp.var("DAY"),
576        )
577        to_eom = exp.DateAdd(this=this.copy(), expression=eom_shift, unit=exp.var("DAY"))
578        is_eom = exp.Day(this=this.copy()).eq(exp.Day(this=exp.LastDay(this=this.copy())))
579
580        return self.sql(exp.case().when(is_eom, to_eom).else_(added))
581
582    def jsonformat_sql(self, expression: exp.JSONFormat) -> str:
583        this = expression.this
584        is_json = expression.args.get("is_json")
585
586        if this and not (is_json or this.type):
587            from sqlglot.optimizer.annotate_types import annotate_types
588
589            this = annotate_types(this, dialect=self.dialect)
590
591        if not (is_json or this.is_type(exp.DType.JSON)):
592            this.replace(exp.cast(this, exp.DType.JSON))
593
594        return self.function_fallback_sql(expression)
595
596    def md5_sql(self, expression: exp.MD5) -> str:
597        this = expression.this
598
599        if not this.type:
600            from sqlglot.optimizer.annotate_types import annotate_types
601
602            this = annotate_types(this, dialect=self.dialect)
603
604        if this.is_type(*exp.DataType.TEXT_TYPES):
605            this = exp.Encode(this=this, charset=exp.Literal.string("utf-8"))
606
607        return self.func("LOWER", self.func("TO_HEX", self.func("MD5", self.sql(this))))
608
609    def sha2_sql(self, expression: exp.SHA2) -> str:
610        length = expression.text("length") or "256"
611        if length not in ("256", "512"):
612            self.unsupported(f"SHA{length} is not supported in Presto")
613
614        this = expression.this
615
616        if this.is_type(*exp.DataType.TEXT_TYPES):
617            this = exp.Encode(this=this, charset=exp.Literal.string("utf-8"))
618
619        return self.func("LOWER", self.func("TO_HEX", self.func(f"SHA{length}", self.sql(this))))
620
621    def timetostr_sql(self, expression: exp.TimeToStr) -> str:
622        if expression.args.get("joda"):
623            from sqlglot.dialects.presto import Presto
624
625            return self.func(
626                "FORMAT_DATETIME",
627                expression.this,
628                self.format_time(
629                    expression, Presto.INVERSE_JODA_TIME_MAPPING, Presto.INVERSE_JODA_TIME_TRIE
630                ),
631            )
632
633        return self.func("DATE_FORMAT", expression.this, self.format_time(expression))
634
635    def strtounix_sql(self, expression: exp.StrToUnix) -> str:
636        # Since `TO_UNIXTIME` requires a `TIMESTAMP`, we need to parse the argument into one.
637        # To do this, we first try to `DATE_PARSE` it, but since this can fail when there's a
638        # timezone involved, we wrap it in a `TRY` call and use `PARSE_DATETIME` as a fallback,
639        # which seems to be using the same time mapping as Hive, as per:
640        # https://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html
641        this = expression.this
642        value_as_text = exp.cast(this, exp.DType.TEXT)
643        value_as_timestamp = exp.cast(this, exp.DType.TIMESTAMP) if this.is_string else this
644
645        parse_without_tz = self.func("DATE_PARSE", value_as_text, self.format_time(expression))
646
647        formatted_value = self.func("DATE_FORMAT", value_as_timestamp, self.format_time(expression))
648        parse_with_tz = self.func(
649            "PARSE_DATETIME",
650            formatted_value,
651            self.format_time(expression, Hive.INVERSE_TIME_MAPPING, Hive.INVERSE_TIME_TRIE),
652        )
653        coalesced = self.func("COALESCE", self.func("TRY", parse_without_tz), parse_with_tz)
654        return self.func("TO_UNIXTIME", coalesced)
655
656    def bracket_sql(self, expression: exp.Bracket) -> str:
657        if expression.args.get("safe"):
658            return bracket_to_element_at_sql(self, expression)
659        return super().bracket_sql(expression)
660
661    def struct_sql(self, expression: exp.Struct) -> str:
662        if not expression.type:
663            from sqlglot.optimizer.annotate_types import annotate_types
664
665            annotate_types(expression, dialect=self.dialect)
666
667        values: list[str] = []
668        schema: list[str] = []
669        unknown_type = False
670
671        for e in expression.expressions:
672            if isinstance(e, exp.PropertyEQ):
673                if e.type and e.type.is_type(exp.DType.UNKNOWN):
674                    unknown_type = True
675                else:
676                    schema.append(f"{self.sql(e, 'this')} {self.sql(e.type)}")
677                values.append(self.sql(e, "expression"))
678            else:
679                values.append(self.sql(e))
680
681        size = len(expression.expressions)
682
683        if not size or len(schema) != size:
684            if unknown_type:
685                self.unsupported(
686                    "Cannot convert untyped key-value definitions (try annotate_types)."
687                )
688            return self.func("ROW", *values)
689        return f"CAST(ROW({', '.join(values)}) AS ROW({', '.join(schema)}))"
690
691    def interval_sql(self, expression: exp.Interval) -> str:
692        this = expression.this
693        if this and expression.text("unit").upper().startswith("WEEK"):
694            if not this.is_string:
695                return f"({self.sql(this)} * INTERVAL '7' DAY)"
696            if is_float(this.name):
697                return f"({this.name} * INTERVAL '7' DAY)"
698        return super().interval_sql(expression)
699
700    def show_sql(self, expression: exp.Show) -> str:
701        target = self.sql(expression, "target")
702        target = f" FOR {target}" if target else ""
703        from_ = self.sql(expression, "from_")
704        from_ = f" FROM {from_}" if from_ else ""
705        like = self.sql(expression, "like")
706        like = f" LIKE {like}" if like else ""
707        return f"SHOW {expression.name}{target}{from_}{like}"
708
709    def transaction_sql(self, expression: exp.Transaction) -> str:
710        modes = expression.args.get("modes")
711        modes = f" {', '.join(modes)}" if modes else ""
712        return f"START TRANSACTION{modes}"
713
714    def offset_limit_modifiers(
715        self, expression: exp.Expr, fetch: bool, limit: exp.Fetch | exp.Limit | None
716    ) -> list[str]:
717        return [
718            self.sql(expression, "offset"),
719            self.sql(limit),
720        ]
721
722    def create_sql(self, expression: exp.Create) -> str:
723        """
724        Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression),
725        so we need to remove them
726        """
727        kind = expression.args["kind"]
728        schema = expression.this
729        if kind == "VIEW" and schema.expressions:
730            expression.this.set("expressions", None)
731        return super().create_sql(expression)
732
733    def delete_sql(self, expression: exp.Delete) -> str:
734        """
735        Presto only supports DELETE FROM for a single table without an alias, so we need
736        to remove the unnecessary parts. If the original DELETE statement contains more
737        than one table to be deleted, we can't safely map it 1-1 to a Presto statement.
738        """
739        tables = expression.args.get("tables") or [expression.this]
740        if len(tables) > 1:
741            return super().delete_sql(expression)
742
743        table = tables[0]
744        expression.set("this", table)
745        expression.set("tables", None)
746
747        if isinstance(table, exp.Table):
748            table_alias = table.args.get("alias")
749            if table_alias:
750                table_alias.pop()
751                expression = t.cast(exp.Delete, expression.transform(unqualify_columns))
752
753        return super().delete_sql(expression)
754
755    def jsonextract_sql(self, expression: exp.JSONExtract) -> str:
756        is_json_extract = self.dialect.settings.get("variant_extract_is_json_extract", True)
757
758        # Generate JSON_EXTRACT unless the user has configured that a Snowflake / Databricks
759        # VARIANT extract (e.g. col:x.y) should map to dot notation (i.e ROW access) in Presto/Trino
760        if not expression.args.get("variant_extract") or is_json_extract:
761            return self.func(
762                "JSON_EXTRACT", expression.this, expression.expression, *expression.expressions
763            )
764
765        this = self.sql(expression, "this")
766
767        # Convert the JSONPath extraction `JSON_EXTRACT(col, '$.x.y) to a ROW access col.x.y
768        segments = []
769        for path_key in expression.expression.expressions[1:]:
770            if not isinstance(path_key, exp.JSONPathKey):
771                # Cannot transpile subscripts, wildcards etc to dot notation
772                self.unsupported(f"Cannot transpile JSONPath segment '{path_key}' to ROW access")
773                continue
774            key = path_key.this
775            if not exp.SAFE_IDENTIFIER_RE.match(key):
776                key = f'"{key}"'
777            segments.append(f".{key}")
778
779        expr = "".join(segments)
780
781        return f"{this}{expr}"
782
783    def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
784        return self.func(
785            "ARRAY_JOIN",
786            self.func("ARRAY_AGG", expression.this),
787            expression.args.get("separator"),
788        )
789
790    def execute_sql(self, expression: exp.Execute) -> str:
791        self._warn_unsupported_arg(expression, "return_status")
792        using = self.expressions(expression, flat=True)
793        using = f" USING {using}" if using else ""
794        return f"EXECUTE {self.sql(expression, 'this')}{using}"
def amend_exploded_column_table( expression: sqlglot.expressions.core.Expr) -> sqlglot.expressions.core.Expr:
240def amend_exploded_column_table(expression: exp.Expr) -> exp.Expr:
241    # We check for expression.type because the columns can be amended only if types were inferred
242    if isinstance(expression, exp.Select) and expression.type:
243        for lateral in expression.args.get("laterals") or []:
244            alias = lateral.args.get("alias")
245            if (
246                not isinstance(lateral.this, exp.Explode)
247                or not isinstance(alias, exp.TableAlias)
248                or len(alias.columns) != 1
249            ):
250                continue
251
252            new_table = alias.this
253            old_table = alias.columns[0].name.lower()
254
255            # When transpiling a LATERAL VIEW EXPLODE Spark query, the exploded fields may be qualified
256            # with the struct column, resulting in invalid Presto references that need to be amended
257            for column in find_all_in_scope(expression, exp.Column, include_udtfs=True):
258                if column.db.lower() == old_table:
259                    column.set("table", column.args["db"].pop())
260                elif column.table.lower() == old_table:
261                    column.set("table", new_table.copy())
262                elif column.name.lower() == old_table and isinstance(column.parent, exp.Dot):
263                    column.parent.replace(exp.column(column.parent.expression, table=new_table))
264
265    return expression
class PrestoGenerator(sqlglot.generator.Generator):
268class PrestoGenerator(generator.Generator):
269    DAYOFWEEK_ZERO_BASED = True
270    SELECT_KINDS = ()
271    SUPPORTS_EXECUTE_IMMEDIATE = False
272    SUPPORTS_DECODE_CASE = False
273    SUPPORTS_MULTI_ARG_CHR = False
274    SUPPORTS_TEMPORAL_PRECISION = False
275    # https://github.com/prestodb/presto/issues/8200
276    SUPPORTS_LEFT_JOIN_UNNEST = False
277
278    AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
279
280    INTERVAL_ALLOWS_PLURAL_FORM = False
281    JOIN_HINTS = False
282    CAST_TO_INT_ROUNDS = True
283    TABLE_HINTS = False
284    QUERY_HINTS = False
285    IS_BOOL_ALLOWED = False
286    TZ_TO_WITH_TIME_ZONE = True
287    NVL2_SUPPORTED = False
288    STRUCT_DELIMITER = ("(", ")")
289    LIMIT_ONLY_LITERALS = True
290    SUPPORTS_SINGLE_ARG_CONCAT = False
291    LIKE_PROPERTY_INSIDE_SCHEMA = True
292    MULTI_ARG_DISTINCT = False
293    SUPPORTS_TO_NUMBER = False
294    HEX_FUNC = "TO_HEX"
295    PARSE_JSON_NAME: str | None = "JSON_PARSE"
296    PAD_FILL_PATTERN_IS_REQUIRED = True
297    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
298    SUPPORTS_MEDIAN = False
299    ARRAY_SIZE_NAME = "CARDINALITY"
300
301    PROPERTIES_LOCATION = {
302        **generator.Generator.PROPERTIES_LOCATION,
303        exp.LocationProperty: exp.Properties.Location.UNSUPPORTED,
304        exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
305    }
306
307    TYPE_MAPPING = {
308        **generator.Generator.TYPE_MAPPING,
309        exp.DType.BINARY: "VARBINARY",
310        exp.DType.BIT: "BOOLEAN",
311        exp.DType.DATETIME: "TIMESTAMP",
312        exp.DType.DATETIME64: "TIMESTAMP",
313        exp.DType.FLOAT: "REAL",
314        exp.DType.HLLSKETCH: "HYPERLOGLOG",
315        exp.DType.INT: "INTEGER",
316        exp.DType.STRUCT: "ROW",
317        exp.DType.TEXT: "VARCHAR",
318        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
319        exp.DType.TIMESTAMPNTZ: "TIMESTAMP",
320        exp.DType.TIMETZ: "TIME",
321    }
322
323    TRANSFORMS = {
324        **generator.Generator.TRANSFORMS,
325        exp.AnyValue: rename_func("ARBITRARY"),
326        exp.ApproxQuantile: lambda self, e: self.func(
327            "APPROX_PERCENTILE",
328            e.this,
329            e.args.get("weight"),
330            e.args.get("quantile"),
331            e.args.get("accuracy"),
332        ),
333        exp.ArgMax: rename_func("MAX_BY"),
334        exp.ArgMin: rename_func("MIN_BY"),
335        exp.Array: transforms.preprocess(
336            [transforms.inherit_struct_field_names],
337            generator=lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]",
338        ),
339        exp.ArrayAny: rename_func("ANY_MATCH"),
340        exp.ArrayConcat: rename_func("CONCAT"),
341        exp.ArrayContains: rename_func("CONTAINS"),
342        exp.ArraySort: _array_sort_sql,
343        exp.ArrayToString: rename_func("ARRAY_JOIN"),
344        exp.ArrayUniqueAgg: rename_func("SET_AGG"),
345        exp.ArraySlice: array_slice_to_slice_sql,
346        exp.AtTimeZone: rename_func("AT_TIMEZONE"),
347        exp.BitwiseAnd: lambda self, e: self.func("BITWISE_AND", e.this, e.expression),
348        exp.BitwiseLeftShift: rename_func("BITWISE_LEFT_SHIFT"),
349        exp.BitwiseNot: lambda self, e: self.func("BITWISE_NOT", e.this),
350        exp.BitwiseOr: lambda self, e: self.func("BITWISE_OR", e.this, e.expression),
351        exp.BitwiseRightShift: rename_func("BITWISE_RIGHT_SHIFT"),
352        exp.BitwiseXor: lambda self, e: self.func("BITWISE_XOR", e.this, e.expression),
353        exp.Cast: transforms.preprocess([transforms.epoch_cast_to_ts]),
354        exp.CurrentTime: lambda *_: "CURRENT_TIME",
355        exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
356        exp.CurrentUser: lambda *_: "CURRENT_USER",
357        exp.DateAdd: _date_delta_sql("DATE_ADD"),
358        exp.DateDiff: _date_diff_sql,
359        exp.DatetimeDiff: _date_diff_sql,
360        exp.TimestampDiff: _date_diff_sql,
361        exp.DateStrToDate: datestrtodate_sql,
362        exp.DateToDi: lambda self, e: (
363            f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {type(self.dialect).DATEINT_FORMAT}) AS INT)"
364        ),
365        exp.DateSub: _date_delta_sql("DATE_ADD", negate_interval=True),
366        exp.DayOfWeekIso: rename_func("DAY_OF_WEEK"),
367        exp.Decode: lambda self, e: encode_decode_sql(self, e, "FROM_UTF8"),
368        exp.DiToDate: lambda self, e: (
369            f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {type(self.dialect).DATEINT_FORMAT}) AS DATE)"
370        ),
371        exp.Encode: lambda self, e: encode_decode_sql(self, e, "TO_UTF8"),
372        exp.FileFormatProperty: lambda self, e: f"format={self.sql(exp.Literal.string(e.name))}",
373        exp.First: _first_last_sql,
374        exp.FromISO8601Date: rename_func("FROM_ISO8601_DATE"),
375        exp.FromISO8601Timestamp: rename_func("FROM_ISO8601_TIMESTAMP"),
376        exp.FromTimeZone: lambda self, e: (
377            f"WITH_TIMEZONE({self.sql(e, 'this')}, {self.sql(e, 'zone')}) AT TIME ZONE 'UTC'"
378        ),
379        exp.GenerateSeries: sequence_sql,
380        exp.GenerateDateArray: sequence_sql,
381        exp.If: if_sql(),
382        exp.ILike: no_ilike_sql,
383        exp.Initcap: _initcap_sql,
384        exp.Last: _first_last_sql,
385        exp.LastDay: lambda self, e: self.func("LAST_DAY_OF_MONTH", e.this),
386        exp.Lateral: _explode_to_unnest_sql,
387        exp.Left: left_to_substring_sql,
388        exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")(
389            rename_func("LEVENSHTEIN_DISTANCE")
390        ),
391        exp.LogicalAnd: rename_func("BOOL_AND"),
392        exp.LogicalOr: rename_func("BOOL_OR"),
393        exp.Pivot: no_pivot_sql,
394        exp.Quantile: _quantile_sql,
395        exp.RegexpExtract: regexp_extract_sql,
396        exp.RegexpExtractAll: regexp_extract_sql,
397        exp.Right: right_to_substring_sql,
398        exp.Schema: _schema_sql,
399        exp.SchemaCommentProperty: lambda self, e: self.naked_property(e),
400        exp.Select: transforms.preprocess(
401            [
402                transforms.eliminate_window_clause,
403                transforms.eliminate_qualify,
404                transforms.eliminate_distinct_on,
405                transforms.explode_projection_to_unnest(1, unnest_map=True),
406                transforms.eliminate_semi_and_anti_joins,
407                amend_exploded_column_table,
408            ]
409        ),
410        exp.SqlSecurityProperty: lambda self, e: f"SECURITY {self.sql(e.this)}",
411        exp.StrPosition: lambda self, e: strposition_sql(self, e, supports_occurrence=True),
412        exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)",
413        exp.StrToMap: rename_func("SPLIT_TO_MAP"),
414        exp.StrToTime: _str_to_time_sql,
415        exp.StructExtract: struct_extract_sql,
416        exp.Table: transforms.preprocess([transforms.unnest_generate_series]),
417        exp.Timestamp: no_timestamp_sql,
418        exp.TimestampAdd: _date_delta_sql("DATE_ADD"),
419        exp.TimestampTrunc: timestamptrunc_sql(),
420        exp.TimeStrToDate: timestrtotime_sql,
421        exp.TimeStrToTime: timestrtotime_sql,
422        exp.TimeStrToUnix: lambda self, e: self.func(
423            "TO_UNIXTIME", self.func("DATE_PARSE", e.this, type(self.dialect).TIME_FORMAT)
424        ),
425        exp.TimeToUnix: rename_func("TO_UNIXTIME"),
426        exp.ToChar: lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e)),
427        exp.TryCast: transforms.preprocess([transforms.epoch_cast_to_ts]),
428        exp.TsOrDiToDi: lambda self, e: (
429            f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)"
430        ),
431        exp.TsOrDsAdd: _ts_or_ds_add_sql,
432        exp.TsOrDsDiff: _ts_or_ds_diff_sql,
433        exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
434        exp.Unhex: rename_func("FROM_HEX"),
435        exp.UnixToStr: lambda self, e: (
436            f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})"
437        ),
438        exp.UnixToTime: _unix_to_time_sql,
439        exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)",
440        exp.VariancePop: rename_func("VAR_POP"),
441        exp.With: transforms.preprocess([transforms.add_recursive_cte_column_names]),
442        exp.WithinGroup: transforms.preprocess([transforms.remove_within_group_for_percentiles]),
443        # Note: Presto's TRUNCATE always returns DOUBLE, even with decimals=0, whereas
444        # most dialects return INT (SQLite also returns REAL, see sqlite.py). This creates
445        # a bidirectional transpilation gap: Presto→Other may change float division to int
446        # division, and vice versa. Modeling precisely would require exp.FloatTrunc or
447        # similar, deemed overengineering for this subtle semantic difference.
448        exp.Trunc: rename_func("TRUNCATE"),
449        exp.Xor: bool_xor_sql,
450        exp.MD5Digest: rename_func("MD5"),
451        exp.SHA: rename_func("SHA1"),
452        exp.SHA1Digest: rename_func("SHA1"),
453        exp.SHA2Digest: _sha2_digest_sql,
454        exp.Substring: rename_func("SUBSTR"),
455    }
456
457    RESERVED_KEYWORDS = {
458        "alter",
459        "and",
460        "as",
461        "between",
462        "by",
463        "case",
464        "cast",
465        "constraint",
466        "create",
467        "cross",
468        "current_time",
469        "current_timestamp",
470        "deallocate",
471        "delete",
472        "describe",
473        "distinct",
474        "drop",
475        "else",
476        "end",
477        "escape",
478        "except",
479        "execute",
480        "exists",
481        "extract",
482        "false",
483        "for",
484        "from",
485        "full",
486        "group",
487        "having",
488        "in",
489        "inner",
490        "insert",
491        "intersect",
492        "into",
493        "is",
494        "join",
495        "left",
496        "like",
497        "natural",
498        "not",
499        "null",
500        "on",
501        "or",
502        "order",
503        "outer",
504        "prepare",
505        "right",
506        "select",
507        "table",
508        "then",
509        "true",
510        "union",
511        "using",
512        "values",
513        "when",
514        "where",
515        "with",
516    }
517
518    def datatype_sql(self, expression: exp.DataType) -> str:
519        if not self.SUPPORTS_TEMPORAL_PRECISION and expression.this in exp.DataType.TEMPORAL_TYPES:
520            if expression.expressions and expression.expressions[0].name != "3":
521                self.unsupported("Presto only supports millisecond precision for temporal types")
522            expression.set("expressions", None)
523        return super().datatype_sql(expression)
524
525    def exists_sql(self, expression: exp.Exists) -> str:
526        if expression.expression:
527            return self.func("ANY_MATCH", expression.this, expression.expression)
528
529        return super().exists_sql(expression)
530
531    def _native_dayofweek_sql(self, expression: exp.DayOfWeek) -> str:
532        # ISO Sunday is 7, so modulo 7 gives Sunday = 0.
533        return self.sql(exp.paren(exp.DayOfWeekIso(this=expression.this) % 7, copy=False))
534
535    def extract_sql(self, expression: exp.Extract) -> str:
536        date_part = expression.name
537
538        if not date_part.startswith("EPOCH"):
539            return super().extract_sql(expression)
540
541        if date_part == "EPOCH_MILLISECOND":
542            scale = 10**3
543        elif date_part == "EPOCH_MICROSECOND":
544            scale = 10**6
545        elif date_part == "EPOCH_NANOSECOND":
546            scale = 10**9
547        else:
548            scale = None
549
550        value = expression.expression
551
552        ts = exp.cast(value, to=exp.DType.TIMESTAMP.into_expr())
553        to_unix: exp.Expr = exp.TimeToUnix(this=ts)
554
555        if scale:
556            to_unix = exp.Mul(this=to_unix, expression=exp.Literal.number(scale))
557
558        return self.sql(to_unix)
559
560    def addmonths_sql(self, expression: exp.AddMonths) -> str:
561        this = expression.this
562        if this.is_string or this.is_type(*exp.DataType.TEXT_TYPES):
563            this = exp.TimeStrToTime(this=this)
564        if expression.is_type(exp.DType.DATE) and not this.is_type(exp.DType.DATE):
565            this = exp.cast(this, exp.DType.DATE)
566
567        added = exp.DateAdd(this=this, expression=expression.expression, unit=exp.var("MONTH"))
568
569        if not expression.args.get("preserve_end_of_month"):
570            return self.sql(added)
571
572        # Shift the original value by whole days to preserve its time of day.
573        eom_shift = exp.DateDiff(
574            this=exp.LastDay(this=added.copy()),
575            expression=exp.cast(this, exp.DType.DATE),
576            unit=exp.var("DAY"),
577        )
578        to_eom = exp.DateAdd(this=this.copy(), expression=eom_shift, unit=exp.var("DAY"))
579        is_eom = exp.Day(this=this.copy()).eq(exp.Day(this=exp.LastDay(this=this.copy())))
580
581        return self.sql(exp.case().when(is_eom, to_eom).else_(added))
582
583    def jsonformat_sql(self, expression: exp.JSONFormat) -> str:
584        this = expression.this
585        is_json = expression.args.get("is_json")
586
587        if this and not (is_json or this.type):
588            from sqlglot.optimizer.annotate_types import annotate_types
589
590            this = annotate_types(this, dialect=self.dialect)
591
592        if not (is_json or this.is_type(exp.DType.JSON)):
593            this.replace(exp.cast(this, exp.DType.JSON))
594
595        return self.function_fallback_sql(expression)
596
597    def md5_sql(self, expression: exp.MD5) -> str:
598        this = expression.this
599
600        if not this.type:
601            from sqlglot.optimizer.annotate_types import annotate_types
602
603            this = annotate_types(this, dialect=self.dialect)
604
605        if this.is_type(*exp.DataType.TEXT_TYPES):
606            this = exp.Encode(this=this, charset=exp.Literal.string("utf-8"))
607
608        return self.func("LOWER", self.func("TO_HEX", self.func("MD5", self.sql(this))))
609
610    def sha2_sql(self, expression: exp.SHA2) -> str:
611        length = expression.text("length") or "256"
612        if length not in ("256", "512"):
613            self.unsupported(f"SHA{length} is not supported in Presto")
614
615        this = expression.this
616
617        if this.is_type(*exp.DataType.TEXT_TYPES):
618            this = exp.Encode(this=this, charset=exp.Literal.string("utf-8"))
619
620        return self.func("LOWER", self.func("TO_HEX", self.func(f"SHA{length}", self.sql(this))))
621
622    def timetostr_sql(self, expression: exp.TimeToStr) -> str:
623        if expression.args.get("joda"):
624            from sqlglot.dialects.presto import Presto
625
626            return self.func(
627                "FORMAT_DATETIME",
628                expression.this,
629                self.format_time(
630                    expression, Presto.INVERSE_JODA_TIME_MAPPING, Presto.INVERSE_JODA_TIME_TRIE
631                ),
632            )
633
634        return self.func("DATE_FORMAT", expression.this, self.format_time(expression))
635
636    def strtounix_sql(self, expression: exp.StrToUnix) -> str:
637        # Since `TO_UNIXTIME` requires a `TIMESTAMP`, we need to parse the argument into one.
638        # To do this, we first try to `DATE_PARSE` it, but since this can fail when there's a
639        # timezone involved, we wrap it in a `TRY` call and use `PARSE_DATETIME` as a fallback,
640        # which seems to be using the same time mapping as Hive, as per:
641        # https://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html
642        this = expression.this
643        value_as_text = exp.cast(this, exp.DType.TEXT)
644        value_as_timestamp = exp.cast(this, exp.DType.TIMESTAMP) if this.is_string else this
645
646        parse_without_tz = self.func("DATE_PARSE", value_as_text, self.format_time(expression))
647
648        formatted_value = self.func("DATE_FORMAT", value_as_timestamp, self.format_time(expression))
649        parse_with_tz = self.func(
650            "PARSE_DATETIME",
651            formatted_value,
652            self.format_time(expression, Hive.INVERSE_TIME_MAPPING, Hive.INVERSE_TIME_TRIE),
653        )
654        coalesced = self.func("COALESCE", self.func("TRY", parse_without_tz), parse_with_tz)
655        return self.func("TO_UNIXTIME", coalesced)
656
657    def bracket_sql(self, expression: exp.Bracket) -> str:
658        if expression.args.get("safe"):
659            return bracket_to_element_at_sql(self, expression)
660        return super().bracket_sql(expression)
661
662    def struct_sql(self, expression: exp.Struct) -> str:
663        if not expression.type:
664            from sqlglot.optimizer.annotate_types import annotate_types
665
666            annotate_types(expression, dialect=self.dialect)
667
668        values: list[str] = []
669        schema: list[str] = []
670        unknown_type = False
671
672        for e in expression.expressions:
673            if isinstance(e, exp.PropertyEQ):
674                if e.type and e.type.is_type(exp.DType.UNKNOWN):
675                    unknown_type = True
676                else:
677                    schema.append(f"{self.sql(e, 'this')} {self.sql(e.type)}")
678                values.append(self.sql(e, "expression"))
679            else:
680                values.append(self.sql(e))
681
682        size = len(expression.expressions)
683
684        if not size or len(schema) != size:
685            if unknown_type:
686                self.unsupported(
687                    "Cannot convert untyped key-value definitions (try annotate_types)."
688                )
689            return self.func("ROW", *values)
690        return f"CAST(ROW({', '.join(values)}) AS ROW({', '.join(schema)}))"
691
692    def interval_sql(self, expression: exp.Interval) -> str:
693        this = expression.this
694        if this and expression.text("unit").upper().startswith("WEEK"):
695            if not this.is_string:
696                return f"({self.sql(this)} * INTERVAL '7' DAY)"
697            if is_float(this.name):
698                return f"({this.name} * INTERVAL '7' DAY)"
699        return super().interval_sql(expression)
700
701    def show_sql(self, expression: exp.Show) -> str:
702        target = self.sql(expression, "target")
703        target = f" FOR {target}" if target else ""
704        from_ = self.sql(expression, "from_")
705        from_ = f" FROM {from_}" if from_ else ""
706        like = self.sql(expression, "like")
707        like = f" LIKE {like}" if like else ""
708        return f"SHOW {expression.name}{target}{from_}{like}"
709
710    def transaction_sql(self, expression: exp.Transaction) -> str:
711        modes = expression.args.get("modes")
712        modes = f" {', '.join(modes)}" if modes else ""
713        return f"START TRANSACTION{modes}"
714
715    def offset_limit_modifiers(
716        self, expression: exp.Expr, fetch: bool, limit: exp.Fetch | exp.Limit | None
717    ) -> list[str]:
718        return [
719            self.sql(expression, "offset"),
720            self.sql(limit),
721        ]
722
723    def create_sql(self, expression: exp.Create) -> str:
724        """
725        Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression),
726        so we need to remove them
727        """
728        kind = expression.args["kind"]
729        schema = expression.this
730        if kind == "VIEW" and schema.expressions:
731            expression.this.set("expressions", None)
732        return super().create_sql(expression)
733
734    def delete_sql(self, expression: exp.Delete) -> str:
735        """
736        Presto only supports DELETE FROM for a single table without an alias, so we need
737        to remove the unnecessary parts. If the original DELETE statement contains more
738        than one table to be deleted, we can't safely map it 1-1 to a Presto statement.
739        """
740        tables = expression.args.get("tables") or [expression.this]
741        if len(tables) > 1:
742            return super().delete_sql(expression)
743
744        table = tables[0]
745        expression.set("this", table)
746        expression.set("tables", None)
747
748        if isinstance(table, exp.Table):
749            table_alias = table.args.get("alias")
750            if table_alias:
751                table_alias.pop()
752                expression = t.cast(exp.Delete, expression.transform(unqualify_columns))
753
754        return super().delete_sql(expression)
755
756    def jsonextract_sql(self, expression: exp.JSONExtract) -> str:
757        is_json_extract = self.dialect.settings.get("variant_extract_is_json_extract", True)
758
759        # Generate JSON_EXTRACT unless the user has configured that a Snowflake / Databricks
760        # VARIANT extract (e.g. col:x.y) should map to dot notation (i.e ROW access) in Presto/Trino
761        if not expression.args.get("variant_extract") or is_json_extract:
762            return self.func(
763                "JSON_EXTRACT", expression.this, expression.expression, *expression.expressions
764            )
765
766        this = self.sql(expression, "this")
767
768        # Convert the JSONPath extraction `JSON_EXTRACT(col, '$.x.y) to a ROW access col.x.y
769        segments = []
770        for path_key in expression.expression.expressions[1:]:
771            if not isinstance(path_key, exp.JSONPathKey):
772                # Cannot transpile subscripts, wildcards etc to dot notation
773                self.unsupported(f"Cannot transpile JSONPath segment '{path_key}' to ROW access")
774                continue
775            key = path_key.this
776            if not exp.SAFE_IDENTIFIER_RE.match(key):
777                key = f'"{key}"'
778            segments.append(f".{key}")
779
780        expr = "".join(segments)
781
782        return f"{this}{expr}"
783
784    def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
785        return self.func(
786            "ARRAY_JOIN",
787            self.func("ARRAY_AGG", expression.this),
788            expression.args.get("separator"),
789        )
790
791    def execute_sql(self, expression: exp.Execute) -> str:
792        self._warn_unsupported_arg(expression, "return_status")
793        using = self.expressions(expression, flat=True)
794        using = f" USING {using}" if using else ""
795        return f"EXECUTE {self.sql(expression, 'this')}{using}"

Generator converts a given syntax tree to the corresponding SQL string.

Arguments:
  • pretty: Whether to format the produced SQL string. Default: False.
  • identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True: Always quote except for specials cases. 'safe': Only quote identifiers that are case insensitive.
  • normalize: Whether to normalize identifiers to lowercase. Default: False.
  • pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
  • indent: The indentation size in a formatted string. For example, this affects the indentation of subqueries and filters under a WHERE clause. Default: 2.
  • normalize_functions: How to normalize function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
  • unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
  • max_unsupported: 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: Whether the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. 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 to preserve comments in the output SQL code. Default: True
DAYOFWEEK_ZERO_BASED = True
SELECT_KINDS = ()
SUPPORTS_EXECUTE_IMMEDIATE = False
SUPPORTS_DECODE_CASE = False
SUPPORTS_MULTI_ARG_CHR = False
SUPPORTS_TEMPORAL_PRECISION = False
SUPPORTS_LEFT_JOIN_UNNEST = False
AFTER_HAVING_MODIFIER_TRANSFORMS = {'windows': <function <lambda>>, 'qualify': <function <lambda>>}
INTERVAL_ALLOWS_PLURAL_FORM = False
JOIN_HINTS = False
CAST_TO_INT_ROUNDS = True
TABLE_HINTS = False
QUERY_HINTS = False
IS_BOOL_ALLOWED = False
TZ_TO_WITH_TIME_ZONE = True
NVL2_SUPPORTED = False
STRUCT_DELIMITER = ('(', ')')
LIMIT_ONLY_LITERALS = True
SUPPORTS_SINGLE_ARG_CONCAT = False
LIKE_PROPERTY_INSIDE_SCHEMA = True
MULTI_ARG_DISTINCT = False
SUPPORTS_TO_NUMBER = False
HEX_FUNC = 'TO_HEX'
PARSE_JSON_NAME: str | None = 'JSON_PARSE'
PAD_FILL_PATTERN_IS_REQUIRED = True
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
SUPPORTS_MEDIAN = False
ARRAY_SIZE_NAME = 'CARDINALITY'
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.properties.AggregateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AlgorithmProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApiProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.AutoIncrementProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BackupProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BlockCompressionProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ChecksumProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CollateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.query.Cluster'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusteredByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusterProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistributedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DuplicateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DataBlocksizeProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DataDeletionProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DefinerProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DictRange'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EncodeProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.EngineProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.FallbackProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.FreespaceProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.HeapProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.HybridProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InteractiveProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.IsolatedLoadingProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.JournalProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LikeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LocationProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.LockProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockingProperty'>: <PropertiesLocation.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.properties.LogProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MergeBlockRatioProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.ModuleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OnProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OptionsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.query.Order'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.PartitionedOfProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PhysicalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.constraints.PrimaryKey'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Property'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.RefreshTriggerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RollupProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowFormatProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatDelimitedProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatSerdeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SampleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SecureProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SerdeProperties'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.Set'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SetProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SharingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.SequenceProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.TriggerProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageHandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.StrictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Tags'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.TableSpaceProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.TransientProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.MergeTreeTTL'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.UsingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithDataProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSystemVersioningProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>}
TYPE_MAPPING = {<DType.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <DType.NCHAR: 'NCHAR'>: 'CHAR', <DType.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <DType.LONGTEXT: 'LONGTEXT'>: 'TEXT', <DType.TINYTEXT: 'TINYTEXT'>: 'TEXT', <DType.BLOB: 'BLOB'>: 'VARBINARY', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <DType.LONGBLOB: 'LONGBLOB'>: 'BLOB', <DType.TINYBLOB: 'TINYBLOB'>: 'BLOB', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP', <DType.BINARY: 'BINARY'>: 'VARBINARY', <DType.BIT: 'BIT'>: 'BOOLEAN', <DType.DATETIME: 'DATETIME'>: 'TIMESTAMP', <DType.DATETIME64: 'DATETIME64'>: 'TIMESTAMP', <DType.FLOAT: 'FLOAT'>: 'REAL', <DType.HLLSKETCH: 'HLLSKETCH'>: 'HYPERLOGLOG', <DType.INT: 'INT'>: 'INTEGER', <DType.STRUCT: 'STRUCT'>: 'ROW', <DType.TEXT: 'TEXT'>: 'VARCHAR', <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'TIMESTAMP', <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>: 'TIMESTAMP', <DType.TIMETZ: 'TIMETZ'>: 'TIME'}
TRANSFORMS = {<class 'sqlglot.expressions.query.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.core.Adjacent'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainedBy'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.AssumeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.BinaryColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApiProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.EndStatement'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HybridProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsTopKey'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.aggregate.AnyValue'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ApproxQuantile'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.ArgMax'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ArgMin'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.Array'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.array.ArrayAny'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArrayConcat'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArrayContains'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArraySort'>: <function _array_sort_sql>, <class 'sqlglot.expressions.array.ArrayToString'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ArrayUniqueAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArraySlice'>: <function array_slice_to_slice_sql>, <class 'sqlglot.expressions.core.AtTimeZone'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseAnd'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.core.BitwiseLeftShift'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseNot'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.core.BitwiseOr'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.core.BitwiseRightShift'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseXor'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.functions.Cast'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.CurrentTime'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.CurrentTimestamp'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentUser'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DateAdd'>: <function _date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DateDiff'>: <function _date_diff_sql>, <class 'sqlglot.expressions.temporal.DatetimeDiff'>: <function _date_diff_sql>, <class 'sqlglot.expressions.temporal.TimestampDiff'>: <function _date_diff_sql>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.temporal.DateToDi'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DateSub'>: <function _date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DayOfWeekIso'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Decode'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DiToDate'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.string.Encode'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.First'>: <function _first_last_sql>, <class 'sqlglot.expressions.temporal.FromISO8601Date'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.FromISO8601Timestamp'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.FromTimeZone'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.array.GenerateSeries'>: <function sequence_sql>, <class 'sqlglot.expressions.temporal.GenerateDateArray'>: <function sequence_sql>, <class 'sqlglot.expressions.functions.If'>: <function if_sql.<locals>._if_sql>, <class 'sqlglot.expressions.core.ILike'>: <function no_ilike_sql>, <class 'sqlglot.expressions.string.Initcap'>: <function _initcap_sql>, <class 'sqlglot.expressions.aggregate.Last'>: <function _first_last_sql>, <class 'sqlglot.expressions.temporal.LastDay'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.query.Lateral'>: <function _explode_to_unnest_sql>, <class 'sqlglot.expressions.string.Left'>: <function left_to_substring_sql>, <class 'sqlglot.expressions.string.Levenshtein'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalAnd'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalOr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.Pivot'>: <function no_pivot_sql>, <class 'sqlglot.expressions.aggregate.Quantile'>: <function _quantile_sql>, <class 'sqlglot.expressions.string.RegexpExtract'>: <function regexp_extract_sql>, <class 'sqlglot.expressions.string.RegexpExtractAll'>: <function regexp_extract_sql>, <class 'sqlglot.expressions.string.Right'>: <function right_to_substring_sql>, <class 'sqlglot.expressions.query.Schema'>: <function _schema_sql>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.query.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.StrPosition'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.StrToDate'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.string.StrToMap'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.StrToTime'>: <function _str_to_time_sql>, <class 'sqlglot.expressions.array.StructExtract'>: <function struct_extract_sql>, <class 'sqlglot.expressions.query.Table'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.Timestamp'>: <function no_timestamp_sql>, <class 'sqlglot.expressions.temporal.TimestampAdd'>: <function _date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TimestampTrunc'>: <function timestamptrunc_sql.<locals>._timestamptrunc_sql>, <class 'sqlglot.expressions.temporal.TimeStrToDate'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.temporal.TimeStrToTime'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.temporal.TimeStrToUnix'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimeToUnix'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.ToChar'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.functions.TryCast'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.TsOrDiToDi'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsAdd'>: <function _ts_or_ds_add_sql>, <class 'sqlglot.expressions.temporal.TsOrDsDiff'>: <function _ts_or_ds_diff_sql>, <class 'sqlglot.expressions.temporal.TsOrDsToDate'>: <function _ts_or_ds_to_date_sql>, <class 'sqlglot.expressions.string.Unhex'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.UnixToStr'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.UnixToTime'>: <function _unix_to_time_sql>, <class 'sqlglot.expressions.temporal.UnixToTimeStr'>: <function PrestoGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.VariancePop'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.With'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.core.WithinGroup'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.math.Trunc'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.Xor'>: <function bool_xor_sql>, <class 'sqlglot.expressions.string.MD5Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.SHA'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.SHA1Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.SHA2Digest'>: <function _sha2_digest_sql>, <class 'sqlglot.expressions.string.Substring'>: <function rename_func.<locals>.<lambda>>}
RESERVED_KEYWORDS = {'for', 'cast', 'execute', 'then', 'true', 'union', 'on', 'like', 'and', 'extract', 'alter', 'where', 'prepare', 'else', 'delete', 'right', 'case', 'full', 'using', 'values', 'by', 'escape', 'or', 'between', 'when', 'describe', 'exists', 'from', 'having', 'constraint', 'group', 'in', 'intersect', 'deallocate', 'except', 'join', 'into', 'is', 'outer', 'current_time', 'end', 'false', 'inner', 'table', 'not', 'create', 'left', 'as', 'distinct', 'cross', 'drop', 'current_timestamp', 'natural', 'select', 'order', 'null', 'with', 'insert'}
def datatype_sql(self, expression: sqlglot.expressions.datatypes.DataType) -> str:
518    def datatype_sql(self, expression: exp.DataType) -> str:
519        if not self.SUPPORTS_TEMPORAL_PRECISION and expression.this in exp.DataType.TEMPORAL_TYPES:
520            if expression.expressions and expression.expressions[0].name != "3":
521                self.unsupported("Presto only supports millisecond precision for temporal types")
522            expression.set("expressions", None)
523        return super().datatype_sql(expression)
def exists_sql(self, expression: sqlglot.expressions.functions.Exists) -> str:
525    def exists_sql(self, expression: exp.Exists) -> str:
526        if expression.expression:
527            return self.func("ANY_MATCH", expression.this, expression.expression)
528
529        return super().exists_sql(expression)
def extract_sql(self, expression: sqlglot.expressions.temporal.Extract) -> str:
535    def extract_sql(self, expression: exp.Extract) -> str:
536        date_part = expression.name
537
538        if not date_part.startswith("EPOCH"):
539            return super().extract_sql(expression)
540
541        if date_part == "EPOCH_MILLISECOND":
542            scale = 10**3
543        elif date_part == "EPOCH_MICROSECOND":
544            scale = 10**6
545        elif date_part == "EPOCH_NANOSECOND":
546            scale = 10**9
547        else:
548            scale = None
549
550        value = expression.expression
551
552        ts = exp.cast(value, to=exp.DType.TIMESTAMP.into_expr())
553        to_unix: exp.Expr = exp.TimeToUnix(this=ts)
554
555        if scale:
556            to_unix = exp.Mul(this=to_unix, expression=exp.Literal.number(scale))
557
558        return self.sql(to_unix)
def addmonths_sql(self, expression: sqlglot.expressions.temporal.AddMonths) -> str:
560    def addmonths_sql(self, expression: exp.AddMonths) -> str:
561        this = expression.this
562        if this.is_string or this.is_type(*exp.DataType.TEXT_TYPES):
563            this = exp.TimeStrToTime(this=this)
564        if expression.is_type(exp.DType.DATE) and not this.is_type(exp.DType.DATE):
565            this = exp.cast(this, exp.DType.DATE)
566
567        added = exp.DateAdd(this=this, expression=expression.expression, unit=exp.var("MONTH"))
568
569        if not expression.args.get("preserve_end_of_month"):
570            return self.sql(added)
571
572        # Shift the original value by whole days to preserve its time of day.
573        eom_shift = exp.DateDiff(
574            this=exp.LastDay(this=added.copy()),
575            expression=exp.cast(this, exp.DType.DATE),
576            unit=exp.var("DAY"),
577        )
578        to_eom = exp.DateAdd(this=this.copy(), expression=eom_shift, unit=exp.var("DAY"))
579        is_eom = exp.Day(this=this.copy()).eq(exp.Day(this=exp.LastDay(this=this.copy())))
580
581        return self.sql(exp.case().when(is_eom, to_eom).else_(added))
def jsonformat_sql(self, expression: sqlglot.expressions.json.JSONFormat) -> str:
583    def jsonformat_sql(self, expression: exp.JSONFormat) -> str:
584        this = expression.this
585        is_json = expression.args.get("is_json")
586
587        if this and not (is_json or this.type):
588            from sqlglot.optimizer.annotate_types import annotate_types
589
590            this = annotate_types(this, dialect=self.dialect)
591
592        if not (is_json or this.is_type(exp.DType.JSON)):
593            this.replace(exp.cast(this, exp.DType.JSON))
594
595        return self.function_fallback_sql(expression)
def md5_sql(self, expression: sqlglot.expressions.string.MD5) -> str:
597    def md5_sql(self, expression: exp.MD5) -> str:
598        this = expression.this
599
600        if not this.type:
601            from sqlglot.optimizer.annotate_types import annotate_types
602
603            this = annotate_types(this, dialect=self.dialect)
604
605        if this.is_type(*exp.DataType.TEXT_TYPES):
606            this = exp.Encode(this=this, charset=exp.Literal.string("utf-8"))
607
608        return self.func("LOWER", self.func("TO_HEX", self.func("MD5", self.sql(this))))
def sha2_sql(self, expression: sqlglot.expressions.string.SHA2) -> str:
610    def sha2_sql(self, expression: exp.SHA2) -> str:
611        length = expression.text("length") or "256"
612        if length not in ("256", "512"):
613            self.unsupported(f"SHA{length} is not supported in Presto")
614
615        this = expression.this
616
617        if this.is_type(*exp.DataType.TEXT_TYPES):
618            this = exp.Encode(this=this, charset=exp.Literal.string("utf-8"))
619
620        return self.func("LOWER", self.func("TO_HEX", self.func(f"SHA{length}", self.sql(this))))
def timetostr_sql(self, expression: sqlglot.expressions.temporal.TimeToStr) -> str:
622    def timetostr_sql(self, expression: exp.TimeToStr) -> str:
623        if expression.args.get("joda"):
624            from sqlglot.dialects.presto import Presto
625
626            return self.func(
627                "FORMAT_DATETIME",
628                expression.this,
629                self.format_time(
630                    expression, Presto.INVERSE_JODA_TIME_MAPPING, Presto.INVERSE_JODA_TIME_TRIE
631                ),
632            )
633
634        return self.func("DATE_FORMAT", expression.this, self.format_time(expression))
def strtounix_sql(self, expression: sqlglot.expressions.temporal.StrToUnix) -> str:
636    def strtounix_sql(self, expression: exp.StrToUnix) -> str:
637        # Since `TO_UNIXTIME` requires a `TIMESTAMP`, we need to parse the argument into one.
638        # To do this, we first try to `DATE_PARSE` it, but since this can fail when there's a
639        # timezone involved, we wrap it in a `TRY` call and use `PARSE_DATETIME` as a fallback,
640        # which seems to be using the same time mapping as Hive, as per:
641        # https://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html
642        this = expression.this
643        value_as_text = exp.cast(this, exp.DType.TEXT)
644        value_as_timestamp = exp.cast(this, exp.DType.TIMESTAMP) if this.is_string else this
645
646        parse_without_tz = self.func("DATE_PARSE", value_as_text, self.format_time(expression))
647
648        formatted_value = self.func("DATE_FORMAT", value_as_timestamp, self.format_time(expression))
649        parse_with_tz = self.func(
650            "PARSE_DATETIME",
651            formatted_value,
652            self.format_time(expression, Hive.INVERSE_TIME_MAPPING, Hive.INVERSE_TIME_TRIE),
653        )
654        coalesced = self.func("COALESCE", self.func("TRY", parse_without_tz), parse_with_tz)
655        return self.func("TO_UNIXTIME", coalesced)
def bracket_sql(self, expression: sqlglot.expressions.core.Bracket) -> str:
657    def bracket_sql(self, expression: exp.Bracket) -> str:
658        if expression.args.get("safe"):
659            return bracket_to_element_at_sql(self, expression)
660        return super().bracket_sql(expression)
def struct_sql(self, expression: sqlglot.expressions.array.Struct) -> str:
662    def struct_sql(self, expression: exp.Struct) -> str:
663        if not expression.type:
664            from sqlglot.optimizer.annotate_types import annotate_types
665
666            annotate_types(expression, dialect=self.dialect)
667
668        values: list[str] = []
669        schema: list[str] = []
670        unknown_type = False
671
672        for e in expression.expressions:
673            if isinstance(e, exp.PropertyEQ):
674                if e.type and e.type.is_type(exp.DType.UNKNOWN):
675                    unknown_type = True
676                else:
677                    schema.append(f"{self.sql(e, 'this')} {self.sql(e.type)}")
678                values.append(self.sql(e, "expression"))
679            else:
680                values.append(self.sql(e))
681
682        size = len(expression.expressions)
683
684        if not size or len(schema) != size:
685            if unknown_type:
686                self.unsupported(
687                    "Cannot convert untyped key-value definitions (try annotate_types)."
688                )
689            return self.func("ROW", *values)
690        return f"CAST(ROW({', '.join(values)}) AS ROW({', '.join(schema)}))"
def interval_sql(self, expression: sqlglot.expressions.datatypes.Interval) -> str:
692    def interval_sql(self, expression: exp.Interval) -> str:
693        this = expression.this
694        if this and expression.text("unit").upper().startswith("WEEK"):
695            if not this.is_string:
696                return f"({self.sql(this)} * INTERVAL '7' DAY)"
697            if is_float(this.name):
698                return f"({this.name} * INTERVAL '7' DAY)"
699        return super().interval_sql(expression)
def show_sql(self, expression: sqlglot.expressions.ddl.Show) -> str:
701    def show_sql(self, expression: exp.Show) -> str:
702        target = self.sql(expression, "target")
703        target = f" FOR {target}" if target else ""
704        from_ = self.sql(expression, "from_")
705        from_ = f" FROM {from_}" if from_ else ""
706        like = self.sql(expression, "like")
707        like = f" LIKE {like}" if like else ""
708        return f"SHOW {expression.name}{target}{from_}{like}"
def transaction_sql(self, expression: sqlglot.expressions.ddl.Transaction) -> str:
710    def transaction_sql(self, expression: exp.Transaction) -> str:
711        modes = expression.args.get("modes")
712        modes = f" {', '.join(modes)}" if modes else ""
713        return f"START TRANSACTION{modes}"
def offset_limit_modifiers( self, expression: sqlglot.expressions.core.Expr, fetch: bool, limit: sqlglot.expressions.query.Fetch | sqlglot.expressions.query.Limit | None) -> list[str]:
715    def offset_limit_modifiers(
716        self, expression: exp.Expr, fetch: bool, limit: exp.Fetch | exp.Limit | None
717    ) -> list[str]:
718        return [
719            self.sql(expression, "offset"),
720            self.sql(limit),
721        ]
def create_sql(self, expression: sqlglot.expressions.ddl.Create) -> str:
723    def create_sql(self, expression: exp.Create) -> str:
724        """
725        Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression),
726        so we need to remove them
727        """
728        kind = expression.args["kind"]
729        schema = expression.this
730        if kind == "VIEW" and schema.expressions:
731            expression.this.set("expressions", None)
732        return super().create_sql(expression)

Presto doesn't support CREATE VIEW with expressions (ex: CREATE VIEW x (cola) then (cola) is the expression), so we need to remove them

def delete_sql(self, expression: sqlglot.expressions.dml.Delete) -> str:
734    def delete_sql(self, expression: exp.Delete) -> str:
735        """
736        Presto only supports DELETE FROM for a single table without an alias, so we need
737        to remove the unnecessary parts. If the original DELETE statement contains more
738        than one table to be deleted, we can't safely map it 1-1 to a Presto statement.
739        """
740        tables = expression.args.get("tables") or [expression.this]
741        if len(tables) > 1:
742            return super().delete_sql(expression)
743
744        table = tables[0]
745        expression.set("this", table)
746        expression.set("tables", None)
747
748        if isinstance(table, exp.Table):
749            table_alias = table.args.get("alias")
750            if table_alias:
751                table_alias.pop()
752                expression = t.cast(exp.Delete, expression.transform(unqualify_columns))
753
754        return super().delete_sql(expression)

Presto only supports DELETE FROM for a single table without an alias, so we need to remove the unnecessary parts. If the original DELETE statement contains more than one table to be deleted, we can't safely map it 1-1 to a Presto statement.

def jsonextract_sql(self, expression: sqlglot.expressions.json.JSONExtract) -> str:
756    def jsonextract_sql(self, expression: exp.JSONExtract) -> str:
757        is_json_extract = self.dialect.settings.get("variant_extract_is_json_extract", True)
758
759        # Generate JSON_EXTRACT unless the user has configured that a Snowflake / Databricks
760        # VARIANT extract (e.g. col:x.y) should map to dot notation (i.e ROW access) in Presto/Trino
761        if not expression.args.get("variant_extract") or is_json_extract:
762            return self.func(
763                "JSON_EXTRACT", expression.this, expression.expression, *expression.expressions
764            )
765
766        this = self.sql(expression, "this")
767
768        # Convert the JSONPath extraction `JSON_EXTRACT(col, '$.x.y) to a ROW access col.x.y
769        segments = []
770        for path_key in expression.expression.expressions[1:]:
771            if not isinstance(path_key, exp.JSONPathKey):
772                # Cannot transpile subscripts, wildcards etc to dot notation
773                self.unsupported(f"Cannot transpile JSONPath segment '{path_key}' to ROW access")
774                continue
775            key = path_key.this
776            if not exp.SAFE_IDENTIFIER_RE.match(key):
777                key = f'"{key}"'
778            segments.append(f".{key}")
779
780        expr = "".join(segments)
781
782        return f"{this}{expr}"
def groupconcat_sql(self, expression: sqlglot.expressions.aggregate.GroupConcat) -> str:
784    def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
785        return self.func(
786            "ARRAY_JOIN",
787            self.func("ARRAY_AGG", expression.this),
788            expression.args.get("separator"),
789        )
def execute_sql(self, expression: sqlglot.expressions.ddl.Execute) -> str:
791    def execute_sql(self, expression: exp.Execute) -> str:
792        self._warn_unsupported_arg(expression, "return_status")
793        using = self.expressions(expression, flat=True)
794        using = f" USING {using}" if using else ""
795        return f"EXECUTE {self.sql(expression, 'this')}{using}"
Inherited Members
sqlglot.generator.Generator
Generator
NULL_ORDERING_SUPPORTED
WINDOW_FUNCS_WITH_NULL_ORDERING
WINDOW_FUNCS_REQUIRING_ORDER
IGNORE_NULLS_IN_FUNC
IGNORE_NULLS_BEFORE_ORDER
LOCKING_READS_SUPPORTED
WRAP_DERIVED_VALUES
CREATE_FUNCTION_RETURN_AS
MATCHED_BY_SOURCE
SUPPORTS_MERGE_WHERE
MERGE_SCHEMA_EVOLUTION_MIN_VERSION
MERGE_ALL_BY_NAME
SINGLE_STRING_INTERVAL
AUTO_REFRESH_BARE_INTERVALS
LIMIT_FETCH
RENAME_TABLE_WITH_DB
GROUPINGS_SEP
SUPPORTS_GROUPING_SETS_AS_SUFFIX
INDEX_ON
INOUT_SEPARATOR
DIRECTED_JOINS
SUPPORTS_NEAREST_JOIN
SUPPORTS_MATCH_CONDITION
MATCH_CONDITION_IN_ON
QUERY_HINT_SEP
SAFE_INT_DIVISION
INT_DIV_OPERATOR
DUPLICATE_KEY_UPDATE_WITH_SET
LIMIT_IS_TOP
RETURNING_END
EXTRACT_ALLOWS_QUOTES
VALUES_AS_TABLE
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
ALTER_TABLE_ADD_COLUMNS_WRAPPED
UNNEST_WITH_ORDINALITY
SEMI_ANTI_JOIN_WITH_SIDE
COMPUTED_COLUMN_WITH_TYPE
SUPPORTS_TABLE_COPY
TABLESAMPLE_REQUIRES_PARENS
TABLESAMPLE_SIZE_IS_ROWS
TABLESAMPLE_KEYWORDS
TABLESAMPLE_WITH_METHOD
TABLESAMPLE_SEED_KEYWORD
HISTORICAL_DATA_POST_ALIAS
COLLATE_IS_FUNC
DATA_TYPE_SPECIFIERS_ALLOWED
ENSURE_BOOLS
CTE_RECURSIVE_KEYWORD_REQUIRED
LAST_DAY_SUPPORTS_DATE_PART
SUPPORTS_TABLE_ALIAS_COLUMNS
SUPPORTS_NAMED_CTE_COLUMNS
UNPIVOT_ALIASES_ARE_IDENTIFIERS
PIVOT_ALIAS_WITH_AS
JSON_KEY_VALUE_PAIR_SEP
INSERT_OVERWRITE
SUPPORTS_SELECT_INTO
SUPPORTS_OPTIMIZE
SUPPORTS_UNLOGGED_TABLES
SUPPORTS_CREATE_TABLE_LIKE
SUPPORTS_MODIFY_COLUMN
SUPPORTS_CHANGE_COLUMN
SUPPORTS_ALTER_COLUMN_NULLABILITY
SUPPORTS_ALTER_COLUMN_IF_EXISTS
JSON_TYPE_REQUIRED_FOR_EXTRACTION
SUPPORTS_NESTED_JSON_SELECT
JSON_PATH_BRACKETED_KEY_SUPPORTED
JSON_PATH_SINGLE_QUOTE_ESCAPE
JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
SUPPORTED_JSON_PATH_PARTS
CAN_IMPLEMENT_ARRAY_ANY
SUPPORTS_WINDOW_EXCLUDE
SET_OP_MODIFIERS
SET_OP_LIMITS
SET_OP_PARENTHESIZED_OPERANDS
COPY_PARAMS_ARE_WRAPPED
COPY_PARAMS_EQ_REQUIRED
COPY_HAS_INTO_KEYWORD
TRY_SUPPORTED
SUPPORTS_UESCAPE
UNICODE_SUBSTITUTE
STAR_EXCEPT
BYTE_STRING_FUNCTION
WITH_PROPERTIES_PREFIX
QUOTE_JSON_PATH
SUPPORTS_EXPLODING_PROJECTIONS
ARRAY_CONCAT_IS_VAR_LEN
SUPPORTS_CONVERT_TIMEZONE
SUPPORTS_UNIX_SECONDS
ALTER_SET_WRAPPED
NORMALIZE_EXTRACT_DATE_PARTS
DAYOFWEEK_NAME
VARIANCE_NAME
VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE
ALTER_SET_TYPE
ARRAY_SIZE_DIM_REQUIRED
SUPPORTS_BETWEEN_FLAGS
SUPPORTS_LIKE_QUANTIFIERS
MATCH_AGAINST_TABLE_PREFIX
SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD
DECLARE_DEFAULT_ASSIGNMENT
UPDATE_STATEMENT_SUPPORTS_FROM
STAR_EXCLUDE_REQUIRES_DERIVED_TABLE
SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY
UNSUPPORTED_TYPES
TYPE_PARAM_SETTINGS
TIME_PART_SINGULARS
TOKEN_MAPPING
PARAMETER_TOKEN
NAMED_PLACEHOLDER_TOKEN
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
WITH_SEPARATED_COMMENTS
EXCLUDE_COMMENTS
UNWRAPPED_INTERVAL_VALUES
PARAMETERIZABLE_TEXT_TYPES
EXPRESSIONS_WITHOUT_NESTED_CTES
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS
MOD_OPERATOR
BARE_OPERATORS
MOD_PAREN_PARENT_TYPES
ALTER_PARTITION_OPTIONS
SAFE_JSON_PATH_KEY_RE
SENTINEL_LINE_BREAK
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages
generate
preprocess
unsupported
sep
seg
sanitize_comment
maybe_comment
wrap
no_identify
normalize_func
indent
sql
uncache_sql
cache_sql
characterset_sql
column_parts
column_sql
pseudocolumn_sql
columnposition_sql
columndef_sql
columnconstraint_sql
computedcolumnconstraint_sql
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
generatedasrowcolumnconstraint_sql
periodforsystemtimeconstraint_sql
notnullcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
inoutcolumnconstraint_sql
createable_sql
sequenceproperties_sql
triggerproperties_sql
triggerreferencing_sql
triggerevent_sql
clone_sql
describe_sql
heredoc_sql
prepend_ctes
with_sql
cte_sql
tablealias_sql
bitstring_sql
hexstring_sql
bytestring_sql
unicodestring_sql
rawstring_sql
datatypeparam_sql
datatype_param_bound_limiter
directory_sql
drop_sql
set_operation
set_operations
fetch_sql
limitoptions_sql
filter_sql
per_sql
hint_sql
indexparameters_sql
index_sql
dynamicidentifier_sql
identifier_sql
hex_sql
lowerhex_sql
inputoutputformat_sql
national_sql
partition_sql
properties_sql
root_properties
properties
with_properties
locate_properties
property_name
property_sql
uuidproperty_sql
likeproperty_sql
fallbackproperty_sql
journalproperty_sql
freespaceproperty_sql
checksumproperty_sql
mergeblockratioproperty_sql
moduleproperty_sql
datablocksizeproperty_sql
blockcompressionproperty_sql
isolatedloadingproperty_sql
partitionboundspec_sql
partitionedofproperty_sql
lockingproperty_sql
lockingstatement_sql
withdataproperty_sql
withsystemversioningproperty_sql
insert_sql
introducer_sql
kill_sql
pseudotype_sql
objectidentifier_sql
onconflict_sql
returning_sql
rowformatdelimitedproperty_sql
withtablehint_sql
indextablehint_sql
historicaldata_sql
table_parts
table_sql
tableargument_sql
tablefromrows_sql
tablesample_sql
pivot_sql
version_sql
tuple_sql
update_sql
values_sql
var_sql
into_sql
from_sql
groupingsets_sql
rollup_sql
rollupindex_sql
rollupproperty_sql
cube_sql
group_sql
having_sql
connectto_sql
disconnect_sql
connect_sql
prior_sql
join_sql
nearest_sql
lambda_sql
lateral_op
lateral_sql
limit_sql
offset_sql
setitem_sql
set_sql
queryband_sql
pragma_sql
lock_sql
literal_sql
escape_str
loaddata_sql
null_sql
boolean_sql
booland_sql
boolor_sql
order_sql
withfill_sql
cluster_sql
clusterproperty_sql
distribute_sql
sort_sql
ordered_sql
matchrecognizemeasure_sql
matchrecognize_sql
query_modifiers
options_modifier
forclause_sql
queryoption_sql
after_limit_modifiers
select_sql
schema_sql
schema_columns_sql
star_sql
parameter_sql
sessionparameter_sql
placeholder_sql
subquery_sql
qualify_sql
unnest_sql
prewhere_sql
where_sql
window_sql
partition_by_sql
partitionbyexcluding_sql
windowspec_sql
withingroup_sql
between_sql
bracket_offset_expressions
all_sql
any_sql
case_sql
constraint_sql
nextvaluefor_sql
dayofweek_sql
extract_date_part
trim_sql
convert_concat_args
concat_sql
concatws_sql
check_sql
foreignkey_sql
primarykey_sql
timeserieskey_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
jsonpath_sql
json_path_part
format_sql
formatjson_sql
formatphrase_sql
teradataconversion_sql
teradatatitle_sql
teradatanamed_sql
jsonarray_sql
jsonarrayagg_sql
jsoncolumndef_sql
jsonschema_sql
jsontable_sql
openjsoncolumndef_sql
openjson_sql
in_sql
in_unnest_op
return_sql
reference_sql
anonymous_sql
paren_sql
pos_sql
neg_sql
not_sql
alias_sql
pivotalias_sql
aliases_sql
atindex_sql
attimezone_sql
fromtimezone_sql
fromiso8601date_sql
fromiso8601timestamp_sql
fromiso8601timestampnanos_sql
add_sql
and_sql
or_sql
xor_sql
connector_sql
bitwiseand_sql
bitwiseleftshift_sql
bitwisenot_sql
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
cast_sql
strtotime_sql
strtodate_sql
parsedatetime_sql
currentdate_sql
collate_sql
command_sql
optimize_sql
comment_sql
mergetreettlaction_sql
mergetreettl_sql
commit_sql
rollback_sql
altercolumn_sql
modifycolumn_sql
alterindex_sql
alterdiststyle_sql
altersortkey_sql
alterrename_sql
renamecolumn_sql
alterset_sql
alter_sql
altersession_sql
add_column_sql
droppartition_sql
dropprimarykey_sql
addconstraint_sql
replacecolumns_sql
addpartition_sql
distinct_sql
ignorenulls_sql
respectnulls_sql
havingmax_sql
intdiv_sql
dpipe_sql
nullif_zero_divisor
div_sql
safedivide_sql
overlaps_sql
distance_sql
distancend_sql
dot_sql
nestedjsonselect_sql
eq_sql
propertyeq_sql
escape_sql
glob_sql
gt_sql
gte_sql
is_sql
like_sql
ilike_sql
match_sql
similarto_sql
lt_sql
lte_sql
mod_sql
mul_sql
neq_sql
nullsafeeq_sql
nullsafeneq_sql
sub_sql
trycast_sql
jsoncast_sql
try_sql
log_sql
use_sql
binary
ceil_floor
function_fallback_sql
function_name
func
format_args
too_wide
format_time
expressions
op_expressions
naked_property
tag_sql
token_sql
userdefinedfunction_sql
macrooverloads_sql
macrooverload_sql
joinhint_sql
kwarg_sql
when_sql
whens_sql
merge_sql
tochar_sql
tonumber_sql
dictproperty_sql
dictrange_sql
dictsubproperty_sql
aggregatekeyproperty_sql
duplicatekeyproperty_sql
uniquekeyproperty_sql
distributedbyproperty_sql
oncluster_sql
clusteredbyproperty_sql
anyvalue_sql
querytransform_sql
indexconstraintoption_sql
checkcolumnconstraint_sql
indexcolumnconstraint_sql
nvl2_sql
nthvalue_sql
comprehension_sql
columnprefix_sql
opclass_sql
predict_sql
generateembedding_sql
generatetext_sql
generatetable_sql
generatebool_sql
generateint_sql
generatedouble_sql
mltranslate_sql
mlforecast_sql
aiforecast_sql
featuresattime_sql
vectorsearch_sql
forin_sql
refresh_sql
toarray_sql
tsordstotime_sql
tsordstotimestamp_sql
tsordstodatetime_sql
tsordstodate_sql
unixdate_sql
lastday_sql
dateadd_sql
arrayinsert_sql
arrayany_sql
partitionrange_sql
truncatetable_sql
convert_sql
copyparameter_sql
credentials_sql
copy_sql
semicolon_sql
datadeletionproperty_sql
maskingpolicycolumnconstraint_sql
gapfill_sql
scope_resolution
scoperesolution_sql
parsejson_sql
rand_sql
changes_sql
pad_sql
summarize_sql
explodinggenerateseries_sql
converttimezone_sql
json_sql
jsonvalue_sql
skipjsoncolumn_sql
conditionalinsert_sql
multitableinserts_sql
oncondition_sql
jsonextractquote_sql
jsonexists_sql
min_sql
max_sql
arrayagg_sql
timeslice_sql
slice_sql
apply_sql
grant_sql
revoke_sql
grantprivilege_sql
grantprincipal_sql
columns_sql
overlay_sql
todouble_sql
string_sql
median_sql
overflowtruncatebehavior_sql
unixseconds_sql
arraysort_sql
variance_sql
arraysize_sql
attach_sql
detach_sql
attachoption_sql
watermarkcolumnconstraint_sql
encodeproperty_sql
includeproperty_sql
xmlelement_sql
xmlkeyvalueoption_sql
partitionbyrangeproperty_sql
partitionbyrangepropertydynamic_sql
unpivotcolumns_sql
analyzesample_sql
analyzestatistics_sql
analyzehistogram_sql
analyzedelete_sql
analyzelistchainedrows_sql
analyzevalidate_sql
analyze_sql
xmltable_sql
xmlnamespace_sql
export_sql
declare_sql
declareitem_sql
recursivewithsearch_sql
parameterizedagg_sql
anonymousaggfunc_sql
combinedaggfunc_sql
combinedparameterizedagg_sql
install_sql
liststage_sql
get_put_sql
translatecharacters_sql
decodecase_sql
semanticview_sql
getextract_sql
datefromunixdate_sql
space_sql
buildproperty_sql
refreshtriggerproperty_sql
modelattribute_sql
directorystage_sql
uuid_sql
initcap_sql
localtime_sql
localtimestamp_sql
weekstart_name
weekstart_sql
datetrunc_sql
chr_sql
weightstring_sql
block_sql
functionspecification_sql
storedprocedure_sql
ifblock_sql
casestatement_sql
whileblock_sql
loopblock_sql
repeatblock_sql
leave_sql
iterate_sql
executesql_sql
executeimmediate_sql
altermodifysqlsecurity_sql
usingproperty_sql
renameindex_sql