sqlglot.dialects.bigquery API documentation

Edit on GitHub

Supports BigQuery Standard SQL.

View Source

      1"""Supports BigQuery Standard SQL."""
      2
      3from __future__ import annotations
      4
      5import typing as t
      6
      7from sqlglot import exp, generator, parser, tokens, transforms
      8from sqlglot.dialects.dialect import (
      9    Dialect,
     10    datestrtodate_sql,
     11    inline_array_sql,
     12    no_ilike_sql,
     13    rename_func,
     14    timestrtotime_sql,
     15)
     16from sqlglot.helper import seq_get
     17from sqlglot.tokens import TokenType
     18
     19E = t.TypeVar("E", bound=exp.Expression)
     20
     21
     22def _date_add(expression_class: t.Type[E]) -> t.Callable[[t.Sequence], E]:
     23    def func(args):
     24        interval = seq_get(args, 1)
     25        return expression_class(
     26            this=seq_get(args, 0),
     27            expression=interval.this,
     28            unit=interval.args.get("unit"),
     29        )
     30
     31    return func
     32
     33
     34def _date_add_sql(
     35    data_type: str, kind: str
     36) -> t.Callable[[generator.Generator, exp.Expression], str]:
     37    def func(self, expression):
     38        this = self.sql(expression, "this")
     39        return f"{data_type}_{kind}({this}, {self.sql(exp.Interval(this=expression.expression, unit=expression.args.get('unit') or exp.Literal.string('day')))})"
     40
     41    return func
     42
     43
     44def _derived_table_values_to_unnest(self: generator.Generator, expression: exp.Values) -> str:
     45    if not isinstance(expression.unnest().parent, exp.From):
     46        expression = t.cast(exp.Values, transforms.remove_precision_parameterized_types(expression))
     47        return self.values_sql(expression)
     48    rows = [tuple_exp.expressions for tuple_exp in expression.find_all(exp.Tuple)]
     49    structs = []
     50    for row in rows:
     51        aliases = [
     52            exp.alias_(value, column_name)
     53            for value, column_name in zip(row, expression.args["alias"].args["columns"])
     54        ]
     55        structs.append(exp.Struct(expressions=aliases))
     56    unnest_exp = exp.Unnest(expressions=[exp.Array(expressions=structs)])
     57    return self.unnest_sql(unnest_exp)
     58
     59
     60def _returnsproperty_sql(self: generator.Generator, expression: exp.ReturnsProperty) -> str:
     61    this = expression.this
     62    if isinstance(this, exp.Schema):
     63        this = f"{this.this} <{self.expressions(this)}>"
     64    else:
     65        this = self.sql(this)
     66    return f"RETURNS {this}"
     67
     68
     69def _create_sql(self: generator.Generator, expression: exp.Create) -> str:
     70    kind = expression.args["kind"]
     71    returns = expression.find(exp.ReturnsProperty)
     72    if kind.upper() == "FUNCTION" and returns and returns.args.get("is_table"):
     73        expression = expression.copy()
     74        expression.set("kind", "TABLE FUNCTION")
     75        if isinstance(
     76            expression.expression,
     77            (
     78                exp.Subquery,
     79                exp.Literal,
     80            ),
     81        ):
     82            expression.set("expression", expression.expression.this)
     83
     84        return self.create_sql(expression)
     85
     86    return self.create_sql(expression)
     87
     88
     89def _unqualify_unnest(expression: exp.Expression) -> exp.Expression:
     90    """Remove references to unnest table aliases since bigquery doesn't allow them.
     91
     92    These are added by the optimizer's qualify_column step.
     93    """
     94    if isinstance(expression, exp.Select):
     95        unnests = {
     96            unnest.alias
     97            for unnest in expression.args.get("from", exp.From(expressions=[])).expressions
     98            if isinstance(unnest, exp.Unnest) and unnest.alias
     99        }
    100
    101        if unnests:
    102            expression = expression.copy()
    103
    104            for select in expression.expressions:
    105                for column in select.find_all(exp.Column):
    106                    if column.table in unnests:
    107                        column.set("table", None)
    108
    109    return expression
    110
    111
    112class BigQuery(Dialect):
    113    unnest_column_only = True
    114    time_mapping = {
    115        "%M": "%-M",
    116        "%d": "%-d",
    117        "%m": "%-m",
    118        "%y": "%-y",
    119        "%H": "%-H",
    120        "%I": "%-I",
    121        "%S": "%-S",
    122        "%j": "%-j",
    123    }
    124
    125    class Tokenizer(tokens.Tokenizer):
    126        QUOTES = [
    127            (prefix + quote, quote) if prefix else quote
    128            for quote in ["'", '"', '"""', "'''"]
    129            for prefix in ["", "r", "R"]
    130        ]
    131        COMMENTS = ["--", "#", ("/*", "*/")]
    132        IDENTIFIERS = ["`"]
    133        STRING_ESCAPES = ["\\"]
    134        HEX_STRINGS = [("0x", ""), ("0X", "")]
    135
    136        KEYWORDS = {
    137            **tokens.Tokenizer.KEYWORDS,
    138            "BEGIN": TokenType.COMMAND,
    139            "BEGIN TRANSACTION": TokenType.BEGIN,
    140            "CURRENT_DATETIME": TokenType.CURRENT_DATETIME,
    141            "CURRENT_TIME": TokenType.CURRENT_TIME,
    142            "DECLARE": TokenType.COMMAND,
    143            "GEOGRAPHY": TokenType.GEOGRAPHY,
    144            "FLOAT64": TokenType.DOUBLE,
    145            "INT64": TokenType.BIGINT,
    146            "NOT DETERMINISTIC": TokenType.VOLATILE,
    147            "UNKNOWN": TokenType.NULL,
    148        }
    149        KEYWORDS.pop("DIV")
    150
    151    class Parser(parser.Parser):
    152        FUNCTIONS = {
    153            **parser.Parser.FUNCTIONS,  # type: ignore
    154            "DATE_TRUNC": lambda args: exp.DateTrunc(
    155                unit=exp.Literal.string(seq_get(args, 1).name),  # type: ignore
    156                this=seq_get(args, 0),
    157            ),
    158            "DATE_ADD": _date_add(exp.DateAdd),
    159            "DATETIME_ADD": _date_add(exp.DatetimeAdd),
    160            "DIV": lambda args: exp.IntDiv(this=seq_get(args, 0), expression=seq_get(args, 1)),
    161            "REGEXP_CONTAINS": exp.RegexpLike.from_arg_list,
    162            "TIME_ADD": _date_add(exp.TimeAdd),
    163            "TIMESTAMP_ADD": _date_add(exp.TimestampAdd),
    164            "DATE_SUB": _date_add(exp.DateSub),
    165            "DATETIME_SUB": _date_add(exp.DatetimeSub),
    166            "TIME_SUB": _date_add(exp.TimeSub),
    167            "TIMESTAMP_SUB": _date_add(exp.TimestampSub),
    168            "PARSE_TIMESTAMP": lambda args: exp.StrToTime(
    169                this=seq_get(args, 1), format=seq_get(args, 0)
    170            ),
    171        }
    172
    173        FUNCTION_PARSERS = {
    174            **parser.Parser.FUNCTION_PARSERS,  # type: ignore
    175            "ARRAY": lambda self: self.expression(exp.Array, expressions=[self._parse_statement()]),
    176        }
    177        FUNCTION_PARSERS.pop("TRIM")
    178
    179        NO_PAREN_FUNCTIONS = {
    180            **parser.Parser.NO_PAREN_FUNCTIONS,  # type: ignore
    181            TokenType.CURRENT_DATETIME: exp.CurrentDatetime,
    182            TokenType.CURRENT_TIME: exp.CurrentTime,
    183        }
    184
    185        NESTED_TYPE_TOKENS = {
    186            *parser.Parser.NESTED_TYPE_TOKENS,  # type: ignore
    187            TokenType.TABLE,
    188        }
    189
    190        ID_VAR_TOKENS = {
    191            *parser.Parser.ID_VAR_TOKENS,  # type: ignore
    192            TokenType.VALUES,
    193        }
    194
    195        PROPERTY_PARSERS = {
    196            **parser.Parser.PROPERTY_PARSERS,  # type: ignore
    197            "NOT DETERMINISTIC": lambda self: self.expression(
    198                exp.VolatilityProperty, this=exp.Literal.string("VOLATILE")
    199            ),
    200        }
    201
    202    class Generator(generator.Generator):
    203        TRANSFORMS = {
    204            **generator.Generator.TRANSFORMS,  # type: ignore
    205            **transforms.REMOVE_PRECISION_PARAMETERIZED_TYPES,  # type: ignore
    206            exp.ArraySize: rename_func("ARRAY_LENGTH"),
    207            exp.DateAdd: _date_add_sql("DATE", "ADD"),
    208            exp.DateSub: _date_add_sql("DATE", "SUB"),
    209            exp.DatetimeAdd: _date_add_sql("DATETIME", "ADD"),
    210            exp.DatetimeSub: _date_add_sql("DATETIME", "SUB"),
    211            exp.DateDiff: lambda self, e: f"DATE_DIFF({self.sql(e, 'this')}, {self.sql(e, 'expression')}, {self.sql(e.args.get('unit', 'DAY'))})",
    212            exp.DateStrToDate: datestrtodate_sql,
    213            exp.DateTrunc: lambda self, e: self.func("DATE_TRUNC", e.this, e.text("unit")),
    214            exp.GroupConcat: rename_func("STRING_AGG"),
    215            exp.ILike: no_ilike_sql,
    216            exp.IntDiv: rename_func("DIV"),
    217            exp.Select: transforms.preprocess(
    218                [_unqualify_unnest], transforms.delegate("select_sql")
    219            ),
    220            exp.StrToTime: lambda self, e: f"PARSE_TIMESTAMP({self.format_time(e)}, {self.sql(e, 'this')})",
    221            exp.TimeAdd: _date_add_sql("TIME", "ADD"),
    222            exp.TimeSub: _date_add_sql("TIME", "SUB"),
    223            exp.TimestampAdd: _date_add_sql("TIMESTAMP", "ADD"),
    224            exp.TimestampSub: _date_add_sql("TIMESTAMP", "SUB"),
    225            exp.TimeStrToTime: timestrtotime_sql,
    226            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    227            exp.VariancePop: rename_func("VAR_POP"),
    228            exp.Values: _derived_table_values_to_unnest,
    229            exp.ReturnsProperty: _returnsproperty_sql,
    230            exp.Create: _create_sql,
    231            exp.Trim: lambda self, e: self.func(f"TRIM", e.this, e.expression),
    232            exp.VolatilityProperty: lambda self, e: f"DETERMINISTIC"
    233            if e.name == "IMMUTABLE"
    234            else "NOT DETERMINISTIC",
    235            exp.RegexpLike: rename_func("REGEXP_CONTAINS"),
    236        }
    237
    238        TYPE_MAPPING = {
    239            **generator.Generator.TYPE_MAPPING,  # type: ignore
    240            exp.DataType.Type.TINYINT: "INT64",
    241            exp.DataType.Type.SMALLINT: "INT64",
    242            exp.DataType.Type.INT: "INT64",
    243            exp.DataType.Type.BIGINT: "INT64",
    244            exp.DataType.Type.DECIMAL: "NUMERIC",
    245            exp.DataType.Type.FLOAT: "FLOAT64",
    246            exp.DataType.Type.DOUBLE: "FLOAT64",
    247            exp.DataType.Type.BOOLEAN: "BOOL",
    248            exp.DataType.Type.TEXT: "STRING",
    249            exp.DataType.Type.VARCHAR: "STRING",
    250            exp.DataType.Type.NVARCHAR: "STRING",
    251        }
    252        PROPERTIES_LOCATION = {
    253            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
    254            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
    255        }
    256
    257        EXPLICIT_UNION = True
    258
    259        def array_sql(self, expression: exp.Array) -> str:
    260            first_arg = seq_get(expression.expressions, 0)
    261            if isinstance(first_arg, exp.Subqueryable):
    262                return f"ARRAY{self.wrap(self.sql(first_arg))}"
    263
    264            return inline_array_sql(self, expression)
    265
    266        def transaction_sql(self, *_) -> str:
    267            return "BEGIN TRANSACTION"
    268
    269        def commit_sql(self, *_) -> str:
    270            return "COMMIT TRANSACTION"
    271
    272        def rollback_sql(self, *_) -> str:
    273            return "ROLLBACK TRANSACTION"
    274
    275        def in_unnest_op(self, expression: exp.Unnest) -> str:
    276            return self.sql(expression)
    277
    278        def except_op(self, expression: exp.Except) -> str:
    279            if not expression.args.get("distinct", False):
    280                self.unsupported("EXCEPT without DISTINCT is not supported in BigQuery")
    281            return f"EXCEPT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"
    282
    283        def intersect_op(self, expression: exp.Intersect) -> str:
    284            if not expression.args.get("distinct", False):
    285                self.unsupported("INTERSECT without DISTINCT is not supported in BigQuery")
    286            return f"INTERSECT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"

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

    113class BigQuery(Dialect):
    114    unnest_column_only = True
    115    time_mapping = {
    116        "%M": "%-M",
    117        "%d": "%-d",
    118        "%m": "%-m",
    119        "%y": "%-y",
    120        "%H": "%-H",
    121        "%I": "%-I",
    122        "%S": "%-S",
    123        "%j": "%-j",
    124    }
    125
    126    class Tokenizer(tokens.Tokenizer):
    127        QUOTES = [
    128            (prefix + quote, quote) if prefix else quote
    129            for quote in ["'", '"', '"""', "'''"]
    130            for prefix in ["", "r", "R"]
    131        ]
    132        COMMENTS = ["--", "#", ("/*", "*/")]
    133        IDENTIFIERS = ["`"]
    134        STRING_ESCAPES = ["\\"]
    135        HEX_STRINGS = [("0x", ""), ("0X", "")]
    136
    137        KEYWORDS = {
    138            **tokens.Tokenizer.KEYWORDS,
    139            "BEGIN": TokenType.COMMAND,
    140            "BEGIN TRANSACTION": TokenType.BEGIN,
    141            "CURRENT_DATETIME": TokenType.CURRENT_DATETIME,
    142            "CURRENT_TIME": TokenType.CURRENT_TIME,
    143            "DECLARE": TokenType.COMMAND,
    144            "GEOGRAPHY": TokenType.GEOGRAPHY,
    145            "FLOAT64": TokenType.DOUBLE,
    146            "INT64": TokenType.BIGINT,
    147            "NOT DETERMINISTIC": TokenType.VOLATILE,
    148            "UNKNOWN": TokenType.NULL,
    149        }
    150        KEYWORDS.pop("DIV")
    151
    152    class Parser(parser.Parser):
    153        FUNCTIONS = {
    154            **parser.Parser.FUNCTIONS,  # type: ignore
    155            "DATE_TRUNC": lambda args: exp.DateTrunc(
    156                unit=exp.Literal.string(seq_get(args, 1).name),  # type: ignore
    157                this=seq_get(args, 0),
    158            ),
    159            "DATE_ADD": _date_add(exp.DateAdd),
    160            "DATETIME_ADD": _date_add(exp.DatetimeAdd),
    161            "DIV": lambda args: exp.IntDiv(this=seq_get(args, 0), expression=seq_get(args, 1)),
    162            "REGEXP_CONTAINS": exp.RegexpLike.from_arg_list,
    163            "TIME_ADD": _date_add(exp.TimeAdd),
    164            "TIMESTAMP_ADD": _date_add(exp.TimestampAdd),
    165            "DATE_SUB": _date_add(exp.DateSub),
    166            "DATETIME_SUB": _date_add(exp.DatetimeSub),
    167            "TIME_SUB": _date_add(exp.TimeSub),
    168            "TIMESTAMP_SUB": _date_add(exp.TimestampSub),
    169            "PARSE_TIMESTAMP": lambda args: exp.StrToTime(
    170                this=seq_get(args, 1), format=seq_get(args, 0)
    171            ),
    172        }
    173
    174        FUNCTION_PARSERS = {
    175            **parser.Parser.FUNCTION_PARSERS,  # type: ignore
    176            "ARRAY": lambda self: self.expression(exp.Array, expressions=[self._parse_statement()]),
    177        }
    178        FUNCTION_PARSERS.pop("TRIM")
    179
    180        NO_PAREN_FUNCTIONS = {
    181            **parser.Parser.NO_PAREN_FUNCTIONS,  # type: ignore
    182            TokenType.CURRENT_DATETIME: exp.CurrentDatetime,
    183            TokenType.CURRENT_TIME: exp.CurrentTime,
    184        }
    185
    186        NESTED_TYPE_TOKENS = {
    187            *parser.Parser.NESTED_TYPE_TOKENS,  # type: ignore
    188            TokenType.TABLE,
    189        }
    190
    191        ID_VAR_TOKENS = {
    192            *parser.Parser.ID_VAR_TOKENS,  # type: ignore
    193            TokenType.VALUES,
    194        }
    195
    196        PROPERTY_PARSERS = {
    197            **parser.Parser.PROPERTY_PARSERS,  # type: ignore
    198            "NOT DETERMINISTIC": lambda self: self.expression(
    199                exp.VolatilityProperty, this=exp.Literal.string("VOLATILE")
    200            ),
    201        }
    202
    203    class Generator(generator.Generator):
    204        TRANSFORMS = {
    205            **generator.Generator.TRANSFORMS,  # type: ignore
    206            **transforms.REMOVE_PRECISION_PARAMETERIZED_TYPES,  # type: ignore
    207            exp.ArraySize: rename_func("ARRAY_LENGTH"),
    208            exp.DateAdd: _date_add_sql("DATE", "ADD"),
    209            exp.DateSub: _date_add_sql("DATE", "SUB"),
    210            exp.DatetimeAdd: _date_add_sql("DATETIME", "ADD"),
    211            exp.DatetimeSub: _date_add_sql("DATETIME", "SUB"),
    212            exp.DateDiff: lambda self, e: f"DATE_DIFF({self.sql(e, 'this')}, {self.sql(e, 'expression')}, {self.sql(e.args.get('unit', 'DAY'))})",
    213            exp.DateStrToDate: datestrtodate_sql,
    214            exp.DateTrunc: lambda self, e: self.func("DATE_TRUNC", e.this, e.text("unit")),
    215            exp.GroupConcat: rename_func("STRING_AGG"),
    216            exp.ILike: no_ilike_sql,
    217            exp.IntDiv: rename_func("DIV"),
    218            exp.Select: transforms.preprocess(
    219                [_unqualify_unnest], transforms.delegate("select_sql")
    220            ),
    221            exp.StrToTime: lambda self, e: f"PARSE_TIMESTAMP({self.format_time(e)}, {self.sql(e, 'this')})",
    222            exp.TimeAdd: _date_add_sql("TIME", "ADD"),
    223            exp.TimeSub: _date_add_sql("TIME", "SUB"),
    224            exp.TimestampAdd: _date_add_sql("TIMESTAMP", "ADD"),
    225            exp.TimestampSub: _date_add_sql("TIMESTAMP", "SUB"),
    226            exp.TimeStrToTime: timestrtotime_sql,
    227            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    228            exp.VariancePop: rename_func("VAR_POP"),
    229            exp.Values: _derived_table_values_to_unnest,
    230            exp.ReturnsProperty: _returnsproperty_sql,
    231            exp.Create: _create_sql,
    232            exp.Trim: lambda self, e: self.func(f"TRIM", e.this, e.expression),
    233            exp.VolatilityProperty: lambda self, e: f"DETERMINISTIC"
    234            if e.name == "IMMUTABLE"
    235            else "NOT DETERMINISTIC",
    236            exp.RegexpLike: rename_func("REGEXP_CONTAINS"),
    237        }
    238
    239        TYPE_MAPPING = {
    240            **generator.Generator.TYPE_MAPPING,  # type: ignore
    241            exp.DataType.Type.TINYINT: "INT64",
    242            exp.DataType.Type.SMALLINT: "INT64",
    243            exp.DataType.Type.INT: "INT64",
    244            exp.DataType.Type.BIGINT: "INT64",
    245            exp.DataType.Type.DECIMAL: "NUMERIC",
    246            exp.DataType.Type.FLOAT: "FLOAT64",
    247            exp.DataType.Type.DOUBLE: "FLOAT64",
    248            exp.DataType.Type.BOOLEAN: "BOOL",
    249            exp.DataType.Type.TEXT: "STRING",
    250            exp.DataType.Type.VARCHAR: "STRING",
    251            exp.DataType.Type.NVARCHAR: "STRING",
    252        }
    253        PROPERTIES_LOCATION = {
    254            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
    255            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
    256        }
    257
    258        EXPLICIT_UNION = True
    259
    260        def array_sql(self, expression: exp.Array) -> str:
    261            first_arg = seq_get(expression.expressions, 0)
    262            if isinstance(first_arg, exp.Subqueryable):
    263                return f"ARRAY{self.wrap(self.sql(first_arg))}"
    264
    265            return inline_array_sql(self, expression)
    266
    267        def transaction_sql(self, *_) -> str:
    268            return "BEGIN TRANSACTION"
    269
    270        def commit_sql(self, *_) -> str:
    271            return "COMMIT TRANSACTION"
    272
    273        def rollback_sql(self, *_) -> str:
    274            return "ROLLBACK TRANSACTION"
    275
    276        def in_unnest_op(self, expression: exp.Unnest) -> str:
    277            return self.sql(expression)
    278
    279        def except_op(self, expression: exp.Except) -> str:
    280            if not expression.args.get("distinct", False):
    281                self.unsupported("EXCEPT without DISTINCT is not supported in BigQuery")
    282            return f"EXCEPT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"
    283
    284        def intersect_op(self, expression: exp.Intersect) -> str:
    285            if not expression.args.get("distinct", False):
    286                self.unsupported("INTERSECT without DISTINCT is not supported in BigQuery")
    287            return f"INTERSECT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"

