sqlglot.generators.postgres
1from __future__ import annotations 2 3import typing as t 4 5from sqlglot import exp, generator, transforms 6from sqlglot.dialects.dialect import ( 7 DATE_ADD_OR_SUB, 8 JSON_EXTRACT_TYPE, 9 any_value_to_max_sql, 10 arrow_json_extract_sql, 11 array_append_sql, 12 array_concat_sql, 13 bool_xor_sql, 14 count_if_to_sum, 15 date_delta_to_binary_sql, 16 datestrtodate_sql, 17 filter_array_using_unnest, 18 generate_series_sql, 19 getbit_sql, 20 groupconcat_sql, 21 inline_array_sql, 22 json_extract_segments, 23 json_path_key_only_name, 24 max_or_greatest, 25 merge_without_target_sql, 26 min_or_least, 27 no_last_day_sql, 28 no_map_from_entries_sql, 29 no_paren_current_date_sql, 30 no_pivot_sql, 31 no_trycast_sql, 32 regexp_replace_global_modifier, 33 rename_func, 34 sha256_sql, 35 sha2_digest_sql, 36 strposition_sql, 37 struct_extract_sql, 38 timestamptrunc_sql, 39 timestrtotime_sql, 40 trim_sql, 41 ts_or_ds_add_cast, 42) 43from sqlglot.generator import unsupported_args 44from sqlglot.helper import ensure_list, seq_get, to_int 45 46 47DATE_DIFF_FACTOR = { 48 "MICROSECOND": " * 1000000", 49 "MILLISECOND": " * 1000", 50 "SECOND": "", 51 "MINUTE": " / 60", 52 "HOUR": " / 3600", 53 "DAY": " / 86400", 54} 55 56DATE_DIFF_BOUNDARY_UNITS = { 57 "MICROSECOND", 58 "MILLISECOND", 59 "SECOND", 60 "MINUTE", 61 "HOUR", 62 "MONTH", 63 "QUARTER", 64 "YEAR", 65} 66 67 68def _date_add_sql(kind: str) -> t.Callable[[PostgresGenerator, DATE_ADD_OR_SUB], str]: 69 def func(self: PostgresGenerator, expression: DATE_ADD_OR_SUB) -> str: 70 if isinstance(expression, exp.TsOrDsAdd): 71 expression = ts_or_ds_add_cast(expression) 72 73 this = expression.this 74 unit = expression.args.get("unit") 75 76 e = self._simplify_unless_literal(expression.expression) 77 interval: exp.Expr 78 if isinstance(e, exp.Interval): 79 interval = e 80 elif e.is_number or e.is_string: 81 interval = exp.Interval(this=exp.Literal.string(e.to_py()), unit=unit) 82 else: 83 one = exp.Literal.number(1) 84 interval = exp.Interval(this=one, unit=unit) * e 85 86 return date_delta_to_binary_sql( 87 self, expression, this + interval if kind == "+" else this - interval 88 ) 89 90 return func 91 92 93def _day_month_year_sql(self: PostgresGenerator, expression: exp.Day | exp.Month | exp.Year) -> str: 94 this = expression.this 95 value = this.this if isinstance(this, exp.TsOrDsToDate) else this 96 97 if value.is_type(*exp.DataType.INTEGER_TYPES) and ( 98 default_date := this.args.get("default_date") 99 ): 100 this = exp.cast(default_date, exp.DType.DATE) + value 101 102 return self.sql(exp.Extract(this=exp.var(expression.sql_name()), expression=this)) 103 104 105def _date_diff_sql(self: PostgresGenerator, expression: exp.DateDiff | exp.TsOrDsDiff) -> str: 106 unit = expression.text("unit").upper() or "DAY" 107 108 # Dialects like MySQL count crossed day boundaries, which maps to DATE subtraction 109 if unit == "DAY" and expression.args.get("date_part_boundary"): 110 this = exp.cast(expression.this, exp.DType.DATE) 111 expr = exp.cast(expression.expression, exp.DType.DATE) 112 return self.sql(exp.paren(this - expr)) 113 114 factor = DATE_DIFF_FACTOR.get(unit) 115 116 end = f"CAST({self.sql(expression, 'this')} AS TIMESTAMP)" 117 start = f"CAST({self.sql(expression, 'expression')} AS TIMESTAMP)" 118 119 # The arithmetic below counts complete units between the operands, whereas dialects that set 120 # date_part_boundary count unit boundary crossings, so the operands are truncated down to the 121 # unit to make the two coincide. WEEK is left out: its start day differs across dialects 122 if expression.args.get("date_part_boundary") and unit in DATE_DIFF_BOUNDARY_UNITS: 123 end = self.func("DATE_TRUNC", exp.Literal.string(unit), end) 124 start = self.func("DATE_TRUNC", exp.Literal.string(unit), start) 125 126 if factor is not None: 127 return f"CAST(EXTRACT(epoch FROM {end} - {start}){factor} AS BIGINT)" 128 129 age = f"AGE({end}, {start})" 130 131 if unit == "WEEK": 132 unit = f"EXTRACT(days FROM ({end} - {start})) / 7" 133 elif unit == "MONTH": 134 unit = f"EXTRACT(year FROM {age}) * 12 + EXTRACT(month FROM {age})" 135 elif unit == "QUARTER": 136 unit = f"EXTRACT(year FROM {age}) * 4 + EXTRACT(month FROM {age}) / 3" 137 elif unit == "YEAR": 138 unit = f"EXTRACT(year FROM {age})" 139 else: 140 unit = age 141 142 return f"CAST({unit} AS BIGINT)" 143 144 145def _substring_sql(self: PostgresGenerator, expression: exp.Substring) -> str: 146 this = self.sql(expression, "this") 147 start = self.sql(expression, "start") 148 length = self.sql(expression, "length") 149 150 from_part = f" FROM {start}" if start else "" 151 for_part = f" FOR {length}" if length else "" 152 153 return f"SUBSTRING({this}{from_part}{for_part})" 154 155 156def _auto_increment_to_serial(expression: exp.Expr) -> exp.Expr: 157 auto = expression.find(exp.AutoIncrementColumnConstraint) 158 159 if auto: 160 expression.args["constraints"].remove(auto.parent) 161 kind = expression.args["kind"] 162 163 if kind.this == exp.DType.INT: 164 kind.replace(exp.DataType(this=exp.DType.SERIAL)) 165 elif kind.this == exp.DType.SMALLINT: 166 kind.replace(exp.DataType(this=exp.DType.SMALLSERIAL)) 167 elif kind.this == exp.DType.BIGINT: 168 kind.replace(exp.DataType(this=exp.DType.BIGSERIAL)) 169 170 return expression 171 172 173def _serial_to_generated(expression: exp.Expr) -> exp.Expr: 174 if not isinstance(expression, exp.ColumnDef): 175 return expression 176 kind = expression.kind 177 if not kind: 178 return expression 179 180 if kind.this == exp.DType.SERIAL: 181 data_type = exp.DataType(this=exp.DType.INT) 182 elif kind.this == exp.DType.SMALLSERIAL: 183 data_type = exp.DataType(this=exp.DType.SMALLINT) 184 elif kind.this == exp.DType.BIGSERIAL: 185 data_type = exp.DataType(this=exp.DType.BIGINT) 186 else: 187 data_type = None 188 189 if data_type: 190 expression.args["kind"].replace(data_type) 191 constraints = expression.args["constraints"] 192 generated = exp.ColumnConstraint(kind=exp.GeneratedAsIdentityColumnConstraint(this=False)) 193 notnull = exp.ColumnConstraint(kind=exp.NotNullColumnConstraint()) 194 195 if notnull not in constraints: 196 constraints.insert(0, notnull) 197 if generated not in constraints: 198 constraints.insert(0, generated) 199 200 return expression 201 202 203def _json_extract_sql( 204 name: str, op: str 205) -> t.Callable[[PostgresGenerator, JSON_EXTRACT_TYPE], str]: 206 def _generate(self: PostgresGenerator, expression: JSON_EXTRACT_TYPE) -> str: 207 path = expression.expression 208 # Single non-literal segment: render as infix, not JSON_EXTRACT_PATH[_TEXT] (jsonb-unsafe). 209 if not isinstance(path, (exp.JSONPath, exp.Variadic)) and not ensure_list( 210 expression.args.get("expressions") 211 ): 212 return arrow_json_extract_sql(self, expression, op=op) 213 214 # JSON_EXTRACT_PATH requires a key, so use an empty variadic array for the root path 215 if len(path.expressions) == 1 and isinstance(path.expressions[0], exp.JSONPathRoot): 216 expression.set("expression", exp.Variadic(this=exp.Literal.string("{}"))) 217 218 if expression.args.get("only_json_types"): 219 return json_extract_segments(name, quoted_index=False, op=op)(self, expression) 220 return json_extract_segments(name)(self, expression) 221 222 return _generate 223 224 225def _unix_to_time_sql(self: PostgresGenerator, expression: exp.UnixToTime) -> str: 226 scale = expression.args.get("scale") 227 timestamp = expression.this 228 229 if scale in (None, exp.UnixToTime.SECONDS): 230 return self.func("TO_TIMESTAMP", timestamp, self.format_time(expression)) 231 232 return self.func( 233 "TO_TIMESTAMP", 234 exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)), 235 self.format_time(expression), 236 ) 237 238 239def _levenshtein_sql(self: PostgresGenerator, expression: exp.Levenshtein) -> str: 240 name = "LEVENSHTEIN_LESS_EQUAL" if expression.args.get("max_dist") else "LEVENSHTEIN" 241 242 return rename_func(name)(self, expression) 243 244 245def _versioned_anyvalue_sql(self: PostgresGenerator, expression: exp.AnyValue) -> str: 246 # https://www.postgresql.org/docs/16/functions-aggregate.html 247 # https://www.postgresql.org/about/featurematrix/ 248 if self.dialect.version < (16,): 249 return any_value_to_max_sql(self, expression) 250 251 return rename_func("ANY_VALUE")(self, expression) 252 253 254def _round_sql(self: PostgresGenerator, expression: exp.Round) -> str: 255 this = self.sql(expression, "this") 256 decimals = self.sql(expression, "decimals") 257 258 if not decimals: 259 return self.func("ROUND", this) 260 261 if not expression.type: 262 from sqlglot.optimizer.annotate_types import annotate_types 263 264 expression = annotate_types(expression, dialect=self.dialect) 265 266 # ROUND(double precision, integer) is not permitted in Postgres 267 # so it's necessary to cast to decimal before rounding. 268 if expression.this.is_type(exp.DType.DOUBLE): 269 decimal_type = exp.DType.DECIMAL.into_expr(expressions=expression.expressions) 270 this = self.sql(exp.Cast(this=this, to=decimal_type)) 271 272 return self.func("ROUND", this, decimals) 273 274 275class PostgresGenerator(generator.Generator): 276 SELECT_KINDS: tuple[str, ...] = () 277 TRY_SUPPORTED = False 278 SUPPORTS_DECODE_CASE = False 279 280 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 281 282 SINGLE_STRING_INTERVAL = True 283 RENAME_TABLE_WITH_DB = False 284 LOCKING_READS_SUPPORTED = True 285 JOIN_HINTS = False 286 TABLE_HINTS = False 287 QUERY_HINTS = False 288 NVL2_SUPPORTED = False 289 PARAMETER_TOKEN = "$" 290 NAMED_PLACEHOLDER_TOKEN = "%" 291 TABLESAMPLE_SIZE_IS_ROWS = False 292 TABLESAMPLE_SEED_KEYWORD = "REPEATABLE" 293 SUPPORTS_SELECT_INTO = True 294 JSON_TYPE_REQUIRED_FOR_EXTRACTION = True 295 SUPPORTS_UNLOGGED_TABLES = True 296 LIKE_PROPERTY_INSIDE_SCHEMA = True 297 MULTI_ARG_DISTINCT = False 298 CAN_IMPLEMENT_ARRAY_ANY = True 299 SUPPORTS_WINDOW_EXCLUDE = True 300 COPY_HAS_INTO_KEYWORD = False 301 ARRAY_CONCAT_IS_VAR_LEN = False 302 SUPPORTS_MEDIAN = False 303 ARRAY_SIZE_DIM_REQUIRED: bool | None = True 304 SUPPORTS_BETWEEN_FLAGS = True 305 INOUT_SEPARATOR = "" # PostgreSQL uses "INOUT" (no space) 306 307 SUPPORTED_JSON_PATH_PARTS = { 308 exp.JSONPathKey, 309 exp.JSONPathRoot, 310 exp.JSONPathSubscript, 311 } 312 313 def lateral_sql(self, expression: exp.Lateral) -> str: 314 sql = super().lateral_sql(expression) 315 316 if expression.args.get("cross_apply") is not None: 317 sql = f"{sql} ON TRUE" 318 319 return sql 320 321 def star_sql(self, expression: exp.Star) -> str: 322 if self.STAR_EXCEPT == "EXCEPT" and expression.args.get("except_"): 323 self.unsupported("PostgreSQL does not support EXCEPT in the SELECT projection") 324 325 return super().star_sql(expression) 326 327 TYPE_MAPPING = { 328 **generator.Generator.TYPE_MAPPING, 329 exp.DType.TINYINT: "SMALLINT", 330 exp.DType.FLOAT: "REAL", 331 exp.DType.DOUBLE: "DOUBLE PRECISION", 332 exp.DType.BINARY: "BYTEA", 333 exp.DType.VARBINARY: "BYTEA", 334 exp.DType.ROWVERSION: "BYTEA", 335 exp.DType.DATETIME: "TIMESTAMP", 336 exp.DType.TIMESTAMPNTZ: "TIMESTAMP", 337 exp.DType.BLOB: "BYTEA", 338 } 339 340 TRANSFORMS = { 341 **{ 342 k: v 343 for k, v in generator.Generator.TRANSFORMS.items() 344 if k != exp.CommentColumnConstraint 345 }, 346 exp.AnyValue: _versioned_anyvalue_sql, 347 exp.ArrayConcat: array_concat_sql("ARRAY_CAT"), 348 exp.ArrayFilter: filter_array_using_unnest, 349 exp.ArrayAppend: array_append_sql("ARRAY_APPEND"), 350 exp.ArrayPrepend: array_append_sql("ARRAY_PREPEND", swap_params=True), 351 exp.BitwiseAndAgg: rename_func("BIT_AND"), 352 exp.BitwiseOrAgg: rename_func("BIT_OR"), 353 exp.BitwiseXor: lambda self, e: self.binary(e, "#"), 354 exp.BitwiseXorAgg: rename_func("BIT_XOR"), 355 exp.ColumnDef: transforms.preprocess([_auto_increment_to_serial, _serial_to_generated]), 356 exp.CurrentDate: no_paren_current_date_sql, 357 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 358 exp.CurrentUser: lambda *_: "CURRENT_USER", 359 exp.CurrentVersion: rename_func("VERSION"), 360 exp.DateAdd: _date_add_sql("+"), 361 exp.DateDiff: _date_diff_sql, 362 exp.DateStrToDate: datestrtodate_sql, 363 exp.DateSub: _date_add_sql("-"), 364 exp.DatetimeAdd: _date_add_sql("+"), 365 exp.DatetimeSub: _date_add_sql("-"), 366 exp.Day: _day_month_year_sql, 367 exp.Explode: rename_func("UNNEST"), 368 exp.ExplodingGenerateSeries: rename_func("GENERATE_SERIES"), 369 exp.GenerateSeries: generate_series_sql("GENERATE_SERIES"), 370 exp.Getbit: getbit_sql, 371 exp.GroupConcat: lambda self, e: groupconcat_sql( 372 self, e, func_name="STRING_AGG", within_group=False 373 ), 374 exp.IntDiv: rename_func("DIV"), 375 exp.JSONArrayAgg: lambda self, e: self.func( 376 "JSON_AGG", 377 self.sql(e, "this"), 378 suffix=f"{self.sql(e, 'order')})", 379 ), 380 exp.JSONExtract: _json_extract_sql("JSON_EXTRACT_PATH", "->"), 381 exp.JSONExtractScalar: _json_extract_sql("JSON_EXTRACT_PATH_TEXT", "->>"), 382 exp.JSONBExtract: lambda self, e: arrow_json_extract_sql(self, e, op="#>"), 383 exp.JSONBExtractScalar: lambda self, e: arrow_json_extract_sql(self, e, op="#>>"), 384 exp.ParseJSON: lambda self, e: self.sql(exp.cast(e.this, exp.DType.JSON)), 385 exp.JSONPathKey: json_path_key_only_name, 386 exp.JSONPathRoot: lambda *_: "", 387 exp.JSONPathSubscript: lambda self, e: self.json_path_part(e.this), 388 exp.LastDay: no_last_day_sql, 389 exp.LogicalOr: rename_func("BOOL_OR"), 390 exp.LogicalAnd: rename_func("BOOL_AND"), 391 exp.Max: max_or_greatest, 392 exp.MapFromEntries: no_map_from_entries_sql, 393 exp.Min: min_or_least, 394 exp.Merge: merge_without_target_sql, 395 exp.Month: _day_month_year_sql, 396 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 397 exp.PercentileCont: transforms.preprocess([transforms.add_within_group_for_percentiles]), 398 exp.PercentileDisc: transforms.preprocess([transforms.add_within_group_for_percentiles]), 399 exp.Pivot: no_pivot_sql, 400 exp.Rand: rename_func("RANDOM"), 401 exp.RegexpILike: lambda self, e: self.binary(e, "~*"), 402 exp.RegexpReplace: lambda self, e: self.func( 403 "REGEXP_REPLACE", 404 e.this, 405 e.expression, 406 e.args.get("replacement") or exp.Literal.string(""), 407 e.args.get("position"), 408 e.args.get("occurrence"), 409 regexp_replace_global_modifier(e), 410 ), 411 exp.Round: _round_sql, 412 exp.Select: transforms.preprocess( 413 [ 414 transforms.eliminate_semi_and_anti_joins, 415 transforms.eliminate_qualify, 416 ] 417 ), 418 exp.SHA2: lambda self, e: self.func( 419 "ENCODE", sha256_sql(self, e), exp.Literal.string("hex") 420 ), 421 exp.SHA2Digest: sha2_digest_sql, 422 exp.StrPosition: lambda self, e: strposition_sql(self, e, func_name="POSITION"), 423 exp.StrToDate: lambda self, e: self.func("TO_DATE", e.this, self.format_time(e)), 424 exp.StrToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, self.format_time(e)), 425 exp.StructExtract: struct_extract_sql, 426 exp.Substring: _substring_sql, 427 exp.TimeFromParts: rename_func("MAKE_TIME"), 428 exp.TimestampFromParts: rename_func("MAKE_TIMESTAMP"), 429 exp.TimestampTrunc: timestamptrunc_sql(zone=True), 430 exp.TimestampAdd: _date_add_sql("+"), 431 exp.TimestampSub: _date_add_sql("-"), 432 exp.TimeStrToTime: timestrtotime_sql, 433 exp.TimeToStr: lambda self, e: self.func("TO_CHAR", e.this, self.format_time(e)), 434 exp.ToChar: lambda self, e: ( 435 self.function_fallback_sql(e) if e.args.get("format") else self.tochar_sql(e) 436 ), 437 exp.Trim: trim_sql, 438 exp.TryCast: no_trycast_sql, 439 exp.TsOrDsAdd: _date_add_sql("+"), 440 exp.TsOrDsDiff: _date_diff_sql, 441 exp.UnixToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this), 442 exp.Uuid: lambda *_: "GEN_RANDOM_UUID()", 443 exp.TimeToUnix: lambda self, e: self.func("DATE_PART", exp.Literal.string("epoch"), e.this), 444 exp.VariancePop: rename_func("VAR_POP"), 445 exp.Variance: rename_func("VAR_SAMP"), 446 exp.Xor: bool_xor_sql, 447 exp.Year: _day_month_year_sql, 448 exp.Unicode: rename_func("ASCII"), 449 exp.UnixToTime: _unix_to_time_sql, 450 exp.Levenshtein: _levenshtein_sql, 451 exp.JSONObjectAgg: rename_func("JSON_OBJECT_AGG"), 452 exp.JSONBObjectAgg: rename_func("JSONB_OBJECT_AGG"), 453 exp.CountIf: count_if_to_sum, 454 exp.FileFormatProperty: lambda self, e: f"USING {self.sql(e, 'this')}", 455 exp.TableSpaceProperty: lambda self, e: f"TABLESPACE {self.sql(e, 'this')}", 456 } 457 458 PROPERTIES_LOCATION = { 459 **generator.Generator.PROPERTIES_LOCATION, 460 exp.FileFormatProperty: exp.Properties.Location.POST_SCHEMA, 461 exp.OnCommitProperty: exp.Properties.Location.POST_WITH, 462 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 463 exp.TableSpaceProperty: exp.Properties.Location.POST_WITH, 464 exp.TransientProperty: exp.Properties.Location.UNSUPPORTED, 465 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 466 } 467 468 def with_properties(self, properties: exp.Properties) -> str: 469 with_properties = [] 470 post_with = [] 471 for prop in properties.expressions: 472 if isinstance(prop, (exp.OnCommitProperty, exp.TableSpaceProperty)): 473 post_with.append(prop) 474 else: 475 with_properties.append(prop) 476 477 post_with.sort(key=lambda prop: isinstance(prop, exp.TableSpaceProperty)) 478 sql = super().with_properties(exp.Properties(expressions=with_properties)) 479 post_sql = self.expressions(sqls=post_with, sep=" ", indent=False) 480 return sql + self.seg(post_sql, sep=" " if sql else "") if post_sql else sql 481 482 def bytestring_sql(self, expression: exp.ByteString) -> str: 483 if not expression.args.get("is_bytes"): 484 return super().bytestring_sql(expression) 485 486 return self.func( 487 "DECODE", 488 exp.Literal.string(expression.this.encode("latin-1").hex()), 489 exp.Literal.string("hex"), 490 ) 491 492 def schemacommentproperty_sql(self, expression: exp.SchemaCommentProperty) -> str: 493 self.unsupported("Table comments are not supported in the CREATE statement") 494 return "" 495 496 def commentcolumnconstraint_sql(self, expression: exp.CommentColumnConstraint) -> str: 497 self.unsupported("Column comments are not supported in the CREATE statement") 498 return "" 499 500 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 501 # PostgreSQL places parameter modes BEFORE parameter name 502 param_constraint = expression.find(exp.InOutColumnConstraint) 503 504 if param_constraint: 505 mode_sql = self.sql(param_constraint) 506 param_constraint.pop() # Remove to prevent double-rendering 507 base_sql = super().columndef_sql(expression, sep) 508 return f"{mode_sql} {base_sql}" 509 510 return super().columndef_sql(expression, sep) 511 512 def unnest_sql(self, expression: exp.Unnest) -> str: 513 if len(expression.expressions) == 1: 514 arg = expression.expressions[0] 515 if isinstance(arg, exp.GenerateDateArray): 516 generate_series: exp.Expr = exp.GenerateSeries(**arg.args) 517 if isinstance(expression.parent, (exp.From, exp.Join)): 518 generate_series = ( 519 exp.select("value::date") 520 .from_(exp.Table(this=generate_series).as_("_t", table=["value"])) 521 .subquery(expression.args.get("alias") or "_unnested_generate_series") 522 ) 523 return self.sql(generate_series) 524 525 from sqlglot.optimizer.annotate_types import annotate_types 526 527 this = annotate_types(arg, dialect=self.dialect) 528 if this.is_type("array<json>"): 529 while isinstance(this, exp.Cast): 530 this = this.this 531 532 arg_as_json = self.sql(exp.cast(this, exp.DType.JSON)) 533 alias = self.sql(expression, "alias") 534 alias = f" AS {alias}" if alias else "" 535 536 if expression.args.get("offset"): 537 self.unsupported("Unsupported JSON_ARRAY_ELEMENTS with offset") 538 539 return f"JSON_ARRAY_ELEMENTS({arg_as_json}){alias}" 540 541 return super().unnest_sql(expression) 542 543 def bracket_sql(self, expression: exp.Bracket) -> str: 544 """Forms like ARRAY[1, 2, 3][3] aren't allowed; we need to wrap the ARRAY.""" 545 if isinstance(expression.this, exp.Array): 546 expression.set("this", exp.paren(expression.this, copy=False)) 547 548 return super().bracket_sql(expression) 549 550 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 551 this = self.sql(expression, "this") 552 expressions = [f"{self.sql(e)} @@ {this}" for e in expression.expressions] 553 sql = " OR ".join(expressions) 554 return f"({sql})" if len(expressions) > 1 else sql 555 556 def alterset_sql(self, expression: exp.AlterSet) -> str: 557 exprs = self.expressions(expression, flat=True) 558 exprs = f"({exprs})" if exprs else "" 559 560 access_method = self.sql(expression, "access_method") 561 access_method = f"ACCESS METHOD {access_method}" if access_method else "" 562 tablespace = self.sql(expression, "tablespace") 563 tablespace = f"TABLESPACE {tablespace}" if tablespace else "" 564 option = self.sql(expression, "option") 565 566 return f"SET {exprs}{access_method}{tablespace}{option}" 567 568 def datatype_sql(self, expression: exp.DataType) -> str: 569 if expression.is_type(exp.DType.ARRAY): 570 if expression.expressions: 571 values = self.expressions(expression, key="values", flat=True) 572 return f"{self.expressions(expression, flat=True)}[{values}]" 573 return "ARRAY" 574 575 if expression.is_type(exp.DType.ENUM): 576 return f"ENUM ({self.expressions(expression, flat=True)})" 577 578 if expression.is_type(exp.DType.DOUBLE, exp.DType.FLOAT) and expression.expressions: 579 # Postgres doesn't support precision for REAL and DOUBLE PRECISION types 580 return f"FLOAT({self.expressions(expression, flat=True)})" 581 582 return super().datatype_sql(expression) 583 584 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 585 this = expression.this 586 587 # Postgres casts DIV() to decimal for transpilation but when roundtripping it's superfluous 588 if ( 589 isinstance(this, exp.IntDiv) 590 and exp.IntDiv in self.TRANSFORMS 591 and expression.to == exp.DType.DECIMAL.into_expr() 592 ): 593 return self.sql(this) 594 595 return super().cast_sql(expression, safe_prefix=safe_prefix) 596 597 def array_sql(self, expression: exp.Array) -> str: 598 exprs = expression.expressions 599 func_name = self.normalize_func("ARRAY") 600 601 if isinstance(seq_get(exprs, 0), exp.Query): 602 return f"{func_name}({self.sql(exprs[0])})" 603 604 return f"{func_name}{inline_array_sql(self, expression)}" 605 606 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 607 return f"GENERATED ALWAYS AS ({self.sql(expression, 'this')}) STORED" 608 609 def isascii_sql(self, expression: exp.IsAscii) -> str: 610 return f"({self.sql(expression.this)} ~ '^[[:ascii:]]*$')" 611 612 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 613 # https://www.postgresql.org/docs/current/functions-window.html 614 self.unsupported("PostgreSQL does not support IGNORE NULLS.") 615 return self.sql(expression.this) 616 617 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 618 # https://www.postgresql.org/docs/current/functions-window.html 619 self.unsupported("PostgreSQL does not support RESPECT NULLS.") 620 return self.sql(expression.this) 621 622 def regexplike_sql(self, expression: exp.RegexpLike) -> str: 623 flag = expression.args.get("flag") 624 if not flag: 625 return self.binary(expression, "~") 626 627 # Postgres has no flags argument for ~, only the case-insensitive ~* operator. Of the 628 # case flags, the last one wins, e.g. 'ic' is case-sensitive and 'ci' is not 629 flags = flag.name if flag.is_string else "" 630 if not flag.is_string or set(flags) - {"i", "c"}: 631 self.unsupported("Only the case flags 'i' and 'c' are supported for ~ in Postgres") 632 633 return self.binary(expression, "~*" if flags.rfind("i") > flags.rfind("c") else "~") 634 635 @unsupported_args("this") 636 def currentschema_sql(self, expression: exp.CurrentSchema) -> str: 637 return "CURRENT_SCHEMA" 638 639 def interval_sql(self, expression: exp.Interval) -> str: 640 unit = expression.text("unit").lower() 641 642 this = expression.this 643 if unit.startswith("quarter") and isinstance(this, exp.Literal): 644 # Postgres has no QUARTER unit and no exponents in interval strings 645 quarters = to_int(this.to_py()) 646 if quarters is None: 647 self.unsupported("Postgres intervals need a whole number of quarters") 648 else: 649 this.replace(exp.Literal.string(quarters * 3)) 650 expression.args["unit"].replace(exp.var("MONTH")) 651 652 return super().interval_sql(expression) 653 654 def placeholder_sql(self, expression: exp.Placeholder) -> str: 655 if expression.args.get("jdbc"): 656 return "?" 657 658 this = f"({expression.name})" if expression.this else "" 659 return f"{self.NAMED_PLACEHOLDER_TOKEN}{this}s" 660 661 def arraycontains_sql(self, expression: exp.ArrayContains) -> str: 662 # Convert DuckDB's LIST_CONTAINS(array, value) to PostgreSQL 663 # DuckDB behavior: 664 # - LIST_CONTAINS([1,2,3], 2) -> true 665 # - LIST_CONTAINS([1,2,3], 4) -> false 666 # - LIST_CONTAINS([1,2,NULL], 4) -> false (not NULL) 667 # - LIST_CONTAINS([1,2,3], NULL) -> NULL 668 # 669 # PostgreSQL equivalent: CASE WHEN value IS NULL THEN NULL 670 # ELSE COALESCE(value = ANY(array), FALSE) END 671 value = expression.expression 672 array = expression.this 673 674 coalesce_expr = exp.Coalesce( 675 this=value.eq(exp.Any(this=exp.paren(expression=array, copy=False))), 676 expressions=[exp.false()], 677 ) 678 679 case_expr = ( 680 exp.Case() 681 .when(exp.Is(this=value, expression=exp.null()), exp.null(), copy=False) 682 .else_(coalesce_expr, copy=False) 683 ) 684 685 return self.sql(case_expr)
DATE_DIFF_FACTOR =
{'MICROSECOND': ' * 1000000', 'MILLISECOND': ' * 1000', 'SECOND': '', 'MINUTE': ' / 60', 'HOUR': ' / 3600', 'DAY': ' / 86400'}
DATE_DIFF_BOUNDARY_UNITS =
{'HOUR', 'MICROSECOND', 'MINUTE', 'SECOND', 'MONTH', 'MILLISECOND', 'YEAR', 'QUARTER'}
276class PostgresGenerator(generator.Generator): 277 SELECT_KINDS: tuple[str, ...] = () 278 TRY_SUPPORTED = False 279 SUPPORTS_DECODE_CASE = False 280 281 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 282 283 SINGLE_STRING_INTERVAL = True 284 RENAME_TABLE_WITH_DB = False 285 LOCKING_READS_SUPPORTED = True 286 JOIN_HINTS = False 287 TABLE_HINTS = False 288 QUERY_HINTS = False 289 NVL2_SUPPORTED = False 290 PARAMETER_TOKEN = "$" 291 NAMED_PLACEHOLDER_TOKEN = "%" 292 TABLESAMPLE_SIZE_IS_ROWS = False 293 TABLESAMPLE_SEED_KEYWORD = "REPEATABLE" 294 SUPPORTS_SELECT_INTO = True 295 JSON_TYPE_REQUIRED_FOR_EXTRACTION = True 296 SUPPORTS_UNLOGGED_TABLES = True 297 LIKE_PROPERTY_INSIDE_SCHEMA = True 298 MULTI_ARG_DISTINCT = False 299 CAN_IMPLEMENT_ARRAY_ANY = True 300 SUPPORTS_WINDOW_EXCLUDE = True 301 COPY_HAS_INTO_KEYWORD = False 302 ARRAY_CONCAT_IS_VAR_LEN = False 303 SUPPORTS_MEDIAN = False 304 ARRAY_SIZE_DIM_REQUIRED: bool | None = True 305 SUPPORTS_BETWEEN_FLAGS = True 306 INOUT_SEPARATOR = "" # PostgreSQL uses "INOUT" (no space) 307 308 SUPPORTED_JSON_PATH_PARTS = { 309 exp.JSONPathKey, 310 exp.JSONPathRoot, 311 exp.JSONPathSubscript, 312 } 313 314 def lateral_sql(self, expression: exp.Lateral) -> str: 315 sql = super().lateral_sql(expression) 316 317 if expression.args.get("cross_apply") is not None: 318 sql = f"{sql} ON TRUE" 319 320 return sql 321 322 def star_sql(self, expression: exp.Star) -> str: 323 if self.STAR_EXCEPT == "EXCEPT" and expression.args.get("except_"): 324 self.unsupported("PostgreSQL does not support EXCEPT in the SELECT projection") 325 326 return super().star_sql(expression) 327 328 TYPE_MAPPING = { 329 **generator.Generator.TYPE_MAPPING, 330 exp.DType.TINYINT: "SMALLINT", 331 exp.DType.FLOAT: "REAL", 332 exp.DType.DOUBLE: "DOUBLE PRECISION", 333 exp.DType.BINARY: "BYTEA", 334 exp.DType.VARBINARY: "BYTEA", 335 exp.DType.ROWVERSION: "BYTEA", 336 exp.DType.DATETIME: "TIMESTAMP", 337 exp.DType.TIMESTAMPNTZ: "TIMESTAMP", 338 exp.DType.BLOB: "BYTEA", 339 } 340 341 TRANSFORMS = { 342 **{ 343 k: v 344 for k, v in generator.Generator.TRANSFORMS.items() 345 if k != exp.CommentColumnConstraint 346 }, 347 exp.AnyValue: _versioned_anyvalue_sql, 348 exp.ArrayConcat: array_concat_sql("ARRAY_CAT"), 349 exp.ArrayFilter: filter_array_using_unnest, 350 exp.ArrayAppend: array_append_sql("ARRAY_APPEND"), 351 exp.ArrayPrepend: array_append_sql("ARRAY_PREPEND", swap_params=True), 352 exp.BitwiseAndAgg: rename_func("BIT_AND"), 353 exp.BitwiseOrAgg: rename_func("BIT_OR"), 354 exp.BitwiseXor: lambda self, e: self.binary(e, "#"), 355 exp.BitwiseXorAgg: rename_func("BIT_XOR"), 356 exp.ColumnDef: transforms.preprocess([_auto_increment_to_serial, _serial_to_generated]), 357 exp.CurrentDate: no_paren_current_date_sql, 358 exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", 359 exp.CurrentUser: lambda *_: "CURRENT_USER", 360 exp.CurrentVersion: rename_func("VERSION"), 361 exp.DateAdd: _date_add_sql("+"), 362 exp.DateDiff: _date_diff_sql, 363 exp.DateStrToDate: datestrtodate_sql, 364 exp.DateSub: _date_add_sql("-"), 365 exp.DatetimeAdd: _date_add_sql("+"), 366 exp.DatetimeSub: _date_add_sql("-"), 367 exp.Day: _day_month_year_sql, 368 exp.Explode: rename_func("UNNEST"), 369 exp.ExplodingGenerateSeries: rename_func("GENERATE_SERIES"), 370 exp.GenerateSeries: generate_series_sql("GENERATE_SERIES"), 371 exp.Getbit: getbit_sql, 372 exp.GroupConcat: lambda self, e: groupconcat_sql( 373 self, e, func_name="STRING_AGG", within_group=False 374 ), 375 exp.IntDiv: rename_func("DIV"), 376 exp.JSONArrayAgg: lambda self, e: self.func( 377 "JSON_AGG", 378 self.sql(e, "this"), 379 suffix=f"{self.sql(e, 'order')})", 380 ), 381 exp.JSONExtract: _json_extract_sql("JSON_EXTRACT_PATH", "->"), 382 exp.JSONExtractScalar: _json_extract_sql("JSON_EXTRACT_PATH_TEXT", "->>"), 383 exp.JSONBExtract: lambda self, e: arrow_json_extract_sql(self, e, op="#>"), 384 exp.JSONBExtractScalar: lambda self, e: arrow_json_extract_sql(self, e, op="#>>"), 385 exp.ParseJSON: lambda self, e: self.sql(exp.cast(e.this, exp.DType.JSON)), 386 exp.JSONPathKey: json_path_key_only_name, 387 exp.JSONPathRoot: lambda *_: "", 388 exp.JSONPathSubscript: lambda self, e: self.json_path_part(e.this), 389 exp.LastDay: no_last_day_sql, 390 exp.LogicalOr: rename_func("BOOL_OR"), 391 exp.LogicalAnd: rename_func("BOOL_AND"), 392 exp.Max: max_or_greatest, 393 exp.MapFromEntries: no_map_from_entries_sql, 394 exp.Min: min_or_least, 395 exp.Merge: merge_without_target_sql, 396 exp.Month: _day_month_year_sql, 397 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 398 exp.PercentileCont: transforms.preprocess([transforms.add_within_group_for_percentiles]), 399 exp.PercentileDisc: transforms.preprocess([transforms.add_within_group_for_percentiles]), 400 exp.Pivot: no_pivot_sql, 401 exp.Rand: rename_func("RANDOM"), 402 exp.RegexpILike: lambda self, e: self.binary(e, "~*"), 403 exp.RegexpReplace: lambda self, e: self.func( 404 "REGEXP_REPLACE", 405 e.this, 406 e.expression, 407 e.args.get("replacement") or exp.Literal.string(""), 408 e.args.get("position"), 409 e.args.get("occurrence"), 410 regexp_replace_global_modifier(e), 411 ), 412 exp.Round: _round_sql, 413 exp.Select: transforms.preprocess( 414 [ 415 transforms.eliminate_semi_and_anti_joins, 416 transforms.eliminate_qualify, 417 ] 418 ), 419 exp.SHA2: lambda self, e: self.func( 420 "ENCODE", sha256_sql(self, e), exp.Literal.string("hex") 421 ), 422 exp.SHA2Digest: sha2_digest_sql, 423 exp.StrPosition: lambda self, e: strposition_sql(self, e, func_name="POSITION"), 424 exp.StrToDate: lambda self, e: self.func("TO_DATE", e.this, self.format_time(e)), 425 exp.StrToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, self.format_time(e)), 426 exp.StructExtract: struct_extract_sql, 427 exp.Substring: _substring_sql, 428 exp.TimeFromParts: rename_func("MAKE_TIME"), 429 exp.TimestampFromParts: rename_func("MAKE_TIMESTAMP"), 430 exp.TimestampTrunc: timestamptrunc_sql(zone=True), 431 exp.TimestampAdd: _date_add_sql("+"), 432 exp.TimestampSub: _date_add_sql("-"), 433 exp.TimeStrToTime: timestrtotime_sql, 434 exp.TimeToStr: lambda self, e: self.func("TO_CHAR", e.this, self.format_time(e)), 435 exp.ToChar: lambda self, e: ( 436 self.function_fallback_sql(e) if e.args.get("format") else self.tochar_sql(e) 437 ), 438 exp.Trim: trim_sql, 439 exp.TryCast: no_trycast_sql, 440 exp.TsOrDsAdd: _date_add_sql("+"), 441 exp.TsOrDsDiff: _date_diff_sql, 442 exp.UnixToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this), 443 exp.Uuid: lambda *_: "GEN_RANDOM_UUID()", 444 exp.TimeToUnix: lambda self, e: self.func("DATE_PART", exp.Literal.string("epoch"), e.this), 445 exp.VariancePop: rename_func("VAR_POP"), 446 exp.Variance: rename_func("VAR_SAMP"), 447 exp.Xor: bool_xor_sql, 448 exp.Year: _day_month_year_sql, 449 exp.Unicode: rename_func("ASCII"), 450 exp.UnixToTime: _unix_to_time_sql, 451 exp.Levenshtein: _levenshtein_sql, 452 exp.JSONObjectAgg: rename_func("JSON_OBJECT_AGG"), 453 exp.JSONBObjectAgg: rename_func("JSONB_OBJECT_AGG"), 454 exp.CountIf: count_if_to_sum, 455 exp.FileFormatProperty: lambda self, e: f"USING {self.sql(e, 'this')}", 456 exp.TableSpaceProperty: lambda self, e: f"TABLESPACE {self.sql(e, 'this')}", 457 } 458 459 PROPERTIES_LOCATION = { 460 **generator.Generator.PROPERTIES_LOCATION, 461 exp.FileFormatProperty: exp.Properties.Location.POST_SCHEMA, 462 exp.OnCommitProperty: exp.Properties.Location.POST_WITH, 463 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 464 exp.TableSpaceProperty: exp.Properties.Location.POST_WITH, 465 exp.TransientProperty: exp.Properties.Location.UNSUPPORTED, 466 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 467 } 468 469 def with_properties(self, properties: exp.Properties) -> str: 470 with_properties = [] 471 post_with = [] 472 for prop in properties.expressions: 473 if isinstance(prop, (exp.OnCommitProperty, exp.TableSpaceProperty)): 474 post_with.append(prop) 475 else: 476 with_properties.append(prop) 477 478 post_with.sort(key=lambda prop: isinstance(prop, exp.TableSpaceProperty)) 479 sql = super().with_properties(exp.Properties(expressions=with_properties)) 480 post_sql = self.expressions(sqls=post_with, sep=" ", indent=False) 481 return sql + self.seg(post_sql, sep=" " if sql else "") if post_sql else sql 482 483 def bytestring_sql(self, expression: exp.ByteString) -> str: 484 if not expression.args.get("is_bytes"): 485 return super().bytestring_sql(expression) 486 487 return self.func( 488 "DECODE", 489 exp.Literal.string(expression.this.encode("latin-1").hex()), 490 exp.Literal.string("hex"), 491 ) 492 493 def schemacommentproperty_sql(self, expression: exp.SchemaCommentProperty) -> str: 494 self.unsupported("Table comments are not supported in the CREATE statement") 495 return "" 496 497 def commentcolumnconstraint_sql(self, expression: exp.CommentColumnConstraint) -> str: 498 self.unsupported("Column comments are not supported in the CREATE statement") 499 return "" 500 501 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 502 # PostgreSQL places parameter modes BEFORE parameter name 503 param_constraint = expression.find(exp.InOutColumnConstraint) 504 505 if param_constraint: 506 mode_sql = self.sql(param_constraint) 507 param_constraint.pop() # Remove to prevent double-rendering 508 base_sql = super().columndef_sql(expression, sep) 509 return f"{mode_sql} {base_sql}" 510 511 return super().columndef_sql(expression, sep) 512 513 def unnest_sql(self, expression: exp.Unnest) -> str: 514 if len(expression.expressions) == 1: 515 arg = expression.expressions[0] 516 if isinstance(arg, exp.GenerateDateArray): 517 generate_series: exp.Expr = exp.GenerateSeries(**arg.args) 518 if isinstance(expression.parent, (exp.From, exp.Join)): 519 generate_series = ( 520 exp.select("value::date") 521 .from_(exp.Table(this=generate_series).as_("_t", table=["value"])) 522 .subquery(expression.args.get("alias") or "_unnested_generate_series") 523 ) 524 return self.sql(generate_series) 525 526 from sqlglot.optimizer.annotate_types import annotate_types 527 528 this = annotate_types(arg, dialect=self.dialect) 529 if this.is_type("array<json>"): 530 while isinstance(this, exp.Cast): 531 this = this.this 532 533 arg_as_json = self.sql(exp.cast(this, exp.DType.JSON)) 534 alias = self.sql(expression, "alias") 535 alias = f" AS {alias}" if alias else "" 536 537 if expression.args.get("offset"): 538 self.unsupported("Unsupported JSON_ARRAY_ELEMENTS with offset") 539 540 return f"JSON_ARRAY_ELEMENTS({arg_as_json}){alias}" 541 542 return super().unnest_sql(expression) 543 544 def bracket_sql(self, expression: exp.Bracket) -> str: 545 """Forms like ARRAY[1, 2, 3][3] aren't allowed; we need to wrap the ARRAY.""" 546 if isinstance(expression.this, exp.Array): 547 expression.set("this", exp.paren(expression.this, copy=False)) 548 549 return super().bracket_sql(expression) 550 551 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 552 this = self.sql(expression, "this") 553 expressions = [f"{self.sql(e)} @@ {this}" for e in expression.expressions] 554 sql = " OR ".join(expressions) 555 return f"({sql})" if len(expressions) > 1 else sql 556 557 def alterset_sql(self, expression: exp.AlterSet) -> str: 558 exprs = self.expressions(expression, flat=True) 559 exprs = f"({exprs})" if exprs else "" 560 561 access_method = self.sql(expression, "access_method") 562 access_method = f"ACCESS METHOD {access_method}" if access_method else "" 563 tablespace = self.sql(expression, "tablespace") 564 tablespace = f"TABLESPACE {tablespace}" if tablespace else "" 565 option = self.sql(expression, "option") 566 567 return f"SET {exprs}{access_method}{tablespace}{option}" 568 569 def datatype_sql(self, expression: exp.DataType) -> str: 570 if expression.is_type(exp.DType.ARRAY): 571 if expression.expressions: 572 values = self.expressions(expression, key="values", flat=True) 573 return f"{self.expressions(expression, flat=True)}[{values}]" 574 return "ARRAY" 575 576 if expression.is_type(exp.DType.ENUM): 577 return f"ENUM ({self.expressions(expression, flat=True)})" 578 579 if expression.is_type(exp.DType.DOUBLE, exp.DType.FLOAT) and expression.expressions: 580 # Postgres doesn't support precision for REAL and DOUBLE PRECISION types 581 return f"FLOAT({self.expressions(expression, flat=True)})" 582 583 return super().datatype_sql(expression) 584 585 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 586 this = expression.this 587 588 # Postgres casts DIV() to decimal for transpilation but when roundtripping it's superfluous 589 if ( 590 isinstance(this, exp.IntDiv) 591 and exp.IntDiv in self.TRANSFORMS 592 and expression.to == exp.DType.DECIMAL.into_expr() 593 ): 594 return self.sql(this) 595 596 return super().cast_sql(expression, safe_prefix=safe_prefix) 597 598 def array_sql(self, expression: exp.Array) -> str: 599 exprs = expression.expressions 600 func_name = self.normalize_func("ARRAY") 601 602 if isinstance(seq_get(exprs, 0), exp.Query): 603 return f"{func_name}({self.sql(exprs[0])})" 604 605 return f"{func_name}{inline_array_sql(self, expression)}" 606 607 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 608 return f"GENERATED ALWAYS AS ({self.sql(expression, 'this')}) STORED" 609 610 def isascii_sql(self, expression: exp.IsAscii) -> str: 611 return f"({self.sql(expression.this)} ~ '^[[:ascii:]]*$')" 612 613 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 614 # https://www.postgresql.org/docs/current/functions-window.html 615 self.unsupported("PostgreSQL does not support IGNORE NULLS.") 616 return self.sql(expression.this) 617 618 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 619 # https://www.postgresql.org/docs/current/functions-window.html 620 self.unsupported("PostgreSQL does not support RESPECT NULLS.") 621 return self.sql(expression.this) 622 623 def regexplike_sql(self, expression: exp.RegexpLike) -> str: 624 flag = expression.args.get("flag") 625 if not flag: 626 return self.binary(expression, "~") 627 628 # Postgres has no flags argument for ~, only the case-insensitive ~* operator. Of the 629 # case flags, the last one wins, e.g. 'ic' is case-sensitive and 'ci' is not 630 flags = flag.name if flag.is_string else "" 631 if not flag.is_string or set(flags) - {"i", "c"}: 632 self.unsupported("Only the case flags 'i' and 'c' are supported for ~ in Postgres") 633 634 return self.binary(expression, "~*" if flags.rfind("i") > flags.rfind("c") else "~") 635 636 @unsupported_args("this") 637 def currentschema_sql(self, expression: exp.CurrentSchema) -> str: 638 return "CURRENT_SCHEMA" 639 640 def interval_sql(self, expression: exp.Interval) -> str: 641 unit = expression.text("unit").lower() 642 643 this = expression.this 644 if unit.startswith("quarter") and isinstance(this, exp.Literal): 645 # Postgres has no QUARTER unit and no exponents in interval strings 646 quarters = to_int(this.to_py()) 647 if quarters is None: 648 self.unsupported("Postgres intervals need a whole number of quarters") 649 else: 650 this.replace(exp.Literal.string(quarters * 3)) 651 expression.args["unit"].replace(exp.var("MONTH")) 652 653 return super().interval_sql(expression) 654 655 def placeholder_sql(self, expression: exp.Placeholder) -> str: 656 if expression.args.get("jdbc"): 657 return "?" 658 659 this = f"({expression.name})" if expression.this else "" 660 return f"{self.NAMED_PLACEHOLDER_TOKEN}{this}s" 661 662 def arraycontains_sql(self, expression: exp.ArrayContains) -> str: 663 # Convert DuckDB's LIST_CONTAINS(array, value) to PostgreSQL 664 # DuckDB behavior: 665 # - LIST_CONTAINS([1,2,3], 2) -> true 666 # - LIST_CONTAINS([1,2,3], 4) -> false 667 # - LIST_CONTAINS([1,2,NULL], 4) -> false (not NULL) 668 # - LIST_CONTAINS([1,2,3], NULL) -> NULL 669 # 670 # PostgreSQL equivalent: CASE WHEN value IS NULL THEN NULL 671 # ELSE COALESCE(value = ANY(array), FALSE) END 672 value = expression.expression 673 array = expression.this 674 675 coalesce_expr = exp.Coalesce( 676 this=value.eq(exp.Any(this=exp.paren(expression=array, copy=False))), 677 expressions=[exp.false()], 678 ) 679 680 case_expr = ( 681 exp.Case() 682 .when(exp.Is(this=value, expression=exp.null()), exp.null(), copy=False) 683 .else_(coalesce_expr, copy=False) 684 ) 685 686 return self.sql(case_expr)
Generator converts a given syntax tree to the corresponding SQL string.
Arguments:
- pretty: Whether 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: Always quote except for specials cases. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether to normalize identifiers to lowercase. Default: False.
- pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
- indent: The indentation size in a formatted string. For example, this affects the
indentation of subqueries and filters under a
WHEREclause. Default: 2. - normalize_functions: How to normalize 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: Whether 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 to preserve comments in the output SQL code. Default: True
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.query.JSONPathKey'>, <class 'sqlglot.expressions.query.JSONPathSubscript'>, <class 'sqlglot.expressions.query.JSONPathRoot'>}
TYPE_MAPPING =
{<DType.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <DType.NCHAR: 'NCHAR'>: 'CHAR', <DType.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <DType.LONGTEXT: 'LONGTEXT'>: 'TEXT', <DType.TINYTEXT: 'TINYTEXT'>: 'TEXT', <DType.BLOB: 'BLOB'>: 'BYTEA', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <DType.LONGBLOB: 'LONGBLOB'>: 'BLOB', <DType.TINYBLOB: 'TINYBLOB'>: 'BLOB', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'BYTEA', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP', <DType.TINYINT: 'TINYINT'>: 'SMALLINT', <DType.FLOAT: 'FLOAT'>: 'REAL', <DType.DOUBLE: 'DOUBLE'>: 'DOUBLE PRECISION', <DType.BINARY: 'BINARY'>: 'BYTEA', <DType.VARBINARY: 'VARBINARY'>: 'BYTEA', <DType.DATETIME: 'DATETIME'>: 'TIMESTAMP', <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>: 'TIMESTAMP'}
TRANSFORMS =
{<class 'sqlglot.expressions.query.JSONPathKey'>: <function json_path_key_only_name>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.query.JSONPathSubscript'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.core.Adjacent'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainedBy'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.AssumeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.BinaryColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApiProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.EndStatement'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HybridProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsTopKey'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.aggregate.AnyValue'>: <function _versioned_anyvalue_sql>, <class 'sqlglot.expressions.array.ArrayConcat'>: <function array_concat_sql.<locals>._array_concat_sql>, <class 'sqlglot.expressions.array.ArrayFilter'>: <function filter_array_using_unnest>, <class 'sqlglot.expressions.array.ArrayAppend'>: <function array_append_sql.<locals>._array_append_sql>, <class 'sqlglot.expressions.array.ArrayPrepend'>: <function array_append_sql.<locals>._array_append_sql>, <class 'sqlglot.expressions.math.BitwiseAndAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseOrAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseXor'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.math.BitwiseXorAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.ColumnDef'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.CurrentDate'>: <function no_paren_current_date_sql>, <class 'sqlglot.expressions.temporal.CurrentTimestamp'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentUser'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentVersion'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DateAdd'>: <function _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.DateDiff'>: <function _date_diff_sql>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.temporal.DateSub'>: <function _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.DatetimeAdd'>: <function _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.DatetimeSub'>: <function _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.Day'>: <function _day_month_year_sql>, <class 'sqlglot.expressions.array.Explode'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ExplodingGenerateSeries'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.GenerateSeries'>: <function generate_series_sql.<locals>._generate_series_sql>, <class 'sqlglot.expressions.math.Getbit'>: <function getbit_sql>, <class 'sqlglot.expressions.aggregate.GroupConcat'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.core.IntDiv'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.json.JSONArrayAgg'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONExtract'>: <function _json_extract_sql.<locals>._generate>, <class 'sqlglot.expressions.json.JSONExtractScalar'>: <function _json_extract_sql.<locals>._generate>, <class 'sqlglot.expressions.json.JSONBExtract'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONBExtractScalar'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.json.ParseJSON'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.LastDay'>: <function no_last_day_sql>, <class 'sqlglot.expressions.aggregate.LogicalOr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalAnd'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.array.MapFromEntries'>: <function no_map_from_entries_sql>, <class 'sqlglot.expressions.aggregate.Min'>: <function min_or_least>, <class 'sqlglot.expressions.dml.Merge'>: <function merge_without_target_sql>, <class 'sqlglot.expressions.temporal.Month'>: <function _day_month_year_sql>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.PercentileCont'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.aggregate.PercentileDisc'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.query.Pivot'>: <function no_pivot_sql>, <class 'sqlglot.expressions.functions.Rand'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.RegexpILike'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.string.RegexpReplace'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.math.Round'>: <function _round_sql>, <class 'sqlglot.expressions.query.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.SHA2'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.string.SHA2Digest'>: <function sha2_digest_sql>, <class 'sqlglot.expressions.string.StrPosition'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.StrToDate'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.StrToTime'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.array.StructExtract'>: <function struct_extract_sql>, <class 'sqlglot.expressions.string.Substring'>: <function _substring_sql>, <class 'sqlglot.expressions.temporal.TimeFromParts'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TimestampFromParts'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TimestampTrunc'>: <function timestamptrunc_sql.<locals>._timestamptrunc_sql>, <class 'sqlglot.expressions.temporal.TimestampAdd'>: <function _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TimestampSub'>: <function _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TimeStrToTime'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.temporal.TimeToStr'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.string.ToChar'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.string.Trim'>: <function trim_sql>, <class 'sqlglot.expressions.functions.TryCast'>: <function no_trycast_sql>, <class 'sqlglot.expressions.temporal.TsOrDsAdd'>: <function _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TsOrDsDiff'>: <function _date_diff_sql>, <class 'sqlglot.expressions.temporal.UnixToTime'>: <function _unix_to_time_sql>, <class 'sqlglot.expressions.functions.Uuid'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimeToUnix'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.VariancePop'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.Variance'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.Xor'>: <function bool_xor_sql>, <class 'sqlglot.expressions.temporal.Year'>: <function _day_month_year_sql>, <class 'sqlglot.expressions.string.Unicode'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Levenshtein'>: <function _levenshtein_sql>, <class 'sqlglot.expressions.json.JSONBObjectAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.CountIf'>: <function count_if_to_sum>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.properties.TableSpaceProperty'>: <function PostgresGenerator.<lambda>>}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.properties.AggregateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AlgorithmProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApiProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.AutoIncrementProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BackupProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BlockCompressionProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ChecksumProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CollateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.query.Cluster'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusteredByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusterProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistributedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DuplicateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DataBlocksizeProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DataDeletionProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DefinerProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DictRange'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EncodeProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.EngineProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.FallbackProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.FreespaceProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.HeapProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.HybridProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InteractiveProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.IsolatedLoadingProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.JournalProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LikeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LocationProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockingProperty'>: <PropertiesLocation.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.properties.LogProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MergeBlockRatioProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.ModuleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OnProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.OptionsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.query.Order'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedOfProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PhysicalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.constraints.PrimaryKey'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Property'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.RefreshTriggerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RollupProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowFormatProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatDelimitedProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatSerdeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SampleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SecureProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SerdeProperties'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.Set'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SetProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SharingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.SequenceProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.TriggerProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageHandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.StrictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Tags'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.TableSpaceProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.TransientProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.MergeTreeTTL'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.UsingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithDataProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSystemVersioningProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>}
469 def with_properties(self, properties: exp.Properties) -> str: 470 with_properties = [] 471 post_with = [] 472 for prop in properties.expressions: 473 if isinstance(prop, (exp.OnCommitProperty, exp.TableSpaceProperty)): 474 post_with.append(prop) 475 else: 476 with_properties.append(prop) 477 478 post_with.sort(key=lambda prop: isinstance(prop, exp.TableSpaceProperty)) 479 sql = super().with_properties(exp.Properties(expressions=with_properties)) 480 post_sql = self.expressions(sqls=post_with, sep=" ", indent=False) 481 return sql + self.seg(post_sql, sep=" " if sql else "") if post_sql else sql
def
schemacommentproperty_sql( self, expression: sqlglot.expressions.properties.SchemaCommentProperty) -> str:
def
commentcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.CommentColumnConstraint) -> str:
501 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 502 # PostgreSQL places parameter modes BEFORE parameter name 503 param_constraint = expression.find(exp.InOutColumnConstraint) 504 505 if param_constraint: 506 mode_sql = self.sql(param_constraint) 507 param_constraint.pop() # Remove to prevent double-rendering 508 base_sql = super().columndef_sql(expression, sep) 509 return f"{mode_sql} {base_sql}" 510 511 return super().columndef_sql(expression, sep)
513 def unnest_sql(self, expression: exp.Unnest) -> str: 514 if len(expression.expressions) == 1: 515 arg = expression.expressions[0] 516 if isinstance(arg, exp.GenerateDateArray): 517 generate_series: exp.Expr = exp.GenerateSeries(**arg.args) 518 if isinstance(expression.parent, (exp.From, exp.Join)): 519 generate_series = ( 520 exp.select("value::date") 521 .from_(exp.Table(this=generate_series).as_("_t", table=["value"])) 522 .subquery(expression.args.get("alias") or "_unnested_generate_series") 523 ) 524 return self.sql(generate_series) 525 526 from sqlglot.optimizer.annotate_types import annotate_types 527 528 this = annotate_types(arg, dialect=self.dialect) 529 if this.is_type("array<json>"): 530 while isinstance(this, exp.Cast): 531 this = this.this 532 533 arg_as_json = self.sql(exp.cast(this, exp.DType.JSON)) 534 alias = self.sql(expression, "alias") 535 alias = f" AS {alias}" if alias else "" 536 537 if expression.args.get("offset"): 538 self.unsupported("Unsupported JSON_ARRAY_ELEMENTS with offset") 539 540 return f"JSON_ARRAY_ELEMENTS({arg_as_json}){alias}" 541 542 return super().unnest_sql(expression)
544 def bracket_sql(self, expression: exp.Bracket) -> str: 545 """Forms like ARRAY[1, 2, 3][3] aren't allowed; we need to wrap the ARRAY.""" 546 if isinstance(expression.this, exp.Array): 547 expression.set("this", exp.paren(expression.this, copy=False)) 548 549 return super().bracket_sql(expression)
Forms like ARRAY[1, 2, 3][3] aren't allowed; we need to wrap the ARRAY.
557 def alterset_sql(self, expression: exp.AlterSet) -> str: 558 exprs = self.expressions(expression, flat=True) 559 exprs = f"({exprs})" if exprs else "" 560 561 access_method = self.sql(expression, "access_method") 562 access_method = f"ACCESS METHOD {access_method}" if access_method else "" 563 tablespace = self.sql(expression, "tablespace") 564 tablespace = f"TABLESPACE {tablespace}" if tablespace else "" 565 option = self.sql(expression, "option") 566 567 return f"SET {exprs}{access_method}{tablespace}{option}"
569 def datatype_sql(self, expression: exp.DataType) -> str: 570 if expression.is_type(exp.DType.ARRAY): 571 if expression.expressions: 572 values = self.expressions(expression, key="values", flat=True) 573 return f"{self.expressions(expression, flat=True)}[{values}]" 574 return "ARRAY" 575 576 if expression.is_type(exp.DType.ENUM): 577 return f"ENUM ({self.expressions(expression, flat=True)})" 578 579 if expression.is_type(exp.DType.DOUBLE, exp.DType.FLOAT) and expression.expressions: 580 # Postgres doesn't support precision for REAL and DOUBLE PRECISION types 581 return f"FLOAT({self.expressions(expression, flat=True)})" 582 583 return super().datatype_sql(expression)
def
cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
585 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 586 this = expression.this 587 588 # Postgres casts DIV() to decimal for transpilation but when roundtripping it's superfluous 589 if ( 590 isinstance(this, exp.IntDiv) 591 and exp.IntDiv in self.TRANSFORMS 592 and expression.to == exp.DType.DECIMAL.into_expr() 593 ): 594 return self.sql(this) 595 596 return super().cast_sql(expression, safe_prefix=safe_prefix)
598 def array_sql(self, expression: exp.Array) -> str: 599 exprs = expression.expressions 600 func_name = self.normalize_func("ARRAY") 601 602 if isinstance(seq_get(exprs, 0), exp.Query): 603 return f"{func_name}({self.sql(exprs[0])})" 604 605 return f"{func_name}{inline_array_sql(self, expression)}"
def
computedcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.ComputedColumnConstraint) -> str:
623 def regexplike_sql(self, expression: exp.RegexpLike) -> str: 624 flag = expression.args.get("flag") 625 if not flag: 626 return self.binary(expression, "~") 627 628 # Postgres has no flags argument for ~, only the case-insensitive ~* operator. Of the 629 # case flags, the last one wins, e.g. 'ic' is case-sensitive and 'ci' is not 630 flags = flag.name if flag.is_string else "" 631 if not flag.is_string or set(flags) - {"i", "c"}: 632 self.unsupported("Only the case flags 'i' and 'c' are supported for ~ in Postgres") 633 634 return self.binary(expression, "~*" if flags.rfind("i") > flags.rfind("c") else "~")
@unsupported_args('this')
def
currentschema_sql(self, expression: sqlglot.expressions.functions.CurrentSchema) -> str:
640 def interval_sql(self, expression: exp.Interval) -> str: 641 unit = expression.text("unit").lower() 642 643 this = expression.this 644 if unit.startswith("quarter") and isinstance(this, exp.Literal): 645 # Postgres has no QUARTER unit and no exponents in interval strings 646 quarters = to_int(this.to_py()) 647 if quarters is None: 648 self.unsupported("Postgres intervals need a whole number of quarters") 649 else: 650 this.replace(exp.Literal.string(quarters * 3)) 651 expression.args["unit"].replace(exp.var("MONTH")) 652 653 return super().interval_sql(expression)
662 def arraycontains_sql(self, expression: exp.ArrayContains) -> str: 663 # Convert DuckDB's LIST_CONTAINS(array, value) to PostgreSQL 664 # DuckDB behavior: 665 # - LIST_CONTAINS([1,2,3], 2) -> true 666 # - LIST_CONTAINS([1,2,3], 4) -> false 667 # - LIST_CONTAINS([1,2,NULL], 4) -> false (not NULL) 668 # - LIST_CONTAINS([1,2,3], NULL) -> NULL 669 # 670 # PostgreSQL equivalent: CASE WHEN value IS NULL THEN NULL 671 # ELSE COALESCE(value = ANY(array), FALSE) END 672 value = expression.expression 673 array = expression.this 674 675 coalesce_expr = exp.Coalesce( 676 this=value.eq(exp.Any(this=exp.paren(expression=array, copy=False))), 677 expressions=[exp.false()], 678 ) 679 680 case_expr = ( 681 exp.Case() 682 .when(exp.Is(this=value, expression=exp.null()), exp.null(), copy=False) 683 .else_(coalesce_expr, copy=False) 684 ) 685 686 return self.sql(case_expr)
Inherited Members
- sqlglot.generator.Generator
- Generator
- NULL_ORDERING_SUPPORTED
- WINDOW_FUNCS_WITH_NULL_ORDERING
- IGNORE_NULLS_IN_FUNC
- IGNORE_NULLS_BEFORE_ORDER
- EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
- WRAP_DERIVED_VALUES
- CREATE_FUNCTION_RETURN_AS
- MATCHED_BY_SOURCE
- SUPPORTS_MERGE_WHERE
- MERGE_ALL_BY_NAME
- INTERVAL_ALLOWS_PLURAL_FORM
- AUTO_REFRESH_BARE_INTERVALS
- LIMIT_FETCH
- LIMIT_ONLY_LITERALS
- GROUPINGS_SEP
- SUPPORTS_GROUPING_SETS_AS_SUFFIX
- INDEX_ON
- DIRECTED_JOINS
- SUPPORTS_NEAREST_JOIN
- QUERY_HINT_SEP
- IS_BOOL_ALLOWED
- CAST_TO_INT_ROUNDS
- SAFE_INT_DIVISION
- DUPLICATE_KEY_UPDATE_WITH_SET
- LIMIT_IS_TOP
- RETURNING_END
- EXTRACT_ALLOWS_QUOTES
- TZ_TO_WITH_TIME_ZONE
- VALUES_AS_TABLE
- ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
- ALTER_TABLE_ADD_COLUMNS_WRAPPED
- UNNEST_WITH_ORDINALITY
- SEMI_ANTI_JOIN_WITH_SIDE
- COMPUTED_COLUMN_WITH_TYPE
- SUPPORTS_TABLE_COPY
- TABLESAMPLE_REQUIRES_PARENS
- TABLESAMPLE_KEYWORDS
- TABLESAMPLE_WITH_METHOD
- HISTORICAL_DATA_POST_ALIAS
- COLLATE_IS_FUNC
- DATA_TYPE_SPECIFIERS_ALLOWED
- ENSURE_BOOLS
- CTE_RECURSIVE_KEYWORD_REQUIRED
- SUPPORTS_SINGLE_ARG_CONCAT
- LAST_DAY_SUPPORTS_DATE_PART
- SUPPORTS_TABLE_ALIAS_COLUMNS
- SUPPORTS_NAMED_CTE_COLUMNS
- UNPIVOT_ALIASES_ARE_IDENTIFIERS
- PIVOT_ALIAS_WITH_AS
- JSON_KEY_VALUE_PAIR_SEP
- INSERT_OVERWRITE
- SUPPORTS_CREATE_TABLE_LIKE
- SUPPORTS_MODIFY_COLUMN
- SUPPORTS_CHANGE_COLUMN
- SUPPORTS_ALTER_COLUMN_NULLABILITY
- SUPPORTS_ALTER_COLUMN_IF_EXISTS
- JSON_PATH_BRACKETED_KEY_SUPPORTED
- JSON_PATH_SINGLE_QUOTE_ESCAPE
- JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
- SUPPORTS_TO_NUMBER
- SET_OP_MODIFIERS
- SET_OP_LIMITS
- SET_OP_PARENTHESIZED_OPERANDS
- COPY_PARAMS_ARE_WRAPPED
- COPY_PARAMS_EQ_REQUIRED
- SUPPORTS_UESCAPE
- UNICODE_SUBSTITUTE
- STAR_EXCEPT
- HEX_FUNC
- BYTE_STRING_FUNCTION
- WITH_PROPERTIES_PREFIX
- QUOTE_JSON_PATH
- PAD_FILL_PATTERN_IS_REQUIRED
- SUPPORTS_EXPLODING_PROJECTIONS
- SUPPORTS_CONVERT_TIMEZONE
- SUPPORTS_UNIX_SECONDS
- ALTER_SET_WRAPPED
- NORMALIZE_EXTRACT_DATE_PARTS
- PARSE_JSON_NAME
- ARRAY_SIZE_NAME
- ALTER_SET_TYPE
- SUPPORTS_LIKE_QUANTIFIERS
- MATCH_AGAINST_TABLE_PREFIX
- SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD
- DECLARE_DEFAULT_ASSIGNMENT
- UPDATE_STATEMENT_SUPPORTS_FROM
- STAR_EXCLUDE_REQUIRES_DERIVED_TABLE
- SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY
- UNSUPPORTED_TYPES
- TYPE_PARAM_SETTINGS
- TIME_PART_SINGULARS
- TOKEN_MAPPING
- STRUCT_DELIMITER
- EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
- RESERVED_KEYWORDS
- WITH_SEPARATED_COMMENTS
- EXCLUDE_COMMENTS
- UNWRAPPED_INTERVAL_VALUES
- PARAMETERIZABLE_TEXT_TYPES
- EXPRESSIONS_WITHOUT_NESTED_CTES
- RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS
- MOD_OPERATOR
- MOD_PAREN_PARENT_TYPES
- ALTER_PARTITION_OPTIONS
- SAFE_JSON_PATH_KEY_RE
- 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
- sanitize_comment
- maybe_comment
- wrap
- no_identify
- normalize_func
- indent
- sql
- uncache_sql
- cache_sql
- characterset_sql
- column_parts
- column_sql
- pseudocolumn_sql
- columnposition_sql
- columnconstraint_sql
- autoincrementcolumnconstraint_sql
- compresscolumnconstraint_sql
- generatedasidentitycolumnconstraint_sql
- generatedasrowcolumnconstraint_sql
- periodforsystemtimeconstraint_sql
- notnullcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_sql
- inoutcolumnconstraint_sql
- createable_sql
- create_sql
- sequenceproperties_sql
- triggerproperties_sql
- triggerreferencing_sql
- triggerevent_sql
- clone_sql
- describe_sql
- heredoc_sql
- prepend_ctes
- with_sql
- cte_sql
- tablealias_sql
- bitstring_sql
- hexstring_sql
- unicodestring_sql
- rawstring_sql
- datatypeparam_sql
- datatype_param_bound_limiter
- directory_sql
- delete_sql
- drop_sql
- set_operation
- set_operations
- fetch_sql
- limitoptions_sql
- filter_sql
- per_sql
- hint_sql
- indexparameters_sql
- index_sql
- dynamicidentifier_sql
- identifier_sql
- hex_sql
- lowerhex_sql
- inputoutputformat_sql
- national_sql
- partition_sql
- properties_sql
- root_properties
- properties
- locate_properties
- property_name
- property_sql
- uuidproperty_sql
- likeproperty_sql
- fallbackproperty_sql
- journalproperty_sql
- freespaceproperty_sql
- checksumproperty_sql
- mergeblockratioproperty_sql
- moduleproperty_sql
- datablocksizeproperty_sql
- blockcompressionproperty_sql
- isolatedloadingproperty_sql
- partitionboundspec_sql
- partitionedofproperty_sql
- lockingproperty_sql
- lockingstatement_sql
- withdataproperty_sql
- withsystemversioningproperty_sql
- insert_sql
- introducer_sql
- kill_sql
- pseudotype_sql
- objectidentifier_sql
- onconflict_sql
- returning_sql
- rowformatdelimitedproperty_sql
- withtablehint_sql
- indextablehint_sql
- historicaldata_sql
- table_parts
- table_sql
- tablefromrows_sql
- tablesample_sql
- pivot_sql
- version_sql
- tuple_sql
- update_sql
- values_sql
- var_sql
- into_sql
- from_sql
- groupingsets_sql
- rollup_sql
- rollupindex_sql
- rollupproperty_sql
- cube_sql
- group_sql
- having_sql
- connectto_sql
- disconnect_sql
- connect_sql
- prior_sql
- join_sql
- nearest_sql
- lambda_sql
- lateral_op
- limit_sql
- offset_sql
- setitem_sql
- set_sql
- queryband_sql
- pragma_sql
- lock_sql
- literal_sql
- escape_str
- loaddata_sql
- null_sql
- boolean_sql
- booland_sql
- boolor_sql
- order_sql
- withfill_sql
- cluster_sql
- clusterproperty_sql
- distribute_sql
- sort_sql
- ordered_sql
- matchrecognizemeasure_sql
- matchrecognize_sql
- query_modifiers
- options_modifier
- forclause_sql
- queryoption_sql
- offset_limit_modifiers
- after_limit_modifiers
- select_sql
- schema_sql
- schema_columns_sql
- parameter_sql
- sessionparameter_sql
- subquery_sql
- qualify_sql
- prewhere_sql
- where_sql
- window_sql
- partition_by_sql
- partitionbyexcluding_sql
- windowspec_sql
- withingroup_sql
- between_sql
- bracket_offset_expressions
- 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
- timeserieskey_sql
- if_sql
- jsonkeyvalue_sql
- jsonpath_sql
- json_path_part
- formatjson_sql
- formatphrase_sql
- teradatatitle_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
- fromtimezone_sql
- fromiso8601date_sql
- fromiso8601timestamp_sql
- fromiso8601timestampnanos_sql
- add_sql
- and_sql
- or_sql
- xor_sql
- connector_sql
- bitwiseand_sql
- bitwiseleftshift_sql
- bitwisenot_sql
- bitwiseor_sql
- bitwiserightshift_sql
- bitwisexor_sql
- strtotime_sql
- strtodate_sql
- parsedatetime_sql
- currentdate_sql
- collate_sql
- command_sql
- comment_sql
- mergetreettlaction_sql
- mergetreettl_sql
- transaction_sql
- commit_sql
- rollback_sql
- altercolumn_sql
- modifycolumn_sql
- alterindex_sql
- alterdiststyle_sql
- altersortkey_sql
- alterrename_sql
- renamecolumn_sql
- alter_sql
- altersession_sql
- add_column_sql
- droppartition_sql
- dropprimarykey_sql
- addconstraint_sql
- replacecolumns_sql
- addpartition_sql
- distinct_sql
- havingmax_sql
- intdiv_sql
- dpipe_sql
- nullif_zero_divisor
- div_sql
- safedivide_sql
- overlaps_sql
- distance_sql
- distancend_sql
- dot_sql
- eq_sql
- propertyeq_sql
- escape_sql
- glob_sql
- gt_sql
- gte_sql
- is_sql
- like_sql
- ilike_sql
- match_sql
- similarto_sql
- lt_sql
- lte_sql
- mod_sql
- mul_sql
- neq_sql
- nullsafeeq_sql
- nullsafeneq_sql
- sub_sql
- trycast_sql
- jsoncast_sql
- try_sql
- log_sql
- use_sql
- binary
- ceil_floor
- function_fallback_sql
- function_name
- func
- format_args
- too_wide
- format_time
- expressions
- op_expressions
- naked_property
- tag_sql
- token_sql
- userdefinedfunction_sql
- macrooverloads_sql
- macrooverload_sql
- joinhint_sql
- kwarg_sql
- when_sql
- whens_sql
- merge_sql
- tochar_sql
- tonumber_sql
- dictproperty_sql
- dictrange_sql
- dictsubproperty_sql
- aggregatekeyproperty_sql
- duplicatekeyproperty_sql
- uniquekeyproperty_sql
- distributedbyproperty_sql
- oncluster_sql
- clusteredbyproperty_sql
- anyvalue_sql
- querytransform_sql
- indexconstraintoption_sql
- checkcolumnconstraint_sql
- indexcolumnconstraint_sql
- nvl2_sql
- nthvalue_sql
- comprehension_sql
- columnprefix_sql
- opclass_sql
- predict_sql
- generateembedding_sql
- generatetext_sql
- generatetable_sql
- generatebool_sql
- generateint_sql
- generatedouble_sql
- mltranslate_sql
- mlforecast_sql
- aiforecast_sql
- featuresattime_sql
- vectorsearch_sql
- forin_sql
- refresh_sql
- toarray_sql
- tsordstotime_sql
- tsordstotimestamp_sql
- tsordstodatetime_sql
- tsordstodate_sql
- unixdate_sql
- lastday_sql
- dateadd_sql
- arrayinsert_sql
- arrayany_sql
- struct_sql
- partitionrange_sql
- truncatetable_sql
- convert_sql
- copyparameter_sql
- credentials_sql
- copy_sql
- semicolon_sql
- datadeletionproperty_sql
- maskingpolicycolumnconstraint_sql
- gapfill_sql
- scope_resolution
- scoperesolution_sql
- parsejson_sql
- rand_sql
- changes_sql
- pad_sql
- summarize_sql
- explodinggenerateseries_sql
- converttimezone_sql
- json_sql
- jsonvalue_sql
- skipjsoncolumn_sql
- conditionalinsert_sql
- multitableinserts_sql
- oncondition_sql
- jsonextractquote_sql
- jsonexists_sql
- min_sql
- max_sql
- arrayagg_sql
- timeslice_sql
- slice_sql
- apply_sql
- grant_sql
- revoke_sql
- grantprivilege_sql
- grantprincipal_sql
- columns_sql
- overlay_sql
- todouble_sql
- string_sql
- median_sql
- overflowtruncatebehavior_sql
- unixseconds_sql
- arraysort_sql
- arraysize_sql
- attach_sql
- detach_sql
- attachoption_sql
- watermarkcolumnconstraint_sql
- encodeproperty_sql
- includeproperty_sql
- xmlelement_sql
- xmlkeyvalueoption_sql
- partitionbyrangeproperty_sql
- partitionbyrangepropertydynamic_sql
- unpivotcolumns_sql
- analyzesample_sql
- analyzestatistics_sql
- analyzehistogram_sql
- analyzedelete_sql
- analyzelistchainedrows_sql
- analyzevalidate_sql
- analyze_sql
- xmltable_sql
- xmlnamespace_sql
- export_sql
- declare_sql
- declareitem_sql
- recursivewithsearch_sql
- parameterizedagg_sql
- anonymousaggfunc_sql
- combinedaggfunc_sql
- combinedparameterizedagg_sql
- show_sql
- install_sql
- liststage_sql
- get_put_sql
- translatecharacters_sql
- decodecase_sql
- semanticview_sql
- getextract_sql
- datefromunixdate_sql
- space_sql
- buildproperty_sql
- refreshtriggerproperty_sql
- modelattribute_sql
- directorystage_sql
- uuid_sql
- initcap_sql
- localtime_sql
- localtimestamp_sql
- weekstart_name
- weekstart_sql
- chr_sql
- weightstring_sql
- block_sql
- functionspecification_sql
- storedprocedure_sql
- ifblock_sql
- casestatement_sql
- whileblock_sql
- loopblock_sql
- repeatblock_sql
- leave_sql
- iterate_sql
- execute_sql
- executesql_sql
- altermodifysqlsecurity_sql
- usingproperty_sql
- renameindex_sql