sqlglot.dialects.snowflake API documentation

Edit on GitHub

# sqlglot.dialects.snowflake

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    datestrtodate_sql,
     10    format_time_lambda,
     11    inline_array_sql,
     12    max_or_greatest,
     13    min_or_least,
     14    rename_func,
     15    timestamptrunc_sql,
     16    timestrtotime_sql,
     17    ts_or_ds_to_date_sql,
     18    var_map_sql,
     19)
     20from sqlglot.expressions import Literal
     21from sqlglot.helper import seq_get
     22from sqlglot.parser import binary_range_parser
     23from sqlglot.tokens import TokenType
     24
     25
     26def _check_int(s: str) -> bool:
     27    if s[0] in ("-", "+"):
     28        return s[1:].isdigit()
     29    return s.isdigit()
     30
     31
     32# from https://docs.snowflake.com/en/sql-reference/functions/to_timestamp.html
     33def _snowflake_to_timestamp(args: t.List) -> t.Union[exp.StrToTime, exp.UnixToTime]:
     34    if len(args) == 2:
     35        first_arg, second_arg = args
     36        if second_arg.is_string:
     37            # case: <string_expr> [ , <format> ]
     38            return format_time_lambda(exp.StrToTime, "snowflake")(args)
     39
     40        # case: <numeric_expr> [ , <scale> ]
     41        if second_arg.name not in ["0", "3", "9"]:
     42            raise ValueError(
     43                f"Scale for snowflake numeric timestamp is {second_arg}, but should be 0, 3, or 9"
     44            )
     45
     46        if second_arg.name == "0":
     47            timescale = exp.UnixToTime.SECONDS
     48        elif second_arg.name == "3":
     49            timescale = exp.UnixToTime.MILLIS
     50        elif second_arg.name == "9":
     51            timescale = exp.UnixToTime.MICROS
     52
     53        return exp.UnixToTime(this=first_arg, scale=timescale)
     54
     55    from sqlglot.optimizer.simplify import simplify_literals
     56
     57    # The first argument might be an expression like 40 * 365 * 86400, so we try to
     58    # reduce it using `simplify_literals` first and then check if it's a Literal.
     59    first_arg = seq_get(args, 0)
     60    if not isinstance(simplify_literals(first_arg, root=True), Literal):
     61        # case: <variant_expr>
     62        return format_time_lambda(exp.StrToTime, "snowflake", default=True)(args)
     63
     64    if first_arg.is_string:
     65        if _check_int(first_arg.this):
     66            # case: <integer>
     67            return exp.UnixToTime.from_arg_list(args)
     68
     69        # case: <date_expr>
     70        return format_time_lambda(exp.StrToTime, "snowflake", default=True)(args)
     71
     72    # case: <numeric_expr>
     73    return exp.UnixToTime.from_arg_list(args)
     74
     75
     76def _parse_object_construct(args: t.List) -> t.Union[exp.StarMap, exp.Struct]:
     77    expression = parser.parse_var_map(args)
     78
     79    if isinstance(expression, exp.StarMap):
     80        return expression
     81
     82    return exp.Struct(
     83        expressions=[
     84            t.cast(exp.Condition, k).eq(v) for k, v in zip(expression.keys, expression.values)
     85        ]
     86    )
     87
     88
     89def _unix_to_time_sql(self: generator.Generator, expression: exp.UnixToTime) -> str:
     90    scale = expression.args.get("scale")
     91    timestamp = self.sql(expression, "this")
     92    if scale in [None, exp.UnixToTime.SECONDS]:
     93        return f"TO_TIMESTAMP({timestamp})"
     94    if scale == exp.UnixToTime.MILLIS:
     95        return f"TO_TIMESTAMP({timestamp}, 3)"
     96    if scale == exp.UnixToTime.MICROS:
     97        return f"TO_TIMESTAMP({timestamp}, 9)"
     98
     99    raise ValueError("Improper scale for timestamp")
    100
    101
    102# https://docs.snowflake.com/en/sql-reference/functions/date_part.html
    103# https://docs.snowflake.com/en/sql-reference/functions-date-time.html#label-supported-date-time-parts
    104def _parse_date_part(self: parser.Parser) -> t.Optional[exp.Expression]:
    105    this = self._parse_var() or self._parse_type()
    106
    107    if not this:
    108        return None
    109
    110    self._match(TokenType.COMMA)
    111    expression = self._parse_bitwise()
    112
    113    name = this.name.upper()
    114    if name.startswith("EPOCH"):
    115        if name.startswith("EPOCH_MILLISECOND"):
    116            scale = 10**3
    117        elif name.startswith("EPOCH_MICROSECOND"):
    118            scale = 10**6
    119        elif name.startswith("EPOCH_NANOSECOND"):
    120            scale = 10**9
    121        else:
    122            scale = None
    123
    124        ts = self.expression(exp.Cast, this=expression, to=exp.DataType.build("TIMESTAMP"))
    125        to_unix: exp.Expression = self.expression(exp.TimeToUnix, this=ts)
    126
    127        if scale:
    128            to_unix = exp.Mul(this=to_unix, expression=exp.Literal.number(scale))
    129
    130        return to_unix
    131
    132    return self.expression(exp.Extract, this=this, expression=expression)
    133
    134
    135# https://docs.snowflake.com/en/sql-reference/functions/div0
    136def _div0_to_if(args: t.List) -> exp.Expression:
    137    cond = exp.EQ(this=seq_get(args, 1), expression=exp.Literal.number(0))
    138    true = exp.Literal.number(0)
    139    false = exp.Div(this=seq_get(args, 0), expression=seq_get(args, 1))
    140    return exp.If(this=cond, true=true, false=false)
    141
    142
    143# https://docs.snowflake.com/en/sql-reference/functions/zeroifnull
    144def _zeroifnull_to_if(args: t.List) -> exp.Expression:
    145    cond = exp.Is(this=seq_get(args, 0), expression=exp.Null())
    146    return exp.If(this=cond, true=exp.Literal.number(0), false=seq_get(args, 0))
    147
    148
    149# https://docs.snowflake.com/en/sql-reference/functions/zeroifnull
    150def _nullifzero_to_if(args: t.List) -> exp.Expression:
    151    cond = exp.EQ(this=seq_get(args, 0), expression=exp.Literal.number(0))
    152    return exp.If(this=cond, true=exp.Null(), false=seq_get(args, 0))
    153
    154
    155def _datatype_sql(self: generator.Generator, expression: exp.DataType) -> str:
    156    if expression.is_type("array"):
    157        return "ARRAY"
    158    elif expression.is_type("map"):
    159        return "OBJECT"
    160    return self.datatype_sql(expression)
    161
    162
    163def _parse_convert_timezone(args: t.List) -> exp.Expression:
    164    if len(args) == 3:
    165        return exp.Anonymous(this="CONVERT_TIMEZONE", expressions=args)
    166    return exp.AtTimeZone(this=seq_get(args, 1), zone=seq_get(args, 0))
    167
    168
    169class Snowflake(Dialect):
    170    NULL_ORDERING = "nulls_are_large"
    171    TIME_FORMAT = "'YYYY-MM-DD HH24:MI:SS'"
    172
    173    TIME_MAPPING = {
    174        "YYYY": "%Y",
    175        "yyyy": "%Y",
    176        "YY": "%y",
    177        "yy": "%y",
    178        "MMMM": "%B",
    179        "mmmm": "%B",
    180        "MON": "%b",
    181        "mon": "%b",
    182        "MM": "%m",
    183        "mm": "%m",
    184        "DD": "%d",
    185        "dd": "%-d",
    186        "DY": "%a",
    187        "dy": "%w",
    188        "HH24": "%H",
    189        "hh24": "%H",
    190        "HH12": "%I",
    191        "hh12": "%I",
    192        "MI": "%M",
    193        "mi": "%M",
    194        "SS": "%S",
    195        "ss": "%S",
    196        "FF": "%f",
    197        "ff": "%f",
    198        "FF6": "%f",
    199        "ff6": "%f",
    200    }
    201
    202    class Parser(parser.Parser):
    203        IDENTIFY_PIVOT_STRINGS = True
    204
    205        FUNCTIONS = {
    206            **parser.Parser.FUNCTIONS,
    207            "ARRAYAGG": exp.ArrayAgg.from_arg_list,
    208            "ARRAY_CONSTRUCT": exp.Array.from_arg_list,
    209            "ARRAY_TO_STRING": exp.ArrayJoin.from_arg_list,
    210            "CONVERT_TIMEZONE": _parse_convert_timezone,
    211            "DATE_TRUNC": date_trunc_to_time,
    212            "DATEADD": lambda args: exp.DateAdd(
    213                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
    214            ),
    215            "DATEDIFF": lambda args: exp.DateDiff(
    216                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
    217            ),
    218            "DIV0": _div0_to_if,
    219            "IFF": exp.If.from_arg_list,
    220            "NULLIFZERO": _nullifzero_to_if,
    221            "OBJECT_CONSTRUCT": _parse_object_construct,
    222            "RLIKE": exp.RegexpLike.from_arg_list,
    223            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
    224            "TO_ARRAY": exp.Array.from_arg_list,
    225            "TO_VARCHAR": exp.ToChar.from_arg_list,
    226            "TO_TIMESTAMP": _snowflake_to_timestamp,
    227            "ZEROIFNULL": _zeroifnull_to_if,
    228        }
    229
    230        FUNCTION_PARSERS = {
    231            **parser.Parser.FUNCTION_PARSERS,
    232            "DATE_PART": _parse_date_part,
    233        }
    234        FUNCTION_PARSERS.pop("TRIM")
    235
    236        FUNC_TOKENS = {
    237            *parser.Parser.FUNC_TOKENS,
    238            TokenType.RLIKE,
    239            TokenType.TABLE,
    240        }
    241
    242        COLUMN_OPERATORS = {
    243            **parser.Parser.COLUMN_OPERATORS,
    244            TokenType.COLON: lambda self, this, path: self.expression(
    245                exp.Bracket, this=this, expressions=[path]
    246            ),
    247        }
    248
    249        TIMESTAMPS = parser.Parser.TIMESTAMPS.copy() - {TokenType.TIME}
    250
    251        RANGE_PARSERS = {
    252            **parser.Parser.RANGE_PARSERS,
    253            TokenType.LIKE_ANY: binary_range_parser(exp.LikeAny),
    254            TokenType.ILIKE_ANY: binary_range_parser(exp.ILikeAny),
    255        }
    256
    257        ALTER_PARSERS = {
    258            **parser.Parser.ALTER_PARSERS,
    259            "UNSET": lambda self: self._parse_alter_table_set_tag(unset=True),
    260            "SET": lambda self: self._parse_alter_table_set_tag(),
    261        }
    262
    263        def _parse_alter_table_set_tag(self, unset: bool = False) -> exp.Expression:
    264            self._match_text_seq("TAG")
    265            parser = t.cast(t.Callable, self._parse_id_var if unset else self._parse_conjunction)
    266            return self.expression(exp.SetTag, expressions=self._parse_csv(parser), unset=unset)
    267
    268    class Tokenizer(tokens.Tokenizer):
    269        QUOTES = ["'", "$$"]
    270        STRING_ESCAPES = ["\\", "'"]
    271        HEX_STRINGS = [("x'", "'"), ("X'", "'")]
    272        COMMENTS = ["--", "//", ("/*", "*/")]
    273
    274        KEYWORDS = {
    275            **tokens.Tokenizer.KEYWORDS,
    276            "CHAR VARYING": TokenType.VARCHAR,
    277            "CHARACTER VARYING": TokenType.VARCHAR,
    278            "EXCLUDE": TokenType.EXCEPT,
    279            "ILIKE ANY": TokenType.ILIKE_ANY,
    280            "LIKE ANY": TokenType.LIKE_ANY,
    281            "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE,
    282            "MINUS": TokenType.EXCEPT,
    283            "NCHAR VARYING": TokenType.VARCHAR,
    284            "PUT": TokenType.COMMAND,
    285            "RENAME": TokenType.REPLACE,
    286            "TIMESTAMP_LTZ": TokenType.TIMESTAMPLTZ,
    287            "TIMESTAMP_NTZ": TokenType.TIMESTAMP,
    288            "TIMESTAMP_TZ": TokenType.TIMESTAMPTZ,
    289            "TIMESTAMPNTZ": TokenType.TIMESTAMP,
    290            "SAMPLE": TokenType.TABLE_SAMPLE,
    291        }
    292
    293        SINGLE_TOKENS = {
    294            **tokens.Tokenizer.SINGLE_TOKENS,
    295            "$": TokenType.PARAMETER,
    296        }
    297
    298        VAR_SINGLE_TOKENS = {"$"}
    299
    300    class Generator(generator.Generator):
    301        PARAMETER_TOKEN = "$"
    302        MATCHED_BY_SOURCE = False
    303        SINGLE_STRING_INTERVAL = True
    304        JOIN_HINTS = False
    305        TABLE_HINTS = False
    306
    307        TRANSFORMS = {
    308            **generator.Generator.TRANSFORMS,
    309            exp.Array: inline_array_sql,
    310            exp.ArrayConcat: rename_func("ARRAY_CAT"),
    311            exp.ArrayJoin: rename_func("ARRAY_TO_STRING"),
    312            exp.AtTimeZone: lambda self, e: self.func(
    313                "CONVERT_TIMEZONE", e.args.get("zone"), e.this
    314            ),
    315            exp.DateAdd: lambda self, e: self.func("DATEADD", e.text("unit"), e.expression, e.this),
    316            exp.DateDiff: lambda self, e: self.func(
    317                "DATEDIFF", e.text("unit"), e.expression, e.this
    318            ),
    319            exp.DateStrToDate: datestrtodate_sql,
    320            exp.DataType: _datatype_sql,
    321            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    322            exp.Extract: rename_func("DATE_PART"),
    323            exp.If: rename_func("IFF"),
    324            exp.LogicalAnd: rename_func("BOOLAND_AGG"),
    325            exp.LogicalOr: rename_func("BOOLOR_AGG"),
    326            exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"),
    327            exp.Max: max_or_greatest,
    328            exp.Min: min_or_least,
    329            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    330            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
    331            exp.StarMap: rename_func("OBJECT_CONSTRUCT"),
    332            exp.StrPosition: lambda self, e: self.func(
    333                "POSITION", e.args.get("substr"), e.this, e.args.get("position")
    334            ),
    335            exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})",
    336            exp.Struct: lambda self, e: self.func(
    337                "OBJECT_CONSTRUCT",
    338                *(arg for expression in e.expressions for arg in expression.flatten()),
    339            ),
    340            exp.TimeStrToTime: timestrtotime_sql,
    341            exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})",
    342            exp.TimeToStr: lambda self, e: self.func(
    343                "TO_CHAR", exp.cast(e.this, "timestamp"), self.format_time(e)
    344            ),
    345            exp.TimestampTrunc: timestamptrunc_sql,
    346            exp.ToChar: lambda self, e: self.function_fallback_sql(e),
    347            exp.Trim: lambda self, e: self.func("TRIM", e.this, e.expression),
    348            exp.TsOrDsToDate: ts_or_ds_to_date_sql("snowflake"),
    349            exp.UnixToTime: _unix_to_time_sql,
    350            exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"),
    351        }
    352
    353        TYPE_MAPPING = {
    354            **generator.Generator.TYPE_MAPPING,
    355            exp.DataType.Type.TIMESTAMP: "TIMESTAMPNTZ",
    356        }
    357
    358        STAR_MAPPING = {
    359            "except": "EXCLUDE",
    360            "replace": "RENAME",
    361        }
    362
    363        PROPERTIES_LOCATION = {
    364            **generator.Generator.PROPERTIES_LOCATION,
    365            exp.SetProperty: exp.Properties.Location.UNSUPPORTED,
    366            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    367        }
    368
    369        def except_op(self, expression: exp.Except) -> str:
    370            if not expression.args.get("distinct", False):
    371                self.unsupported("EXCEPT with All is not supported in Snowflake")
    372            return super().except_op(expression)
    373
    374        def intersect_op(self, expression: exp.Intersect) -> str:
    375            if not expression.args.get("distinct", False):
    376                self.unsupported("INTERSECT with All is not supported in Snowflake")
    377            return super().intersect_op(expression)
    378
    379        def settag_sql(self, expression: exp.SetTag) -> str:
    380            action = "UNSET" if expression.args.get("unset") else "SET"
    381            return f"{action} TAG {self.expressions(expression)}"
    382
    383        def describe_sql(self, expression: exp.Describe) -> str:
    384            # Default to table if kind is unknown
    385            kind_value = expression.args.get("kind") or "TABLE"
    386            kind = f" {kind_value}" if kind_value else ""
    387            this = f" {self.sql(expression, 'this')}"
    388            return f"DESCRIBE{kind}{this}"
    389
    390        def generatedasidentitycolumnconstraint_sql(
    391            self, expression: exp.GeneratedAsIdentityColumnConstraint
    392        ) -> str:
    393            start = expression.args.get("start")
    394            start = f" START {start}" if start else ""
    395            increment = expression.args.get("increment")
    396            increment = f" INCREMENT {increment}" if increment else ""
    397            return f"AUTOINCREMENT{start}{increment}"

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

    170class Snowflake(Dialect):
    171    NULL_ORDERING = "nulls_are_large"
    172    TIME_FORMAT = "'YYYY-MM-DD HH24:MI:SS'"
    173
    174    TIME_MAPPING = {
    175        "YYYY": "%Y",
    176        "yyyy": "%Y",
    177        "YY": "%y",
    178        "yy": "%y",
    179        "MMMM": "%B",
    180        "mmmm": "%B",
    181        "MON": "%b",
    182        "mon": "%b",
    183        "MM": "%m",
    184        "mm": "%m",
    185        "DD": "%d",
    186        "dd": "%-d",
    187        "DY": "%a",
    188        "dy": "%w",
    189        "HH24": "%H",
    190        "hh24": "%H",
    191        "HH12": "%I",
    192        "hh12": "%I",
    193        "MI": "%M",
    194        "mi": "%M",
    195        "SS": "%S",
    196        "ss": "%S",
    197        "FF": "%f",
    198        "ff": "%f",
    199        "FF6": "%f",
    200        "ff6": "%f",
    201    }
    202
    203    class Parser(parser.Parser):
    204        IDENTIFY_PIVOT_STRINGS = True
    205
    206        FUNCTIONS = {
    207            **parser.Parser.FUNCTIONS,
    208            "ARRAYAGG": exp.ArrayAgg.from_arg_list,
    209            "ARRAY_CONSTRUCT": exp.Array.from_arg_list,
    210            "ARRAY_TO_STRING": exp.ArrayJoin.from_arg_list,
    211            "CONVERT_TIMEZONE": _parse_convert_timezone,
    212            "DATE_TRUNC": date_trunc_to_time,
    213            "DATEADD": lambda args: exp.DateAdd(
    214                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
    215            ),
    216            "DATEDIFF": lambda args: exp.DateDiff(
    217                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
    218            ),
    219            "DIV0": _div0_to_if,
    220            "IFF": exp.If.from_arg_list,
    221            "NULLIFZERO": _nullifzero_to_if,
    222            "OBJECT_CONSTRUCT": _parse_object_construct,
    223            "RLIKE": exp.RegexpLike.from_arg_list,
    224            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
    225            "TO_ARRAY": exp.Array.from_arg_list,
    226            "TO_VARCHAR": exp.ToChar.from_arg_list,
    227            "TO_TIMESTAMP": _snowflake_to_timestamp,
    228            "ZEROIFNULL": _zeroifnull_to_if,
    229        }
    230
    231        FUNCTION_PARSERS = {
    232            **parser.Parser.FUNCTION_PARSERS,
    233            "DATE_PART": _parse_date_part,
    234        }
    235        FUNCTION_PARSERS.pop("TRIM")
    236
    237        FUNC_TOKENS = {
    238            *parser.Parser.FUNC_TOKENS,
    239            TokenType.RLIKE,
    240            TokenType.TABLE,
    241        }
    242
    243        COLUMN_OPERATORS = {
    244            **parser.Parser.COLUMN_OPERATORS,
    245            TokenType.COLON: lambda self, this, path: self.expression(
    246                exp.Bracket, this=this, expressions=[path]
    247            ),
    248        }
    249
    250        TIMESTAMPS = parser.Parser.TIMESTAMPS.copy() - {TokenType.TIME}
    251
    252        RANGE_PARSERS = {
    253            **parser.Parser.RANGE_PARSERS,
    254            TokenType.LIKE_ANY: binary_range_parser(exp.LikeAny),
    255            TokenType.ILIKE_ANY: binary_range_parser(exp.ILikeAny),
    256        }
    257
    258        ALTER_PARSERS = {
    259            **parser.Parser.ALTER_PARSERS,
    260            "UNSET": lambda self: self._parse_alter_table_set_tag(unset=True),
    261            "SET": lambda self: self._parse_alter_table_set_tag(),
    262        }
    263
    264        def _parse_alter_table_set_tag(self, unset: bool = False) -> exp.Expression:
    265            self._match_text_seq("TAG")
    266            parser = t.cast(t.Callable, self._parse_id_var if unset else self._parse_conjunction)
    267            return self.expression(exp.SetTag, expressions=self._parse_csv(parser), unset=unset)
    268
    269    class Tokenizer(tokens.Tokenizer):
    270        QUOTES = ["'", "$$"]
    271        STRING_ESCAPES = ["\\", "'"]
    272        HEX_STRINGS = [("x'", "'"), ("X'", "'")]
    273        COMMENTS = ["--", "//", ("/*", "*/")]
    274
    275        KEYWORDS = {
    276            **tokens.Tokenizer.KEYWORDS,
    277            "CHAR VARYING": TokenType.VARCHAR,
    278            "CHARACTER VARYING": TokenType.VARCHAR,
    279            "EXCLUDE": TokenType.EXCEPT,
    280            "ILIKE ANY": TokenType.ILIKE_ANY,
    281            "LIKE ANY": TokenType.LIKE_ANY,
    282            "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE,
    283            "MINUS": TokenType.EXCEPT,
    284            "NCHAR VARYING": TokenType.VARCHAR,
    285            "PUT": TokenType.COMMAND,
    286            "RENAME": TokenType.REPLACE,
    287            "TIMESTAMP_LTZ": TokenType.TIMESTAMPLTZ,
    288            "TIMESTAMP_NTZ": TokenType.TIMESTAMP,
    289            "TIMESTAMP_TZ": TokenType.TIMESTAMPTZ,
    290            "TIMESTAMPNTZ": TokenType.TIMESTAMP,
    291            "SAMPLE": TokenType.TABLE_SAMPLE,
    292        }
    293
    294        SINGLE_TOKENS = {
    295            **tokens.Tokenizer.SINGLE_TOKENS,
    296            "$": TokenType.PARAMETER,
    297        }
    298
    299        VAR_SINGLE_TOKENS = {"$"}
    300
    301    class Generator(generator.Generator):
    302        PARAMETER_TOKEN = "$"
    303        MATCHED_BY_SOURCE = False
    304        SINGLE_STRING_INTERVAL = True
    305        JOIN_HINTS = False
    306        TABLE_HINTS = False
    307
    308        TRANSFORMS = {
    309            **generator.Generator.TRANSFORMS,
    310            exp.Array: inline_array_sql,
    311            exp.ArrayConcat: rename_func("ARRAY_CAT"),
    312            exp.ArrayJoin: rename_func("ARRAY_TO_STRING"),
    313            exp.AtTimeZone: lambda self, e: self.func(
    314                "CONVERT_TIMEZONE", e.args.get("zone"), e.this
    315            ),
    316            exp.DateAdd: lambda self, e: self.func("DATEADD", e.text("unit"), e.expression, e.this),
    317            exp.DateDiff: lambda self, e: self.func(
    318                "DATEDIFF", e.text("unit"), e.expression, e.this
    319            ),
    320            exp.DateStrToDate: datestrtodate_sql,
    321            exp.DataType: _datatype_sql,
    322            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    323            exp.Extract: rename_func("DATE_PART"),
    324            exp.If: rename_func("IFF"),
    325            exp.LogicalAnd: rename_func("BOOLAND_AGG"),
    326            exp.LogicalOr: rename_func("BOOLOR_AGG"),
    327            exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"),
    328            exp.Max: max_or_greatest,
    329            exp.Min: min_or_least,
    330            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    331            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
    332            exp.StarMap: rename_func("OBJECT_CONSTRUCT"),
    333            exp.StrPosition: lambda self, e: self.func(
    334                "POSITION", e.args.get("substr"), e.this, e.args.get("position")
    335            ),
    336            exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})",
    337            exp.Struct: lambda self, e: self.func(
    338                "OBJECT_CONSTRUCT",
    339                *(arg for expression in e.expressions for arg in expression.flatten()),
    340            ),
    341            exp.TimeStrToTime: timestrtotime_sql,
    342            exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})",
    343            exp.TimeToStr: lambda self, e: self.func(
    344                "TO_CHAR", exp.cast(e.this, "timestamp"), self.format_time(e)
    345            ),
    346            exp.TimestampTrunc: timestamptrunc_sql,
    347            exp.ToChar: lambda self, e: self.function_fallback_sql(e),
    348            exp.Trim: lambda self, e: self.func("TRIM", e.this, e.expression),
    349            exp.TsOrDsToDate: ts_or_ds_to_date_sql("snowflake"),
    350            exp.UnixToTime: _unix_to_time_sql,
    351            exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"),
    352        }
    353
    354        TYPE_MAPPING = {
    355            **generator.Generator.TYPE_MAPPING,
    356            exp.DataType.Type.TIMESTAMP: "TIMESTAMPNTZ",
    357        }
    358
    359        STAR_MAPPING = {
    360            "except": "EXCLUDE",
    361            "replace": "RENAME",
    362        }
    363
    364        PROPERTIES_LOCATION = {
    365            **generator.Generator.PROPERTIES_LOCATION,
    366            exp.SetProperty: exp.Properties.Location.UNSUPPORTED,
    367            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    368        }
    369
    370        def except_op(self, expression: exp.Except) -> str:
    371            if not expression.args.get("distinct", False):
    372                self.unsupported("EXCEPT with All is not supported in Snowflake")
    373            return super().except_op(expression)
    374
    375        def intersect_op(self, expression: exp.Intersect) -> str:
    376            if not expression.args.get("distinct", False):
    377                self.unsupported("INTERSECT with All is not supported in Snowflake")
    378            return super().intersect_op(expression)
    379
    380        def settag_sql(self, expression: exp.SetTag) -> str:
    381            action = "UNSET" if expression.args.get("unset") else "SET"
    382            return f"{action} TAG {self.expressions(expression)}"
    383
    384        def describe_sql(self, expression: exp.Describe) -> str:
    385            # Default to table if kind is unknown
    386            kind_value = expression.args.get("kind") or "TABLE"
    387            kind = f" {kind_value}" if kind_value else ""
    388            this = f" {self.sql(expression, 'this')}"
    389            return f"DESCRIBE{kind}{this}"
    390
    391        def generatedasidentitycolumnconstraint_sql(
    392            self, expression: exp.GeneratedAsIdentityColumnConstraint
    393        ) -> str:
    394            start = expression.args.get("start")
    395            start = f" START {start}" if start else ""
    396            increment = expression.args.get("increment")
    397            increment = f" INCREMENT {increment}" if increment else ""
    398            return f"AUTOINCREMENT{start}{increment}"

