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