sqlglot.dialects.presto
1from __future__ import annotations 2 3import typing as t 4 5from sqlglot import exp, generator, parser, tokens, transforms 6from sqlglot.dialects.dialect import ( 7 Dialect, 8 NormalizationStrategy, 9 binary_from_function, 10 bool_xor_sql, 11 date_trunc_to_time, 12 datestrtodate_sql, 13 encode_decode_sql, 14 format_time_lambda, 15 if_sql, 16 left_to_substring_sql, 17 no_ilike_sql, 18 no_pivot_sql, 19 no_safe_divide_sql, 20 no_timestamp_sql, 21 regexp_extract_sql, 22 rename_func, 23 right_to_substring_sql, 24 struct_extract_sql, 25 timestamptrunc_sql, 26 timestrtotime_sql, 27 ts_or_ds_add_cast, 28) 29from sqlglot.dialects.mysql import MySQL 30from sqlglot.helper import apply_index_offset, seq_get 31from sqlglot.tokens import TokenType 32 33 34def _approx_distinct_sql(self: Presto.Generator, expression: exp.ApproxDistinct) -> str: 35 accuracy = expression.args.get("accuracy") 36 accuracy = ", " + self.sql(accuracy) if accuracy else "" 37 return f"APPROX_DISTINCT({self.sql(expression, 'this')}{accuracy})" 38 39 40def _explode_to_unnest_sql(self: Presto.Generator, expression: exp.Lateral) -> str: 41 if isinstance(expression.this, exp.Explode): 42 return self.sql( 43 exp.Join( 44 this=exp.Unnest( 45 expressions=[expression.this.this], 46 alias=expression.args.get("alias"), 47 offset=isinstance(expression.this, exp.Posexplode), 48 ), 49 kind="cross", 50 ) 51 ) 52 return self.lateral_sql(expression) 53 54 55def _initcap_sql(self: Presto.Generator, expression: exp.Initcap) -> str: 56 regex = r"(\w)(\w*)" 57 return f"REGEXP_REPLACE({self.sql(expression, 'this')}, '{regex}', x -> UPPER(x[1]) || LOWER(x[2]))" 58 59 60def _no_sort_array(self: Presto.Generator, expression: exp.SortArray) -> str: 61 if expression.args.get("asc") == exp.false(): 62 comparator = "(a, b) -> CASE WHEN a < b THEN 1 WHEN a > b THEN -1 ELSE 0 END" 63 else: 64 comparator = None 65 return self.func("ARRAY_SORT", expression.this, comparator) 66 67 68def _schema_sql(self: Presto.Generator, expression: exp.Schema) -> str: 69 if isinstance(expression.parent, exp.Property): 70 columns = ", ".join(f"'{c.name}'" for c in expression.expressions) 71 return f"ARRAY[{columns}]" 72 73 if expression.parent: 74 for schema in expression.parent.find_all(exp.Schema): 75 column_defs = schema.find_all(exp.ColumnDef) 76 if column_defs and isinstance(schema.parent, exp.Property): 77 expression.expressions.extend(column_defs) 78 79 return self.schema_sql(expression) 80 81 82def _quantile_sql(self: Presto.Generator, expression: exp.Quantile) -> str: 83 self.unsupported("Presto does not support exact quantiles") 84 return f"APPROX_PERCENTILE({self.sql(expression, 'this')}, {self.sql(expression, 'quantile')})" 85 86 87def _str_to_time_sql( 88 self: Presto.Generator, expression: exp.StrToDate | exp.StrToTime | exp.TsOrDsToDate 89) -> str: 90 return f"DATE_PARSE({self.sql(expression, 'this')}, {self.format_time(expression)})" 91 92 93def _ts_or_ds_to_date_sql(self: Presto.Generator, expression: exp.TsOrDsToDate) -> str: 94 time_format = self.format_time(expression) 95 if time_format and time_format not in (Presto.TIME_FORMAT, Presto.DATE_FORMAT): 96 return exp.cast(_str_to_time_sql(self, expression), "DATE").sql(dialect="presto") 97 return exp.cast(exp.cast(expression.this, "TIMESTAMP", copy=True), "DATE").sql(dialect="presto") 98 99 100def _ts_or_ds_add_sql(self: Presto.Generator, expression: exp.TsOrDsAdd) -> str: 101 expression = ts_or_ds_add_cast(expression) 102 unit = exp.Literal.string(expression.text("unit") or "DAY") 103 return self.func("DATE_ADD", unit, expression.expression, expression.this) 104 105 106def _ts_or_ds_diff_sql(self: Presto.Generator, expression: exp.TsOrDsDiff) -> str: 107 this = exp.cast(expression.this, "TIMESTAMP") 108 expr = exp.cast(expression.expression, "TIMESTAMP") 109 unit = exp.Literal.string(expression.text("unit") or "DAY") 110 return self.func("DATE_DIFF", unit, expr, this) 111 112 113def _approx_percentile(args: t.List) -> exp.Expression: 114 if len(args) == 4: 115 return exp.ApproxQuantile( 116 this=seq_get(args, 0), 117 weight=seq_get(args, 1), 118 quantile=seq_get(args, 2), 119 accuracy=seq_get(args, 3), 120 ) 121 if len(args) == 3: 122 return exp.ApproxQuantile( 123 this=seq_get(args, 0), quantile=seq_get(args, 1), accuracy=seq_get(args, 2) 124 ) 125 return exp.ApproxQuantile.from_arg_list(args) 126 127 128def _from_unixtime(args: t.List) -> exp.Expression: 129 if len(args) == 3: 130 return exp.UnixToTime( 131 this=seq_get(args, 0), 132 hours=seq_get(args, 1), 133 minutes=seq_get(args, 2), 134 ) 135 if len(args) == 2: 136 return exp.UnixToTime(this=seq_get(args, 0), zone=seq_get(args, 1)) 137 138 return exp.UnixToTime.from_arg_list(args) 139 140 141def _parse_element_at(args: t.List) -> exp.Bracket: 142 this = seq_get(args, 0) 143 index = seq_get(args, 1) 144 assert isinstance(this, exp.Expression) and isinstance(index, exp.Expression) 145 return exp.Bracket(this=this, expressions=[index], offset=1, safe=True) 146 147 148def _unnest_sequence(expression: exp.Expression) -> exp.Expression: 149 if isinstance(expression, exp.Table): 150 if isinstance(expression.this, exp.GenerateSeries): 151 unnest = exp.Unnest(expressions=[expression.this]) 152 153 if expression.alias: 154 return exp.alias_(unnest, alias="_u", table=[expression.alias], copy=False) 155 return unnest 156 return expression 157 158 159def _first_last_sql(self: Presto.Generator, expression: exp.First | exp.Last) -> str: 160 """ 161 Trino doesn't support FIRST / LAST as functions, but they're valid in the context 162 of MATCH_RECOGNIZE, so we need to preserve them in that case. In all other cases 163 they're converted into an ARBITRARY call. 164 165 Reference: https://trino.io/docs/current/sql/match-recognize.html#logical-navigation-functions 166 """ 167 if isinstance(expression.find_ancestor(exp.MatchRecognize, exp.Select), exp.MatchRecognize): 168 return self.function_fallback_sql(expression) 169 170 return rename_func("ARBITRARY")(self, expression) 171 172 173def _unix_to_time_sql(self: Presto.Generator, expression: exp.UnixToTime) -> str: 174 scale = expression.args.get("scale") 175 timestamp = self.sql(expression, "this") 176 if scale in (None, exp.UnixToTime.SECONDS): 177 return rename_func("FROM_UNIXTIME")(self, expression) 178 if scale == exp.UnixToTime.MILLIS: 179 return f"FROM_UNIXTIME(CAST({timestamp} AS DOUBLE) / 1000)" 180 if scale == exp.UnixToTime.MICROS: 181 return f"FROM_UNIXTIME(CAST({timestamp} AS DOUBLE) / 1000000)" 182 if scale == exp.UnixToTime.NANOS: 183 return f"FROM_UNIXTIME(CAST({timestamp} AS DOUBLE) / 1000000000)" 184 185 self.unsupported(f"Unsupported scale for timestamp: {scale}.") 186 return "" 187 188 189def _to_int(expression: exp.Expression) -> exp.Expression: 190 if not expression.type: 191 from sqlglot.optimizer.annotate_types import annotate_types 192 193 annotate_types(expression) 194 if expression.type and expression.type.this not in exp.DataType.INTEGER_TYPES: 195 return exp.cast(expression, to=exp.DataType.Type.BIGINT) 196 return expression 197 198 199def _parse_to_char(args: t.List) -> exp.TimeToStr: 200 fmt = seq_get(args, 1) 201 if isinstance(fmt, exp.Literal): 202 # We uppercase this to match Teradata's format mapping keys 203 fmt.set("this", fmt.this.upper()) 204 205 # We use "teradata" on purpose here, because the time formats are different in Presto. 206 # See https://prestodb.io/docs/current/functions/teradata.html?highlight=to_char#to_char 207 return format_time_lambda(exp.TimeToStr, "teradata")(args) 208 209 210class Presto(Dialect): 211 INDEX_OFFSET = 1 212 NULL_ORDERING = "nulls_are_last" 213 TIME_FORMAT = MySQL.TIME_FORMAT 214 TIME_MAPPING = MySQL.TIME_MAPPING 215 STRICT_STRING_CONCAT = True 216 SUPPORTS_SEMI_ANTI_JOIN = False 217 TYPED_DIVISION = True 218 219 # https://github.com/trinodb/trino/issues/17 220 # https://github.com/trinodb/trino/issues/12289 221 # https://github.com/prestodb/presto/issues/2863 222 NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE 223 224 class Tokenizer(tokens.Tokenizer): 225 UNICODE_STRINGS = [ 226 (prefix + q, q) 227 for q in t.cast(t.List[str], tokens.Tokenizer.QUOTES) 228 for prefix in ("U&", "u&") 229 ] 230 231 KEYWORDS = { 232 **tokens.Tokenizer.KEYWORDS, 233 "START": TokenType.BEGIN, 234 "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, 235 "ROW": TokenType.STRUCT, 236 "IPADDRESS": TokenType.IPADDRESS, 237 "IPPREFIX": TokenType.IPPREFIX, 238 } 239 240 class Parser(parser.Parser): 241 FUNCTIONS = { 242 **parser.Parser.FUNCTIONS, 243 "ARBITRARY": exp.AnyValue.from_arg_list, 244 "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list, 245 "APPROX_PERCENTILE": _approx_percentile, 246 "BITWISE_AND": binary_from_function(exp.BitwiseAnd), 247 "BITWISE_NOT": lambda args: exp.BitwiseNot(this=seq_get(args, 0)), 248 "BITWISE_OR": binary_from_function(exp.BitwiseOr), 249 "BITWISE_XOR": binary_from_function(exp.BitwiseXor), 250 "CARDINALITY": exp.ArraySize.from_arg_list, 251 "CONTAINS": exp.ArrayContains.from_arg_list, 252 "DATE_ADD": lambda args: exp.DateAdd( 253 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 254 ), 255 "DATE_DIFF": lambda args: exp.DateDiff( 256 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 257 ), 258 "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"), 259 "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"), 260 "DATE_TRUNC": date_trunc_to_time, 261 "ELEMENT_AT": _parse_element_at, 262 "FROM_HEX": exp.Unhex.from_arg_list, 263 "FROM_UNIXTIME": _from_unixtime, 264 "FROM_UTF8": lambda args: exp.Decode( 265 this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8") 266 ), 267 "NOW": exp.CurrentTimestamp.from_arg_list, 268 "REGEXP_EXTRACT": lambda args: exp.RegexpExtract( 269 this=seq_get(args, 0), expression=seq_get(args, 1), group=seq_get(args, 2) 270 ), 271 "REGEXP_REPLACE": lambda args: exp.RegexpReplace( 272 this=seq_get(args, 0), 273 expression=seq_get(args, 1), 274 replacement=seq_get(args, 2) or exp.Literal.string(""), 275 ), 276 "ROW": exp.Struct.from_arg_list, 277 "SEQUENCE": exp.GenerateSeries.from_arg_list, 278 "SET_AGG": exp.ArrayUniqueAgg.from_arg_list, 279 "SPLIT_TO_MAP": exp.StrToMap.from_arg_list, 280 "STRPOS": lambda args: exp.StrPosition( 281 this=seq_get(args, 0), substr=seq_get(args, 1), instance=seq_get(args, 2) 282 ), 283 "TO_CHAR": _parse_to_char, 284 "TO_HEX": exp.Hex.from_arg_list, 285 "TO_UNIXTIME": exp.TimeToUnix.from_arg_list, 286 "TO_UTF8": lambda args: exp.Encode( 287 this=seq_get(args, 0), charset=exp.Literal.string("utf-8") 288 ), 289 } 290 291 FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy() 292 FUNCTION_PARSERS.pop("TRIM") 293 294 class Generator(generator.Generator): 295 INTERVAL_ALLOWS_PLURAL_FORM = False 296 JOIN_HINTS = False 297 TABLE_HINTS = False 298 QUERY_HINTS = False 299 IS_BOOL_ALLOWED = False 300 TZ_TO_WITH_TIME_ZONE = True 301 NVL2_SUPPORTED = False 302 STRUCT_DELIMITER = ("(", ")") 303 LIMIT_ONLY_LITERALS = True 304 SUPPORTS_SINGLE_ARG_CONCAT = False 305 306 PROPERTIES_LOCATION = { 307 **generator.Generator.PROPERTIES_LOCATION, 308 exp.LocationProperty: exp.Properties.Location.UNSUPPORTED, 309 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 310 } 311 312 TYPE_MAPPING = { 313 **generator.Generator.TYPE_MAPPING, 314 exp.DataType.Type.INT: "INTEGER", 315 exp.DataType.Type.FLOAT: "REAL", 316 exp.DataType.Type.BINARY: "VARBINARY", 317 exp.DataType.Type.TEXT: "VARCHAR", 318 exp.DataType.Type.TIMETZ: "TIME", 319 exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP", 320 exp.DataType.Type.STRUCT: "ROW", 321 exp.DataType.Type.DATETIME: "TIMESTAMP", 322 exp.DataType.Type.DATETIME64: "TIMESTAMP", 323 } 324 325 TRANSFORMS = { 326 **generator.Generator.TRANSFORMS, 327 exp.AnyValue: rename_func("ARBITRARY"), 328 exp.ApproxDistinct: _approx_distinct_sql, 329 exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"), 330 exp.ArgMax: rename_func("MAX_BY"), 331 exp.ArgMin: rename_func("MIN_BY"), 332 exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]", 333 exp.ArrayConcat: rename_func("CONCAT"), 334 exp.ArrayContains: rename_func("CONTAINS"), 335 exp.ArraySize: rename_func("CARDINALITY"), 336 exp.ArrayUniqueAgg: rename_func("SET_AGG"), 337 exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 338 exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 339 exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})", 340 exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 341 exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 342 exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 343 exp.Cast: transforms.preprocess([transforms.epoch_cast_to_ts]), 344 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 345 exp.DateAdd: lambda self, e: self.func( 346 "DATE_ADD", 347 exp.Literal.string(e.text("unit") or "DAY"), 348 _to_int( 349 e.expression, 350 ), 351 e.this, 352 ), 353 exp.DateDiff: lambda self, e: self.func( 354 "DATE_DIFF", exp.Literal.string(e.text("unit") or "DAY"), e.expression, e.this 355 ), 356 exp.DateStrToDate: datestrtodate_sql, 357 exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.DATEINT_FORMAT}) AS INT)", 358 exp.DateSub: lambda self, e: self.func( 359 "DATE_ADD", 360 exp.Literal.string(e.text("unit") or "DAY"), 361 _to_int(e.expression * -1), 362 e.this, 363 ), 364 exp.Decode: lambda self, e: encode_decode_sql(self, e, "FROM_UTF8"), 365 exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.DATEINT_FORMAT}) AS DATE)", 366 exp.Encode: lambda self, e: encode_decode_sql(self, e, "TO_UTF8"), 367 exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'", 368 exp.First: _first_last_sql, 369 exp.Group: transforms.preprocess([transforms.unalias_group]), 370 exp.GroupConcat: lambda self, e: self.func( 371 "ARRAY_JOIN", self.func("ARRAY_AGG", e.this), e.args.get("separator") 372 ), 373 exp.Hex: rename_func("TO_HEX"), 374 exp.If: if_sql(), 375 exp.ILike: no_ilike_sql, 376 exp.Initcap: _initcap_sql, 377 exp.ParseJSON: rename_func("JSON_PARSE"), 378 exp.Last: _first_last_sql, 379 exp.Lateral: _explode_to_unnest_sql, 380 exp.Left: left_to_substring_sql, 381 exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"), 382 exp.LogicalAnd: rename_func("BOOL_AND"), 383 exp.LogicalOr: rename_func("BOOL_OR"), 384 exp.Pivot: no_pivot_sql, 385 exp.Quantile: _quantile_sql, 386 exp.RegexpExtract: regexp_extract_sql, 387 exp.Right: right_to_substring_sql, 388 exp.SafeDivide: no_safe_divide_sql, 389 exp.Schema: _schema_sql, 390 exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), 391 exp.Select: transforms.preprocess( 392 [ 393 transforms.eliminate_qualify, 394 transforms.eliminate_distinct_on, 395 transforms.explode_to_unnest(1), 396 transforms.eliminate_semi_and_anti_joins, 397 ] 398 ), 399 exp.SortArray: _no_sort_array, 400 exp.StrPosition: rename_func("STRPOS"), 401 exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)", 402 exp.StrToMap: rename_func("SPLIT_TO_MAP"), 403 exp.StrToTime: _str_to_time_sql, 404 exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))", 405 exp.StructExtract: struct_extract_sql, 406 exp.Table: transforms.preprocess([_unnest_sequence]), 407 exp.Timestamp: no_timestamp_sql, 408 exp.TimestampTrunc: timestamptrunc_sql, 409 exp.TimeStrToDate: timestrtotime_sql, 410 exp.TimeStrToTime: timestrtotime_sql, 411 exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.TIME_FORMAT}))", 412 exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 413 exp.TimeToUnix: rename_func("TO_UNIXTIME"), 414 exp.ToChar: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 415 exp.TryCast: transforms.preprocess([transforms.epoch_cast_to_ts]), 416 exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)", 417 exp.TsOrDsAdd: _ts_or_ds_add_sql, 418 exp.TsOrDsDiff: _ts_or_ds_diff_sql, 419 exp.TsOrDsToDate: _ts_or_ds_to_date_sql, 420 exp.Unhex: rename_func("FROM_HEX"), 421 exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})", 422 exp.UnixToTime: _unix_to_time_sql, 423 exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)", 424 exp.VariancePop: rename_func("VAR_POP"), 425 exp.With: transforms.preprocess([transforms.add_recursive_cte_column_names]), 426 exp.WithinGroup: transforms.preprocess( 427 [transforms.remove_within_group_for_percentiles] 428 ), 429 exp.Xor: bool_xor_sql, 430 } 431 432 def bracket_sql(self, expression: exp.Bracket) -> str: 433 if expression.args.get("safe"): 434 return self.func( 435 "ELEMENT_AT", 436 expression.this, 437 seq_get( 438 apply_index_offset( 439 expression.this, 440 expression.expressions, 441 1 - expression.args.get("offset", 0), 442 ), 443 0, 444 ), 445 ) 446 return super().bracket_sql(expression) 447 448 def struct_sql(self, expression: exp.Struct) -> str: 449 if any(isinstance(arg, self.KEY_VALUE_DEFINITIONS) for arg in expression.expressions): 450 self.unsupported("Struct with key-value definitions is unsupported.") 451 return self.function_fallback_sql(expression) 452 453 return rename_func("ROW")(self, expression) 454 455 def interval_sql(self, expression: exp.Interval) -> str: 456 unit = self.sql(expression, "unit") 457 if expression.this and unit.startswith("WEEK"): 458 return f"({expression.this.name} * INTERVAL '7' DAY)" 459 return super().interval_sql(expression) 460 461 def transaction_sql(self, expression: exp.Transaction) -> str: 462 modes = expression.args.get("modes") 463 modes = f" {', '.join(modes)}" if modes else "" 464 return f"START TRANSACTION{modes}" 465 466 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 467 start = expression.args["start"] 468 end = expression.args["end"] 469 step = expression.args.get("step") 470 471 if isinstance(start, exp.Cast): 472 target_type = start.to 473 elif isinstance(end, exp.Cast): 474 target_type = end.to 475 else: 476 target_type = None 477 478 if target_type and target_type.is_type("timestamp"): 479 if target_type is start.to: 480 end = exp.cast(end, target_type) 481 else: 482 start = exp.cast(start, target_type) 483 484 return self.func("SEQUENCE", start, end, step) 485 486 def offset_limit_modifiers( 487 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 488 ) -> t.List[str]: 489 return [ 490 self.sql(expression, "offset"), 491 self.sql(limit), 492 ] 493 494 def create_sql(self, expression: exp.Create) -> str: 495 """ 496 Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression), 497 so we need to remove them 498 """ 499 kind = expression.args["kind"] 500 schema = expression.this 501 if kind == "VIEW" and schema.expressions: 502 expression.this.set("expressions", None) 503 return super().create_sql(expression)
211class Presto(Dialect): 212 INDEX_OFFSET = 1 213 NULL_ORDERING = "nulls_are_last" 214 TIME_FORMAT = MySQL.TIME_FORMAT 215 TIME_MAPPING = MySQL.TIME_MAPPING 216 STRICT_STRING_CONCAT = True 217 SUPPORTS_SEMI_ANTI_JOIN = False 218 TYPED_DIVISION = True 219 220 # https://github.com/trinodb/trino/issues/17 221 # https://github.com/trinodb/trino/issues/12289 222 # https://github.com/prestodb/presto/issues/2863 223 NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE 224 225 class Tokenizer(tokens.Tokenizer): 226 UNICODE_STRINGS = [ 227 (prefix + q, q) 228 for q in t.cast(t.List[str], tokens.Tokenizer.QUOTES) 229 for prefix in ("U&", "u&") 230 ] 231 232 KEYWORDS = { 233 **tokens.Tokenizer.KEYWORDS, 234 "START": TokenType.BEGIN, 235 "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, 236 "ROW": TokenType.STRUCT, 237 "IPADDRESS": TokenType.IPADDRESS, 238 "IPPREFIX": TokenType.IPPREFIX, 239 } 240 241 class Parser(parser.Parser): 242 FUNCTIONS = { 243 **parser.Parser.FUNCTIONS, 244 "ARBITRARY": exp.AnyValue.from_arg_list, 245 "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list, 246 "APPROX_PERCENTILE": _approx_percentile, 247 "BITWISE_AND": binary_from_function(exp.BitwiseAnd), 248 "BITWISE_NOT": lambda args: exp.BitwiseNot(this=seq_get(args, 0)), 249 "BITWISE_OR": binary_from_function(exp.BitwiseOr), 250 "BITWISE_XOR": binary_from_function(exp.BitwiseXor), 251 "CARDINALITY": exp.ArraySize.from_arg_list, 252 "CONTAINS": exp.ArrayContains.from_arg_list, 253 "DATE_ADD": lambda args: exp.DateAdd( 254 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 255 ), 256 "DATE_DIFF": lambda args: exp.DateDiff( 257 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 258 ), 259 "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"), 260 "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"), 261 "DATE_TRUNC": date_trunc_to_time, 262 "ELEMENT_AT": _parse_element_at, 263 "FROM_HEX": exp.Unhex.from_arg_list, 264 "FROM_UNIXTIME": _from_unixtime, 265 "FROM_UTF8": lambda args: exp.Decode( 266 this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8") 267 ), 268 "NOW": exp.CurrentTimestamp.from_arg_list, 269 "REGEXP_EXTRACT": lambda args: exp.RegexpExtract( 270 this=seq_get(args, 0), expression=seq_get(args, 1), group=seq_get(args, 2) 271 ), 272 "REGEXP_REPLACE": lambda args: exp.RegexpReplace( 273 this=seq_get(args, 0), 274 expression=seq_get(args, 1), 275 replacement=seq_get(args, 2) or exp.Literal.string(""), 276 ), 277 "ROW": exp.Struct.from_arg_list, 278 "SEQUENCE": exp.GenerateSeries.from_arg_list, 279 "SET_AGG": exp.ArrayUniqueAgg.from_arg_list, 280 "SPLIT_TO_MAP": exp.StrToMap.from_arg_list, 281 "STRPOS": lambda args: exp.StrPosition( 282 this=seq_get(args, 0), substr=seq_get(args, 1), instance=seq_get(args, 2) 283 ), 284 "TO_CHAR": _parse_to_char, 285 "TO_HEX": exp.Hex.from_arg_list, 286 "TO_UNIXTIME": exp.TimeToUnix.from_arg_list, 287 "TO_UTF8": lambda args: exp.Encode( 288 this=seq_get(args, 0), charset=exp.Literal.string("utf-8") 289 ), 290 } 291 292 FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy() 293 FUNCTION_PARSERS.pop("TRIM") 294 295 class Generator(generator.Generator): 296 INTERVAL_ALLOWS_PLURAL_FORM = False 297 JOIN_HINTS = False 298 TABLE_HINTS = False 299 QUERY_HINTS = False 300 IS_BOOL_ALLOWED = False 301 TZ_TO_WITH_TIME_ZONE = True 302 NVL2_SUPPORTED = False 303 STRUCT_DELIMITER = ("(", ")") 304 LIMIT_ONLY_LITERALS = True 305 SUPPORTS_SINGLE_ARG_CONCAT = False 306 307 PROPERTIES_LOCATION = { 308 **generator.Generator.PROPERTIES_LOCATION, 309 exp.LocationProperty: exp.Properties.Location.UNSUPPORTED, 310 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 311 } 312 313 TYPE_MAPPING = { 314 **generator.Generator.TYPE_MAPPING, 315 exp.DataType.Type.INT: "INTEGER", 316 exp.DataType.Type.FLOAT: "REAL", 317 exp.DataType.Type.BINARY: "VARBINARY", 318 exp.DataType.Type.TEXT: "VARCHAR", 319 exp.DataType.Type.TIMETZ: "TIME", 320 exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP", 321 exp.DataType.Type.STRUCT: "ROW", 322 exp.DataType.Type.DATETIME: "TIMESTAMP", 323 exp.DataType.Type.DATETIME64: "TIMESTAMP", 324 } 325 326 TRANSFORMS = { 327 **generator.Generator.TRANSFORMS, 328 exp.AnyValue: rename_func("ARBITRARY"), 329 exp.ApproxDistinct: _approx_distinct_sql, 330 exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"), 331 exp.ArgMax: rename_func("MAX_BY"), 332 exp.ArgMin: rename_func("MIN_BY"), 333 exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]", 334 exp.ArrayConcat: rename_func("CONCAT"), 335 exp.ArrayContains: rename_func("CONTAINS"), 336 exp.ArraySize: rename_func("CARDINALITY"), 337 exp.ArrayUniqueAgg: rename_func("SET_AGG"), 338 exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 339 exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 340 exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})", 341 exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 342 exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 343 exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 344 exp.Cast: transforms.preprocess([transforms.epoch_cast_to_ts]), 345 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 346 exp.DateAdd: lambda self, e: self.func( 347 "DATE_ADD", 348 exp.Literal.string(e.text("unit") or "DAY"), 349 _to_int( 350 e.expression, 351 ), 352 e.this, 353 ), 354 exp.DateDiff: lambda self, e: self.func( 355 "DATE_DIFF", exp.Literal.string(e.text("unit") or "DAY"), e.expression, e.this 356 ), 357 exp.DateStrToDate: datestrtodate_sql, 358 exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.DATEINT_FORMAT}) AS INT)", 359 exp.DateSub: lambda self, e: self.func( 360 "DATE_ADD", 361 exp.Literal.string(e.text("unit") or "DAY"), 362 _to_int(e.expression * -1), 363 e.this, 364 ), 365 exp.Decode: lambda self, e: encode_decode_sql(self, e, "FROM_UTF8"), 366 exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.DATEINT_FORMAT}) AS DATE)", 367 exp.Encode: lambda self, e: encode_decode_sql(self, e, "TO_UTF8"), 368 exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'", 369 exp.First: _first_last_sql, 370 exp.Group: transforms.preprocess([transforms.unalias_group]), 371 exp.GroupConcat: lambda self, e: self.func( 372 "ARRAY_JOIN", self.func("ARRAY_AGG", e.this), e.args.get("separator") 373 ), 374 exp.Hex: rename_func("TO_HEX"), 375 exp.If: if_sql(), 376 exp.ILike: no_ilike_sql, 377 exp.Initcap: _initcap_sql, 378 exp.ParseJSON: rename_func("JSON_PARSE"), 379 exp.Last: _first_last_sql, 380 exp.Lateral: _explode_to_unnest_sql, 381 exp.Left: left_to_substring_sql, 382 exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"), 383 exp.LogicalAnd: rename_func("BOOL_AND"), 384 exp.LogicalOr: rename_func("BOOL_OR"), 385 exp.Pivot: no_pivot_sql, 386 exp.Quantile: _quantile_sql, 387 exp.RegexpExtract: regexp_extract_sql, 388 exp.Right: right_to_substring_sql, 389 exp.SafeDivide: no_safe_divide_sql, 390 exp.Schema: _schema_sql, 391 exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), 392 exp.Select: transforms.preprocess( 393 [ 394 transforms.eliminate_qualify, 395 transforms.eliminate_distinct_on, 396 transforms.explode_to_unnest(1), 397 transforms.eliminate_semi_and_anti_joins, 398 ] 399 ), 400 exp.SortArray: _no_sort_array, 401 exp.StrPosition: rename_func("STRPOS"), 402 exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)", 403 exp.StrToMap: rename_func("SPLIT_TO_MAP"), 404 exp.StrToTime: _str_to_time_sql, 405 exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))", 406 exp.StructExtract: struct_extract_sql, 407 exp.Table: transforms.preprocess([_unnest_sequence]), 408 exp.Timestamp: no_timestamp_sql, 409 exp.TimestampTrunc: timestamptrunc_sql, 410 exp.TimeStrToDate: timestrtotime_sql, 411 exp.TimeStrToTime: timestrtotime_sql, 412 exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.TIME_FORMAT}))", 413 exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 414 exp.TimeToUnix: rename_func("TO_UNIXTIME"), 415 exp.ToChar: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 416 exp.TryCast: transforms.preprocess([transforms.epoch_cast_to_ts]), 417 exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)", 418 exp.TsOrDsAdd: _ts_or_ds_add_sql, 419 exp.TsOrDsDiff: _ts_or_ds_diff_sql, 420 exp.TsOrDsToDate: _ts_or_ds_to_date_sql, 421 exp.Unhex: rename_func("FROM_HEX"), 422 exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})", 423 exp.UnixToTime: _unix_to_time_sql, 424 exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)", 425 exp.VariancePop: rename_func("VAR_POP"), 426 exp.With: transforms.preprocess([transforms.add_recursive_cte_column_names]), 427 exp.WithinGroup: transforms.preprocess( 428 [transforms.remove_within_group_for_percentiles] 429 ), 430 exp.Xor: bool_xor_sql, 431 } 432 433 def bracket_sql(self, expression: exp.Bracket) -> str: 434 if expression.args.get("safe"): 435 return self.func( 436 "ELEMENT_AT", 437 expression.this, 438 seq_get( 439 apply_index_offset( 440 expression.this, 441 expression.expressions, 442 1 - expression.args.get("offset", 0), 443 ), 444 0, 445 ), 446 ) 447 return super().bracket_sql(expression) 448 449 def struct_sql(self, expression: exp.Struct) -> str: 450 if any(isinstance(arg, self.KEY_VALUE_DEFINITIONS) for arg in expression.expressions): 451 self.unsupported("Struct with key-value definitions is unsupported.") 452 return self.function_fallback_sql(expression) 453 454 return rename_func("ROW")(self, expression) 455 456 def interval_sql(self, expression: exp.Interval) -> str: 457 unit = self.sql(expression, "unit") 458 if expression.this and unit.startswith("WEEK"): 459 return f"({expression.this.name} * INTERVAL '7' DAY)" 460 return super().interval_sql(expression) 461 462 def transaction_sql(self, expression: exp.Transaction) -> str: 463 modes = expression.args.get("modes") 464 modes = f" {', '.join(modes)}" if modes else "" 465 return f"START TRANSACTION{modes}" 466 467 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 468 start = expression.args["start"] 469 end = expression.args["end"] 470 step = expression.args.get("step") 471 472 if isinstance(start, exp.Cast): 473 target_type = start.to 474 elif isinstance(end, exp.Cast): 475 target_type = end.to 476 else: 477 target_type = None 478 479 if target_type and target_type.is_type("timestamp"): 480 if target_type is start.to: 481 end = exp.cast(end, target_type) 482 else: 483 start = exp.cast(start, target_type) 484 485 return self.func("SEQUENCE", start, end, step) 486 487 def offset_limit_modifiers( 488 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 489 ) -> t.List[str]: 490 return [ 491 self.sql(expression, "offset"), 492 self.sql(limit), 493 ] 494 495 def create_sql(self, expression: exp.Create) -> str: 496 """ 497 Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression), 498 so we need to remove them 499 """ 500 kind = expression.args["kind"] 501 schema = expression.this 502 if kind == "VIEW" and schema.expressions: 503 expression.this.set("expressions", None) 504 return super().create_sql(expression)
Indicates the default NULL
ordering method to use if not explicitly set.
Possible values: "nulls_are_small"
, "nulls_are_large"
, "nulls_are_last"
Associates this dialect's time formats with their equivalent Python strftime
format.
Whether the behavior of a / b
depends on the types of a
and b
.
False means a / b
is always float division.
True means a / b
is integer division if both a
and b
are integers.
Specifies the strategy according to which identifiers should be normalized.
Inherited Members
- sqlglot.dialects.dialect.Dialect
- Dialect
- WEEK_OFFSET
- UNNEST_COLUMN_ONLY
- ALIAS_POST_TABLESAMPLE
- IDENTIFIERS_CAN_START_WITH_DIGIT
- DPIPE_IS_STRING_CONCAT
- SUPPORTS_USER_DEFINED_TYPES
- NORMALIZE_FUNCTIONS
- LOG_BASE_FIRST
- SAFE_DIVISION
- CONCAT_COALESCE
- DATE_FORMAT
- DATEINT_FORMAT
- FORMAT_MAPPING
- ESCAPE_SEQUENCES
- PSEUDOCOLUMNS
- PREFER_CTE_ALIAS_COLUMN
- get_or_raise
- format_time
- normalize_identifier
- case_sensitive
- can_identify
- quote_identifier
- parse
- parse_into
- generate
- transpile
- tokenize
- tokenizer
- parser
- generator
225 class Tokenizer(tokens.Tokenizer): 226 UNICODE_STRINGS = [ 227 (prefix + q, q) 228 for q in t.cast(t.List[str], tokens.Tokenizer.QUOTES) 229 for prefix in ("U&", "u&") 230 ] 231 232 KEYWORDS = { 233 **tokens.Tokenizer.KEYWORDS, 234 "START": TokenType.BEGIN, 235 "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, 236 "ROW": TokenType.STRUCT, 237 "IPADDRESS": TokenType.IPADDRESS, 238 "IPPREFIX": TokenType.IPPREFIX, 239 }
Inherited Members
- sqlglot.tokens.Tokenizer
- Tokenizer
- SINGLE_TOKENS
- BIT_STRINGS
- BYTE_STRINGS
- HEX_STRINGS
- RAW_STRINGS
- HEREDOC_STRINGS
- IDENTIFIERS
- IDENTIFIER_ESCAPES
- QUOTES
- STRING_ESCAPES
- VAR_SINGLE_TOKENS
- WHITE_SPACE
- COMMANDS
- COMMAND_PREFIX_TOKENS
- NUMERIC_LITERALS
- COMMENTS
- dialect
- reset
- tokenize
- peek
- tokenize_rs
- size
- sql
- tokens
241 class Parser(parser.Parser): 242 FUNCTIONS = { 243 **parser.Parser.FUNCTIONS, 244 "ARBITRARY": exp.AnyValue.from_arg_list, 245 "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list, 246 "APPROX_PERCENTILE": _approx_percentile, 247 "BITWISE_AND": binary_from_function(exp.BitwiseAnd), 248 "BITWISE_NOT": lambda args: exp.BitwiseNot(this=seq_get(args, 0)), 249 "BITWISE_OR": binary_from_function(exp.BitwiseOr), 250 "BITWISE_XOR": binary_from_function(exp.BitwiseXor), 251 "CARDINALITY": exp.ArraySize.from_arg_list, 252 "CONTAINS": exp.ArrayContains.from_arg_list, 253 "DATE_ADD": lambda args: exp.DateAdd( 254 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 255 ), 256 "DATE_DIFF": lambda args: exp.DateDiff( 257 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 258 ), 259 "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"), 260 "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"), 261 "DATE_TRUNC": date_trunc_to_time, 262 "ELEMENT_AT": _parse_element_at, 263 "FROM_HEX": exp.Unhex.from_arg_list, 264 "FROM_UNIXTIME": _from_unixtime, 265 "FROM_UTF8": lambda args: exp.Decode( 266 this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8") 267 ), 268 "NOW": exp.CurrentTimestamp.from_arg_list, 269 "REGEXP_EXTRACT": lambda args: exp.RegexpExtract( 270 this=seq_get(args, 0), expression=seq_get(args, 1), group=seq_get(args, 2) 271 ), 272 "REGEXP_REPLACE": lambda args: exp.RegexpReplace( 273 this=seq_get(args, 0), 274 expression=seq_get(args, 1), 275 replacement=seq_get(args, 2) or exp.Literal.string(""), 276 ), 277 "ROW": exp.Struct.from_arg_list, 278 "SEQUENCE": exp.GenerateSeries.from_arg_list, 279 "SET_AGG": exp.ArrayUniqueAgg.from_arg_list, 280 "SPLIT_TO_MAP": exp.StrToMap.from_arg_list, 281 "STRPOS": lambda args: exp.StrPosition( 282 this=seq_get(args, 0), substr=seq_get(args, 1), instance=seq_get(args, 2) 283 ), 284 "TO_CHAR": _parse_to_char, 285 "TO_HEX": exp.Hex.from_arg_list, 286 "TO_UNIXTIME": exp.TimeToUnix.from_arg_list, 287 "TO_UTF8": lambda args: exp.Encode( 288 this=seq_get(args, 0), charset=exp.Literal.string("utf-8") 289 ), 290 } 291 292 FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy() 293 FUNCTION_PARSERS.pop("TRIM")
Parser consumes a list of tokens produced by the Tokenizer and produces a parsed syntax tree.
Arguments:
- error_level: The desired error level. Default: ErrorLevel.IMMEDIATE
- error_message_context: Determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 100
- max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
Inherited Members
- sqlglot.parser.Parser
- Parser
- NO_PAREN_FUNCTIONS
- STRUCT_TYPE_TOKENS
- NESTED_TYPE_TOKENS
- ENUM_TYPE_TOKENS
- TYPE_TOKENS
- SIGNED_TO_UNSIGNED_TYPE_TOKEN
- SUBQUERY_PREDICATES
- RESERVED_TOKENS
- DB_CREATABLES
- CREATABLES
- ID_VAR_TOKENS
- INTERVAL_VARS
- COMMENT_TABLE_ALIAS_TOKENS
- UPDATE_ALIAS_TOKENS
- TRIM_TYPES
- FUNC_TOKENS
- CONJUNCTION
- EQUALITY
- COMPARISON
- BITWISE
- TERM
- FACTOR
- EXPONENT
- TIMES
- TIMESTAMPS
- SET_OPERATIONS
- JOIN_METHODS
- JOIN_SIDES
- JOIN_KINDS
- JOIN_HINTS
- LAMBDAS
- COLUMN_OPERATORS
- EXPRESSION_PARSERS
- STATEMENT_PARSERS
- UNARY_PARSERS
- PRIMARY_PARSERS
- PLACEHOLDER_PARSERS
- RANGE_PARSERS
- PROPERTY_PARSERS
- CONSTRAINT_PARSERS
- ALTER_PARSERS
- SCHEMA_UNNAMED_CONSTRAINTS
- NO_PAREN_FUNCTION_PARSERS
- INVALID_FUNC_NAME_TOKENS
- FUNCTIONS_WITH_ALIASED_ARGS
- QUERY_MODIFIER_PARSERS
- SET_PARSERS
- SHOW_PARSERS
- TYPE_LITERAL_PARSERS
- MODIFIABLES
- DDL_SELECT_TOKENS
- PRE_VOLATILE_TOKENS
- TRANSACTION_KIND
- TRANSACTION_CHARACTERISTICS
- INSERT_ALTERNATIVES
- CLONE_KEYWORDS
- HISTORICAL_DATA_KIND
- OPCLASS_FOLLOW_KEYWORDS
- OPTYPE_FOLLOW_TOKENS
- TABLE_INDEX_HINT_TOKENS
- WINDOW_ALIAS_TOKENS
- WINDOW_BEFORE_PAREN_TOKENS
- WINDOW_SIDES
- FETCH_TOKENS
- ADD_CONSTRAINT_TOKENS
- DISTINCT_TOKENS
- NULL_TOKENS
- UNNEST_OFFSET_ALIAS_TOKENS
- STRICT_CAST
- PREFIXED_PIVOT_COLUMNS
- IDENTIFY_PIVOT_STRINGS
- LOG_DEFAULTS_TO_LN
- ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN
- TABLESAMPLE_CSV
- SET_REQUIRES_ASSIGNMENT_DELIMITER
- TRIM_PATTERN_FIRST
- MODIFIERS_ATTACHED_TO_UNION
- UNION_MODIFIERS
- error_level
- error_message_context
- max_errors
- dialect
- reset
- parse
- parse_into
- check_errors
- raise_error
- expression
- validate_expression
- errors
- sql
295 class Generator(generator.Generator): 296 INTERVAL_ALLOWS_PLURAL_FORM = False 297 JOIN_HINTS = False 298 TABLE_HINTS = False 299 QUERY_HINTS = False 300 IS_BOOL_ALLOWED = False 301 TZ_TO_WITH_TIME_ZONE = True 302 NVL2_SUPPORTED = False 303 STRUCT_DELIMITER = ("(", ")") 304 LIMIT_ONLY_LITERALS = True 305 SUPPORTS_SINGLE_ARG_CONCAT = False 306 307 PROPERTIES_LOCATION = { 308 **generator.Generator.PROPERTIES_LOCATION, 309 exp.LocationProperty: exp.Properties.Location.UNSUPPORTED, 310 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 311 } 312 313 TYPE_MAPPING = { 314 **generator.Generator.TYPE_MAPPING, 315 exp.DataType.Type.INT: "INTEGER", 316 exp.DataType.Type.FLOAT: "REAL", 317 exp.DataType.Type.BINARY: "VARBINARY", 318 exp.DataType.Type.TEXT: "VARCHAR", 319 exp.DataType.Type.TIMETZ: "TIME", 320 exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP", 321 exp.DataType.Type.STRUCT: "ROW", 322 exp.DataType.Type.DATETIME: "TIMESTAMP", 323 exp.DataType.Type.DATETIME64: "TIMESTAMP", 324 } 325 326 TRANSFORMS = { 327 **generator.Generator.TRANSFORMS, 328 exp.AnyValue: rename_func("ARBITRARY"), 329 exp.ApproxDistinct: _approx_distinct_sql, 330 exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"), 331 exp.ArgMax: rename_func("MAX_BY"), 332 exp.ArgMin: rename_func("MIN_BY"), 333 exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]", 334 exp.ArrayConcat: rename_func("CONCAT"), 335 exp.ArrayContains: rename_func("CONTAINS"), 336 exp.ArraySize: rename_func("CARDINALITY"), 337 exp.ArrayUniqueAgg: rename_func("SET_AGG"), 338 exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 339 exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 340 exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})", 341 exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 342 exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 343 exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 344 exp.Cast: transforms.preprocess([transforms.epoch_cast_to_ts]), 345 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 346 exp.DateAdd: lambda self, e: self.func( 347 "DATE_ADD", 348 exp.Literal.string(e.text("unit") or "DAY"), 349 _to_int( 350 e.expression, 351 ), 352 e.this, 353 ), 354 exp.DateDiff: lambda self, e: self.func( 355 "DATE_DIFF", exp.Literal.string(e.text("unit") or "DAY"), e.expression, e.this 356 ), 357 exp.DateStrToDate: datestrtodate_sql, 358 exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.DATEINT_FORMAT}) AS INT)", 359 exp.DateSub: lambda self, e: self.func( 360 "DATE_ADD", 361 exp.Literal.string(e.text("unit") or "DAY"), 362 _to_int(e.expression * -1), 363 e.this, 364 ), 365 exp.Decode: lambda self, e: encode_decode_sql(self, e, "FROM_UTF8"), 366 exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.DATEINT_FORMAT}) AS DATE)", 367 exp.Encode: lambda self, e: encode_decode_sql(self, e, "TO_UTF8"), 368 exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'", 369 exp.First: _first_last_sql, 370 exp.Group: transforms.preprocess([transforms.unalias_group]), 371 exp.GroupConcat: lambda self, e: self.func( 372 "ARRAY_JOIN", self.func("ARRAY_AGG", e.this), e.args.get("separator") 373 ), 374 exp.Hex: rename_func("TO_HEX"), 375 exp.If: if_sql(), 376 exp.ILike: no_ilike_sql, 377 exp.Initcap: _initcap_sql, 378 exp.ParseJSON: rename_func("JSON_PARSE"), 379 exp.Last: _first_last_sql, 380 exp.Lateral: _explode_to_unnest_sql, 381 exp.Left: left_to_substring_sql, 382 exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"), 383 exp.LogicalAnd: rename_func("BOOL_AND"), 384 exp.LogicalOr: rename_func("BOOL_OR"), 385 exp.Pivot: no_pivot_sql, 386 exp.Quantile: _quantile_sql, 387 exp.RegexpExtract: regexp_extract_sql, 388 exp.Right: right_to_substring_sql, 389 exp.SafeDivide: no_safe_divide_sql, 390 exp.Schema: _schema_sql, 391 exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), 392 exp.Select: transforms.preprocess( 393 [ 394 transforms.eliminate_qualify, 395 transforms.eliminate_distinct_on, 396 transforms.explode_to_unnest(1), 397 transforms.eliminate_semi_and_anti_joins, 398 ] 399 ), 400 exp.SortArray: _no_sort_array, 401 exp.StrPosition: rename_func("STRPOS"), 402 exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)", 403 exp.StrToMap: rename_func("SPLIT_TO_MAP"), 404 exp.StrToTime: _str_to_time_sql, 405 exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))", 406 exp.StructExtract: struct_extract_sql, 407 exp.Table: transforms.preprocess([_unnest_sequence]), 408 exp.Timestamp: no_timestamp_sql, 409 exp.TimestampTrunc: timestamptrunc_sql, 410 exp.TimeStrToDate: timestrtotime_sql, 411 exp.TimeStrToTime: timestrtotime_sql, 412 exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.TIME_FORMAT}))", 413 exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 414 exp.TimeToUnix: rename_func("TO_UNIXTIME"), 415 exp.ToChar: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 416 exp.TryCast: transforms.preprocess([transforms.epoch_cast_to_ts]), 417 exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)", 418 exp.TsOrDsAdd: _ts_or_ds_add_sql, 419 exp.TsOrDsDiff: _ts_or_ds_diff_sql, 420 exp.TsOrDsToDate: _ts_or_ds_to_date_sql, 421 exp.Unhex: rename_func("FROM_HEX"), 422 exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})", 423 exp.UnixToTime: _unix_to_time_sql, 424 exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)", 425 exp.VariancePop: rename_func("VAR_POP"), 426 exp.With: transforms.preprocess([transforms.add_recursive_cte_column_names]), 427 exp.WithinGroup: transforms.preprocess( 428 [transforms.remove_within_group_for_percentiles] 429 ), 430 exp.Xor: bool_xor_sql, 431 } 432 433 def bracket_sql(self, expression: exp.Bracket) -> str: 434 if expression.args.get("safe"): 435 return self.func( 436 "ELEMENT_AT", 437 expression.this, 438 seq_get( 439 apply_index_offset( 440 expression.this, 441 expression.expressions, 442 1 - expression.args.get("offset", 0), 443 ), 444 0, 445 ), 446 ) 447 return super().bracket_sql(expression) 448 449 def struct_sql(self, expression: exp.Struct) -> str: 450 if any(isinstance(arg, self.KEY_VALUE_DEFINITIONS) for arg in expression.expressions): 451 self.unsupported("Struct with key-value definitions is unsupported.") 452 return self.function_fallback_sql(expression) 453 454 return rename_func("ROW")(self, expression) 455 456 def interval_sql(self, expression: exp.Interval) -> str: 457 unit = self.sql(expression, "unit") 458 if expression.this and unit.startswith("WEEK"): 459 return f"({expression.this.name} * INTERVAL '7' DAY)" 460 return super().interval_sql(expression) 461 462 def transaction_sql(self, expression: exp.Transaction) -> str: 463 modes = expression.args.get("modes") 464 modes = f" {', '.join(modes)}" if modes else "" 465 return f"START TRANSACTION{modes}" 466 467 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 468 start = expression.args["start"] 469 end = expression.args["end"] 470 step = expression.args.get("step") 471 472 if isinstance(start, exp.Cast): 473 target_type = start.to 474 elif isinstance(end, exp.Cast): 475 target_type = end.to 476 else: 477 target_type = None 478 479 if target_type and target_type.is_type("timestamp"): 480 if target_type is start.to: 481 end = exp.cast(end, target_type) 482 else: 483 start = exp.cast(start, target_type) 484 485 return self.func("SEQUENCE", start, end, step) 486 487 def offset_limit_modifiers( 488 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 489 ) -> t.List[str]: 490 return [ 491 self.sql(expression, "offset"), 492 self.sql(limit), 493 ] 494 495 def create_sql(self, expression: exp.Create) -> str: 496 """ 497 Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression), 498 so we need to remove them 499 """ 500 kind = expression.args["kind"] 501 schema = expression.this 502 if kind == "VIEW" and schema.expressions: 503 expression.this.set("expressions", None) 504 return super().create_sql(expression)
Generator converts a given syntax tree to the corresponding SQL string.
Arguments:
- pretty: Whether or not to format the produced SQL string. Default: False.
- identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether or not to normalize identifiers to lowercase. Default: False.
- pad: Determines the pad size in a formatted string. Default: 2.
- indent: Determines the indentation size in a formatted string. Default: 2.
- normalize_functions: Whether or not to normalize all function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
- unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma: Determines whether or not the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether or not to preserve comments in the output SQL code. Default: True
433 def bracket_sql(self, expression: exp.Bracket) -> str: 434 if expression.args.get("safe"): 435 return self.func( 436 "ELEMENT_AT", 437 expression.this, 438 seq_get( 439 apply_index_offset( 440 expression.this, 441 expression.expressions, 442 1 - expression.args.get("offset", 0), 443 ), 444 0, 445 ), 446 ) 447 return super().bracket_sql(expression)
449 def struct_sql(self, expression: exp.Struct) -> str: 450 if any(isinstance(arg, self.KEY_VALUE_DEFINITIONS) for arg in expression.expressions): 451 self.unsupported("Struct with key-value definitions is unsupported.") 452 return self.function_fallback_sql(expression) 453 454 return rename_func("ROW")(self, expression)
467 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 468 start = expression.args["start"] 469 end = expression.args["end"] 470 step = expression.args.get("step") 471 472 if isinstance(start, exp.Cast): 473 target_type = start.to 474 elif isinstance(end, exp.Cast): 475 target_type = end.to 476 else: 477 target_type = None 478 479 if target_type and target_type.is_type("timestamp"): 480 if target_type is start.to: 481 end = exp.cast(end, target_type) 482 else: 483 start = exp.cast(start, target_type) 484 485 return self.func("SEQUENCE", start, end, step)
495 def create_sql(self, expression: exp.Create) -> str: 496 """ 497 Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression), 498 so we need to remove them 499 """ 500 kind = expression.args["kind"] 501 schema = expression.this 502 if kind == "VIEW" and schema.expressions: 503 expression.this.set("expressions", None) 504 return super().create_sql(expression)
Presto doesn't support CREATE VIEW with expressions (ex: CREATE VIEW x (cola)
then (cola)
is the expression),
so we need to remove them
Inherited Members
- sqlglot.generator.Generator
- Generator
- NULL_ORDERING_SUPPORTED
- LOCKING_READS_SUPPORTED
- EXPLICIT_UNION
- WRAP_DERIVED_VALUES
- CREATE_FUNCTION_RETURN_AS
- MATCHED_BY_SOURCE
- SINGLE_STRING_INTERVAL
- TABLESAMPLE_WITH_METHOD
- TABLESAMPLE_SIZE_IS_PERCENT
- LIMIT_FETCH
- RENAME_TABLE_WITH_DB
- GROUPINGS_SEP
- INDEX_ON
- QUERY_HINT_SEP
- DUPLICATE_KEY_UPDATE_WITH_SET
- LIMIT_IS_TOP
- RETURNING_END
- COLUMN_JOIN_MARKS_SUPPORTED
- EXTRACT_ALLOWS_QUOTES
- VALUES_AS_TABLE
- ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
- UNNEST_WITH_ORDINALITY
- AGGREGATE_FILTER_SUPPORTED
- SEMI_ANTI_JOIN_WITH_SIDE
- COMPUTED_COLUMN_WITH_TYPE
- SUPPORTS_TABLE_COPY
- TABLESAMPLE_REQUIRES_PARENS
- COLLATE_IS_FUNC
- DATA_TYPE_SPECIFIERS_ALLOWED
- ENSURE_BOOLS
- CTE_RECURSIVE_KEYWORD_REQUIRED
- STAR_MAPPING
- TIME_PART_SINGULARS
- TOKEN_MAPPING
- PARAMETER_TOKEN
- RESERVED_KEYWORDS
- WITH_SEPARATED_COMMENTS
- EXCLUDE_COMMENTS
- UNWRAPPED_INTERVAL_VALUES
- EXPRESSIONS_WITHOUT_NESTED_CTES
- KEY_VALUE_DEFINITIONS
- SENTINEL_LINE_BREAK
- pretty
- identify
- normalize
- pad
- unsupported_level
- max_unsupported
- leading_comma
- max_text_width
- comments
- dialect
- normalize_functions
- unsupported_messages
- generate
- preprocess
- 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
- computedcolumnconstraint_sql
- autoincrementcolumnconstraint_sql
- compresscolumnconstraint_sql
- generatedasidentitycolumnconstraint_sql
- generatedasrowcolumnconstraint_sql
- periodforsystemtimeconstraint_sql
- notnullcolumnconstraint_sql
- transformcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_sql
- createable_sql
- clone_sql
- describe_sql
- prepend_ctes
- with_sql
- cte_sql
- tablealias_sql
- bitstring_sql
- hexstring_sql
- bytestring_sql
- unicodestring_sql
- rawstring_sql
- datatypeparam_sql
- datatype_sql
- directory_sql
- delete_sql
- drop_sql
- except_sql
- except_op
- fetch_sql
- filter_sql
- hint_sql
- index_sql
- identifier_sql
- inputoutputformat_sql
- national_sql
- partition_sql
- properties_sql
- root_properties
- properties
- with_properties
- locate_properties
- property_name
- property_sql
- likeproperty_sql
- fallbackproperty_sql
- journalproperty_sql
- freespaceproperty_sql
- checksumproperty_sql
- mergeblockratioproperty_sql
- datablocksizeproperty_sql
- blockcompressionproperty_sql
- isolatedloadingproperty_sql
- partitionboundspec_sql
- partitionedofproperty_sql
- lockingproperty_sql
- withdataproperty_sql
- withsystemversioningproperty_sql
- insert_sql
- intersect_sql
- intersect_op
- introducer_sql
- kill_sql
- pseudotype_sql
- objectidentifier_sql
- onconflict_sql
- returning_sql
- rowformatdelimitedproperty_sql
- withtablehint_sql
- indextablehint_sql
- historicaldata_sql
- table_sql
- tablesample_sql
- pivot_sql
- version_sql
- tuple_sql
- update_sql
- values_sql
- var_sql
- into_sql
- from_sql
- group_sql
- having_sql
- connect_sql
- prior_sql
- join_sql
- lambda_sql
- lateral_sql
- limit_sql
- offset_sql
- setitem_sql
- set_sql
- pragma_sql
- lock_sql
- literal_sql
- escape_str
- loaddata_sql
- null_sql
- boolean_sql
- order_sql
- withfill_sql
- cluster_sql
- distribute_sql
- sort_sql
- ordered_sql
- matchrecognize_sql
- query_modifiers
- after_having_modifiers
- after_limit_modifiers
- select_sql
- schema_sql
- schema_columns_sql
- star_sql
- parameter_sql
- sessionparameter_sql
- placeholder_sql
- subquery_sql
- qualify_sql
- union_sql
- union_op
- unnest_sql
- where_sql
- window_sql
- partition_by_sql
- windowspec_sql
- withingroup_sql
- between_sql
- all_sql
- any_sql
- exists_sql
- case_sql
- constraint_sql
- nextvaluefor_sql
- extract_sql
- trim_sql
- convert_concat_args
- concat_sql
- concatws_sql
- check_sql
- foreignkey_sql
- primarykey_sql
- if_sql
- matchagainst_sql
- jsonkeyvalue_sql
- formatjson_sql
- jsonobject_sql
- jsonarray_sql
- jsonarrayagg_sql
- jsoncolumndef_sql
- jsonschema_sql
- jsontable_sql
- openjsoncolumndef_sql
- openjson_sql
- in_sql
- in_unnest_op
- return_sql
- reference_sql
- anonymous_sql
- paren_sql
- neg_sql
- not_sql
- alias_sql
- aliases_sql
- atindex_sql
- attimezone_sql
- add_sql
- and_sql
- xor_sql
- connector_sql
- bitwiseand_sql
- bitwiseleftshift_sql
- bitwisenot_sql
- bitwiseor_sql
- bitwiserightshift_sql
- bitwisexor_sql
- cast_sql
- currentdate_sql
- collate_sql
- command_sql
- comment_sql
- mergetreettlaction_sql
- mergetreettl_sql
- commit_sql
- rollback_sql
- altercolumn_sql
- renametable_sql
- altertable_sql
- add_column_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
- propertyeq_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
- log_sql
- use_sql
- binary
- function_fallback_sql
- func
- format_args
- text_width
- format_time
- expressions
- op_expressions
- naked_property
- set_operation
- tag_sql
- token_sql
- userdefinedfunction_sql
- joinhint_sql
- kwarg_sql
- when_sql
- merge_sql
- tochar_sql
- dictproperty_sql
- dictrange_sql
- dictsubproperty_sql
- oncluster_sql
- clusteredbyproperty_sql
- anyvalue_sql
- querytransform_sql
- indexconstraintoption_sql
- indexcolumnconstraint_sql
- nvl2_sql
- comprehension_sql
- columnprefix_sql
- opclass_sql
- predict_sql
- forin_sql
- refresh_sql
- operator_sql
- toarray_sql