##### Inherited Members

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

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

    203    class Parser(parser.Parser):
    204        IDENTIFY_PIVOT_STRINGS = True
    205
    206        FUNCTIONS = {
    207            **parser.Parser.FUNCTIONS,
    208            "ARRAYAGG": exp.ArrayAgg.from_arg_list,
    209            "ARRAY_CONSTRUCT": exp.Array.from_arg_list,
    210            "ARRAY_TO_STRING": exp.ArrayJoin.from_arg_list,
    211            "CONVERT_TIMEZONE": _parse_convert_timezone,
    212            "DATE_TRUNC": date_trunc_to_time,
    213            "DATEADD": lambda args: exp.DateAdd(
    214                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
    215            ),
    216            "DATEDIFF": lambda args: exp.DateDiff(
    217                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
    218            ),
    219            "DIV0": _div0_to_if,
    220            "IFF": exp.If.from_arg_list,
    221            "NULLIFZERO": _nullifzero_to_if,
    222            "OBJECT_CONSTRUCT": _parse_object_construct,
    223            "RLIKE": exp.RegexpLike.from_arg_list,
    224            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
    225            "TO_ARRAY": exp.Array.from_arg_list,
    226            "TO_VARCHAR": exp.ToChar.from_arg_list,
    227            "TO_TIMESTAMP": _snowflake_to_timestamp,
    228            "ZEROIFNULL": _zeroifnull_to_if,
    229        }
    230
    231        FUNCTION_PARSERS = {
    232            **parser.Parser.FUNCTION_PARSERS,
    233            "DATE_PART": _parse_date_part,
    234        }
    235        FUNCTION_PARSERS.pop("TRIM")
    236
    237        FUNC_TOKENS = {
    238            *parser.Parser.FUNC_TOKENS,
    239            TokenType.RLIKE,
    240            TokenType.TABLE,
    241        }
    242
    243        COLUMN_OPERATORS = {
    244            **parser.Parser.COLUMN_OPERATORS,
    245            TokenType.COLON: lambda self, this, path: self.expression(
    246                exp.Bracket, this=this, expressions=[path]
    247            ),
    248        }
    249
    250        TIMESTAMPS = parser.Parser.TIMESTAMPS.copy() - {TokenType.TIME}
    251
    252        RANGE_PARSERS = {
    253            **parser.Parser.RANGE_PARSERS,
    254            TokenType.LIKE_ANY: binary_range_parser(exp.LikeAny),
    255            TokenType.ILIKE_ANY: binary_range_parser(exp.ILikeAny),
    256        }
    257
    258        ALTER_PARSERS = {
    259            **parser.Parser.ALTER_PARSERS,
    260            "UNSET": lambda self: self._parse_alter_table_set_tag(unset=True),
    261            "SET": lambda self: self._parse_alter_table_set_tag(),
    262        }
    263
    264        def _parse_alter_table_set_tag(self, unset: bool = False) -> exp.Expression:
    265            self._match_text_seq("TAG")
    266            parser = t.cast(t.Callable, self._parse_id_var if unset else self._parse_conjunction)
    267            return self.expression(exp.SetTag, expressions=self._parse_csv(parser), unset=unset)

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