BigQuery()

##### Inherited Members

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

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

    126    class Tokenizer(tokens.Tokenizer):
    127        QUOTES = [
    128            (prefix + quote, quote) if prefix else quote
    129            for quote in ["'", '"', '"""', "'''"]
    130            for prefix in ["", "r", "R"]
    131        ]
    132        COMMENTS = ["--", "#", ("/*", "*/")]
    133        IDENTIFIERS = ["`"]
    134        STRING_ESCAPES = ["\\"]
    135        HEX_STRINGS = [("0x", ""), ("0X", "")]
    136
    137        KEYWORDS = {
    138            **tokens.Tokenizer.KEYWORDS,
    139            "BEGIN": TokenType.COMMAND,
    140            "BEGIN TRANSACTION": TokenType.BEGIN,
    141            "CURRENT_DATETIME": TokenType.CURRENT_DATETIME,
    142            "CURRENT_TIME": TokenType.CURRENT_TIME,
    143            "DECLARE": TokenType.COMMAND,
    144            "GEOGRAPHY": TokenType.GEOGRAPHY,
    145            "FLOAT64": TokenType.DOUBLE,
    146            "INT64": TokenType.BIGINT,
    147            "NOT DETERMINISTIC": TokenType.VOLATILE,
    148            "UNKNOWN": TokenType.NULL,
    149        }
    150        KEYWORDS.pop("DIV")

