sqlglot.dialects.presto API documentation

Edit on GitHub

# sqlglot.dialects.presto

View Source

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

class Presto(sqlglot.dialects.dialect.Dialect): View Source

    195class Presto(Dialect):
    196    index_offset = 1
    197    null_ordering = "nulls_are_last"
    198    time_format = MySQL.time_format  # type: ignore
    199    time_mapping = MySQL.time_mapping  # type: ignore
    200
    201    class Tokenizer(tokens.Tokenizer):
    202        KEYWORDS = {
    203            **tokens.Tokenizer.KEYWORDS,
    204            "START": TokenType.BEGIN,
    205            "ROW": TokenType.STRUCT,
    206        }
    207
    208    class Parser(parser.Parser):
    209        FUNCTIONS = {
    210            **parser.Parser.FUNCTIONS,  # type: ignore
    211            "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list,
    212            "APPROX_PERCENTILE": _approx_percentile,
    213            "CARDINALITY": exp.ArraySize.from_arg_list,
    214            "CONTAINS": exp.ArrayContains.from_arg_list,
    215            "DATE_ADD": lambda args: exp.DateAdd(
    216                this=seq_get(args, 2),
    217                expression=seq_get(args, 1),
    218                unit=seq_get(args, 0),
    219            ),
    220            "DATE_DIFF": lambda args: exp.DateDiff(
    221                this=seq_get(args, 2),
    222                expression=seq_get(args, 1),
    223                unit=seq_get(args, 0),
    224            ),
    225            "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"),
    226            "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"),
    227            "DATE_TRUNC": date_trunc_to_time,
    228            "FROM_HEX": exp.Unhex.from_arg_list,
    229            "FROM_UNIXTIME": _from_unixtime,
    230            "FROM_UTF8": lambda args: exp.Decode(
    231                this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8")
    232            ),
    233            "NOW": exp.CurrentTimestamp.from_arg_list,
    234            "SEQUENCE": exp.GenerateSeries.from_arg_list,
    235            "STRPOS": lambda args: exp.StrPosition(
    236                this=seq_get(args, 0),
    237                substr=seq_get(args, 1),
    238                instance=seq_get(args, 2),
    239            ),
    240            "TO_UNIXTIME": exp.TimeToUnix.from_arg_list,
    241            "TO_HEX": exp.Hex.from_arg_list,
    242            "TO_UTF8": lambda args: exp.Encode(
    243                this=seq_get(args, 0), charset=exp.Literal.string("utf-8")
    244            ),
    245        }
    246        FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy()
    247        FUNCTION_PARSERS.pop("TRIM")
    248
    249    class Generator(generator.Generator):
    250        INTERVAL_ALLOWS_PLURAL_FORM = False
    251        JOIN_HINTS = False
    252        TABLE_HINTS = False
    253        STRUCT_DELIMITER = ("(", ")")
    254
    255        PROPERTIES_LOCATION = {
    256            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
    257            exp.LocationProperty: exp.Properties.Location.UNSUPPORTED,
    258            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    259        }
    260
    261        TYPE_MAPPING = {
    262            **generator.Generator.TYPE_MAPPING,  # type: ignore
    263            exp.DataType.Type.INT: "INTEGER",
    264            exp.DataType.Type.FLOAT: "REAL",
    265            exp.DataType.Type.BINARY: "VARBINARY",
    266            exp.DataType.Type.TEXT: "VARCHAR",
    267            exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP",
    268            exp.DataType.Type.STRUCT: "ROW",
    269        }
    270
    271        TRANSFORMS = {
    272            **generator.Generator.TRANSFORMS,  # type: ignore
    273            exp.ApproxDistinct: _approx_distinct_sql,
    274            exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]",
    275            exp.ArrayConcat: rename_func("CONCAT"),
    276            exp.ArrayContains: rename_func("CONTAINS"),
    277            exp.ArraySize: rename_func("CARDINALITY"),
    278            exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
    279            exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
    280            exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})",
    281            exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
    282            exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
    283            exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
    284            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    285            exp.DataType: _datatype_sql,
    286            exp.DateAdd: lambda self, e: self.func(
    287                "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
    288            ),
    289            exp.DateDiff: lambda self, e: self.func(
    290                "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
    291            ),
    292            exp.DateStrToDate: lambda self, e: f"CAST(DATE_PARSE({self.sql(e, 'this')}, {Presto.date_format}) AS DATE)",
    293            exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.dateint_format}) AS INT)",
    294            exp.Decode: _decode_sql,
    295            exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.dateint_format}) AS DATE)",
    296            exp.Encode: _encode_sql,
    297            exp.GenerateSeries: _sequence_sql,
    298            exp.Group: transforms.preprocess([transforms.unalias_group]),
    299            exp.Hex: rename_func("TO_HEX"),
    300            exp.If: if_sql,
    301            exp.ILike: no_ilike_sql,
    302            exp.Initcap: _initcap_sql,
    303            exp.Lateral: _explode_to_unnest_sql,
    304            exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"),
    305            exp.LogicalOr: rename_func("BOOL_OR"),
    306            exp.LogicalAnd: rename_func("BOOL_AND"),
    307            exp.Quantile: _quantile_sql,
    308            exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"),
    309            exp.SafeDivide: no_safe_divide_sql,
    310            exp.Schema: _schema_sql,
    311            exp.Select: transforms.preprocess(
    312                [
    313                    transforms.eliminate_qualify,
    314                    transforms.eliminate_distinct_on,
    315                    transforms.explode_to_unnest,
    316                ]
    317            ),
    318            exp.SortArray: _no_sort_array,
    319            exp.StrPosition: rename_func("STRPOS"),
    320            exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)",
    321            exp.StrToTime: _str_to_time_sql,
    322            exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))",
    323            exp.StructExtract: struct_extract_sql,
    324            exp.TableFormatProperty: lambda self, e: f"TABLE_FORMAT='{e.name.upper()}'",
    325            exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'",
    326            exp.TimestampTrunc: timestamptrunc_sql,
    327            exp.TimeStrToDate: timestrtotime_sql,
    328            exp.TimeStrToTime: timestrtotime_sql,
    329            exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.time_format}))",
    330            exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})",
    331            exp.TimeToUnix: rename_func("TO_UNIXTIME"),
    332            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)",
    333            exp.TsOrDsAdd: _ts_or_ds_add_sql,
    334            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
    335            exp.Unhex: rename_func("FROM_HEX"),
    336            exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})",
    337            exp.UnixToTime: rename_func("FROM_UNIXTIME"),
    338            exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)",
    339            exp.VariancePop: rename_func("VAR_POP"),
    340        }
    341
    342        def interval_sql(self, expression: exp.Interval) -> str:
    343            unit = self.sql(expression, "unit")
    344            if expression.this and unit.lower().startswith("week"):
    345                return f"({expression.this.name} * INTERVAL '7' day)"
    346            return super().interval_sql(expression)
    347
    348        def transaction_sql(self, expression: exp.Transaction) -> str:
    349            modes = expression.args.get("modes")
    350            modes = f" {', '.join(modes)}" if modes else ""
    351            return f"START TRANSACTION{modes}"

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  get_or_raise
  format_time
  parse
  parse_into
  generate
  transpile
  tokenize
  parser
  generator