###### Arguments:

- error_level: The desired error level. Default: ErrorLevel.IMMEDIATE
- error_message_context: Determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 100
- 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

##### Inherited Members

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

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

    269    class Tokenizer(tokens.Tokenizer):
    270        QUOTES = ["'", "$$"]
    271        STRING_ESCAPES = ["\\", "'"]
    272        HEX_STRINGS = [("x'", "'"), ("X'", "'")]
    273        COMMENTS = ["--", "//", ("/*", "*/")]
    274
    275        KEYWORDS = {
    276            **tokens.Tokenizer.KEYWORDS,
    277            "CHAR VARYING": TokenType.VARCHAR,
    278            "CHARACTER VARYING": TokenType.VARCHAR,
    279            "EXCLUDE": TokenType.EXCEPT,
    280            "ILIKE ANY": TokenType.ILIKE_ANY,
    281            "LIKE ANY": TokenType.LIKE_ANY,
    282            "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE,
    283            "MINUS": TokenType.EXCEPT,
    284            "NCHAR VARYING": TokenType.VARCHAR,
    285            "PUT": TokenType.COMMAND,
    286            "RENAME": TokenType.REPLACE,
    287            "TIMESTAMP_LTZ": TokenType.TIMESTAMPLTZ,
    288            "TIMESTAMP_NTZ": TokenType.TIMESTAMP,
    289            "TIMESTAMP_TZ": TokenType.TIMESTAMPTZ,
    290            "TIMESTAMPNTZ": TokenType.TIMESTAMP,
    291            "SAMPLE": TokenType.TABLE_SAMPLE,
    292        }
    293
    294        SINGLE_TOKENS = {
    295            **tokens.Tokenizer.SINGLE_TOKENS,
    296            "$": TokenType.PARAMETER,
    297        }
    298
    299        VAR_SINGLE_TOKENS = {"$"}

