Edit on GitHub

Supports BigQuery Standard SQL.

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

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

Arguments:
  • error_level: the desired error level. Default: ErrorLevel.RAISE
  • error_message_context: determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 50.
  • index_offset: Index offset for arrays eg ARRAY[0] vs ARRAY[1] as the head of a list. Default: 0
  • alias_post_tablesample: If the table alias comes after tablesample. Default: False
  • max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
  • null_ordering: Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
class BigQuery.Generator(sqlglot.generator.Generator):
220    class Generator(generator.Generator):
221        INTEGER_DIVISION = False
222
223        TRANSFORMS = {
224            **generator.Generator.TRANSFORMS,  # type: ignore
225            **transforms.REMOVE_PRECISION_PARAMETERIZED_TYPES,  # type: ignore
226            exp.ArraySize: rename_func("ARRAY_LENGTH"),
227            exp.DateAdd: _date_add_sql("DATE", "ADD"),
228            exp.DateSub: _date_add_sql("DATE", "SUB"),
229            exp.DatetimeAdd: _date_add_sql("DATETIME", "ADD"),
230            exp.DatetimeSub: _date_add_sql("DATETIME", "SUB"),
231            exp.DateDiff: lambda self, e: f"DATE_DIFF({self.sql(e, 'this')}, {self.sql(e, 'expression')}, {self.sql(e.args.get('unit', 'DAY'))})",
232            exp.DateStrToDate: datestrtodate_sql,
233            exp.DateTrunc: lambda self, e: self.func("DATE_TRUNC", e.this, e.text("unit")),
234            exp.GroupConcat: rename_func("STRING_AGG"),
235            exp.ILike: no_ilike_sql,
236            exp.IntDiv: rename_func("DIV"),
237            exp.Min: min_or_least,
238            exp.Select: transforms.preprocess(
239                [_unqualify_unnest], transforms.delegate("select_sql")
240            ),
241            exp.StrToTime: lambda self, e: f"PARSE_TIMESTAMP({self.format_time(e)}, {self.sql(e, 'this')})",
242            exp.TimeAdd: _date_add_sql("TIME", "ADD"),
243            exp.TimeSub: _date_add_sql("TIME", "SUB"),
244            exp.TimestampAdd: _date_add_sql("TIMESTAMP", "ADD"),
245            exp.TimestampSub: _date_add_sql("TIMESTAMP", "SUB"),
246            exp.TimeStrToTime: timestrtotime_sql,
247            exp.TsOrDsToDate: ts_or_ds_to_date_sql("bigquery"),
248            exp.TsOrDsAdd: _date_add_sql("DATE", "ADD"),
249            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
250            exp.VariancePop: rename_func("VAR_POP"),
251            exp.Values: _derived_table_values_to_unnest,
252            exp.ReturnsProperty: _returnsproperty_sql,
253            exp.Create: _create_sql,
254            exp.Trim: lambda self, e: self.func(f"TRIM", e.this, e.expression),
255            exp.VolatilityProperty: lambda self, e: f"DETERMINISTIC"
256            if e.name == "IMMUTABLE"
257            else "NOT DETERMINISTIC",
258            exp.RegexpLike: rename_func("REGEXP_CONTAINS"),
259        }
260
261        TYPE_MAPPING = {
262            **generator.Generator.TYPE_MAPPING,  # type: ignore
263            exp.DataType.Type.TINYINT: "INT64",
264            exp.DataType.Type.SMALLINT: "INT64",
265            exp.DataType.Type.INT: "INT64",
266            exp.DataType.Type.BIGINT: "INT64",
267            exp.DataType.Type.DECIMAL: "NUMERIC",
268            exp.DataType.Type.FLOAT: "FLOAT64",
269            exp.DataType.Type.DOUBLE: "FLOAT64",
270            exp.DataType.Type.BOOLEAN: "BOOL",
271            exp.DataType.Type.TEXT: "STRING",
272            exp.DataType.Type.VARCHAR: "STRING",
273            exp.DataType.Type.NVARCHAR: "STRING",
274        }
275        PROPERTIES_LOCATION = {
276            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
277            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
278        }
279
280        EXPLICIT_UNION = True
281
282        def array_sql(self, expression: exp.Array) -> str:
283            first_arg = seq_get(expression.expressions, 0)
284            if isinstance(first_arg, exp.Subqueryable):
285                return f"ARRAY{self.wrap(self.sql(first_arg))}"
286
287            return inline_array_sql(self, expression)
288
289        def transaction_sql(self, *_) -> str:
290            return "BEGIN TRANSACTION"
291
292        def commit_sql(self, *_) -> str:
293            return "COMMIT TRANSACTION"
294
295        def rollback_sql(self, *_) -> str:
296            return "ROLLBACK TRANSACTION"
297
298        def in_unnest_op(self, expression: exp.Unnest) -> str:
299            return self.sql(expression)
300
301        def except_op(self, expression: exp.Except) -> str:
302            if not expression.args.get("distinct", False):
303                self.unsupported("EXCEPT without DISTINCT is not supported in BigQuery")
304            return f"EXCEPT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"
305
306        def intersect_op(self, expression: exp.Intersect) -> str:
307            if not expression.args.get("distinct", False):
308                self.unsupported("INTERSECT without DISTINCT is not supported in BigQuery")
309            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:
282        def array_sql(self, expression: exp.Array) -> str:
283            first_arg = seq_get(expression.expressions, 0)
284            if isinstance(first_arg, exp.Subqueryable):
285                return f"ARRAY{self.wrap(self.sql(first_arg))}"
286
287            return inline_array_sql(self, expression)
def transaction_sql(self, *_) -> str:
289        def transaction_sql(self, *_) -> str:
290            return "BEGIN TRANSACTION"
def commit_sql(self, *_) -> str:
292        def commit_sql(self, *_) -> str:
293            return "COMMIT TRANSACTION"
def rollback_sql(self, *_) -> str:
295        def rollback_sql(self, *_) -> str:
296            return "ROLLBACK TRANSACTION"
def in_unnest_op(self, expression: sqlglot.expressions.Unnest) -> str:
298        def in_unnest_op(self, expression: exp.Unnest) -> str:
299            return self.sql(expression)
def except_op(self, expression: sqlglot.expressions.Except) -> str:
301        def except_op(self, expression: exp.Except) -> str:
302            if not expression.args.get("distinct", False):
303                self.unsupported("EXCEPT without DISTINCT is not supported in BigQuery")
304            return f"EXCEPT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"
def intersect_op(self, expression: sqlglot.expressions.Intersect) -> str:
306        def intersect_op(self, expression: exp.Intersect) -> str:
307            if not expression.args.get("distinct", False):
308                self.unsupported("INTERSECT without DISTINCT is not supported in BigQuery")
309            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
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
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
withdataproperty_sql
insert_sql
intersect_sql
introducer_sql
pseudotype_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
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
comment_sql
altercolumn_sql
renametable_sql
altertable_sql
droppartition_sql
addconstraint_sql
distinct_sql
ignorenulls_sql
respectnulls_sql
intdiv_sql
dpipe_sql
div_sql
floatdiv_sql
overlaps_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