class Presto.Tokenizer(sqlglot.tokens.Tokenizer): View Source

    201    class Tokenizer(tokens.Tokenizer):
    202        KEYWORDS = {
    203            **tokens.Tokenizer.KEYWORDS,
    204            "START": TokenType.BEGIN,
    205            "ROW": TokenType.STRUCT,
    206        }

##### Inherited Members

sqlglot.tokens.Tokenizer
  reset
  tokenize

class Presto.Parser(sqlglot.parser.Parser): View Source

    208    class Parser(parser.Parser):
    209        FUNCTIONS = {
    210            **parser.Parser.FUNCTIONS,  # type: ignore
    211            "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list,
    212            "APPROX_PERCENTILE": _approx_percentile,
    213            "CARDINALITY": exp.ArraySize.from_arg_list,
    214            "CONTAINS": exp.ArrayContains.from_arg_list,
    215            "DATE_ADD": lambda args: exp.DateAdd(
    216                this=seq_get(args, 2),
    217                expression=seq_get(args, 1),
    218                unit=seq_get(args, 0),
    219            ),
    220            "DATE_DIFF": lambda args: exp.DateDiff(
    221                this=seq_get(args, 2),
    222                expression=seq_get(args, 1),
    223                unit=seq_get(args, 0),
    224            ),
    225            "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"),
    226            "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"),
    227            "DATE_TRUNC": date_trunc_to_time,
    228            "FROM_HEX": exp.Unhex.from_arg_list,
    229            "FROM_UNIXTIME": _from_unixtime,
    230            "FROM_UTF8": lambda args: exp.Decode(
    231                this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8")
    232            ),
    233            "NOW": exp.CurrentTimestamp.from_arg_list,
    234            "SEQUENCE": exp.GenerateSeries.from_arg_list,
    235            "STRPOS": lambda args: exp.StrPosition(
    236                this=seq_get(args, 0),
    237                substr=seq_get(args, 1),
    238                instance=seq_get(args, 2),
    239            ),
    240            "TO_UNIXTIME": exp.TimeToUnix.from_arg_list,
    241            "TO_HEX": exp.Hex.from_arg_list,
    242            "TO_UTF8": lambda args: exp.Encode(
    243                this=seq_get(args, 0), charset=exp.Literal.string("utf-8")
    244            ),
    245        }
    246        FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy()
    247        FUNCTION_PARSERS.pop("TRIM")

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