##### Inherited Members

sqlglot.tokens.Tokenizer
  reset
  tokenize
  peek

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

    301    class Generator(generator.Generator):
    302        PARAMETER_TOKEN = "$"
    303        MATCHED_BY_SOURCE = False
    304        SINGLE_STRING_INTERVAL = True
    305        JOIN_HINTS = False
    306        TABLE_HINTS = False
    307
    308        TRANSFORMS = {
    309            **generator.Generator.TRANSFORMS,
    310            exp.Array: inline_array_sql,
    311            exp.ArrayConcat: rename_func("ARRAY_CAT"),
    312            exp.ArrayJoin: rename_func("ARRAY_TO_STRING"),
    313            exp.AtTimeZone: lambda self, e: self.func(
    314                "CONVERT_TIMEZONE", e.args.get("zone"), e.this
    315            ),
    316            exp.DateAdd: lambda self, e: self.func("DATEADD", e.text("unit"), e.expression, e.this),
    317            exp.DateDiff: lambda self, e: self.func(
    318                "DATEDIFF", e.text("unit"), e.expression, e.this
    319            ),
    320            exp.DateStrToDate: datestrtodate_sql,
    321            exp.DataType: _datatype_sql,
    322            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    323            exp.Extract: rename_func("DATE_PART"),
    324            exp.If: rename_func("IFF"),
    325            exp.LogicalAnd: rename_func("BOOLAND_AGG"),
    326            exp.LogicalOr: rename_func("BOOLOR_AGG"),
    327            exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"),
    328            exp.Max: max_or_greatest,
    329            exp.Min: min_or_least,
    330            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    331            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
    332            exp.StarMap: rename_func("OBJECT_CONSTRUCT"),
    333            exp.StrPosition: lambda self, e: self.func(
    334                "POSITION", e.args.get("substr"), e.this, e.args.get("position")
    335            ),
    336            exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})",
    337            exp.Struct: lambda self, e: self.func(
    338                "OBJECT_CONSTRUCT",
    339                *(arg for expression in e.expressions for arg in expression.flatten()),
    340            ),
    341            exp.TimeStrToTime: timestrtotime_sql,
    342            exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})",
    343            exp.TimeToStr: lambda self, e: self.func(
    344                "TO_CHAR", exp.cast(e.this, "timestamp"), self.format_time(e)
    345            ),
    346            exp.TimestampTrunc: timestamptrunc_sql,
    347            exp.ToChar: lambda self, e: self.function_fallback_sql(e),
    348            exp.Trim: lambda self, e: self.func("TRIM", e.this, e.expression),
    349            exp.TsOrDsToDate: ts_or_ds_to_date_sql("snowflake"),
    350            exp.UnixToTime: _unix_to_time_sql,
    351            exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"),
    352        }
    353
    354        TYPE_MAPPING = {
    355            **generator.Generator.TYPE_MAPPING,
    356            exp.DataType.Type.TIMESTAMP: "TIMESTAMPNTZ",
    357        }
    358
    359        STAR_MAPPING = {
    360            "except": "EXCLUDE",
    361            "replace": "RENAME",
    362        }
    363
    364        PROPERTIES_LOCATION = {
    365            **generator.Generator.PROPERTIES_LOCATION,
    366            exp.SetProperty: exp.Properties.Location.UNSUPPORTED,
    367            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    368        }
    369
    370        def except_op(self, expression: exp.Except) -> str:
    371            if not expression.args.get("distinct", False):
    372                self.unsupported("EXCEPT with All is not supported in Snowflake")
    373            return super().except_op(expression)
    374
    375        def intersect_op(self, expression: exp.Intersect) -> str:
    376            if not expression.args.get("distinct", False):
    377                self.unsupported("INTERSECT with All is not supported in Snowflake")
    378            return super().intersect_op(expression)
    379
    380        def settag_sql(self, expression: exp.SetTag) -> str:
    381            action = "UNSET" if expression.args.get("unset") else "SET"
    382            return f"{action} TAG {self.expressions(expression)}"
    383
    384        def describe_sql(self, expression: exp.Describe) -> str:
    385            # Default to table if kind is unknown
    386            kind_value = expression.args.get("kind") or "TABLE"
    387            kind = f" {kind_value}" if kind_value else ""
    388            this = f" {self.sql(expression, 'this')}"
    389            return f"DESCRIBE{kind}{this}"
    390
    391        def generatedasidentitycolumnconstraint_sql(
    392            self, expression: exp.GeneratedAsIdentityColumnConstraint
    393        ) -> str:
    394            start = expression.args.get("start")
    395            start = f" START {start}" if start else ""
    396            increment = expression.args.get("increment")
    397            increment = f" INCREMENT {increment}" if increment else ""
    398            return f"AUTOINCREMENT{start}{increment}"

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