##### Inherited Members

sqlglot.tokens.Tokenizer
  Tokenizer
  reset
  tokenize

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

    152    class Parser(parser.Parser):
    153        FUNCTIONS = {
    154            **parser.Parser.FUNCTIONS,  # type: ignore
    155            "DATE_TRUNC": lambda args: exp.DateTrunc(
    156                unit=exp.Literal.string(seq_get(args, 1).name),  # type: ignore
    157                this=seq_get(args, 0),
    158            ),
    159            "DATE_ADD": _date_add(exp.DateAdd),
    160            "DATETIME_ADD": _date_add(exp.DatetimeAdd),
    161            "DIV": lambda args: exp.IntDiv(this=seq_get(args, 0), expression=seq_get(args, 1)),
    162            "REGEXP_CONTAINS": exp.RegexpLike.from_arg_list,
    163            "TIME_ADD": _date_add(exp.TimeAdd),
    164            "TIMESTAMP_ADD": _date_add(exp.TimestampAdd),
    165            "DATE_SUB": _date_add(exp.DateSub),
    166            "DATETIME_SUB": _date_add(exp.DatetimeSub),
    167            "TIME_SUB": _date_add(exp.TimeSub),
    168            "TIMESTAMP_SUB": _date_add(exp.TimestampSub),
    169            "PARSE_TIMESTAMP": lambda args: exp.StrToTime(
    170                this=seq_get(args, 1), format=seq_get(args, 0)
    171            ),
    172        }
    173
    174        FUNCTION_PARSERS = {
    175            **parser.Parser.FUNCTION_PARSERS,  # type: ignore
    176            "ARRAY": lambda self: self.expression(exp.Array, expressions=[self._parse_statement()]),
    177        }
    178        FUNCTION_PARSERS.pop("TRIM")
    179
    180        NO_PAREN_FUNCTIONS = {
    181            **parser.Parser.NO_PAREN_FUNCTIONS,  # type: ignore
    182            TokenType.CURRENT_DATETIME: exp.CurrentDatetime,
    183            TokenType.CURRENT_TIME: exp.CurrentTime,
    184        }
    185
    186        NESTED_TYPE_TOKENS = {
    187            *parser.Parser.NESTED_TYPE_TOKENS,  # type: ignore
    188            TokenType.TABLE,
    189        }
    190
    191        ID_VAR_TOKENS = {
    192            *parser.Parser.ID_VAR_TOKENS,  # type: ignore
    193            TokenType.VALUES,
    194        }
    195
    196        PROPERTY_PARSERS = {
    197            **parser.Parser.PROPERTY_PARSERS,  # type: ignore
    198            "NOT DETERMINISTIC": lambda self: self.expression(
    199                exp.VolatilityProperty, this=exp.Literal.string("VOLATILE")
    200            ),
    201        }

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 BigQuery.Generator(sqlglot.generator.Generator): View Source

    203    class Generator(generator.Generator):
    204        TRANSFORMS = {
    205            **generator.Generator.TRANSFORMS,  # type: ignore
    206            **transforms.REMOVE_PRECISION_PARAMETERIZED_TYPES,  # type: ignore
    207            exp.ArraySize: rename_func("ARRAY_LENGTH"),
    208            exp.DateAdd: _date_add_sql("DATE", "ADD"),
    209            exp.DateSub: _date_add_sql("DATE", "SUB"),
    210            exp.DatetimeAdd: _date_add_sql("DATETIME", "ADD"),
    211            exp.DatetimeSub: _date_add_sql("DATETIME", "SUB"),
    212            exp.DateDiff: lambda self, e: f"DATE_DIFF({self.sql(e, 'this')}, {self.sql(e, 'expression')}, {self.sql(e.args.get('unit', 'DAY'))})",
    213            exp.DateStrToDate: datestrtodate_sql,
    214            exp.DateTrunc: lambda self, e: self.func("DATE_TRUNC", e.this, e.text("unit")),
    215            exp.GroupConcat: rename_func("STRING_AGG"),
    216            exp.ILike: no_ilike_sql,
    217            exp.IntDiv: rename_func("DIV"),
    218            exp.Select: transforms.preprocess(
    219                [_unqualify_unnest], transforms.delegate("select_sql")
    220            ),
    221            exp.StrToTime: lambda self, e: f"PARSE_TIMESTAMP({self.format_time(e)}, {self.sql(e, 'this')})",
    222            exp.TimeAdd: _date_add_sql("TIME", "ADD"),
    223            exp.TimeSub: _date_add_sql("TIME", "SUB"),
    224            exp.TimestampAdd: _date_add_sql("TIMESTAMP", "ADD"),
    225            exp.TimestampSub: _date_add_sql("TIMESTAMP", "SUB"),
    226            exp.TimeStrToTime: timestrtotime_sql,
    227            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    228            exp.VariancePop: rename_func("VAR_POP"),
    229            exp.Values: _derived_table_values_to_unnest,
    230            exp.ReturnsProperty: _returnsproperty_sql,
    231            exp.Create: _create_sql,
    232            exp.Trim: lambda self, e: self.func(f"TRIM", e.this, e.expression),
    233            exp.VolatilityProperty: lambda self, e: f"DETERMINISTIC"
    234            if e.name == "IMMUTABLE"
    235            else "NOT DETERMINISTIC",
    236            exp.RegexpLike: rename_func("REGEXP_CONTAINS"),
    237        }
    238
    239        TYPE_MAPPING = {
    240            **generator.Generator.TYPE_MAPPING,  # type: ignore
    241            exp.DataType.Type.TINYINT: "INT64",
    242            exp.DataType.Type.SMALLINT: "INT64",
    243            exp.DataType.Type.INT: "INT64",
    244            exp.DataType.Type.BIGINT: "INT64",
    245            exp.DataType.Type.DECIMAL: "NUMERIC",
    246            exp.DataType.Type.FLOAT: "FLOAT64",
    247            exp.DataType.Type.DOUBLE: "FLOAT64",
    248            exp.DataType.Type.BOOLEAN: "BOOL",
    249            exp.DataType.Type.TEXT: "STRING",
    250            exp.DataType.Type.VARCHAR: "STRING",
    251            exp.DataType.Type.NVARCHAR: "STRING",
    252        }
    253        PROPERTIES_LOCATION = {
    254            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
    255            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
    256        }
    257
    258        EXPLICIT_UNION = True
    259
    260        def array_sql(self, expression: exp.Array) -> str:
    261            first_arg = seq_get(expression.expressions, 0)
    262            if isinstance(first_arg, exp.Subqueryable):
    263                return f"ARRAY{self.wrap(self.sql(first_arg))}"
    264
    265            return inline_array_sql(self, expression)
    266
    267        def transaction_sql(self, *_) -> str:
    268            return "BEGIN TRANSACTION"
    269
    270        def commit_sql(self, *_) -> str:
    271            return "COMMIT TRANSACTION"
    272
    273        def rollback_sql(self, *_) -> str:
    274            return "ROLLBACK TRANSACTION"
    275
    276        def in_unnest_op(self, expression: exp.Unnest) -> str:
    277            return self.sql(expression)
    278
    279        def except_op(self, expression: exp.Except) -> str:
    280            if not expression.args.get("distinct", False):
    281                self.unsupported("EXCEPT without DISTINCT is not supported in BigQuery")
    282            return f"EXCEPT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"
    283
    284        def intersect_op(self, expression: exp.Intersect) -> str:
    285            if not expression.args.get("distinct", False):
    286                self.unsupported("INTERSECT without DISTINCT is not supported in BigQuery")
    287            return f"INTERSECT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"

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): if set to True all identifiers will be delimited by the corresponding character.
- 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 array_sql(self, expression: sqlglot.expressions.Array) -> str: View Source

    260        def array_sql(self, expression: exp.Array) -> str:
    261            first_arg = seq_get(expression.expressions, 0)
    262            if isinstance(first_arg, exp.Subqueryable):
    263                return f"ARRAY{self.wrap(self.sql(first_arg))}"
    264
    265            return inline_array_sql(self, expression)