###### Arguments:

- error_level: the desired error level. Default: ErrorLevel.RAISE
- error_message_context: determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 50.
- index_offset: Index offset for arrays eg ARRAY[0] vs ARRAY[1] as the head of a list. Default: 0
- alias_post_tablesample: If the table alias comes after tablesample. Default: False
- max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
- null_ordering: Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"

##### Inherited Members

sqlglot.parser.Parser
  Parser
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression

class Presto.Generator(sqlglot.generator.Generator): View Source

    249    class Generator(generator.Generator):
    250        INTERVAL_ALLOWS_PLURAL_FORM = False
    251        JOIN_HINTS = False
    252        TABLE_HINTS = False
    253        STRUCT_DELIMITER = ("(", ")")
    254
    255        PROPERTIES_LOCATION = {
    256            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
    257            exp.LocationProperty: exp.Properties.Location.UNSUPPORTED,
    258            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    259        }
    260
    261        TYPE_MAPPING = {
    262            **generator.Generator.TYPE_MAPPING,  # type: ignore
    263            exp.DataType.Type.INT: "INTEGER",
    264            exp.DataType.Type.FLOAT: "REAL",
    265            exp.DataType.Type.BINARY: "VARBINARY",
    266            exp.DataType.Type.TEXT: "VARCHAR",
    267            exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP",
    268            exp.DataType.Type.STRUCT: "ROW",
    269        }
    270
    271        TRANSFORMS = {
    272            **generator.Generator.TRANSFORMS,  # type: ignore
    273            exp.ApproxDistinct: _approx_distinct_sql,
    274            exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]",
    275            exp.ArrayConcat: rename_func("CONCAT"),
    276            exp.ArrayContains: rename_func("CONTAINS"),
    277            exp.ArraySize: rename_func("CARDINALITY"),
    278            exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
    279            exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
    280            exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})",
    281            exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
    282            exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
    283            exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})",
    284            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    285            exp.DataType: _datatype_sql,
    286            exp.DateAdd: lambda self, e: self.func(
    287                "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
    288            ),
    289            exp.DateDiff: lambda self, e: self.func(
    290                "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
    291            ),
    292            exp.DateStrToDate: lambda self, e: f"CAST(DATE_PARSE({self.sql(e, 'this')}, {Presto.date_format}) AS DATE)",
    293            exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.dateint_format}) AS INT)",
    294            exp.Decode: _decode_sql,
    295            exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.dateint_format}) AS DATE)",
    296            exp.Encode: _encode_sql,
    297            exp.GenerateSeries: _sequence_sql,
    298            exp.Group: transforms.preprocess([transforms.unalias_group]),
    299            exp.Hex: rename_func("TO_HEX"),
    300            exp.If: if_sql,
    301            exp.ILike: no_ilike_sql,
    302            exp.Initcap: _initcap_sql,
    303            exp.Lateral: _explode_to_unnest_sql,
    304            exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"),
    305            exp.LogicalOr: rename_func("BOOL_OR"),
    306            exp.LogicalAnd: rename_func("BOOL_AND"),
    307            exp.Quantile: _quantile_sql,
    308            exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"),
    309            exp.SafeDivide: no_safe_divide_sql,
    310            exp.Schema: _schema_sql,
    311            exp.Select: transforms.preprocess(
    312                [
    313                    transforms.eliminate_qualify,
    314                    transforms.eliminate_distinct_on,
    315                    transforms.explode_to_unnest,
    316                ]
    317            ),
    318            exp.SortArray: _no_sort_array,
    319            exp.StrPosition: rename_func("STRPOS"),
    320            exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)",
    321            exp.StrToTime: _str_to_time_sql,
    322            exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))",
    323            exp.StructExtract: struct_extract_sql,
    324            exp.TableFormatProperty: lambda self, e: f"TABLE_FORMAT='{e.name.upper()}'",
    325            exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'",
    326            exp.TimestampTrunc: timestamptrunc_sql,
    327            exp.TimeStrToDate: timestrtotime_sql,
    328            exp.TimeStrToTime: timestrtotime_sql,
    329            exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.time_format}))",
    330            exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})",
    331            exp.TimeToUnix: rename_func("TO_UNIXTIME"),
    332            exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)",
    333            exp.TsOrDsAdd: _ts_or_ds_add_sql,
    334            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
    335            exp.Unhex: rename_func("FROM_HEX"),
    336            exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})",
    337            exp.UnixToTime: rename_func("FROM_UNIXTIME"),
    338            exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)",
    339            exp.VariancePop: rename_func("VAR_POP"),
    340        }
    341
    342        def interval_sql(self, expression: exp.Interval) -> str:
    343            unit = self.sql(expression, "unit")
    344            if expression.this and unit.lower().startswith("week"):
    345                return f"({expression.this.name} * INTERVAL '7' day)"
    346            return super().interval_sql(expression)
    347
    348        def transaction_sql(self, expression: exp.Transaction) -> str:
    349            modes = expression.args.get("modes")
    350            modes = f" {', '.join(modes)}" if modes else ""
    351            return f"START TRANSACTION{modes}"

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