###### Arguments:

- pretty: Whether or not 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 or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether or not to normalize identifiers to lowercase. Default: False.
- pad: Determines the pad size in a formatted string. Default: 2.
- indent: Determines the indentation size in a formatted string. Default: 2.
- normalize_functions: Whether or not to normalize all 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: Determines whether or not 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 or not to preserve comments in the output SQL code. Default: True

def except_op(self, expression: sqlglot.expressions.Except) -> str: View Source

    370        def except_op(self, expression: exp.Except) -> str:
    371            if not expression.args.get("distinct", False):
    372                self.unsupported("EXCEPT with All is not supported in Snowflake")
    373            return super().except_op(expression)

def intersect_op(self, expression: sqlglot.expressions.Intersect) -> str: View Source

    375        def intersect_op(self, expression: exp.Intersect) -> str:
    376            if not expression.args.get("distinct", False):
    377                self.unsupported("INTERSECT with All is not supported in Snowflake")
    378            return super().intersect_op(expression)

def settag_sql(self, expression: sqlglot.expressions.SetTag) -> str: View Source

    380        def settag_sql(self, expression: exp.SetTag) -> str:
    381            action = "UNSET" if expression.args.get("unset") else "SET"
    382            return f"{action} TAG {self.expressions(expression)}"

