sqlglot.dialects.snowflake
1from __future__ import annotations 2 3import typing as t 4 5from sqlglot import exp, generator, parser, tokens 6from sqlglot.dialects.dialect import ( 7 Dialect, 8 date_trunc_to_time, 9 datestrtodate_sql, 10 format_time_lambda, 11 inline_array_sql, 12 max_or_greatest, 13 min_or_least, 14 rename_func, 15 timestamptrunc_sql, 16 timestrtotime_sql, 17 ts_or_ds_to_date_sql, 18 var_map_sql, 19) 20from sqlglot.expressions import Literal 21from sqlglot.helper import flatten, seq_get 22from sqlglot.parser import binary_range_parser 23from sqlglot.tokens import TokenType 24 25 26def _check_int(s): 27 if s[0] in ("-", "+"): 28 return s[1:].isdigit() 29 return s.isdigit() 30 31 32# from https://docs.snowflake.com/en/sql-reference/functions/to_timestamp.html 33def _snowflake_to_timestamp(args): 34 if len(args) == 2: 35 first_arg, second_arg = args 36 if second_arg.is_string: 37 # case: <string_expr> [ , <format> ] 38 return format_time_lambda(exp.StrToTime, "snowflake")(args) 39 40 # case: <numeric_expr> [ , <scale> ] 41 if second_arg.name not in ["0", "3", "9"]: 42 raise ValueError( 43 f"Scale for snowflake numeric timestamp is {second_arg}, but should be 0, 3, or 9" 44 ) 45 46 if second_arg.name == "0": 47 timescale = exp.UnixToTime.SECONDS 48 elif second_arg.name == "3": 49 timescale = exp.UnixToTime.MILLIS 50 elif second_arg.name == "9": 51 timescale = exp.UnixToTime.MICROS 52 53 return exp.UnixToTime(this=first_arg, scale=timescale) 54 55 first_arg = seq_get(args, 0) 56 if not isinstance(first_arg, Literal): 57 # case: <variant_expr> 58 return format_time_lambda(exp.StrToTime, "snowflake", default=True)(args) 59 60 if first_arg.is_string: 61 if _check_int(first_arg.this): 62 # case: <integer> 63 return exp.UnixToTime.from_arg_list(args) 64 65 # case: <date_expr> 66 return format_time_lambda(exp.StrToTime, "snowflake", default=True)(args) 67 68 # case: <numeric_expr> 69 return exp.UnixToTime.from_arg_list(args) 70 71 72def _unix_to_time_sql(self, expression): 73 scale = expression.args.get("scale") 74 timestamp = self.sql(expression, "this") 75 if scale in [None, exp.UnixToTime.SECONDS]: 76 return f"TO_TIMESTAMP({timestamp})" 77 if scale == exp.UnixToTime.MILLIS: 78 return f"TO_TIMESTAMP({timestamp}, 3)" 79 if scale == exp.UnixToTime.MICROS: 80 return f"TO_TIMESTAMP({timestamp}, 9)" 81 82 raise ValueError("Improper scale for timestamp") 83 84 85# https://docs.snowflake.com/en/sql-reference/functions/date_part.html 86# https://docs.snowflake.com/en/sql-reference/functions-date-time.html#label-supported-date-time-parts 87def _parse_date_part(self): 88 this = self._parse_var() or self._parse_type() 89 self._match(TokenType.COMMA) 90 expression = self._parse_bitwise() 91 92 name = this.name.upper() 93 if name.startswith("EPOCH"): 94 if name.startswith("EPOCH_MILLISECOND"): 95 scale = 10**3 96 elif name.startswith("EPOCH_MICROSECOND"): 97 scale = 10**6 98 elif name.startswith("EPOCH_NANOSECOND"): 99 scale = 10**9 100 else: 101 scale = None 102 103 ts = self.expression(exp.Cast, this=expression, to=exp.DataType.build("TIMESTAMP")) 104 to_unix = self.expression(exp.TimeToUnix, this=ts) 105 106 if scale: 107 to_unix = exp.Mul(this=to_unix, expression=exp.Literal.number(scale)) 108 109 return to_unix 110 111 return self.expression(exp.Extract, this=this, expression=expression) 112 113 114# https://docs.snowflake.com/en/sql-reference/functions/div0 115def _div0_to_if(args): 116 cond = exp.EQ(this=seq_get(args, 1), expression=exp.Literal.number(0)) 117 true = exp.Literal.number(0) 118 false = exp.Div(this=seq_get(args, 0), expression=seq_get(args, 1)) 119 return exp.If(this=cond, true=true, false=false) 120 121 122# https://docs.snowflake.com/en/sql-reference/functions/zeroifnull 123def _zeroifnull_to_if(args): 124 cond = exp.Is(this=seq_get(args, 0), expression=exp.Null()) 125 return exp.If(this=cond, true=exp.Literal.number(0), false=seq_get(args, 0)) 126 127 128# https://docs.snowflake.com/en/sql-reference/functions/zeroifnull 129def _nullifzero_to_if(args): 130 cond = exp.EQ(this=seq_get(args, 0), expression=exp.Literal.number(0)) 131 return exp.If(this=cond, true=exp.Null(), false=seq_get(args, 0)) 132 133 134def _datatype_sql(self, expression): 135 if expression.this == exp.DataType.Type.ARRAY: 136 return "ARRAY" 137 elif expression.this == exp.DataType.Type.MAP: 138 return "OBJECT" 139 return self.datatype_sql(expression) 140 141 142class Snowflake(Dialect): 143 null_ordering = "nulls_are_large" 144 time_format = "'yyyy-mm-dd hh24:mi:ss'" 145 146 time_mapping = { 147 "YYYY": "%Y", 148 "yyyy": "%Y", 149 "YY": "%y", 150 "yy": "%y", 151 "MMMM": "%B", 152 "mmmm": "%B", 153 "MON": "%b", 154 "mon": "%b", 155 "MM": "%m", 156 "mm": "%m", 157 "DD": "%d", 158 "dd": "%d", 159 "d": "%-d", 160 "DY": "%w", 161 "dy": "%w", 162 "HH24": "%H", 163 "hh24": "%H", 164 "HH12": "%I", 165 "hh12": "%I", 166 "MI": "%M", 167 "mi": "%M", 168 "SS": "%S", 169 "ss": "%S", 170 "FF": "%f", 171 "ff": "%f", 172 "FF6": "%f", 173 "ff6": "%f", 174 } 175 176 class Parser(parser.Parser): 177 FUNCTIONS = { 178 **parser.Parser.FUNCTIONS, 179 "ARRAYAGG": exp.ArrayAgg.from_arg_list, 180 "ARRAY_CONSTRUCT": exp.Array.from_arg_list, 181 "ARRAY_TO_STRING": exp.ArrayJoin.from_arg_list, 182 "CONVERT_TIMEZONE": lambda args: exp.AtTimeZone( 183 this=seq_get(args, 1), 184 zone=seq_get(args, 0), 185 ), 186 "DATE_TRUNC": date_trunc_to_time, 187 "DATEADD": lambda args: exp.DateAdd( 188 this=seq_get(args, 2), 189 expression=seq_get(args, 1), 190 unit=seq_get(args, 0), 191 ), 192 "DATEDIFF": lambda args: exp.DateDiff( 193 this=seq_get(args, 2), 194 expression=seq_get(args, 1), 195 unit=seq_get(args, 0), 196 ), 197 "DIV0": _div0_to_if, 198 "IFF": exp.If.from_arg_list, 199 "NULLIFZERO": _nullifzero_to_if, 200 "OBJECT_CONSTRUCT": parser.parse_var_map, 201 "RLIKE": exp.RegexpLike.from_arg_list, 202 "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)), 203 "TO_ARRAY": exp.Array.from_arg_list, 204 "TO_VARCHAR": exp.ToChar.from_arg_list, 205 "TO_TIMESTAMP": _snowflake_to_timestamp, 206 "ZEROIFNULL": _zeroifnull_to_if, 207 } 208 209 FUNCTION_PARSERS = { 210 **parser.Parser.FUNCTION_PARSERS, 211 "DATE_PART": _parse_date_part, 212 } 213 FUNCTION_PARSERS.pop("TRIM") 214 215 FUNC_TOKENS = { 216 *parser.Parser.FUNC_TOKENS, 217 TokenType.RLIKE, 218 TokenType.TABLE, 219 } 220 221 COLUMN_OPERATORS = { 222 **parser.Parser.COLUMN_OPERATORS, # type: ignore 223 TokenType.COLON: lambda self, this, path: self.expression( 224 exp.Bracket, 225 this=this, 226 expressions=[path], 227 ), 228 } 229 230 RANGE_PARSERS = { 231 **parser.Parser.RANGE_PARSERS, # type: ignore 232 TokenType.LIKE_ANY: binary_range_parser(exp.LikeAny), 233 TokenType.ILIKE_ANY: binary_range_parser(exp.ILikeAny), 234 } 235 236 ALTER_PARSERS = { 237 **parser.Parser.ALTER_PARSERS, # type: ignore 238 "UNSET": lambda self: self._parse_alter_table_set_tag(unset=True), 239 "SET": lambda self: self._parse_alter_table_set_tag(), 240 } 241 242 def _parse_alter_table_set_tag(self, unset: bool = False) -> exp.Expression: 243 self._match_text_seq("TAG") 244 parser = t.cast(t.Callable, self._parse_id_var if unset else self._parse_conjunction) 245 return self.expression(exp.SetTag, expressions=self._parse_csv(parser), unset=unset) 246 247 class Tokenizer(tokens.Tokenizer): 248 QUOTES = ["'", "$$"] 249 STRING_ESCAPES = ["\\", "'"] 250 251 KEYWORDS = { 252 **tokens.Tokenizer.KEYWORDS, 253 "EXCLUDE": TokenType.EXCEPT, 254 "ILIKE ANY": TokenType.ILIKE_ANY, 255 "LIKE ANY": TokenType.LIKE_ANY, 256 "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, 257 "PUT": TokenType.COMMAND, 258 "RENAME": TokenType.REPLACE, 259 "TIMESTAMP_LTZ": TokenType.TIMESTAMPLTZ, 260 "TIMESTAMP_NTZ": TokenType.TIMESTAMP, 261 "TIMESTAMP_TZ": TokenType.TIMESTAMPTZ, 262 "TIMESTAMPNTZ": TokenType.TIMESTAMP, 263 "MINUS": TokenType.EXCEPT, 264 "SAMPLE": TokenType.TABLE_SAMPLE, 265 } 266 267 SINGLE_TOKENS = { 268 **tokens.Tokenizer.SINGLE_TOKENS, 269 "$": TokenType.PARAMETER, 270 } 271 272 class Generator(generator.Generator): 273 PARAMETER_TOKEN = "$" 274 MATCHED_BY_SOURCE = False 275 276 TRANSFORMS = { 277 **generator.Generator.TRANSFORMS, # type: ignore 278 exp.Array: inline_array_sql, 279 exp.ArrayConcat: rename_func("ARRAY_CAT"), 280 exp.ArrayJoin: rename_func("ARRAY_TO_STRING"), 281 exp.AtTimeZone: lambda self, e: self.func( 282 "CONVERT_TIMEZONE", e.args.get("zone"), e.this 283 ), 284 exp.DateAdd: lambda self, e: self.func("DATEADD", e.text("unit"), e.expression, e.this), 285 exp.DateDiff: lambda self, e: self.func( 286 "DATEDIFF", e.text("unit"), e.expression, e.this 287 ), 288 exp.DateStrToDate: datestrtodate_sql, 289 exp.DataType: _datatype_sql, 290 exp.If: rename_func("IFF"), 291 exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 292 exp.LogicalOr: rename_func("BOOLOR_AGG"), 293 exp.LogicalAnd: rename_func("BOOLAND_AGG"), 294 exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 295 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 296 exp.StrPosition: lambda self, e: self.func( 297 "POSITION", e.args.get("substr"), e.this, e.args.get("position") 298 ), 299 exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})", 300 exp.TimestampTrunc: timestamptrunc_sql, 301 exp.TimeStrToTime: timestrtotime_sql, 302 exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})", 303 exp.Trim: lambda self, e: self.func("TRIM", e.this, e.expression), 304 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 305 exp.TsOrDsToDate: ts_or_ds_to_date_sql("snowflake"), 306 exp.UnixToTime: _unix_to_time_sql, 307 exp.DayOfWeek: rename_func("DAYOFWEEK"), 308 exp.Max: max_or_greatest, 309 exp.Min: min_or_least, 310 } 311 312 TYPE_MAPPING = { 313 **generator.Generator.TYPE_MAPPING, # type: ignore 314 exp.DataType.Type.TIMESTAMP: "TIMESTAMPNTZ", 315 } 316 317 STAR_MAPPING = { 318 "except": "EXCLUDE", 319 "replace": "RENAME", 320 } 321 322 PROPERTIES_LOCATION = { 323 **generator.Generator.PROPERTIES_LOCATION, # type: ignore 324 exp.SetProperty: exp.Properties.Location.UNSUPPORTED, 325 } 326 327 def except_op(self, expression): 328 if not expression.args.get("distinct", False): 329 self.unsupported("EXCEPT with All is not supported in Snowflake") 330 return super().except_op(expression) 331 332 def intersect_op(self, expression): 333 if not expression.args.get("distinct", False): 334 self.unsupported("INTERSECT with All is not supported in Snowflake") 335 return super().intersect_op(expression) 336 337 def values_sql(self, expression: exp.Values) -> str: 338 """Due to a bug in Snowflake we want to make sure that all columns in a VALUES table alias are unquoted. 339 340 We also want to make sure that after we find matches where we need to unquote a column that we prevent users 341 from adding quotes to the column by using the `identify` argument when generating the SQL. 342 """ 343 alias = expression.args.get("alias") 344 if alias and alias.args.get("columns"): 345 expression = expression.transform( 346 lambda node: exp.Identifier(**{**node.args, "quoted": False}) 347 if isinstance(node, exp.Identifier) 348 and isinstance(node.parent, exp.TableAlias) 349 and node.arg_key == "columns" 350 else node, 351 ) 352 return self.no_identify(lambda: super(self.__class__, self).values_sql(expression)) 353 return super().values_sql(expression) 354 355 def settag_sql(self, expression: exp.SetTag) -> str: 356 action = "UNSET" if expression.args.get("unset") else "SET" 357 return f"{action} TAG {self.expressions(expression)}" 358 359 def select_sql(self, expression: exp.Select) -> str: 360 """Due to a bug in Snowflake we want to make sure that all columns in a VALUES table alias are unquoted and also 361 that all columns in a SELECT are unquoted. We also want to make sure that after we find matches where we need 362 to unquote a column that we prevent users from adding quotes to the column by using the `identify` argument when 363 generating the SQL. 364 365 Note: We make an assumption that any columns referenced in a VALUES expression should be unquoted throughout the 366 expression. This might not be true in a case where the same column name can be sourced from another table that can 367 properly quote but should be true in most cases. 368 """ 369 values_identifiers = set( 370 flatten( 371 (v.args.get("alias") or exp.Alias()).args.get("columns", []) 372 for v in expression.find_all(exp.Values) 373 ) 374 ) 375 if values_identifiers: 376 expression = expression.transform( 377 lambda node: exp.Identifier(**{**node.args, "quoted": False}) 378 if isinstance(node, exp.Identifier) and node in values_identifiers 379 else node, 380 ) 381 return self.no_identify(lambda: super(self.__class__, self).select_sql(expression)) 382 return super().select_sql(expression) 383 384 def describe_sql(self, expression: exp.Describe) -> str: 385 # Default to table if kind is unknown 386 kind_value = expression.args.get("kind") or "TABLE" 387 kind = f" {kind_value}" if kind_value else "" 388 this = f" {self.sql(expression, 'this')}" 389 return f"DESCRIBE{kind}{this}" 390 391 def generatedasidentitycolumnconstraint_sql( 392 self, expression: exp.GeneratedAsIdentityColumnConstraint 393 ) -> str: 394 start = expression.args.get("start") 395 start = f" START {start}" if start else "" 396 increment = expression.args.get("increment") 397 increment = f" INCREMENT {increment}" if increment else "" 398 return f"AUTOINCREMENT{start}{increment}"
143class Snowflake(Dialect): 144 null_ordering = "nulls_are_large" 145 time_format = "'yyyy-mm-dd hh24:mi:ss'" 146 147 time_mapping = { 148 "YYYY": "%Y", 149 "yyyy": "%Y", 150 "YY": "%y", 151 "yy": "%y", 152 "MMMM": "%B", 153 "mmmm": "%B", 154 "MON": "%b", 155 "mon": "%b", 156 "MM": "%m", 157 "mm": "%m", 158 "DD": "%d", 159 "dd": "%d", 160 "d": "%-d", 161 "DY": "%w", 162 "dy": "%w", 163 "HH24": "%H", 164 "hh24": "%H", 165 "HH12": "%I", 166 "hh12": "%I", 167 "MI": "%M", 168 "mi": "%M", 169 "SS": "%S", 170 "ss": "%S", 171 "FF": "%f", 172 "ff": "%f", 173 "FF6": "%f", 174 "ff6": "%f", 175 } 176 177 class Parser(parser.Parser): 178 FUNCTIONS = { 179 **parser.Parser.FUNCTIONS, 180 "ARRAYAGG": exp.ArrayAgg.from_arg_list, 181 "ARRAY_CONSTRUCT": exp.Array.from_arg_list, 182 "ARRAY_TO_STRING": exp.ArrayJoin.from_arg_list, 183 "CONVERT_TIMEZONE": lambda args: exp.AtTimeZone( 184 this=seq_get(args, 1), 185 zone=seq_get(args, 0), 186 ), 187 "DATE_TRUNC": date_trunc_to_time, 188 "DATEADD": lambda args: exp.DateAdd( 189 this=seq_get(args, 2), 190 expression=seq_get(args, 1), 191 unit=seq_get(args, 0), 192 ), 193 "DATEDIFF": lambda args: exp.DateDiff( 194 this=seq_get(args, 2), 195 expression=seq_get(args, 1), 196 unit=seq_get(args, 0), 197 ), 198 "DIV0": _div0_to_if, 199 "IFF": exp.If.from_arg_list, 200 "NULLIFZERO": _nullifzero_to_if, 201 "OBJECT_CONSTRUCT": parser.parse_var_map, 202 "RLIKE": exp.RegexpLike.from_arg_list, 203 "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)), 204 "TO_ARRAY": exp.Array.from_arg_list, 205 "TO_VARCHAR": exp.ToChar.from_arg_list, 206 "TO_TIMESTAMP": _snowflake_to_timestamp, 207 "ZEROIFNULL": _zeroifnull_to_if, 208 } 209 210 FUNCTION_PARSERS = { 211 **parser.Parser.FUNCTION_PARSERS, 212 "DATE_PART": _parse_date_part, 213 } 214 FUNCTION_PARSERS.pop("TRIM") 215 216 FUNC_TOKENS = { 217 *parser.Parser.FUNC_TOKENS, 218 TokenType.RLIKE, 219 TokenType.TABLE, 220 } 221 222 COLUMN_OPERATORS = { 223 **parser.Parser.COLUMN_OPERATORS, # type: ignore 224 TokenType.COLON: lambda self, this, path: self.expression( 225 exp.Bracket, 226 this=this, 227 expressions=[path], 228 ), 229 } 230 231 RANGE_PARSERS = { 232 **parser.Parser.RANGE_PARSERS, # type: ignore 233 TokenType.LIKE_ANY: binary_range_parser(exp.LikeAny), 234 TokenType.ILIKE_ANY: binary_range_parser(exp.ILikeAny), 235 } 236 237 ALTER_PARSERS = { 238 **parser.Parser.ALTER_PARSERS, # type: ignore 239 "UNSET": lambda self: self._parse_alter_table_set_tag(unset=True), 240 "SET": lambda self: self._parse_alter_table_set_tag(), 241 } 242 243 def _parse_alter_table_set_tag(self, unset: bool = False) -> exp.Expression: 244 self._match_text_seq("TAG") 245 parser = t.cast(t.Callable, self._parse_id_var if unset else self._parse_conjunction) 246 return self.expression(exp.SetTag, expressions=self._parse_csv(parser), unset=unset) 247 248 class Tokenizer(tokens.Tokenizer): 249 QUOTES = ["'", "$$"] 250 STRING_ESCAPES = ["\\", "'"] 251 252 KEYWORDS = { 253 **tokens.Tokenizer.KEYWORDS, 254 "EXCLUDE": TokenType.EXCEPT, 255 "ILIKE ANY": TokenType.ILIKE_ANY, 256 "LIKE ANY": TokenType.LIKE_ANY, 257 "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, 258 "PUT": TokenType.COMMAND, 259 "RENAME": TokenType.REPLACE, 260 "TIMESTAMP_LTZ": TokenType.TIMESTAMPLTZ, 261 "TIMESTAMP_NTZ": TokenType.TIMESTAMP, 262 "TIMESTAMP_TZ": TokenType.TIMESTAMPTZ, 263 "TIMESTAMPNTZ": TokenType.TIMESTAMP, 264 "MINUS": TokenType.EXCEPT, 265 "SAMPLE": TokenType.TABLE_SAMPLE, 266 } 267 268 SINGLE_TOKENS = { 269 **tokens.Tokenizer.SINGLE_TOKENS, 270 "$": TokenType.PARAMETER, 271 } 272 273 class Generator(generator.Generator): 274 PARAMETER_TOKEN = "$" 275 MATCHED_BY_SOURCE = False 276 277 TRANSFORMS = { 278 **generator.Generator.TRANSFORMS, # type: ignore 279 exp.Array: inline_array_sql, 280 exp.ArrayConcat: rename_func("ARRAY_CAT"), 281 exp.ArrayJoin: rename_func("ARRAY_TO_STRING"), 282 exp.AtTimeZone: lambda self, e: self.func( 283 "CONVERT_TIMEZONE", e.args.get("zone"), e.this 284 ), 285 exp.DateAdd: lambda self, e: self.func("DATEADD", e.text("unit"), e.expression, e.this), 286 exp.DateDiff: lambda self, e: self.func( 287 "DATEDIFF", e.text("unit"), e.expression, e.this 288 ), 289 exp.DateStrToDate: datestrtodate_sql, 290 exp.DataType: _datatype_sql, 291 exp.If: rename_func("IFF"), 292 exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 293 exp.LogicalOr: rename_func("BOOLOR_AGG"), 294 exp.LogicalAnd: rename_func("BOOLAND_AGG"), 295 exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 296 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 297 exp.StrPosition: lambda self, e: self.func( 298 "POSITION", e.args.get("substr"), e.this, e.args.get("position") 299 ), 300 exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})", 301 exp.TimestampTrunc: timestamptrunc_sql, 302 exp.TimeStrToTime: timestrtotime_sql, 303 exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})", 304 exp.Trim: lambda self, e: self.func("TRIM", e.this, e.expression), 305 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 306 exp.TsOrDsToDate: ts_or_ds_to_date_sql("snowflake"), 307 exp.UnixToTime: _unix_to_time_sql, 308 exp.DayOfWeek: rename_func("DAYOFWEEK"), 309 exp.Max: max_or_greatest, 310 exp.Min: min_or_least, 311 } 312 313 TYPE_MAPPING = { 314 **generator.Generator.TYPE_MAPPING, # type: ignore 315 exp.DataType.Type.TIMESTAMP: "TIMESTAMPNTZ", 316 } 317 318 STAR_MAPPING = { 319 "except": "EXCLUDE", 320 "replace": "RENAME", 321 } 322 323 PROPERTIES_LOCATION = { 324 **generator.Generator.PROPERTIES_LOCATION, # type: ignore 325 exp.SetProperty: exp.Properties.Location.UNSUPPORTED, 326 } 327 328 def except_op(self, expression): 329 if not expression.args.get("distinct", False): 330 self.unsupported("EXCEPT with All is not supported in Snowflake") 331 return super().except_op(expression) 332 333 def intersect_op(self, expression): 334 if not expression.args.get("distinct", False): 335 self.unsupported("INTERSECT with All is not supported in Snowflake") 336 return super().intersect_op(expression) 337 338 def values_sql(self, expression: exp.Values) -> str: 339 """Due to a bug in Snowflake we want to make sure that all columns in a VALUES table alias are unquoted. 340 341 We also want to make sure that after we find matches where we need to unquote a column that we prevent users 342 from adding quotes to the column by using the `identify` argument when generating the SQL. 343 """ 344 alias = expression.args.get("alias") 345 if alias and alias.args.get("columns"): 346 expression = expression.transform( 347 lambda node: exp.Identifier(**{**node.args, "quoted": False}) 348 if isinstance(node, exp.Identifier) 349 and isinstance(node.parent, exp.TableAlias) 350 and node.arg_key == "columns" 351 else node, 352 ) 353 return self.no_identify(lambda: super(self.__class__, self).values_sql(expression)) 354 return super().values_sql(expression) 355 356 def settag_sql(self, expression: exp.SetTag) -> str: 357 action = "UNSET" if expression.args.get("unset") else "SET" 358 return f"{action} TAG {self.expressions(expression)}" 359 360 def select_sql(self, expression: exp.Select) -> str: 361 """Due to a bug in Snowflake we want to make sure that all columns in a VALUES table alias are unquoted and also 362 that all columns in a SELECT are unquoted. We also want to make sure that after we find matches where we need 363 to unquote a column that we prevent users from adding quotes to the column by using the `identify` argument when 364 generating the SQL. 365 366 Note: We make an assumption that any columns referenced in a VALUES expression should be unquoted throughout the 367 expression. This might not be true in a case where the same column name can be sourced from another table that can 368 properly quote but should be true in most cases. 369 """ 370 values_identifiers = set( 371 flatten( 372 (v.args.get("alias") or exp.Alias()).args.get("columns", []) 373 for v in expression.find_all(exp.Values) 374 ) 375 ) 376 if values_identifiers: 377 expression = expression.transform( 378 lambda node: exp.Identifier(**{**node.args, "quoted": False}) 379 if isinstance(node, exp.Identifier) and node in values_identifiers 380 else node, 381 ) 382 return self.no_identify(lambda: super(self.__class__, self).select_sql(expression)) 383 return super().select_sql(expression) 384 385 def describe_sql(self, expression: exp.Describe) -> str: 386 # Default to table if kind is unknown 387 kind_value = expression.args.get("kind") or "TABLE" 388 kind = f" {kind_value}" if kind_value else "" 389 this = f" {self.sql(expression, 'this')}" 390 return f"DESCRIBE{kind}{this}" 391 392 def generatedasidentitycolumnconstraint_sql( 393 self, expression: exp.GeneratedAsIdentityColumnConstraint 394 ) -> str: 395 start = expression.args.get("start") 396 start = f" START {start}" if start else "" 397 increment = expression.args.get("increment") 398 increment = f" INCREMENT {increment}" if increment else "" 399 return f"AUTOINCREMENT{start}{increment}"
177 class Parser(parser.Parser): 178 FUNCTIONS = { 179 **parser.Parser.FUNCTIONS, 180 "ARRAYAGG": exp.ArrayAgg.from_arg_list, 181 "ARRAY_CONSTRUCT": exp.Array.from_arg_list, 182 "ARRAY_TO_STRING": exp.ArrayJoin.from_arg_list, 183 "CONVERT_TIMEZONE": lambda args: exp.AtTimeZone( 184 this=seq_get(args, 1), 185 zone=seq_get(args, 0), 186 ), 187 "DATE_TRUNC": date_trunc_to_time, 188 "DATEADD": lambda args: exp.DateAdd( 189 this=seq_get(args, 2), 190 expression=seq_get(args, 1), 191 unit=seq_get(args, 0), 192 ), 193 "DATEDIFF": lambda args: exp.DateDiff( 194 this=seq_get(args, 2), 195 expression=seq_get(args, 1), 196 unit=seq_get(args, 0), 197 ), 198 "DIV0": _div0_to_if, 199 "IFF": exp.If.from_arg_list, 200 "NULLIFZERO": _nullifzero_to_if, 201 "OBJECT_CONSTRUCT": parser.parse_var_map, 202 "RLIKE": exp.RegexpLike.from_arg_list, 203 "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)), 204 "TO_ARRAY": exp.Array.from_arg_list, 205 "TO_VARCHAR": exp.ToChar.from_arg_list, 206 "TO_TIMESTAMP": _snowflake_to_timestamp, 207 "ZEROIFNULL": _zeroifnull_to_if, 208 } 209 210 FUNCTION_PARSERS = { 211 **parser.Parser.FUNCTION_PARSERS, 212 "DATE_PART": _parse_date_part, 213 } 214 FUNCTION_PARSERS.pop("TRIM") 215 216 FUNC_TOKENS = { 217 *parser.Parser.FUNC_TOKENS, 218 TokenType.RLIKE, 219 TokenType.TABLE, 220 } 221 222 COLUMN_OPERATORS = { 223 **parser.Parser.COLUMN_OPERATORS, # type: ignore 224 TokenType.COLON: lambda self, this, path: self.expression( 225 exp.Bracket, 226 this=this, 227 expressions=[path], 228 ), 229 } 230 231 RANGE_PARSERS = { 232 **parser.Parser.RANGE_PARSERS, # type: ignore 233 TokenType.LIKE_ANY: binary_range_parser(exp.LikeAny), 234 TokenType.ILIKE_ANY: binary_range_parser(exp.ILikeAny), 235 } 236 237 ALTER_PARSERS = { 238 **parser.Parser.ALTER_PARSERS, # type: ignore 239 "UNSET": lambda self: self._parse_alter_table_set_tag(unset=True), 240 "SET": lambda self: self._parse_alter_table_set_tag(), 241 } 242 243 def _parse_alter_table_set_tag(self, unset: bool = False) -> exp.Expression: 244 self._match_text_seq("TAG") 245 parser = t.cast(t.Callable, self._parse_id_var if unset else self._parse_conjunction) 246 return self.expression(exp.SetTag, expressions=self._parse_csv(parser), unset=unset)
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
248 class Tokenizer(tokens.Tokenizer): 249 QUOTES = ["'", "$$"] 250 STRING_ESCAPES = ["\\", "'"] 251 252 KEYWORDS = { 253 **tokens.Tokenizer.KEYWORDS, 254 "EXCLUDE": TokenType.EXCEPT, 255 "ILIKE ANY": TokenType.ILIKE_ANY, 256 "LIKE ANY": TokenType.LIKE_ANY, 257 "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, 258 "PUT": TokenType.COMMAND, 259 "RENAME": TokenType.REPLACE, 260 "TIMESTAMP_LTZ": TokenType.TIMESTAMPLTZ, 261 "TIMESTAMP_NTZ": TokenType.TIMESTAMP, 262 "TIMESTAMP_TZ": TokenType.TIMESTAMPTZ, 263 "TIMESTAMPNTZ": TokenType.TIMESTAMP, 264 "MINUS": TokenType.EXCEPT, 265 "SAMPLE": TokenType.TABLE_SAMPLE, 266 } 267 268 SINGLE_TOKENS = { 269 **tokens.Tokenizer.SINGLE_TOKENS, 270 "$": TokenType.PARAMETER, 271 }
Inherited Members
273 class Generator(generator.Generator): 274 PARAMETER_TOKEN = "$" 275 MATCHED_BY_SOURCE = False 276 277 TRANSFORMS = { 278 **generator.Generator.TRANSFORMS, # type: ignore 279 exp.Array: inline_array_sql, 280 exp.ArrayConcat: rename_func("ARRAY_CAT"), 281 exp.ArrayJoin: rename_func("ARRAY_TO_STRING"), 282 exp.AtTimeZone: lambda self, e: self.func( 283 "CONVERT_TIMEZONE", e.args.get("zone"), e.this 284 ), 285 exp.DateAdd: lambda self, e: self.func("DATEADD", e.text("unit"), e.expression, e.this), 286 exp.DateDiff: lambda self, e: self.func( 287 "DATEDIFF", e.text("unit"), e.expression, e.this 288 ), 289 exp.DateStrToDate: datestrtodate_sql, 290 exp.DataType: _datatype_sql, 291 exp.If: rename_func("IFF"), 292 exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 293 exp.LogicalOr: rename_func("BOOLOR_AGG"), 294 exp.LogicalAnd: rename_func("BOOLAND_AGG"), 295 exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 296 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 297 exp.StrPosition: lambda self, e: self.func( 298 "POSITION", e.args.get("substr"), e.this, e.args.get("position") 299 ), 300 exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})", 301 exp.TimestampTrunc: timestamptrunc_sql, 302 exp.TimeStrToTime: timestrtotime_sql, 303 exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})", 304 exp.Trim: lambda self, e: self.func("TRIM", e.this, e.expression), 305 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 306 exp.TsOrDsToDate: ts_or_ds_to_date_sql("snowflake"), 307 exp.UnixToTime: _unix_to_time_sql, 308 exp.DayOfWeek: rename_func("DAYOFWEEK"), 309 exp.Max: max_or_greatest, 310 exp.Min: min_or_least, 311 } 312 313 TYPE_MAPPING = { 314 **generator.Generator.TYPE_MAPPING, # type: ignore 315 exp.DataType.Type.TIMESTAMP: "TIMESTAMPNTZ", 316 } 317 318 STAR_MAPPING = { 319 "except": "EXCLUDE", 320 "replace": "RENAME", 321 } 322 323 PROPERTIES_LOCATION = { 324 **generator.Generator.PROPERTIES_LOCATION, # type: ignore 325 exp.SetProperty: exp.Properties.Location.UNSUPPORTED, 326 } 327 328 def except_op(self, expression): 329 if not expression.args.get("distinct", False): 330 self.unsupported("EXCEPT with All is not supported in Snowflake") 331 return super().except_op(expression) 332 333 def intersect_op(self, expression): 334 if not expression.args.get("distinct", False): 335 self.unsupported("INTERSECT with All is not supported in Snowflake") 336 return super().intersect_op(expression) 337 338 def values_sql(self, expression: exp.Values) -> str: 339 """Due to a bug in Snowflake we want to make sure that all columns in a VALUES table alias are unquoted. 340 341 We also want to make sure that after we find matches where we need to unquote a column that we prevent users 342 from adding quotes to the column by using the `identify` argument when generating the SQL. 343 """ 344 alias = expression.args.get("alias") 345 if alias and alias.args.get("columns"): 346 expression = expression.transform( 347 lambda node: exp.Identifier(**{**node.args, "quoted": False}) 348 if isinstance(node, exp.Identifier) 349 and isinstance(node.parent, exp.TableAlias) 350 and node.arg_key == "columns" 351 else node, 352 ) 353 return self.no_identify(lambda: super(self.__class__, self).values_sql(expression)) 354 return super().values_sql(expression) 355 356 def settag_sql(self, expression: exp.SetTag) -> str: 357 action = "UNSET" if expression.args.get("unset") else "SET" 358 return f"{action} TAG {self.expressions(expression)}" 359 360 def select_sql(self, expression: exp.Select) -> str: 361 """Due to a bug in Snowflake we want to make sure that all columns in a VALUES table alias are unquoted and also 362 that all columns in a SELECT are unquoted. We also want to make sure that after we find matches where we need 363 to unquote a column that we prevent users from adding quotes to the column by using the `identify` argument when 364 generating the SQL. 365 366 Note: We make an assumption that any columns referenced in a VALUES expression should be unquoted throughout the 367 expression. This might not be true in a case where the same column name can be sourced from another table that can 368 properly quote but should be true in most cases. 369 """ 370 values_identifiers = set( 371 flatten( 372 (v.args.get("alias") or exp.Alias()).args.get("columns", []) 373 for v in expression.find_all(exp.Values) 374 ) 375 ) 376 if values_identifiers: 377 expression = expression.transform( 378 lambda node: exp.Identifier(**{**node.args, "quoted": False}) 379 if isinstance(node, exp.Identifier) and node in values_identifiers 380 else node, 381 ) 382 return self.no_identify(lambda: super(self.__class__, self).select_sql(expression)) 383 return super().select_sql(expression) 384 385 def describe_sql(self, expression: exp.Describe) -> str: 386 # Default to table if kind is unknown 387 kind_value = expression.args.get("kind") or "TABLE" 388 kind = f" {kind_value}" if kind_value else "" 389 this = f" {self.sql(expression, 'this')}" 390 return f"DESCRIBE{kind}{this}" 391 392 def generatedasidentitycolumnconstraint_sql( 393 self, expression: exp.GeneratedAsIdentityColumnConstraint 394 ) -> str: 395 start = expression.args.get("start") 396 start = f" START {start}" if start else "" 397 increment = expression.args.get("increment") 398 increment = f" INCREMENT {increment}" if increment else "" 399 return f"AUTOINCREMENT{start}{increment}"
Generator interprets the given syntax tree and produces a SQL string as an output.
Arguments:
- time_mapping (dict): the dictionary of custom time mappings in which the key represents a python time format and the output the target time format
- time_trie (trie): a trie of the time_mapping keys
- pretty (bool): if set to True the returned string will be formatted. Default: False.
- quote_start (str): specifies which starting character to use to delimit quotes. Default: '.
- quote_end (str): specifies which ending character to use to delimit quotes. Default: '.
- identifier_start (str): specifies which starting character to use to delimit identifiers. Default: ".
- identifier_end (str): specifies which ending character to use to delimit identifiers. Default: ".
- identify (bool | str): 'always': always quote, 'safe': quote identifiers if they don't contain an upcase, True defaults to always.
- normalize (bool): if set to True all identifiers will lower cased
- string_escape (str): specifies a string escape character. Default: '.
- identifier_escape (str): specifies an identifier escape character. Default: ".
- pad (int): determines padding in a formatted string. Default: 2.
- indent (int): determines the size of indentation in a formatted string. Default: 4.
- unnest_column_only (bool): if true unnest table aliases are considered only as column aliases
- normalize_functions (str): normalize function names, "upper", "lower", or None Default: "upper"
- alias_post_tablesample (bool): if the table alias comes after tablesample Default: False
- unsupported_level (ErrorLevel): determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- null_ordering (str): Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
- max_unsupported (int): Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma (bool): if the the comma is leading or trailing in select statements Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether or not to preserve comments in the output SQL code. Default: True
338 def values_sql(self, expression: exp.Values) -> str: 339 """Due to a bug in Snowflake we want to make sure that all columns in a VALUES table alias are unquoted. 340 341 We also want to make sure that after we find matches where we need to unquote a column that we prevent users 342 from adding quotes to the column by using the `identify` argument when generating the SQL. 343 """ 344 alias = expression.args.get("alias") 345 if alias and alias.args.get("columns"): 346 expression = expression.transform( 347 lambda node: exp.Identifier(**{**node.args, "quoted": False}) 348 if isinstance(node, exp.Identifier) 349 and isinstance(node.parent, exp.TableAlias) 350 and node.arg_key == "columns" 351 else node, 352 ) 353 return self.no_identify(lambda: super(self.__class__, self).values_sql(expression)) 354 return super().values_sql(expression)
Due to a bug in Snowflake we want to make sure that all columns in a VALUES table alias are unquoted.
We also want to make sure that after we find matches where we need to unquote a column that we prevent users
from adding quotes to the column by using the identify
argument when generating the SQL.
360 def select_sql(self, expression: exp.Select) -> str: 361 """Due to a bug in Snowflake we want to make sure that all columns in a VALUES table alias are unquoted and also 362 that all columns in a SELECT are unquoted. We also want to make sure that after we find matches where we need 363 to unquote a column that we prevent users from adding quotes to the column by using the `identify` argument when 364 generating the SQL. 365 366 Note: We make an assumption that any columns referenced in a VALUES expression should be unquoted throughout the 367 expression. This might not be true in a case where the same column name can be sourced from another table that can 368 properly quote but should be true in most cases. 369 """ 370 values_identifiers = set( 371 flatten( 372 (v.args.get("alias") or exp.Alias()).args.get("columns", []) 373 for v in expression.find_all(exp.Values) 374 ) 375 ) 376 if values_identifiers: 377 expression = expression.transform( 378 lambda node: exp.Identifier(**{**node.args, "quoted": False}) 379 if isinstance(node, exp.Identifier) and node in values_identifiers 380 else node, 381 ) 382 return self.no_identify(lambda: super(self.__class__, self).select_sql(expression)) 383 return super().select_sql(expression)
Due to a bug in Snowflake we want to make sure that all columns in a VALUES table alias are unquoted and also
that all columns in a SELECT are unquoted. We also want to make sure that after we find matches where we need
to unquote a column that we prevent users from adding quotes to the column by using the identify
argument when
generating the SQL.
Note: We make an assumption that any columns referenced in a VALUES expression should be unquoted throughout the expression. This might not be true in a case where the same column name can be sourced from another table that can properly quote but should be true in most cases.
392 def generatedasidentitycolumnconstraint_sql( 393 self, expression: exp.GeneratedAsIdentityColumnConstraint 394 ) -> str: 395 start = expression.args.get("start") 396 start = f" START {start}" if start else "" 397 increment = expression.args.get("increment") 398 increment = f" INCREMENT {increment}" if increment else "" 399 return f"AUTOINCREMENT{start}{increment}"
Inherited Members
- sqlglot.generator.Generator
- Generator
- generate
- unsupported
- sep
- seg
- pad_comment
- maybe_comment
- wrap
- no_identify
- normalize_func
- indent
- sql
- uncache_sql
- cache_sql
- characterset_sql
- column_sql
- columnposition_sql
- columndef_sql
- columnconstraint_sql
- autoincrementcolumnconstraint_sql
- compresscolumnconstraint_sql
- notnullcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_sql
- create_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
- var_sql
- into_sql
- from_sql
- group_sql
- having_sql
- join_sql
- lambda_sql
- lateral_sql
- limit_sql
- offset_sql
- setitem_sql
- set_sql
- pragma_sql
- lock_sql
- literal_sql
- loaddata_sql
- null_sql
- boolean_sql
- order_sql
- cluster_sql
- distribute_sql
- sort_sql
- ordered_sql
- matchrecognize_sql
- query_modifiers
- 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
- matchagainst_sql
- jsonkeyvalue_sql
- jsonobject_sql
- in_sql
- in_unnest_op
- interval_sql
- return_sql
- reference_sql
- anonymous_sql
- paren_sql
- neg_sql
- not_sql
- alias_sql
- aliases_sql
- attimezone_sql
- add_sql
- and_sql
- connector_sql
- bitwiseand_sql
- bitwiseleftshift_sql
- bitwisenot_sql
- bitwiseor_sql
- bitwiserightshift_sql
- bitwisexor_sql
- cast_sql
- currentdate_sql
- collate_sql
- command_sql
- comment_sql
- transaction_sql
- commit_sql
- rollback_sql
- altercolumn_sql
- renametable_sql
- altertable_sql
- droppartition_sql
- addconstraint_sql
- distinct_sql
- ignorenulls_sql
- respectnulls_sql
- intdiv_sql
- dpipe_sql
- div_sql
- overlaps_sql
- distance_sql
- dot_sql
- eq_sql
- escape_sql
- glob_sql
- gt_sql
- gte_sql
- ilike_sql
- ilikeany_sql
- is_sql
- like_sql
- likeany_sql
- similarto_sql
- lt_sql
- lte_sql
- mod_sql
- mul_sql
- neq_sql
- nullsafeeq_sql
- nullsafeneq_sql
- or_sql
- slice_sql
- sub_sql
- trycast_sql
- use_sql
- binary
- function_fallback_sql
- func
- format_args
- text_width
- format_time
- expressions
- op_expressions
- naked_property
- set_operation
- tag_sql
- token_sql
- userdefinedfunction_sql
- joinhint_sql
- kwarg_sql
- when_sql
- merge_sql
- tochar_sql