###### Arguments:

- time_mapping (dict): the dictionary of custom time mappings in which the key represents a python time format and the output the target time format
- time_trie (trie): a trie of the time_mapping keys
- pretty (bool): if set to True the returned string will be formatted. Default: False.
- quote_start (str): specifies which starting character to use to delimit quotes. Default: '.
- quote_end (str): specifies which ending character to use to delimit quotes. Default: '.
- identifier_start (str): specifies which starting character to use to delimit identifiers. Default: ".
- identifier_end (str): specifies which ending character to use to delimit identifiers. Default: ".
- identify (bool | str): 'always': always quote, 'safe': quote identifiers if they don't contain an upcase, True defaults to always.
- normalize (bool): if set to True all identifiers will lower cased
- string_escape (str): specifies a string escape character. Default: '.
- identifier_escape (str): specifies an identifier escape character. Default: ".
- pad (int): determines padding in a formatted string. Default: 2.
- indent (int): determines the size of indentation in a formatted string. Default: 4.
- unnest_column_only (bool): if true unnest table aliases are considered only as column aliases
- normalize_functions (str): normalize function names, "upper", "lower", or None Default: "upper"
- alias_post_tablesample (bool): if the table alias comes after tablesample Default: False
- unsupported_level (ErrorLevel): determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- null_ordering (str): Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
- max_unsupported (int): Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma (bool): if the the comma is leading or trailing in select statements Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether or not to preserve comments in the output SQL code. Default: True

def interval_sql(self, expression: sqlglot.expressions.Interval) -> str: View Source

    342        def interval_sql(self, expression: exp.Interval) -> str:
    343            unit = self.sql(expression, "unit")
    344            if expression.this and unit.lower().startswith("week"):
    345                return f"({expression.this.name} * INTERVAL '7' day)"
    346            return super().interval_sql(expression)

def transaction_sql(self, expression: sqlglot.expressions.Transaction) -> str: View Source

    348        def transaction_sql(self, expression: exp.Transaction) -> str:
    349            modes = expression.args.get("modes")
    350            modes = f" {', '.join(modes)}" if modes else ""
    351            return f"START TRANSACTION{modes}"

##### Inherited Members

sqlglot.generator.Generator
  Generator
  generate
  unsupported
  sep
  seg
  pad_comment
  maybe_comment
  wrap
  no_identify
  normalize_func
  indent
  sql
  uncache_sql
  cache_sql
  characterset_sql
  column_sql
  columnposition_sql
  columndef_sql
  columnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  create_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  bytestring_sql
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_sql
  inputoutputformat_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  with_properties
  locate_properties
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  afterjournalproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  pseudotype_sql
  onconflict_sql
  returning_sql
  rowformatdelimitedproperty_sql
  table_sql
  tablesample_sql
  pivot_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  join_sql
  lambda_sql
  lateral_sql
  limit_sql
  offset_sql
  setitem_sql
  set_sql
  pragma_sql
  lock_sql
  literal_sql
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  select_sql
  schema_sql
  star_sql
  structkwarg_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  windowspec_sql
  withingroup_sql
  between_sql
  bracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  nextvaluefor_sql
  extract_sql
  trim_sql
  concat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  unique_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  jsonobject_sql
  in_sql
  in_unnest_op
  return_sql
  reference_sql
  anonymous_sql
  paren_sql
  neg_sql
  not_sql
  alias_sql
  aliases_sql
  attimezone_sql
  add_sql
  and_sql
  connector_sql
  bitwiseand_sql
  bitwiseleftshift_sql
  bitwisenot_sql
  bitwiseor_sql
  bitwiserightshift_sql
  bitwisexor_sql
  cast_sql
  currentdate_sql
  collate_sql
  command_sql
  comment_sql
  commit_sql
  rollback_sql
  altercolumn_sql
  renametable_sql
  altertable_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  ilikeany_sql
  is_sql
  like_sql
  likeany_sql
  similarto_sql
  lt_sql
  lte_sql
  mod_sql
  mul_sql
  neq_sql
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  use_sql
  binary
  function_fallback_sql
  func
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  set_operation
  tag_sql
  token_sql
  userdefinedfunction_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql
  tochar_sql