def describe_sql(self, expression: sqlglot.expressions.Describe) -> str: View Source

    384        def describe_sql(self, expression: exp.Describe) -> str:
    385            # Default to table if kind is unknown
    386            kind_value = expression.args.get("kind") or "TABLE"
    387            kind = f" {kind_value}" if kind_value else ""
    388            this = f" {self.sql(expression, 'this')}"
    389            return f"DESCRIBE{kind}{this}"

def generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str: View Source

    391        def generatedasidentitycolumnconstraint_sql(
    392            self, expression: exp.GeneratedAsIdentityColumnConstraint
    393        ) -> str:
    394            start = expression.args.get("start")
    395            start = f" START {start}" if start else ""
    396            increment = expression.args.get("increment")
    397            increment = f" INCREMENT {increment}" if increment else ""
    398            return f"AUTOINCREMENT{start}{increment}"

##### 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
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  createable_sql
  create_sql
  clone_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  bytestring_sql
  rawstring_sql
  datatypesize_sql
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  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
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  insert_sql
  intersect_sql
  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
  offset_limit_modifiers
  after_having_modifiers
  after_limit_modifiers
  select_sql
  schema_sql
  schema_columns_sql
  star_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
  safeconcat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  jsonobject_sql
  openjsoncolumndef_sql
  openjson_sql
  in_sql
  in_unnest_op
  interval_sql
  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
  mergetreettlaction_sql
  mergetreettl_sql
  transaction_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
  safedpipe_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
  dictproperty_sql
  dictrange_sql
  dictsubproperty_sql
  oncluster_sql