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 path_to_jsonpath, 22 regexp_extract_sql, 23 rename_func, 24 right_to_substring_sql, 25 struct_extract_sql, 26 timestamptrunc_sql, 27 timestrtotime_sql, 28 ts_or_ds_add_cast, 29) 30from sqlglot.dialects.mysql import MySQL 31from sqlglot.helper import apply_index_offset, seq_get 32from sqlglot.tokens import TokenType 33 34 35def _approx_distinct_sql(self: Presto.Generator, expression: exp.ApproxDistinct) -> str: 36 accuracy = expression.args.get("accuracy") 37 accuracy = ", " + self.sql(accuracy) if accuracy else "" 38 return f"APPROX_DISTINCT({self.sql(expression, 'this')}{accuracy})" 39 40 41def _explode_to_unnest_sql(self: Presto.Generator, expression: exp.Lateral) -> str: 42 if isinstance(expression.this, exp.Explode): 43 return self.sql( 44 exp.Join( 45 this=exp.Unnest( 46 expressions=[expression.this.this], 47 alias=expression.args.get("alias"), 48 offset=isinstance(expression.this, exp.Posexplode), 49 ), 50 kind="cross", 51 ) 52 ) 53 return self.lateral_sql(expression) 54 55 56def _initcap_sql(self: Presto.Generator, expression: exp.Initcap) -> str: 57 regex = r"(\w)(\w*)" 58 return f"REGEXP_REPLACE({self.sql(expression, 'this')}, '{regex}', x -> UPPER(x[1]) || LOWER(x[2]))" 59 60 61def _no_sort_array(self: Presto.Generator, expression: exp.SortArray) -> str: 62 if expression.args.get("asc") == exp.false(): 63 comparator = "(a, b) -> CASE WHEN a < b THEN 1 WHEN a > b THEN -1 ELSE 0 END" 64 else: 65 comparator = None 66 return self.func("ARRAY_SORT", expression.this, comparator) 67 68 69def _schema_sql(self: Presto.Generator, expression: exp.Schema) -> str: 70 if isinstance(expression.parent, exp.Property): 71 columns = ", ".join(f"'{c.name}'" for c in expression.expressions) 72 return f"ARRAY[{columns}]" 73 74 if expression.parent: 75 for schema in expression.parent.find_all(exp.Schema): 76 column_defs = schema.find_all(exp.ColumnDef) 77 if column_defs and isinstance(schema.parent, exp.Property): 78 expression.expressions.extend(column_defs) 79 80 return self.schema_sql(expression) 81 82 83def _quantile_sql(self: Presto.Generator, expression: exp.Quantile) -> str: 84 self.unsupported("Presto does not support exact quantiles") 85 return f"APPROX_PERCENTILE({self.sql(expression, 'this')}, {self.sql(expression, 'quantile')})" 86 87 88def _str_to_time_sql( 89 self: Presto.Generator, expression: exp.StrToDate | exp.StrToTime | exp.TsOrDsToDate 90) -> str: 91 return f"DATE_PARSE({self.sql(expression, 'this')}, {self.format_time(expression)})" 92 93 94def _ts_or_ds_to_date_sql(self: Presto.Generator, expression: exp.TsOrDsToDate) -> str: 95 time_format = self.format_time(expression) 96 if time_format and time_format not in (Presto.TIME_FORMAT, Presto.DATE_FORMAT): 97 return exp.cast(_str_to_time_sql(self, expression), "DATE").sql(dialect="presto") 98 return exp.cast(exp.cast(expression.this, "TIMESTAMP", copy=True), "DATE").sql(dialect="presto") 99 100 101def _ts_or_ds_add_sql(self: Presto.Generator, expression: exp.TsOrDsAdd) -> str: 102 expression = ts_or_ds_add_cast(expression) 103 unit = exp.Literal.string(expression.text("unit") or "DAY") 104 return self.func("DATE_ADD", unit, expression.expression, expression.this) 105 106 107def _ts_or_ds_diff_sql(self: Presto.Generator, expression: exp.TsOrDsDiff) -> str: 108 this = exp.cast(expression.this, "TIMESTAMP") 109 expr = exp.cast(expression.expression, "TIMESTAMP") 110 unit = exp.Literal.string(expression.text("unit") or "DAY") 111 return self.func("DATE_DIFF", unit, expr, this) 112 113 114def _approx_percentile(args: t.List) -> exp.Expression: 115 if len(args) == 4: 116 return exp.ApproxQuantile( 117 this=seq_get(args, 0), 118 weight=seq_get(args, 1), 119 quantile=seq_get(args, 2), 120 accuracy=seq_get(args, 3), 121 ) 122 if len(args) == 3: 123 return exp.ApproxQuantile( 124 this=seq_get(args, 0), quantile=seq_get(args, 1), accuracy=seq_get(args, 2) 125 ) 126 return exp.ApproxQuantile.from_arg_list(args) 127 128 129def _from_unixtime(args: t.List) -> exp.Expression: 130 if len(args) == 3: 131 return exp.UnixToTime( 132 this=seq_get(args, 0), 133 hours=seq_get(args, 1), 134 minutes=seq_get(args, 2), 135 ) 136 if len(args) == 2: 137 return exp.UnixToTime(this=seq_get(args, 0), zone=seq_get(args, 1)) 138 139 return exp.UnixToTime.from_arg_list(args) 140 141 142def _parse_element_at(args: t.List) -> exp.Bracket: 143 this = seq_get(args, 0) 144 index = seq_get(args, 1) 145 assert isinstance(this, exp.Expression) and isinstance(index, exp.Expression) 146 return exp.Bracket(this=this, expressions=[index], offset=1, safe=True) 147 148 149def _unnest_sequence(expression: exp.Expression) -> exp.Expression: 150 if isinstance(expression, exp.Table): 151 if isinstance(expression.this, exp.GenerateSeries): 152 unnest = exp.Unnest(expressions=[expression.this]) 153 154 if expression.alias: 155 return exp.alias_(unnest, alias="_u", table=[expression.alias], copy=False) 156 return unnest 157 return expression 158 159 160def _first_last_sql(self: Presto.Generator, expression: exp.First | exp.Last) -> str: 161 """ 162 Trino doesn't support FIRST / LAST as functions, but they're valid in the context 163 of MATCH_RECOGNIZE, so we need to preserve them in that case. In all other cases 164 they're converted into an ARBITRARY call. 165 166 Reference: https://trino.io/docs/current/sql/match-recognize.html#logical-navigation-functions 167 """ 168 if isinstance(expression.find_ancestor(exp.MatchRecognize, exp.Select), exp.MatchRecognize): 169 return self.function_fallback_sql(expression) 170 171 return rename_func("ARBITRARY")(self, expression) 172 173 174def _unix_to_time_sql(self: Presto.Generator, expression: exp.UnixToTime) -> str: 175 scale = expression.args.get("scale") 176 timestamp = self.sql(expression, "this") 177 if scale in (None, exp.UnixToTime.SECONDS): 178 return rename_func("FROM_UNIXTIME")(self, expression) 179 if scale == exp.UnixToTime.MILLIS: 180 return f"FROM_UNIXTIME(CAST({timestamp} AS DOUBLE) / 1000)" 181 if scale == exp.UnixToTime.MICROS: 182 return f"FROM_UNIXTIME(CAST({timestamp} AS DOUBLE) / 1000000)" 183 if scale == exp.UnixToTime.NANOS: 184 return f"FROM_UNIXTIME(CAST({timestamp} AS DOUBLE) / 1000000000)" 185 186 self.unsupported(f"Unsupported scale for timestamp: {scale}.") 187 return "" 188 189 190def _to_int(expression: exp.Expression) -> exp.Expression: 191 if not expression.type: 192 from sqlglot.optimizer.annotate_types import annotate_types 193 194 annotate_types(expression) 195 if expression.type and expression.type.this not in exp.DataType.INTEGER_TYPES: 196 return exp.cast(expression, to=exp.DataType.Type.BIGINT) 197 return expression 198 199 200def _parse_to_char(args: t.List) -> exp.TimeToStr: 201 fmt = seq_get(args, 1) 202 if isinstance(fmt, exp.Literal): 203 # We uppercase this to match Teradata's format mapping keys 204 fmt.set("this", fmt.this.upper()) 205 206 # We use "teradata" on purpose here, because the time formats are different in Presto. 207 # See https://prestodb.io/docs/current/functions/teradata.html?highlight=to_char#to_char 208 return format_time_lambda(exp.TimeToStr, "teradata")(args) 209 210 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 TABLESAMPLE_SIZE_IS_PERCENT = True 220 221 # https://github.com/trinodb/trino/issues/17 222 # https://github.com/trinodb/trino/issues/12289 223 # https://github.com/prestodb/presto/issues/2863 224 NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE 225 226 class Tokenizer(tokens.Tokenizer): 227 UNICODE_STRINGS = [ 228 (prefix + q, q) 229 for q in t.cast(t.List[str], tokens.Tokenizer.QUOTES) 230 for prefix in ("U&", "u&") 231 ] 232 233 KEYWORDS = { 234 **tokens.Tokenizer.KEYWORDS, 235 "START": TokenType.BEGIN, 236 "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, 237 "ROW": TokenType.STRUCT, 238 "IPADDRESS": TokenType.IPADDRESS, 239 "IPPREFIX": TokenType.IPPREFIX, 240 } 241 242 class Parser(parser.Parser): 243 FUNCTIONS = { 244 **parser.Parser.FUNCTIONS, 245 "ARBITRARY": exp.AnyValue.from_arg_list, 246 "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list, 247 "APPROX_PERCENTILE": _approx_percentile, 248 "BITWISE_AND": binary_from_function(exp.BitwiseAnd), 249 "BITWISE_NOT": lambda args: exp.BitwiseNot(this=seq_get(args, 0)), 250 "BITWISE_OR": binary_from_function(exp.BitwiseOr), 251 "BITWISE_XOR": binary_from_function(exp.BitwiseXor), 252 "CARDINALITY": exp.ArraySize.from_arg_list, 253 "CONTAINS": exp.ArrayContains.from_arg_list, 254 "DATE_ADD": lambda args: exp.DateAdd( 255 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 256 ), 257 "DATE_DIFF": lambda args: exp.DateDiff( 258 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 259 ), 260 "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"), 261 "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"), 262 "DATE_TRUNC": date_trunc_to_time, 263 "ELEMENT_AT": _parse_element_at, 264 "FROM_HEX": exp.Unhex.from_arg_list, 265 "FROM_UNIXTIME": _from_unixtime, 266 "FROM_UTF8": lambda args: exp.Decode( 267 this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8") 268 ), 269 "NOW": exp.CurrentTimestamp.from_arg_list, 270 "REGEXP_EXTRACT": lambda args: exp.RegexpExtract( 271 this=seq_get(args, 0), expression=seq_get(args, 1), group=seq_get(args, 2) 272 ), 273 "REGEXP_REPLACE": lambda args: exp.RegexpReplace( 274 this=seq_get(args, 0), 275 expression=seq_get(args, 1), 276 replacement=seq_get(args, 2) or exp.Literal.string(""), 277 ), 278 "ROW": exp.Struct.from_arg_list, 279 "SEQUENCE": exp.GenerateSeries.from_arg_list, 280 "SET_AGG": exp.ArrayUniqueAgg.from_arg_list, 281 "SPLIT_TO_MAP": exp.StrToMap.from_arg_list, 282 "STRPOS": lambda args: exp.StrPosition( 283 this=seq_get(args, 0), substr=seq_get(args, 1), instance=seq_get(args, 2) 284 ), 285 "TO_CHAR": _parse_to_char, 286 "TO_HEX": exp.Hex.from_arg_list, 287 "TO_UNIXTIME": exp.TimeToUnix.from_arg_list, 288 "TO_UTF8": lambda args: exp.Encode( 289 this=seq_get(args, 0), charset=exp.Literal.string("utf-8") 290 ), 291 } 292 293 FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy() 294 FUNCTION_PARSERS.pop("TRIM") 295 296 class Generator(generator.Generator): 297 INTERVAL_ALLOWS_PLURAL_FORM = False 298 JOIN_HINTS = False 299 TABLE_HINTS = False 300 QUERY_HINTS = False 301 IS_BOOL_ALLOWED = False 302 TZ_TO_WITH_TIME_ZONE = True 303 NVL2_SUPPORTED = False 304 STRUCT_DELIMITER = ("(", ")") 305 LIMIT_ONLY_LITERALS = True 306 SUPPORTS_SINGLE_ARG_CONCAT = False 307 308 PROPERTIES_LOCATION = { 309 **generator.Generator.PROPERTIES_LOCATION, 310 exp.LocationProperty: exp.Properties.Location.UNSUPPORTED, 311 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 312 } 313 314 TYPE_MAPPING = { 315 **generator.Generator.TYPE_MAPPING, 316 exp.DataType.Type.INT: "INTEGER", 317 exp.DataType.Type.FLOAT: "REAL", 318 exp.DataType.Type.BINARY: "VARBINARY", 319 exp.DataType.Type.TEXT: "VARCHAR", 320 exp.DataType.Type.TIMETZ: "TIME", 321 exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP", 322 exp.DataType.Type.STRUCT: "ROW", 323 exp.DataType.Type.DATETIME: "TIMESTAMP", 324 exp.DataType.Type.DATETIME64: "TIMESTAMP", 325 } 326 327 TRANSFORMS = { 328 **generator.Generator.TRANSFORMS, 329 exp.AnyValue: rename_func("ARBITRARY"), 330 exp.ApproxDistinct: _approx_distinct_sql, 331 exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"), 332 exp.ArgMax: rename_func("MAX_BY"), 333 exp.ArgMin: rename_func("MIN_BY"), 334 exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]", 335 exp.ArrayConcat: rename_func("CONCAT"), 336 exp.ArrayContains: rename_func("CONTAINS"), 337 exp.ArraySize: rename_func("CARDINALITY"), 338 exp.ArrayUniqueAgg: rename_func("SET_AGG"), 339 exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 340 exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 341 exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})", 342 exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 343 exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 344 exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 345 exp.Cast: transforms.preprocess([transforms.epoch_cast_to_ts]), 346 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 347 exp.DateAdd: lambda self, e: self.func( 348 "DATE_ADD", 349 exp.Literal.string(e.text("unit") or "DAY"), 350 _to_int( 351 e.expression, 352 ), 353 e.this, 354 ), 355 exp.DateDiff: lambda self, e: self.func( 356 "DATE_DIFF", exp.Literal.string(e.text("unit") or "DAY"), e.expression, e.this 357 ), 358 exp.DateStrToDate: datestrtodate_sql, 359 exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.DATEINT_FORMAT}) AS INT)", 360 exp.DateSub: lambda self, e: self.func( 361 "DATE_ADD", 362 exp.Literal.string(e.text("unit") or "DAY"), 363 _to_int(e.expression * -1), 364 e.this, 365 ), 366 exp.Decode: lambda self, e: encode_decode_sql(self, e, "FROM_UTF8"), 367 exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.DATEINT_FORMAT}) AS DATE)", 368 exp.Encode: lambda self, e: encode_decode_sql(self, e, "TO_UTF8"), 369 exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'", 370 exp.First: _first_last_sql, 371 exp.GetPath: path_to_jsonpath(), 372 exp.Group: transforms.preprocess([transforms.unalias_group]), 373 exp.GroupConcat: lambda self, e: self.func( 374 "ARRAY_JOIN", self.func("ARRAY_AGG", e.this), e.args.get("separator") 375 ), 376 exp.Hex: rename_func("TO_HEX"), 377 exp.If: if_sql(), 378 exp.ILike: no_ilike_sql, 379 exp.Initcap: _initcap_sql, 380 exp.ParseJSON: rename_func("JSON_PARSE"), 381 exp.Last: _first_last_sql, 382 exp.LastDay: lambda self, e: self.func("LAST_DAY_OF_MONTH", e.this), 383 exp.Lateral: _explode_to_unnest_sql, 384 exp.Left: left_to_substring_sql, 385 exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"), 386 exp.LogicalAnd: rename_func("BOOL_AND"), 387 exp.LogicalOr: rename_func("BOOL_OR"), 388 exp.Pivot: no_pivot_sql, 389 exp.Quantile: _quantile_sql, 390 exp.RegexpExtract: regexp_extract_sql, 391 exp.Right: right_to_substring_sql, 392 exp.SafeDivide: no_safe_divide_sql, 393 exp.Schema: _schema_sql, 394 exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), 395 exp.Select: transforms.preprocess( 396 [ 397 transforms.eliminate_qualify, 398 transforms.eliminate_distinct_on, 399 transforms.explode_to_unnest(1), 400 transforms.eliminate_semi_and_anti_joins, 401 ] 402 ), 403 exp.SortArray: _no_sort_array, 404 exp.StrPosition: rename_func("STRPOS"), 405 exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)", 406 exp.StrToMap: rename_func("SPLIT_TO_MAP"), 407 exp.StrToTime: _str_to_time_sql, 408 exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))", 409 exp.StructExtract: struct_extract_sql, 410 exp.Table: transforms.preprocess([_unnest_sequence]), 411 exp.Timestamp: no_timestamp_sql, 412 exp.TimestampTrunc: timestamptrunc_sql, 413 exp.TimeStrToDate: timestrtotime_sql, 414 exp.TimeStrToTime: timestrtotime_sql, 415 exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.TIME_FORMAT}))", 416 exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 417 exp.TimeToUnix: rename_func("TO_UNIXTIME"), 418 exp.ToChar: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 419 exp.TryCast: transforms.preprocess([transforms.epoch_cast_to_ts]), 420 exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)", 421 exp.TsOrDsAdd: _ts_or_ds_add_sql, 422 exp.TsOrDsDiff: _ts_or_ds_diff_sql, 423 exp.TsOrDsToDate: _ts_or_ds_to_date_sql, 424 exp.Unhex: rename_func("FROM_HEX"), 425 exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})", 426 exp.UnixToTime: _unix_to_time_sql, 427 exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)", 428 exp.VariancePop: rename_func("VAR_POP"), 429 exp.With: transforms.preprocess([transforms.add_recursive_cte_column_names]), 430 exp.WithinGroup: transforms.preprocess( 431 [transforms.remove_within_group_for_percentiles] 432 ), 433 exp.Xor: bool_xor_sql, 434 } 435 436 def bracket_sql(self, expression: exp.Bracket) -> str: 437 if expression.args.get("safe"): 438 return self.func( 439 "ELEMENT_AT", 440 expression.this, 441 seq_get( 442 apply_index_offset( 443 expression.this, 444 expression.expressions, 445 1 - expression.args.get("offset", 0), 446 ), 447 0, 448 ), 449 ) 450 return super().bracket_sql(expression) 451 452 def struct_sql(self, expression: exp.Struct) -> str: 453 if any(isinstance(arg, self.KEY_VALUE_DEFINITIONS) for arg in expression.expressions): 454 self.unsupported("Struct with key-value definitions is unsupported.") 455 return self.function_fallback_sql(expression) 456 457 return rename_func("ROW")(self, expression) 458 459 def interval_sql(self, expression: exp.Interval) -> str: 460 unit = self.sql(expression, "unit") 461 if expression.this and unit.startswith("WEEK"): 462 return f"({expression.this.name} * INTERVAL '7' DAY)" 463 return super().interval_sql(expression) 464 465 def transaction_sql(self, expression: exp.Transaction) -> str: 466 modes = expression.args.get("modes") 467 modes = f" {', '.join(modes)}" if modes else "" 468 return f"START TRANSACTION{modes}" 469 470 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 471 start = expression.args["start"] 472 end = expression.args["end"] 473 step = expression.args.get("step") 474 475 if isinstance(start, exp.Cast): 476 target_type = start.to 477 elif isinstance(end, exp.Cast): 478 target_type = end.to 479 else: 480 target_type = None 481 482 if target_type and target_type.is_type("timestamp"): 483 if target_type is start.to: 484 end = exp.cast(end, target_type) 485 else: 486 start = exp.cast(start, target_type) 487 488 return self.func("SEQUENCE", start, end, step) 489 490 def offset_limit_modifiers( 491 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 492 ) -> t.List[str]: 493 return [ 494 self.sql(expression, "offset"), 495 self.sql(limit), 496 ] 497 498 def create_sql(self, expression: exp.Create) -> str: 499 """ 500 Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression), 501 so we need to remove them 502 """ 503 kind = expression.args["kind"] 504 schema = expression.this 505 if kind == "VIEW" and schema.expressions: 506 expression.this.set("expressions", None) 507 return super().create_sql(expression)
212class Presto(Dialect): 213 INDEX_OFFSET = 1 214 NULL_ORDERING = "nulls_are_last" 215 TIME_FORMAT = MySQL.TIME_FORMAT 216 TIME_MAPPING = MySQL.TIME_MAPPING 217 STRICT_STRING_CONCAT = True 218 SUPPORTS_SEMI_ANTI_JOIN = False 219 TYPED_DIVISION = True 220 TABLESAMPLE_SIZE_IS_PERCENT = True 221 222 # https://github.com/trinodb/trino/issues/17 223 # https://github.com/trinodb/trino/issues/12289 224 # https://github.com/prestodb/presto/issues/2863 225 NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE 226 227 class Tokenizer(tokens.Tokenizer): 228 UNICODE_STRINGS = [ 229 (prefix + q, q) 230 for q in t.cast(t.List[str], tokens.Tokenizer.QUOTES) 231 for prefix in ("U&", "u&") 232 ] 233 234 KEYWORDS = { 235 **tokens.Tokenizer.KEYWORDS, 236 "START": TokenType.BEGIN, 237 "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, 238 "ROW": TokenType.STRUCT, 239 "IPADDRESS": TokenType.IPADDRESS, 240 "IPPREFIX": TokenType.IPPREFIX, 241 } 242 243 class Parser(parser.Parser): 244 FUNCTIONS = { 245 **parser.Parser.FUNCTIONS, 246 "ARBITRARY": exp.AnyValue.from_arg_list, 247 "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list, 248 "APPROX_PERCENTILE": _approx_percentile, 249 "BITWISE_AND": binary_from_function(exp.BitwiseAnd), 250 "BITWISE_NOT": lambda args: exp.BitwiseNot(this=seq_get(args, 0)), 251 "BITWISE_OR": binary_from_function(exp.BitwiseOr), 252 "BITWISE_XOR": binary_from_function(exp.BitwiseXor), 253 "CARDINALITY": exp.ArraySize.from_arg_list, 254 "CONTAINS": exp.ArrayContains.from_arg_list, 255 "DATE_ADD": lambda args: exp.DateAdd( 256 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 257 ), 258 "DATE_DIFF": lambda args: exp.DateDiff( 259 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 260 ), 261 "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"), 262 "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"), 263 "DATE_TRUNC": date_trunc_to_time, 264 "ELEMENT_AT": _parse_element_at, 265 "FROM_HEX": exp.Unhex.from_arg_list, 266 "FROM_UNIXTIME": _from_unixtime, 267 "FROM_UTF8": lambda args: exp.Decode( 268 this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8") 269 ), 270 "NOW": exp.CurrentTimestamp.from_arg_list, 271 "REGEXP_EXTRACT": lambda args: exp.RegexpExtract( 272 this=seq_get(args, 0), expression=seq_get(args, 1), group=seq_get(args, 2) 273 ), 274 "REGEXP_REPLACE": lambda args: exp.RegexpReplace( 275 this=seq_get(args, 0), 276 expression=seq_get(args, 1), 277 replacement=seq_get(args, 2) or exp.Literal.string(""), 278 ), 279 "ROW": exp.Struct.from_arg_list, 280 "SEQUENCE": exp.GenerateSeries.from_arg_list, 281 "SET_AGG": exp.ArrayUniqueAgg.from_arg_list, 282 "SPLIT_TO_MAP": exp.StrToMap.from_arg_list, 283 "STRPOS": lambda args: exp.StrPosition( 284 this=seq_get(args, 0), substr=seq_get(args, 1), instance=seq_get(args, 2) 285 ), 286 "TO_CHAR": _parse_to_char, 287 "TO_HEX": exp.Hex.from_arg_list, 288 "TO_UNIXTIME": exp.TimeToUnix.from_arg_list, 289 "TO_UTF8": lambda args: exp.Encode( 290 this=seq_get(args, 0), charset=exp.Literal.string("utf-8") 291 ), 292 } 293 294 FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy() 295 FUNCTION_PARSERS.pop("TRIM") 296 297 class Generator(generator.Generator): 298 INTERVAL_ALLOWS_PLURAL_FORM = False 299 JOIN_HINTS = False 300 TABLE_HINTS = False 301 QUERY_HINTS = False 302 IS_BOOL_ALLOWED = False 303 TZ_TO_WITH_TIME_ZONE = True 304 NVL2_SUPPORTED = False 305 STRUCT_DELIMITER = ("(", ")") 306 LIMIT_ONLY_LITERALS = True 307 SUPPORTS_SINGLE_ARG_CONCAT = False 308 309 PROPERTIES_LOCATION = { 310 **generator.Generator.PROPERTIES_LOCATION, 311 exp.LocationProperty: exp.Properties.Location.UNSUPPORTED, 312 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 313 } 314 315 TYPE_MAPPING = { 316 **generator.Generator.TYPE_MAPPING, 317 exp.DataType.Type.INT: "INTEGER", 318 exp.DataType.Type.FLOAT: "REAL", 319 exp.DataType.Type.BINARY: "VARBINARY", 320 exp.DataType.Type.TEXT: "VARCHAR", 321 exp.DataType.Type.TIMETZ: "TIME", 322 exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP", 323 exp.DataType.Type.STRUCT: "ROW", 324 exp.DataType.Type.DATETIME: "TIMESTAMP", 325 exp.DataType.Type.DATETIME64: "TIMESTAMP", 326 } 327 328 TRANSFORMS = { 329 **generator.Generator.TRANSFORMS, 330 exp.AnyValue: rename_func("ARBITRARY"), 331 exp.ApproxDistinct: _approx_distinct_sql, 332 exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"), 333 exp.ArgMax: rename_func("MAX_BY"), 334 exp.ArgMin: rename_func("MIN_BY"), 335 exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]", 336 exp.ArrayConcat: rename_func("CONCAT"), 337 exp.ArrayContains: rename_func("CONTAINS"), 338 exp.ArraySize: rename_func("CARDINALITY"), 339 exp.ArrayUniqueAgg: rename_func("SET_AGG"), 340 exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 341 exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 342 exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})", 343 exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 344 exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 345 exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 346 exp.Cast: transforms.preprocess([transforms.epoch_cast_to_ts]), 347 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 348 exp.DateAdd: lambda self, e: self.func( 349 "DATE_ADD", 350 exp.Literal.string(e.text("unit") or "DAY"), 351 _to_int( 352 e.expression, 353 ), 354 e.this, 355 ), 356 exp.DateDiff: lambda self, e: self.func( 357 "DATE_DIFF", exp.Literal.string(e.text("unit") or "DAY"), e.expression, e.this 358 ), 359 exp.DateStrToDate: datestrtodate_sql, 360 exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.DATEINT_FORMAT}) AS INT)", 361 exp.DateSub: lambda self, e: self.func( 362 "DATE_ADD", 363 exp.Literal.string(e.text("unit") or "DAY"), 364 _to_int(e.expression * -1), 365 e.this, 366 ), 367 exp.Decode: lambda self, e: encode_decode_sql(self, e, "FROM_UTF8"), 368 exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.DATEINT_FORMAT}) AS DATE)", 369 exp.Encode: lambda self, e: encode_decode_sql(self, e, "TO_UTF8"), 370 exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'", 371 exp.First: _first_last_sql, 372 exp.GetPath: path_to_jsonpath(), 373 exp.Group: transforms.preprocess([transforms.unalias_group]), 374 exp.GroupConcat: lambda self, e: self.func( 375 "ARRAY_JOIN", self.func("ARRAY_AGG", e.this), e.args.get("separator") 376 ), 377 exp.Hex: rename_func("TO_HEX"), 378 exp.If: if_sql(), 379 exp.ILike: no_ilike_sql, 380 exp.Initcap: _initcap_sql, 381 exp.ParseJSON: rename_func("JSON_PARSE"), 382 exp.Last: _first_last_sql, 383 exp.LastDay: lambda self, e: self.func("LAST_DAY_OF_MONTH", e.this), 384 exp.Lateral: _explode_to_unnest_sql, 385 exp.Left: left_to_substring_sql, 386 exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"), 387 exp.LogicalAnd: rename_func("BOOL_AND"), 388 exp.LogicalOr: rename_func("BOOL_OR"), 389 exp.Pivot: no_pivot_sql, 390 exp.Quantile: _quantile_sql, 391 exp.RegexpExtract: regexp_extract_sql, 392 exp.Right: right_to_substring_sql, 393 exp.SafeDivide: no_safe_divide_sql, 394 exp.Schema: _schema_sql, 395 exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), 396 exp.Select: transforms.preprocess( 397 [ 398 transforms.eliminate_qualify, 399 transforms.eliminate_distinct_on, 400 transforms.explode_to_unnest(1), 401 transforms.eliminate_semi_and_anti_joins, 402 ] 403 ), 404 exp.SortArray: _no_sort_array, 405 exp.StrPosition: rename_func("STRPOS"), 406 exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)", 407 exp.StrToMap: rename_func("SPLIT_TO_MAP"), 408 exp.StrToTime: _str_to_time_sql, 409 exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))", 410 exp.StructExtract: struct_extract_sql, 411 exp.Table: transforms.preprocess([_unnest_sequence]), 412 exp.Timestamp: no_timestamp_sql, 413 exp.TimestampTrunc: timestamptrunc_sql, 414 exp.TimeStrToDate: timestrtotime_sql, 415 exp.TimeStrToTime: timestrtotime_sql, 416 exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.TIME_FORMAT}))", 417 exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 418 exp.TimeToUnix: rename_func("TO_UNIXTIME"), 419 exp.ToChar: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 420 exp.TryCast: transforms.preprocess([transforms.epoch_cast_to_ts]), 421 exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)", 422 exp.TsOrDsAdd: _ts_or_ds_add_sql, 423 exp.TsOrDsDiff: _ts_or_ds_diff_sql, 424 exp.TsOrDsToDate: _ts_or_ds_to_date_sql, 425 exp.Unhex: rename_func("FROM_HEX"), 426 exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})", 427 exp.UnixToTime: _unix_to_time_sql, 428 exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)", 429 exp.VariancePop: rename_func("VAR_POP"), 430 exp.With: transforms.preprocess([transforms.add_recursive_cte_column_names]), 431 exp.WithinGroup: transforms.preprocess( 432 [transforms.remove_within_group_for_percentiles] 433 ), 434 exp.Xor: bool_xor_sql, 435 } 436 437 def bracket_sql(self, expression: exp.Bracket) -> str: 438 if expression.args.get("safe"): 439 return self.func( 440 "ELEMENT_AT", 441 expression.this, 442 seq_get( 443 apply_index_offset( 444 expression.this, 445 expression.expressions, 446 1 - expression.args.get("offset", 0), 447 ), 448 0, 449 ), 450 ) 451 return super().bracket_sql(expression) 452 453 def struct_sql(self, expression: exp.Struct) -> str: 454 if any(isinstance(arg, self.KEY_VALUE_DEFINITIONS) for arg in expression.expressions): 455 self.unsupported("Struct with key-value definitions is unsupported.") 456 return self.function_fallback_sql(expression) 457 458 return rename_func("ROW")(self, expression) 459 460 def interval_sql(self, expression: exp.Interval) -> str: 461 unit = self.sql(expression, "unit") 462 if expression.this and unit.startswith("WEEK"): 463 return f"({expression.this.name} * INTERVAL '7' DAY)" 464 return super().interval_sql(expression) 465 466 def transaction_sql(self, expression: exp.Transaction) -> str: 467 modes = expression.args.get("modes") 468 modes = f" {', '.join(modes)}" if modes else "" 469 return f"START TRANSACTION{modes}" 470 471 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 472 start = expression.args["start"] 473 end = expression.args["end"] 474 step = expression.args.get("step") 475 476 if isinstance(start, exp.Cast): 477 target_type = start.to 478 elif isinstance(end, exp.Cast): 479 target_type = end.to 480 else: 481 target_type = None 482 483 if target_type and target_type.is_type("timestamp"): 484 if target_type is start.to: 485 end = exp.cast(end, target_type) 486 else: 487 start = exp.cast(start, target_type) 488 489 return self.func("SEQUENCE", start, end, step) 490 491 def offset_limit_modifiers( 492 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 493 ) -> t.List[str]: 494 return [ 495 self.sql(expression, "offset"), 496 self.sql(limit), 497 ] 498 499 def create_sql(self, expression: exp.Create) -> str: 500 """ 501 Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression), 502 so we need to remove them 503 """ 504 kind = expression.args["kind"] 505 schema = expression.this 506 if kind == "VIEW" and schema.expressions: 507 expression.this.set("expressions", None) 508 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.
Determines whether or not a size in the table sample clause represents percentage.
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
227 class Tokenizer(tokens.Tokenizer): 228 UNICODE_STRINGS = [ 229 (prefix + q, q) 230 for q in t.cast(t.List[str], tokens.Tokenizer.QUOTES) 231 for prefix in ("U&", "u&") 232 ] 233 234 KEYWORDS = { 235 **tokens.Tokenizer.KEYWORDS, 236 "START": TokenType.BEGIN, 237 "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE, 238 "ROW": TokenType.STRUCT, 239 "IPADDRESS": TokenType.IPADDRESS, 240 "IPPREFIX": TokenType.IPPREFIX, 241 }
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
243 class Parser(parser.Parser): 244 FUNCTIONS = { 245 **parser.Parser.FUNCTIONS, 246 "ARBITRARY": exp.AnyValue.from_arg_list, 247 "APPROX_DISTINCT": exp.ApproxDistinct.from_arg_list, 248 "APPROX_PERCENTILE": _approx_percentile, 249 "BITWISE_AND": binary_from_function(exp.BitwiseAnd), 250 "BITWISE_NOT": lambda args: exp.BitwiseNot(this=seq_get(args, 0)), 251 "BITWISE_OR": binary_from_function(exp.BitwiseOr), 252 "BITWISE_XOR": binary_from_function(exp.BitwiseXor), 253 "CARDINALITY": exp.ArraySize.from_arg_list, 254 "CONTAINS": exp.ArrayContains.from_arg_list, 255 "DATE_ADD": lambda args: exp.DateAdd( 256 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 257 ), 258 "DATE_DIFF": lambda args: exp.DateDiff( 259 this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0) 260 ), 261 "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "presto"), 262 "DATE_PARSE": format_time_lambda(exp.StrToTime, "presto"), 263 "DATE_TRUNC": date_trunc_to_time, 264 "ELEMENT_AT": _parse_element_at, 265 "FROM_HEX": exp.Unhex.from_arg_list, 266 "FROM_UNIXTIME": _from_unixtime, 267 "FROM_UTF8": lambda args: exp.Decode( 268 this=seq_get(args, 0), replace=seq_get(args, 1), charset=exp.Literal.string("utf-8") 269 ), 270 "NOW": exp.CurrentTimestamp.from_arg_list, 271 "REGEXP_EXTRACT": lambda args: exp.RegexpExtract( 272 this=seq_get(args, 0), expression=seq_get(args, 1), group=seq_get(args, 2) 273 ), 274 "REGEXP_REPLACE": lambda args: exp.RegexpReplace( 275 this=seq_get(args, 0), 276 expression=seq_get(args, 1), 277 replacement=seq_get(args, 2) or exp.Literal.string(""), 278 ), 279 "ROW": exp.Struct.from_arg_list, 280 "SEQUENCE": exp.GenerateSeries.from_arg_list, 281 "SET_AGG": exp.ArrayUniqueAgg.from_arg_list, 282 "SPLIT_TO_MAP": exp.StrToMap.from_arg_list, 283 "STRPOS": lambda args: exp.StrPosition( 284 this=seq_get(args, 0), substr=seq_get(args, 1), instance=seq_get(args, 2) 285 ), 286 "TO_CHAR": _parse_to_char, 287 "TO_HEX": exp.Hex.from_arg_list, 288 "TO_UNIXTIME": exp.TimeToUnix.from_arg_list, 289 "TO_UTF8": lambda args: exp.Encode( 290 this=seq_get(args, 0), charset=exp.Literal.string("utf-8") 291 ), 292 } 293 294 FUNCTION_PARSERS = parser.Parser.FUNCTION_PARSERS.copy() 295 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
- STRING_ALIASES
- 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
297 class Generator(generator.Generator): 298 INTERVAL_ALLOWS_PLURAL_FORM = False 299 JOIN_HINTS = False 300 TABLE_HINTS = False 301 QUERY_HINTS = False 302 IS_BOOL_ALLOWED = False 303 TZ_TO_WITH_TIME_ZONE = True 304 NVL2_SUPPORTED = False 305 STRUCT_DELIMITER = ("(", ")") 306 LIMIT_ONLY_LITERALS = True 307 SUPPORTS_SINGLE_ARG_CONCAT = False 308 309 PROPERTIES_LOCATION = { 310 **generator.Generator.PROPERTIES_LOCATION, 311 exp.LocationProperty: exp.Properties.Location.UNSUPPORTED, 312 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 313 } 314 315 TYPE_MAPPING = { 316 **generator.Generator.TYPE_MAPPING, 317 exp.DataType.Type.INT: "INTEGER", 318 exp.DataType.Type.FLOAT: "REAL", 319 exp.DataType.Type.BINARY: "VARBINARY", 320 exp.DataType.Type.TEXT: "VARCHAR", 321 exp.DataType.Type.TIMETZ: "TIME", 322 exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP", 323 exp.DataType.Type.STRUCT: "ROW", 324 exp.DataType.Type.DATETIME: "TIMESTAMP", 325 exp.DataType.Type.DATETIME64: "TIMESTAMP", 326 } 327 328 TRANSFORMS = { 329 **generator.Generator.TRANSFORMS, 330 exp.AnyValue: rename_func("ARBITRARY"), 331 exp.ApproxDistinct: _approx_distinct_sql, 332 exp.ApproxQuantile: rename_func("APPROX_PERCENTILE"), 333 exp.ArgMax: rename_func("MAX_BY"), 334 exp.ArgMin: rename_func("MIN_BY"), 335 exp.Array: lambda self, e: f"ARRAY[{self.expressions(e, flat=True)}]", 336 exp.ArrayConcat: rename_func("CONCAT"), 337 exp.ArrayContains: rename_func("CONTAINS"), 338 exp.ArraySize: rename_func("CARDINALITY"), 339 exp.ArrayUniqueAgg: rename_func("SET_AGG"), 340 exp.BitwiseAnd: lambda self, e: f"BITWISE_AND({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 341 exp.BitwiseLeftShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_LEFT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 342 exp.BitwiseNot: lambda self, e: f"BITWISE_NOT({self.sql(e, 'this')})", 343 exp.BitwiseOr: lambda self, e: f"BITWISE_OR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 344 exp.BitwiseRightShift: lambda self, e: f"BITWISE_ARITHMETIC_SHIFT_RIGHT({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 345 exp.BitwiseXor: lambda self, e: f"BITWISE_XOR({self.sql(e, 'this')}, {self.sql(e, 'expression')})", 346 exp.Cast: transforms.preprocess([transforms.epoch_cast_to_ts]), 347 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 348 exp.DateAdd: lambda self, e: self.func( 349 "DATE_ADD", 350 exp.Literal.string(e.text("unit") or "DAY"), 351 _to_int( 352 e.expression, 353 ), 354 e.this, 355 ), 356 exp.DateDiff: lambda self, e: self.func( 357 "DATE_DIFF", exp.Literal.string(e.text("unit") or "DAY"), e.expression, e.this 358 ), 359 exp.DateStrToDate: datestrtodate_sql, 360 exp.DateToDi: lambda self, e: f"CAST(DATE_FORMAT({self.sql(e, 'this')}, {Presto.DATEINT_FORMAT}) AS INT)", 361 exp.DateSub: lambda self, e: self.func( 362 "DATE_ADD", 363 exp.Literal.string(e.text("unit") or "DAY"), 364 _to_int(e.expression * -1), 365 e.this, 366 ), 367 exp.Decode: lambda self, e: encode_decode_sql(self, e, "FROM_UTF8"), 368 exp.DiToDate: lambda self, e: f"CAST(DATE_PARSE(CAST({self.sql(e, 'this')} AS VARCHAR), {Presto.DATEINT_FORMAT}) AS DATE)", 369 exp.Encode: lambda self, e: encode_decode_sql(self, e, "TO_UTF8"), 370 exp.FileFormatProperty: lambda self, e: f"FORMAT='{e.name.upper()}'", 371 exp.First: _first_last_sql, 372 exp.GetPath: path_to_jsonpath(), 373 exp.Group: transforms.preprocess([transforms.unalias_group]), 374 exp.GroupConcat: lambda self, e: self.func( 375 "ARRAY_JOIN", self.func("ARRAY_AGG", e.this), e.args.get("separator") 376 ), 377 exp.Hex: rename_func("TO_HEX"), 378 exp.If: if_sql(), 379 exp.ILike: no_ilike_sql, 380 exp.Initcap: _initcap_sql, 381 exp.ParseJSON: rename_func("JSON_PARSE"), 382 exp.Last: _first_last_sql, 383 exp.LastDay: lambda self, e: self.func("LAST_DAY_OF_MONTH", e.this), 384 exp.Lateral: _explode_to_unnest_sql, 385 exp.Left: left_to_substring_sql, 386 exp.Levenshtein: rename_func("LEVENSHTEIN_DISTANCE"), 387 exp.LogicalAnd: rename_func("BOOL_AND"), 388 exp.LogicalOr: rename_func("BOOL_OR"), 389 exp.Pivot: no_pivot_sql, 390 exp.Quantile: _quantile_sql, 391 exp.RegexpExtract: regexp_extract_sql, 392 exp.Right: right_to_substring_sql, 393 exp.SafeDivide: no_safe_divide_sql, 394 exp.Schema: _schema_sql, 395 exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), 396 exp.Select: transforms.preprocess( 397 [ 398 transforms.eliminate_qualify, 399 transforms.eliminate_distinct_on, 400 transforms.explode_to_unnest(1), 401 transforms.eliminate_semi_and_anti_joins, 402 ] 403 ), 404 exp.SortArray: _no_sort_array, 405 exp.StrPosition: rename_func("STRPOS"), 406 exp.StrToDate: lambda self, e: f"CAST({_str_to_time_sql(self, e)} AS DATE)", 407 exp.StrToMap: rename_func("SPLIT_TO_MAP"), 408 exp.StrToTime: _str_to_time_sql, 409 exp.StrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {self.format_time(e)}))", 410 exp.StructExtract: struct_extract_sql, 411 exp.Table: transforms.preprocess([_unnest_sequence]), 412 exp.Timestamp: no_timestamp_sql, 413 exp.TimestampTrunc: timestamptrunc_sql, 414 exp.TimeStrToDate: timestrtotime_sql, 415 exp.TimeStrToTime: timestrtotime_sql, 416 exp.TimeStrToUnix: lambda self, e: f"TO_UNIXTIME(DATE_PARSE({self.sql(e, 'this')}, {Presto.TIME_FORMAT}))", 417 exp.TimeToStr: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 418 exp.TimeToUnix: rename_func("TO_UNIXTIME"), 419 exp.ToChar: lambda self, e: f"DATE_FORMAT({self.sql(e, 'this')}, {self.format_time(e)})", 420 exp.TryCast: transforms.preprocess([transforms.epoch_cast_to_ts]), 421 exp.TsOrDiToDi: lambda self, e: f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS VARCHAR), '-', ''), 1, 8) AS INT)", 422 exp.TsOrDsAdd: _ts_or_ds_add_sql, 423 exp.TsOrDsDiff: _ts_or_ds_diff_sql, 424 exp.TsOrDsToDate: _ts_or_ds_to_date_sql, 425 exp.Unhex: rename_func("FROM_HEX"), 426 exp.UnixToStr: lambda self, e: f"DATE_FORMAT(FROM_UNIXTIME({self.sql(e, 'this')}), {self.format_time(e)})", 427 exp.UnixToTime: _unix_to_time_sql, 428 exp.UnixToTimeStr: lambda self, e: f"CAST(FROM_UNIXTIME({self.sql(e, 'this')}) AS VARCHAR)", 429 exp.VariancePop: rename_func("VAR_POP"), 430 exp.With: transforms.preprocess([transforms.add_recursive_cte_column_names]), 431 exp.WithinGroup: transforms.preprocess( 432 [transforms.remove_within_group_for_percentiles] 433 ), 434 exp.Xor: bool_xor_sql, 435 } 436 437 def bracket_sql(self, expression: exp.Bracket) -> str: 438 if expression.args.get("safe"): 439 return self.func( 440 "ELEMENT_AT", 441 expression.this, 442 seq_get( 443 apply_index_offset( 444 expression.this, 445 expression.expressions, 446 1 - expression.args.get("offset", 0), 447 ), 448 0, 449 ), 450 ) 451 return super().bracket_sql(expression) 452 453 def struct_sql(self, expression: exp.Struct) -> str: 454 if any(isinstance(arg, self.KEY_VALUE_DEFINITIONS) for arg in expression.expressions): 455 self.unsupported("Struct with key-value definitions is unsupported.") 456 return self.function_fallback_sql(expression) 457 458 return rename_func("ROW")(self, expression) 459 460 def interval_sql(self, expression: exp.Interval) -> str: 461 unit = self.sql(expression, "unit") 462 if expression.this and unit.startswith("WEEK"): 463 return f"({expression.this.name} * INTERVAL '7' DAY)" 464 return super().interval_sql(expression) 465 466 def transaction_sql(self, expression: exp.Transaction) -> str: 467 modes = expression.args.get("modes") 468 modes = f" {', '.join(modes)}" if modes else "" 469 return f"START TRANSACTION{modes}" 470 471 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 472 start = expression.args["start"] 473 end = expression.args["end"] 474 step = expression.args.get("step") 475 476 if isinstance(start, exp.Cast): 477 target_type = start.to 478 elif isinstance(end, exp.Cast): 479 target_type = end.to 480 else: 481 target_type = None 482 483 if target_type and target_type.is_type("timestamp"): 484 if target_type is start.to: 485 end = exp.cast(end, target_type) 486 else: 487 start = exp.cast(start, target_type) 488 489 return self.func("SEQUENCE", start, end, step) 490 491 def offset_limit_modifiers( 492 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 493 ) -> t.List[str]: 494 return [ 495 self.sql(expression, "offset"), 496 self.sql(limit), 497 ] 498 499 def create_sql(self, expression: exp.Create) -> str: 500 """ 501 Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression), 502 so we need to remove them 503 """ 504 kind = expression.args["kind"] 505 schema = expression.this 506 if kind == "VIEW" and schema.expressions: 507 expression.this.set("expressions", None) 508 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
437 def bracket_sql(self, expression: exp.Bracket) -> str: 438 if expression.args.get("safe"): 439 return self.func( 440 "ELEMENT_AT", 441 expression.this, 442 seq_get( 443 apply_index_offset( 444 expression.this, 445 expression.expressions, 446 1 - expression.args.get("offset", 0), 447 ), 448 0, 449 ), 450 ) 451 return super().bracket_sql(expression)
453 def struct_sql(self, expression: exp.Struct) -> str: 454 if any(isinstance(arg, self.KEY_VALUE_DEFINITIONS) for arg in expression.expressions): 455 self.unsupported("Struct with key-value definitions is unsupported.") 456 return self.function_fallback_sql(expression) 457 458 return rename_func("ROW")(self, expression)
471 def generateseries_sql(self, expression: exp.GenerateSeries) -> str: 472 start = expression.args["start"] 473 end = expression.args["end"] 474 step = expression.args.get("step") 475 476 if isinstance(start, exp.Cast): 477 target_type = start.to 478 elif isinstance(end, exp.Cast): 479 target_type = end.to 480 else: 481 target_type = None 482 483 if target_type and target_type.is_type("timestamp"): 484 if target_type is start.to: 485 end = exp.cast(end, target_type) 486 else: 487 start = exp.cast(start, target_type) 488 489 return self.func("SEQUENCE", start, end, step)
499 def create_sql(self, expression: exp.Create) -> str: 500 """ 501 Presto doesn't support CREATE VIEW with expressions (ex: `CREATE VIEW x (cola)` then `(cola)` is the expression), 502 so we need to remove them 503 """ 504 kind = expression.args["kind"] 505 schema = expression.this 506 if kind == "VIEW" and schema.expressions: 507 expression.this.set("expressions", None) 508 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
- 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
- TABLESAMPLE_SIZE_IS_ROWS
- TABLESAMPLE_KEYWORDS
- TABLESAMPLE_WITH_METHOD
- TABLESAMPLE_SEED_KEYWORD
- COLLATE_IS_FUNC
- DATA_TYPE_SPECIFIERS_ALLOWED
- ENSURE_BOOLS
- CTE_RECURSIVE_KEYWORD_REQUIRED
- LAST_DAY_SUPPORTS_DATE_PART
- SUPPORTS_TABLE_ALIAS_COLUMNS
- UNPIVOT_ALIASES_ARE_IDENTIFIERS
- 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_op
- 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
- pivotalias_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
- tsordstotime_sql
- tsordstodate_sql
- unixdate_sql
- lastday_sql