def transaction_sql(self, *_) -> str: View Source

    267        def transaction_sql(self, *_) -> str:
    268            return "BEGIN TRANSACTION"

def commit_sql(self, *_) -> str: View Source

    270        def commit_sql(self, *_) -> str:
    271            return "COMMIT TRANSACTION"

def rollback_sql(self, *_) -> str: View Source

    273        def rollback_sql(self, *_) -> str:
    274            return "ROLLBACK TRANSACTION"

def in_unnest_op(self, expression: sqlglot.expressions.Unnest) -> str: View Source

    276        def in_unnest_op(self, expression: exp.Unnest) -> str:
    277            return self.sql(expression)

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

    279        def except_op(self, expression: exp.Except) -> str:
    280            if not expression.args.get("distinct", False):
    281                self.unsupported("EXCEPT without DISTINCT is not supported in BigQuery")
    282            return f"EXCEPT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"

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

    284        def intersect_op(self, expression: exp.Intersect) -> str:
    285            if not expression.args.get("distinct", False):
    286                self.unsupported("INTERSECT without DISTINCT is not supported in BigQuery")
    287            return f"INTERSECT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"

##### 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
  columndef_sql
  columnconstraint_sql
  autoincrementcolumnconstraint_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
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_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
  insert_sql
  intersect_sql
  introducer_sql
  pseudotype_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
  lock_sql
  literal_sql
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  select_sql
  schema_sql
  star_sql
  structkwarg_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  window_spec_sql
  withingroup_sql
  between_sql
  bracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  extract_sql
  trim_sql
  concat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  unique_sql
  if_sql
  in_sql
  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
  altercolumn_sql
  renametable_sql
  altertable_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  div_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  is_sql
  like_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