Edit on GitHub

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    week_unit_to_dow,
 43)
 44from sqlglot.generator import unsupported_args
 45from sqlglot.helper import ensure_list, seq_get, to_int
 46
 47
 48_REGEXP_FULL_MATCH_METACHARS = frozenset(r"\|*+?{}()[].^$%_")
 49
 50DATE_DIFF_FACTOR = {
 51    "MICROSECOND": " * 1000000",
 52    "MILLISECOND": " * 1000",
 53    "SECOND": "",
 54    "MINUTE": " / 60",
 55    "HOUR": " / 3600",
 56    "DAY": " / 86400",
 57}
 58
 59DATE_DIFF_BOUNDARY_UNITS = {
 60    "MICROSECOND",
 61    "MILLISECOND",
 62    "SECOND",
 63    "MINUTE",
 64    "HOUR",
 65    "WEEK",
 66    "MONTH",
 67    "QUARTER",
 68    "YEAR",
 69}
 70
 71
 72def _date_add_sql(kind: str) -> t.Callable[[PostgresGenerator, DATE_ADD_OR_SUB], str]:
 73    def func(self: PostgresGenerator, expression: DATE_ADD_OR_SUB) -> str:
 74        if isinstance(expression, exp.TsOrDsAdd):
 75            expression = ts_or_ds_add_cast(expression)
 76
 77        this = expression.this
 78        unit = expression.args.get("unit")
 79
 80        e = self._simplify_unless_literal(expression.expression)
 81        interval: exp.Expr
 82        if isinstance(e, exp.Interval):
 83            interval = e
 84        elif e.is_number or e.is_string:
 85            interval = exp.Interval(this=exp.Literal.string(e.to_py()), unit=unit)
 86        else:
 87            one = exp.Literal.number(1)
 88            interval = exp.Interval(this=one, unit=unit) * e
 89
 90        return date_delta_to_binary_sql(
 91            self, expression, this + interval if kind == "+" else this - interval
 92        )
 93
 94    return func
 95
 96
 97def _day_month_year_sql(self: PostgresGenerator, expression: exp.Day | exp.Month | exp.Year) -> str:
 98    this = expression.this
 99    value = this.this if isinstance(this, exp.TsOrDsToDate) else this
100
101    if value.is_type(*exp.DataType.INTEGER_TYPES) and (
102        default_date := this.args.get("default_date")
103    ):
104        this = exp.cast(default_date, exp.DType.DATE) + value
105
106    return self.sql(exp.Extract(this=exp.var(expression.sql_name()), expression=this))
107
108
109def _date_diff_sql(self: PostgresGenerator, expression: exp.DateDiff | exp.TsOrDsDiff) -> str:
110    week_start = week_unit_to_dow(expression.unit)
111    unit = "WEEK" if week_start else expression.text("unit").upper() or "DAY"
112    boundary = expression.args.get("date_part_boundary")
113
114    # Dialects like MySQL count crossed day boundaries, which maps to DATE subtraction
115    if unit == "DAY" and boundary:
116        this = exp.cast(expression.this, exp.DType.DATE)
117        expr = exp.cast(expression.expression, exp.DType.DATE)
118        return self.sql(exp.paren(this - expr))
119
120    def timestamp_sql(operand: exp.Expr) -> str:
121        value: exp.Expr = exp.cast(operand, exp.DType.TIMESTAMP)
122        if boundary and unit in DATE_DIFF_BOUNDARY_UNITS:
123            if week_start and week_start != 1:
124                # Shift the requested week start onto Monday before truncating both operands.
125                shift = (1 - week_start) % 7
126                value = value + exp.Interval(
127                    this=exp.Literal.string(str(shift)), unit=exp.var("DAY")
128                )
129            value = exp.DateTrunc(this=value, unit=exp.Literal.string(unit))
130        return self.sql(value)
131
132    end = timestamp_sql(expression.this)
133    start = timestamp_sql(expression.expression)
134    factor = DATE_DIFF_FACTOR.get(unit)
135
136    if factor is not None:
137        return f"CAST(EXTRACT(epoch FROM {end} - {start}){factor} AS BIGINT)"
138
139    age = f"AGE({end}, {start})"
140
141    if unit == "WEEK":
142        unit = f"EXTRACT(days FROM ({end} - {start})) / 7"
143    elif unit == "MONTH":
144        unit = f"EXTRACT(year FROM {age}) * 12 + EXTRACT(month FROM {age})"
145    elif unit == "QUARTER":
146        unit = f"EXTRACT(year FROM {age}) * 4 + EXTRACT(month FROM {age}) / 3"
147    elif unit == "YEAR":
148        unit = f"EXTRACT(year FROM {age})"
149    else:
150        unit = age
151
152    return f"CAST({unit} AS BIGINT)"
153
154
155def _substring_sql(self: PostgresGenerator, expression: exp.Substring) -> str:
156    this = self.sql(expression, "this")
157    start = self.sql(expression, "start")
158    length = self.sql(expression, "length")
159
160    from_part = f" FROM {start}" if start else ""
161    for_part = f" FOR {length}" if length else ""
162
163    return f"SUBSTRING({this}{from_part}{for_part})"
164
165
166def _auto_increment_to_serial(expression: exp.Expr) -> exp.Expr:
167    auto = expression.find(exp.AutoIncrementColumnConstraint)
168
169    if auto:
170        expression.args["constraints"].remove(auto.parent)
171        kind = expression.args["kind"]
172
173        if kind.this == exp.DType.INT:
174            kind.replace(exp.DataType(this=exp.DType.SERIAL))
175        elif kind.this == exp.DType.SMALLINT:
176            kind.replace(exp.DataType(this=exp.DType.SMALLSERIAL))
177        elif kind.this == exp.DType.BIGINT:
178            kind.replace(exp.DataType(this=exp.DType.BIGSERIAL))
179
180    return expression
181
182
183def _serial_to_generated(expression: exp.Expr) -> exp.Expr:
184    if not isinstance(expression, exp.ColumnDef):
185        return expression
186    kind = expression.kind
187    if not kind:
188        return expression
189
190    if kind.this == exp.DType.SERIAL:
191        data_type = exp.DataType(this=exp.DType.INT)
192    elif kind.this == exp.DType.SMALLSERIAL:
193        data_type = exp.DataType(this=exp.DType.SMALLINT)
194    elif kind.this == exp.DType.BIGSERIAL:
195        data_type = exp.DataType(this=exp.DType.BIGINT)
196    else:
197        data_type = None
198
199    if data_type:
200        expression.args["kind"].replace(data_type)
201        constraints = expression.args["constraints"]
202        generated = exp.ColumnConstraint(kind=exp.GeneratedAsIdentityColumnConstraint(this=False))
203        notnull = exp.ColumnConstraint(kind=exp.NotNullColumnConstraint())
204
205        if notnull not in constraints:
206            constraints.insert(0, notnull)
207        if generated not in constraints:
208            constraints.insert(0, generated)
209
210    return expression
211
212
213def _json_extract_sql(
214    name: str, op: str
215) -> t.Callable[[PostgresGenerator, JSON_EXTRACT_TYPE], str]:
216    def _generate(self: PostgresGenerator, expression: JSON_EXTRACT_TYPE) -> str:
217        path = expression.expression
218        # Single non-literal segment: render as infix, not JSON_EXTRACT_PATH[_TEXT] (jsonb-unsafe).
219        if not isinstance(path, (exp.JSONPath, exp.Variadic)) and not ensure_list(
220            expression.args.get("expressions")
221        ):
222            return arrow_json_extract_sql(self, expression, op=op)
223
224        # JSON_EXTRACT_PATH requires a key, so use an empty variadic array for the root path
225        if len(path.expressions) == 1 and isinstance(path.expressions[0], exp.JSONPathRoot):
226            expression.set("expression", exp.Variadic(this=exp.Literal.string("{}")))
227
228        if expression.args.get("only_json_types"):
229            return json_extract_segments(name, quoted_index=False, op=op)(self, expression)
230        return json_extract_segments(name)(self, expression)
231
232    return _generate
233
234
235def _unix_to_time_sql(self: PostgresGenerator, expression: exp.UnixToTime) -> str:
236    scale = expression.args.get("scale")
237    timestamp = expression.this
238
239    if scale in (None, exp.UnixToTime.SECONDS):
240        return self.func("TO_TIMESTAMP", timestamp, self.format_time(expression))
241
242    return self.func(
243        "TO_TIMESTAMP",
244        exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)),
245        self.format_time(expression),
246    )
247
248
249def _levenshtein_sql(self: PostgresGenerator, expression: exp.Levenshtein) -> str:
250    name = "LEVENSHTEIN_LESS_EQUAL" if expression.args.get("max_dist") else "LEVENSHTEIN"
251
252    return rename_func(name)(self, expression)
253
254
255def _versioned_anyvalue_sql(self: PostgresGenerator, expression: exp.AnyValue) -> str:
256    # https://www.postgresql.org/docs/16/functions-aggregate.html
257    # https://www.postgresql.org/about/featurematrix/
258    if self.dialect.version < (16,):
259        return any_value_to_max_sql(self, expression)
260
261    return rename_func("ANY_VALUE")(self, expression)
262
263
264def _round_sql(self: PostgresGenerator, expression: exp.Round) -> str:
265    this = self.sql(expression, "this")
266    decimals = self.sql(expression, "decimals")
267
268    if not decimals:
269        return self.func("ROUND", this)
270
271    if not expression.type:
272        from sqlglot.optimizer.annotate_types import annotate_types
273
274        expression = annotate_types(expression, dialect=self.dialect)
275
276    # ROUND(double precision, integer) is not permitted in Postgres
277    # so it's necessary to cast to decimal before rounding.
278    if expression.this.is_type(exp.DType.DOUBLE):
279        decimal_type = exp.DType.DECIMAL.into_expr(expressions=expression.expressions)
280        this = self.sql(exp.Cast(this=this, to=decimal_type))
281
282    return self.func("ROUND", this, decimals)
283
284
285def _left_right_sql(self: PostgresGenerator, expression: exp.Left | exp.Right) -> str:
286    length = expression.expression
287
288    # Postgres drops characters from the other end for a negative length,
289    # so clamp it to 0 to return an empty string instead
290    if expression.args.get("negative_length_returns_empty"):
291        length = exp.If(this=length < 0, true=exp.Literal.number(0), false=length)
292
293    return self.func(expression.sql_name(), expression.this, length)
294
295
296class PostgresGenerator(generator.Generator):
297    BARE_OPERATORS = {"<=>"}
298    DAYOFWEEK_ZERO_BASED = True
299    SELECT_KINDS = ()
300    VARIANCE_NAME = "VAR_SAMP"
301    DATE_PART_WITH_EXPRESSION = "DATE_PART"
302    TRY_SUPPORTED = False
303    SUPPORTS_DECODE_CASE = False
304    SUPPORTS_MULTI_ARG_CHR = False
305
306    AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
307
308    SINGLE_STRING_INTERVAL = True
309    RENAME_TABLE_WITH_DB = False
310    LOCKING_READS_SUPPORTED = True
311    JOIN_HINTS = False
312    TABLE_HINTS = False
313    QUERY_HINTS = False
314    NVL2_SUPPORTED = False
315    PARAMETER_TOKEN = "$"
316    NAMED_PLACEHOLDER_TOKEN = "%"
317    TABLESAMPLE_SIZE_IS_ROWS = False
318    TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
319    SUPPORTS_SELECT_INTO = True
320    JSON_TYPE_REQUIRED_FOR_EXTRACTION = True
321    SUPPORTS_UNLOGGED_TABLES = True
322    LIKE_PROPERTY_INSIDE_SCHEMA = True
323    MULTI_ARG_DISTINCT = False
324    CAN_IMPLEMENT_ARRAY_ANY = True
325    SUPPORTS_WINDOW_EXCLUDE = True
326    COPY_HAS_INTO_KEYWORD = False
327    ARRAY_CONCAT_IS_VAR_LEN = False
328    SUPPORTS_MEDIAN = False
329    ARRAY_SIZE_DIM_REQUIRED: bool | None = True
330    SUPPORTS_BETWEEN_FLAGS = True
331    INOUT_SEPARATOR = ""  # PostgreSQL uses "INOUT" (no space)
332
333    SUPPORTED_JSON_PATH_PARTS = {
334        exp.JSONPathKey,
335        exp.JSONPathRoot,
336        exp.JSONPathSubscript,
337    }
338
339    def lateral_sql(self, expression: exp.Lateral) -> str:
340        sql = super().lateral_sql(expression)
341
342        if expression.args.get("cross_apply") is not None:
343            sql = f"{sql} ON TRUE"
344
345        return sql
346
347    def arraysize_sql(self, expression: exp.ArraySize) -> str:
348        # ARRAY_LENGTH(arr, 1) returns NULL for an empty array, whereas CARDINALITY returns 0
349        if not expression.expression:
350            return self.func("CARDINALITY", expression.this)
351
352        return super().arraysize_sql(expression)
353
354    def star_sql(self, expression: exp.Star) -> str:
355        if self.STAR_EXCEPT == "EXCEPT" and expression.args.get("except_"):
356            self.unsupported("PostgreSQL does not support EXCEPT in the SELECT projection")
357
358        return super().star_sql(expression)
359
360    TYPE_MAPPING = {
361        **generator.Generator.TYPE_MAPPING,
362        exp.DType.TINYINT: "SMALLINT",
363        exp.DType.FLOAT: "REAL",
364        exp.DType.DOUBLE: "DOUBLE PRECISION",
365        exp.DType.BINARY: "BYTEA",
366        exp.DType.VARBINARY: "BYTEA",
367        exp.DType.ROWVERSION: "BYTEA",
368        exp.DType.DATETIME: "TIMESTAMP",
369        exp.DType.TIMESTAMPNTZ: "TIMESTAMP",
370        exp.DType.BLOB: "BYTEA",
371    }
372
373    TRANSFORMS = {
374        **{
375            k: v
376            for k, v in generator.Generator.TRANSFORMS.items()
377            if k not in (exp.CommentColumnConstraint, exp.JSONObjectAgg)
378        },
379        exp.AnyValue: _versioned_anyvalue_sql,
380        exp.ArrayConcat: array_concat_sql("ARRAY_CAT"),
381        exp.ArrayFilter: filter_array_using_unnest,
382        exp.ArrayAppend: array_append_sql("ARRAY_APPEND"),
383        exp.ArrayPrepend: array_append_sql("ARRAY_PREPEND", swap_params=True),
384        exp.BitwiseAndAgg: rename_func("BIT_AND"),
385        exp.BitwiseOrAgg: rename_func("BIT_OR"),
386        exp.BitwiseXor: lambda self, e: self.binary(e, "#"),
387        exp.BitwiseXorAgg: rename_func("BIT_XOR"),
388        exp.ColumnDef: transforms.preprocess([_auto_increment_to_serial, _serial_to_generated]),
389        exp.ConvertToCharset: lambda self, e: self.func(
390            "CONVERT", e.this, e.args.get("source"), e.args["dest"]
391        ),
392        exp.CurrentDate: no_paren_current_date_sql,
393        exp.CurrentUser: lambda *_: "CURRENT_USER",
394        exp.CurrentVersion: rename_func("VERSION"),
395        exp.DateAdd: _date_add_sql("+"),
396        exp.DateDiff: _date_diff_sql,
397        exp.DateFromParts: rename_func("MAKE_DATE"),
398        exp.DateStrToDate: datestrtodate_sql,
399        exp.DateSub: _date_add_sql("-"),
400        exp.DatetimeAdd: _date_add_sql("+"),
401        exp.DatetimeSub: _date_add_sql("-"),
402        exp.Day: _day_month_year_sql,
403        exp.Explode: rename_func("UNNEST"),
404        exp.ExplodingGenerateSeries: rename_func("GENERATE_SERIES"),
405        exp.GenerateSeries: generate_series_sql("GENERATE_SERIES"),
406        exp.Getbit: getbit_sql,
407        exp.GroupConcat: lambda self, e: groupconcat_sql(
408            self, e, func_name="STRING_AGG", within_group=False
409        ),
410        exp.IntDiv: rename_func("DIV"),
411        exp.JSONArrayAgg: lambda self, e: self.func(
412            "JSON_AGG",
413            self.sql(e, "this"),
414            suffix=f"{self.sql(e, 'order')})",
415        ),
416        exp.JSONExtract: _json_extract_sql("JSON_EXTRACT_PATH", "->"),
417        exp.JSONExtractScalar: _json_extract_sql("JSON_EXTRACT_PATH_TEXT", "->>"),
418        exp.JSONBExtract: lambda self, e: arrow_json_extract_sql(self, e, op="#>"),
419        exp.JSONBExtractScalar: lambda self, e: arrow_json_extract_sql(self, e, op="#>>"),
420        exp.ParseJSON: lambda self, e: self.sql(exp.cast(e.this, exp.DType.JSON)),
421        exp.JSONPathKey: json_path_key_only_name,
422        exp.JSONPathRoot: lambda *_: "",
423        exp.JSONPathSubscript: lambda self, e: self.json_path_part(e.this),
424        exp.LastDay: no_last_day_sql,
425        exp.Left: _left_right_sql,
426        exp.LogicalOr: rename_func("BOOL_OR"),
427        exp.LogicalAnd: rename_func("BOOL_AND"),
428        exp.Max: max_or_greatest,
429        exp.MapFromEntries: no_map_from_entries_sql,
430        exp.Min: min_or_least,
431        exp.Merge: merge_without_target_sql,
432        exp.Month: _day_month_year_sql,
433        exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
434        exp.PercentileCont: transforms.preprocess([transforms.add_within_group_for_percentiles]),
435        exp.PercentileDisc: transforms.preprocess([transforms.add_within_group_for_percentiles]),
436        exp.Pivot: no_pivot_sql,
437        exp.Rand: rename_func("RANDOM"),
438        exp.RegexpILike: lambda self, e: self.binary(e, "~*"),
439        exp.RegexpReplace: lambda self, e: self.func(
440            "REGEXP_REPLACE",
441            e.this,
442            e.expression,
443            e.args.get("replacement") or exp.Literal.string(""),
444            e.args.get("position"),
445            e.args.get("occurrence"),
446            regexp_replace_global_modifier(e),
447        ),
448        exp.Right: _left_right_sql,
449        exp.Round: _round_sql,
450        exp.Select: transforms.preprocess(
451            [
452                transforms.eliminate_semi_and_anti_joins,
453                transforms.eliminate_qualify,
454            ]
455        ),
456        exp.SHA2: lambda self, e: self.func(
457            "ENCODE", sha256_sql(self, e), exp.Literal.string("hex")
458        ),
459        exp.SHA2Digest: sha2_digest_sql,
460        exp.StrPosition: lambda self, e: strposition_sql(self, e, func_name="POSITION"),
461        exp.StrToDate: lambda self, e: self.func("TO_DATE", e.this, self.format_time(e)),
462        exp.StrToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, self.format_time(e)),
463        exp.StructExtract: struct_extract_sql,
464        exp.Substring: _substring_sql,
465        exp.TimeFromParts: rename_func("MAKE_TIME"),
466        exp.TimestampFromParts: rename_func("MAKE_TIMESTAMP"),
467        exp.TimestampTrunc: timestamptrunc_sql(zone=True),
468        exp.TimestampAdd: _date_add_sql("+"),
469        exp.TimestampSub: _date_add_sql("-"),
470        exp.TimeStrToTime: timestrtotime_sql,
471        exp.TimeToStr: lambda self, e: self.func("TO_CHAR", e.this, self.format_time(e)),
472        exp.ToChar: lambda self, e: (
473            self.function_fallback_sql(e) if e.args.get("format") else self.tochar_sql(e)
474        ),
475        exp.Trim: trim_sql,
476        exp.TryCast: no_trycast_sql,
477        exp.TsOrDsAdd: _date_add_sql("+"),
478        exp.TsOrDsDiff: _date_diff_sql,
479        exp.UnixToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this),
480        exp.Uuid: lambda *_: "GEN_RANDOM_UUID()",
481        exp.TimeToUnix: lambda self, e: self.func("DATE_PART", exp.Literal.string("epoch"), e.this),
482        exp.VariancePop: rename_func("VAR_POP"),
483        exp.Xor: bool_xor_sql,
484        exp.Year: _day_month_year_sql,
485        exp.Unicode: rename_func("ASCII"),
486        exp.UnixToTime: _unix_to_time_sql,
487        exp.Levenshtein: _levenshtein_sql,
488        exp.JSONBObjectAgg: rename_func("JSONB_OBJECT_AGG"),
489        exp.CountIf: count_if_to_sum,
490        exp.FileFormatProperty: lambda self, e: f"USING {self.sql(e, 'this')}",
491        exp.TableSpaceProperty: lambda self, e: f"TABLESPACE {self.sql(e, 'this')}",
492    }
493
494    PROPERTIES_LOCATION = {
495        **generator.Generator.PROPERTIES_LOCATION,
496        exp.FileFormatProperty: exp.Properties.Location.POST_SCHEMA,
497        exp.OnCommitProperty: exp.Properties.Location.POST_WITH,
498        exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
499        exp.TableSpaceProperty: exp.Properties.Location.POST_WITH,
500        exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
501        exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
502    }
503
504    def with_properties(self, properties: exp.Properties) -> str:
505        with_properties = []
506        post_with = []
507        for prop in properties.expressions:
508            if isinstance(prop, (exp.OnCommitProperty, exp.TableSpaceProperty)):
509                post_with.append(prop)
510            else:
511                with_properties.append(prop)
512
513        post_with.sort(key=lambda prop: isinstance(prop, exp.TableSpaceProperty))
514        sql = super().with_properties(exp.Properties(expressions=with_properties))
515        post_sql = self.expressions(sqls=post_with, sep=" ", indent=False)
516        return sql + self.seg(post_sql, sep=" " if sql else "") if post_sql else sql
517
518    def _native_dayofweek_sql(self, expression: exp.DayOfWeek) -> str:
519        return self.sql(exp.Extract(this=exp.var("DOW"), expression=expression.this))
520
521    def extract_sql(self, expression: exp.Extract) -> str:
522        if not expression.args.get("date_part"):
523            return super().extract_sql(expression)
524
525        part = expression.this
526        name = self.DATE_PART_WITH_EXPRESSION
527        if isinstance(part, exp.Var):
528            name = "DATE_PART"
529            part = exp.Literal.string(part.name.lower())
530        return self.func(name, part, expression.expression)
531
532    def bytestring_sql(self, expression: exp.ByteString) -> str:
533        if not expression.args.get("is_bytes"):
534            return super().bytestring_sql(expression)
535
536        return self.func(
537            "DECODE",
538            exp.Literal.string(expression.this.encode("latin-1").hex()),
539            exp.Literal.string("hex"),
540        )
541
542    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
543        args = expression.expressions
544        pair = args[0] if len(args) == 1 else None
545        # Only the SQL/JSON spelling, JSON_OBJECTAGG, accepts these clauses.
546        if (
547            isinstance(pair, exp.FormatJson)
548            or expression.args.get("null_handling")
549            or expression.args.get("unique_keys") is not None
550            or expression.args.get("return_type")
551            or expression.args.get("encoding")
552        ):
553            return self._jsonobject_sql(expression)
554
555        if isinstance(pair, exp.JSONKeyValue):
556            args = [pair.this, pair.expression]
557        return self.func("JSON_OBJECT_AGG", *args)
558
559    def schemacommentproperty_sql(self, expression: exp.SchemaCommentProperty) -> str:
560        self.unsupported("Table comments are not supported in the CREATE statement")
561        return ""
562
563    def commentcolumnconstraint_sql(self, expression: exp.CommentColumnConstraint) -> str:
564        self.unsupported("Column comments are not supported in the CREATE statement")
565        return ""
566
567    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
568        # PostgreSQL places parameter modes BEFORE parameter name
569        param_constraint = expression.find(exp.InOutColumnConstraint)
570
571        if param_constraint:
572            mode_sql = self.sql(param_constraint)
573            param_constraint.pop()  # Remove to prevent double-rendering
574            base_sql = super().columndef_sql(expression, sep)
575            return f"{mode_sql} {base_sql}"
576
577        return super().columndef_sql(expression, sep)
578
579    def unnest_sql(self, expression: exp.Unnest) -> str:
580        if len(expression.expressions) == 1:
581            arg = expression.expressions[0]
582            if isinstance(arg, exp.GenerateDateArray):
583                generate_series: exp.Expr = exp.GenerateSeries(**arg.args)
584                if isinstance(expression.parent, (exp.From, exp.Join)):
585                    generate_series = (
586                        exp.select("value::date")
587                        .from_(exp.Table(this=generate_series).as_("_t", table=["value"]))
588                        .subquery(expression.args.get("alias") or "_unnested_generate_series")
589                    )
590                return self.sql(generate_series)
591
592            from sqlglot.optimizer.annotate_types import annotate_types
593
594            this = annotate_types(arg, dialect=self.dialect)
595            if this.is_type("array<json>"):
596                while isinstance(this, exp.Cast):
597                    this = this.this
598
599                arg_as_json = self.sql(exp.cast(this, exp.DType.JSON))
600                alias = self.sql(expression, "alias")
601                alias = f" AS {alias}" if alias else ""
602
603                if expression.args.get("offset"):
604                    self.unsupported("Unsupported JSON_ARRAY_ELEMENTS with offset")
605
606                return f"JSON_ARRAY_ELEMENTS({arg_as_json}){alias}"
607
608            # PostgreSQL before 16 requires an alias for subqueries in FROM.
609            if query := transforms.unnest_with_offset(expression, require_alias=True):
610                if isinstance(expression.parent, exp.Join):
611                    return self.sql(exp.Lateral(this=query))
612                return self.sql(query)
613
614        return super().unnest_sql(expression)
615
616    def bracket_sql(self, expression: exp.Bracket) -> str:
617        """Forms like ARRAY[1, 2, 3][3] aren't allowed; we need to wrap the ARRAY."""
618        if isinstance(expression.this, exp.Array):
619            expression.set("this", exp.paren(expression.this, copy=False))
620
621        return super().bracket_sql(expression)
622
623    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
624        this = self.sql(expression, "this")
625        expressions = [f"{self.sql(e)} @@ {this}" for e in expression.expressions]
626        sql = " OR ".join(expressions)
627        return f"({sql})" if len(expressions) > 1 else sql
628
629    def alterset_sql(self, expression: exp.AlterSet) -> str:
630        exprs = self.expressions(expression, flat=True)
631        exprs = f"({exprs})" if exprs else ""
632
633        access_method = self.sql(expression, "access_method")
634        access_method = f"ACCESS METHOD {access_method}" if access_method else ""
635        tablespace = self.sql(expression, "tablespace")
636        tablespace = f"TABLESPACE {tablespace}" if tablespace else ""
637        option = self.sql(expression, "option")
638
639        return f"SET {exprs}{access_method}{tablespace}{option}"
640
641    def datatype_sql(self, expression: exp.DataType) -> str:
642        if expression.is_type(exp.DType.ARRAY):
643            if expression.expressions:
644                values = self.expressions(expression, key="values", flat=True)
645                return f"{self.expressions(expression, flat=True)}[{values}]"
646            return "ARRAY"
647
648        if expression.is_type(exp.DType.ENUM):
649            return f"ENUM ({self.expressions(expression, flat=True)})"
650
651        if expression.is_type(exp.DType.DOUBLE, exp.DType.FLOAT) and expression.expressions:
652            # Postgres doesn't support precision for REAL and DOUBLE PRECISION types
653            return f"FLOAT({self.expressions(expression, flat=True)})"
654
655        return super().datatype_sql(expression)
656
657    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
658        this = expression.this
659
660        # Postgres casts DIV() to decimal for transpilation but when roundtripping it's superfluous
661        if (
662            isinstance(this, exp.IntDiv)
663            and exp.IntDiv in self.TRANSFORMS
664            and expression.to == exp.DType.DECIMAL.into_expr()
665        ):
666            return self.sql(this)
667
668        return super().cast_sql(expression, safe_prefix=safe_prefix)
669
670    def array_sql(self, expression: exp.Array) -> str:
671        exprs = expression.expressions
672        func_name = self.normalize_func("ARRAY")
673
674        if isinstance(seq_get(exprs, 0), exp.Query):
675            return f"{func_name}({self.sql(exprs[0])})"
676
677        return f"{func_name}{inline_array_sql(self, expression)}"
678
679    def struct_sql(self, expression: exp.Struct) -> str:
680        fields = expression.expressions
681
682        if any(isinstance(e, (exp.PropertyEQ, exp.Alias)) for e in fields):
683            self.unsupported("PostgreSQL does not support named structs")
684
685        return self.func(
686            "ROW",
687            *[e.expression if isinstance(e, exp.PropertyEQ) else e.unalias() for e in fields],
688        )
689
690    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
691        return f"GENERATED ALWAYS AS ({self.sql(expression, 'this')}) STORED"
692
693    def isascii_sql(self, expression: exp.IsAscii) -> str:
694        return f"({self.sql(expression.this)} ~ '^[[:ascii:]]*$')"
695
696    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
697        # https://www.postgresql.org/docs/current/functions-window.html
698        self.unsupported("PostgreSQL does not support IGNORE NULLS.")
699        return self.sql(expression.this)
700
701    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
702        # https://www.postgresql.org/docs/current/functions-window.html
703        self.unsupported("PostgreSQL does not support RESPECT NULLS.")
704        return self.sql(expression.this)
705
706    @unsupported_args("options")
707    def regexpfullmatch_sql(self, expression: exp.RegexpFullMatch) -> str:
708        pattern = expression.expression.unnest()
709        if not pattern.is_string or not _REGEXP_FULL_MATCH_METACHARS.isdisjoint(pattern.name):
710            self.unsupported(
711                "Only plain literal REGEXP_FULL_MATCH patterns translate to SIMILAR TO"
712            )
713
714        predicate = exp.SimilarTo(this=expression.this, expression=expression.expression)
715        return self.sql(exp.paren(predicate, copy=False))
716
717    # PostgreSQL reads adjacent +~ and ~+ as single operator names.
718    def pos_sql(self, expression: exp.Pos) -> str:
719        operand = self.sql(expression, "this")
720        return f"+ {operand}" if operand.startswith("~") else f"+{operand}"
721
722    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
723        operand = self.sql(expression, "this")
724        return f"~ {operand}" if operand.startswith("+") else f"~{operand}"
725
726    def regexplike_sql(self, expression: exp.RegexpLike) -> str:
727        flag = expression.args.get("flag")
728        if not flag:
729            return self.binary(expression, "~")
730
731        # Postgres has no flags argument for ~, only the case-insensitive ~* operator. Of the
732        # case flags, the last one wins, e.g. 'ic' is case-sensitive and 'ci' is not
733        flags = flag.name if flag.is_string else ""
734        if not flag.is_string or set(flags) - {"i", "c"}:
735            self.unsupported("Only the case flags 'i' and 'c' are supported for ~ in Postgres")
736
737        return self.binary(expression, "~*" if flags.rfind("i") > flags.rfind("c") else "~")
738
739    @unsupported_args("this")
740    def currentschema_sql(self, expression: exp.CurrentSchema) -> str:
741        return "CURRENT_SCHEMA"
742
743    def currenttime_sql(self, expression: exp.CurrentTime) -> str:
744        precision = expression.this
745        return self.func("CURRENT_TIME", precision) if precision else "CURRENT_TIME"
746
747    def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str:
748        # Other dialects can use this argument for a time zone instead of a precision.
749        precision = expression.this
750        if precision and precision.is_int:
751            return self.func("CURRENT_TIMESTAMP", precision)
752        return "CURRENT_TIMESTAMP"
753
754    def interval_sql(self, expression: exp.Interval) -> str:
755        unit = expression.text("unit").lower()
756
757        this = expression.this
758        if unit.startswith("quarter") and isinstance(this, exp.Literal):
759            # Postgres has no QUARTER unit and no exponents in interval strings
760            quarters = to_int(this.to_py())
761            if quarters is None:
762                self.unsupported("Postgres intervals need a whole number of quarters")
763            else:
764                this.replace(exp.Literal.string(quarters * 3))
765                expression.args["unit"].replace(exp.var("MONTH"))
766
767        return super().interval_sql(expression)
768
769    def placeholder_sql(self, expression: exp.Placeholder) -> str:
770        if expression.args.get("jdbc"):
771            return "?"
772
773        this = f"({expression.name})" if expression.this else ""
774        return f"{self.NAMED_PLACEHOLDER_TOKEN}{this}s"
775
776    def arraycontains_sql(self, expression: exp.ArrayContains) -> str:
777        # Convert DuckDB's LIST_CONTAINS(array, value) to PostgreSQL
778        # DuckDB behavior:
779        #   - LIST_CONTAINS([1,2,3], 2) -> true
780        #   - LIST_CONTAINS([1,2,3], 4) -> false
781        #   - LIST_CONTAINS([1,2,NULL], 4) -> false (not NULL)
782        #   - LIST_CONTAINS([1,2,3], NULL) -> NULL
783        #
784        # PostgreSQL equivalent: CASE WHEN value IS NULL THEN NULL
785        #                            ELSE COALESCE(value = ANY(array), FALSE) END
786        value = expression.expression
787        array = expression.this
788
789        coalesce_expr = exp.Coalesce(
790            this=value.eq(exp.Any(this=exp.paren(expression=array, copy=False))),
791            expressions=[exp.false()],
792        )
793
794        case_expr = (
795            exp.Case()
796            .when(exp.Is(this=value, expression=exp.null()), exp.null(), copy=False)
797            .else_(coalesce_expr, copy=False)
798        )
799
800        return self.sql(case_expr)
DATE_DIFF_FACTOR = {'MICROSECOND': ' * 1000000', 'MILLISECOND': ' * 1000', 'SECOND': '', 'MINUTE': ' / 60', 'HOUR': ' / 3600', 'DAY': ' / 86400'}
DATE_DIFF_BOUNDARY_UNITS = {'MILLISECOND', 'MICROSECOND', 'MONTH', 'MINUTE', 'QUARTER', 'SECOND', 'WEEK', 'YEAR', 'HOUR'}
class PostgresGenerator(sqlglot.generator.Generator):
297class PostgresGenerator(generator.Generator):
298    BARE_OPERATORS = {"<=>"}
299    DAYOFWEEK_ZERO_BASED = True
300    SELECT_KINDS = ()
301    VARIANCE_NAME = "VAR_SAMP"
302    DATE_PART_WITH_EXPRESSION = "DATE_PART"
303    TRY_SUPPORTED = False
304    SUPPORTS_DECODE_CASE = False
305    SUPPORTS_MULTI_ARG_CHR = False
306
307    AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
308
309    SINGLE_STRING_INTERVAL = True
310    RENAME_TABLE_WITH_DB = False
311    LOCKING_READS_SUPPORTED = True
312    JOIN_HINTS = False
313    TABLE_HINTS = False
314    QUERY_HINTS = False
315    NVL2_SUPPORTED = False
316    PARAMETER_TOKEN = "$"
317    NAMED_PLACEHOLDER_TOKEN = "%"
318    TABLESAMPLE_SIZE_IS_ROWS = False
319    TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
320    SUPPORTS_SELECT_INTO = True
321    JSON_TYPE_REQUIRED_FOR_EXTRACTION = True
322    SUPPORTS_UNLOGGED_TABLES = True
323    LIKE_PROPERTY_INSIDE_SCHEMA = True
324    MULTI_ARG_DISTINCT = False
325    CAN_IMPLEMENT_ARRAY_ANY = True
326    SUPPORTS_WINDOW_EXCLUDE = True
327    COPY_HAS_INTO_KEYWORD = False
328    ARRAY_CONCAT_IS_VAR_LEN = False
329    SUPPORTS_MEDIAN = False
330    ARRAY_SIZE_DIM_REQUIRED: bool | None = True
331    SUPPORTS_BETWEEN_FLAGS = True
332    INOUT_SEPARATOR = ""  # PostgreSQL uses "INOUT" (no space)
333
334    SUPPORTED_JSON_PATH_PARTS = {
335        exp.JSONPathKey,
336        exp.JSONPathRoot,
337        exp.JSONPathSubscript,
338    }
339
340    def lateral_sql(self, expression: exp.Lateral) -> str:
341        sql = super().lateral_sql(expression)
342
343        if expression.args.get("cross_apply") is not None:
344            sql = f"{sql} ON TRUE"
345
346        return sql
347
348    def arraysize_sql(self, expression: exp.ArraySize) -> str:
349        # ARRAY_LENGTH(arr, 1) returns NULL for an empty array, whereas CARDINALITY returns 0
350        if not expression.expression:
351            return self.func("CARDINALITY", expression.this)
352
353        return super().arraysize_sql(expression)
354
355    def star_sql(self, expression: exp.Star) -> str:
356        if self.STAR_EXCEPT == "EXCEPT" and expression.args.get("except_"):
357            self.unsupported("PostgreSQL does not support EXCEPT in the SELECT projection")
358
359        return super().star_sql(expression)
360
361    TYPE_MAPPING = {
362        **generator.Generator.TYPE_MAPPING,
363        exp.DType.TINYINT: "SMALLINT",
364        exp.DType.FLOAT: "REAL",
365        exp.DType.DOUBLE: "DOUBLE PRECISION",
366        exp.DType.BINARY: "BYTEA",
367        exp.DType.VARBINARY: "BYTEA",
368        exp.DType.ROWVERSION: "BYTEA",
369        exp.DType.DATETIME: "TIMESTAMP",
370        exp.DType.TIMESTAMPNTZ: "TIMESTAMP",
371        exp.DType.BLOB: "BYTEA",
372    }
373
374    TRANSFORMS = {
375        **{
376            k: v
377            for k, v in generator.Generator.TRANSFORMS.items()
378            if k not in (exp.CommentColumnConstraint, exp.JSONObjectAgg)
379        },
380        exp.AnyValue: _versioned_anyvalue_sql,
381        exp.ArrayConcat: array_concat_sql("ARRAY_CAT"),
382        exp.ArrayFilter: filter_array_using_unnest,
383        exp.ArrayAppend: array_append_sql("ARRAY_APPEND"),
384        exp.ArrayPrepend: array_append_sql("ARRAY_PREPEND", swap_params=True),
385        exp.BitwiseAndAgg: rename_func("BIT_AND"),
386        exp.BitwiseOrAgg: rename_func("BIT_OR"),
387        exp.BitwiseXor: lambda self, e: self.binary(e, "#"),
388        exp.BitwiseXorAgg: rename_func("BIT_XOR"),
389        exp.ColumnDef: transforms.preprocess([_auto_increment_to_serial, _serial_to_generated]),
390        exp.ConvertToCharset: lambda self, e: self.func(
391            "CONVERT", e.this, e.args.get("source"), e.args["dest"]
392        ),
393        exp.CurrentDate: no_paren_current_date_sql,
394        exp.CurrentUser: lambda *_: "CURRENT_USER",
395        exp.CurrentVersion: rename_func("VERSION"),
396        exp.DateAdd: _date_add_sql("+"),
397        exp.DateDiff: _date_diff_sql,
398        exp.DateFromParts: rename_func("MAKE_DATE"),
399        exp.DateStrToDate: datestrtodate_sql,
400        exp.DateSub: _date_add_sql("-"),
401        exp.DatetimeAdd: _date_add_sql("+"),
402        exp.DatetimeSub: _date_add_sql("-"),
403        exp.Day: _day_month_year_sql,
404        exp.Explode: rename_func("UNNEST"),
405        exp.ExplodingGenerateSeries: rename_func("GENERATE_SERIES"),
406        exp.GenerateSeries: generate_series_sql("GENERATE_SERIES"),
407        exp.Getbit: getbit_sql,
408        exp.GroupConcat: lambda self, e: groupconcat_sql(
409            self, e, func_name="STRING_AGG", within_group=False
410        ),
411        exp.IntDiv: rename_func("DIV"),
412        exp.JSONArrayAgg: lambda self, e: self.func(
413            "JSON_AGG",
414            self.sql(e, "this"),
415            suffix=f"{self.sql(e, 'order')})",
416        ),
417        exp.JSONExtract: _json_extract_sql("JSON_EXTRACT_PATH", "->"),
418        exp.JSONExtractScalar: _json_extract_sql("JSON_EXTRACT_PATH_TEXT", "->>"),
419        exp.JSONBExtract: lambda self, e: arrow_json_extract_sql(self, e, op="#>"),
420        exp.JSONBExtractScalar: lambda self, e: arrow_json_extract_sql(self, e, op="#>>"),
421        exp.ParseJSON: lambda self, e: self.sql(exp.cast(e.this, exp.DType.JSON)),
422        exp.JSONPathKey: json_path_key_only_name,
423        exp.JSONPathRoot: lambda *_: "",
424        exp.JSONPathSubscript: lambda self, e: self.json_path_part(e.this),
425        exp.LastDay: no_last_day_sql,
426        exp.Left: _left_right_sql,
427        exp.LogicalOr: rename_func("BOOL_OR"),
428        exp.LogicalAnd: rename_func("BOOL_AND"),
429        exp.Max: max_or_greatest,
430        exp.MapFromEntries: no_map_from_entries_sql,
431        exp.Min: min_or_least,
432        exp.Merge: merge_without_target_sql,
433        exp.Month: _day_month_year_sql,
434        exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
435        exp.PercentileCont: transforms.preprocess([transforms.add_within_group_for_percentiles]),
436        exp.PercentileDisc: transforms.preprocess([transforms.add_within_group_for_percentiles]),
437        exp.Pivot: no_pivot_sql,
438        exp.Rand: rename_func("RANDOM"),
439        exp.RegexpILike: lambda self, e: self.binary(e, "~*"),
440        exp.RegexpReplace: lambda self, e: self.func(
441            "REGEXP_REPLACE",
442            e.this,
443            e.expression,
444            e.args.get("replacement") or exp.Literal.string(""),
445            e.args.get("position"),
446            e.args.get("occurrence"),
447            regexp_replace_global_modifier(e),
448        ),
449        exp.Right: _left_right_sql,
450        exp.Round: _round_sql,
451        exp.Select: transforms.preprocess(
452            [
453                transforms.eliminate_semi_and_anti_joins,
454                transforms.eliminate_qualify,
455            ]
456        ),
457        exp.SHA2: lambda self, e: self.func(
458            "ENCODE", sha256_sql(self, e), exp.Literal.string("hex")
459        ),
460        exp.SHA2Digest: sha2_digest_sql,
461        exp.StrPosition: lambda self, e: strposition_sql(self, e, func_name="POSITION"),
462        exp.StrToDate: lambda self, e: self.func("TO_DATE", e.this, self.format_time(e)),
463        exp.StrToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, self.format_time(e)),
464        exp.StructExtract: struct_extract_sql,
465        exp.Substring: _substring_sql,
466        exp.TimeFromParts: rename_func("MAKE_TIME"),
467        exp.TimestampFromParts: rename_func("MAKE_TIMESTAMP"),
468        exp.TimestampTrunc: timestamptrunc_sql(zone=True),
469        exp.TimestampAdd: _date_add_sql("+"),
470        exp.TimestampSub: _date_add_sql("-"),
471        exp.TimeStrToTime: timestrtotime_sql,
472        exp.TimeToStr: lambda self, e: self.func("TO_CHAR", e.this, self.format_time(e)),
473        exp.ToChar: lambda self, e: (
474            self.function_fallback_sql(e) if e.args.get("format") else self.tochar_sql(e)
475        ),
476        exp.Trim: trim_sql,
477        exp.TryCast: no_trycast_sql,
478        exp.TsOrDsAdd: _date_add_sql("+"),
479        exp.TsOrDsDiff: _date_diff_sql,
480        exp.UnixToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this),
481        exp.Uuid: lambda *_: "GEN_RANDOM_UUID()",
482        exp.TimeToUnix: lambda self, e: self.func("DATE_PART", exp.Literal.string("epoch"), e.this),
483        exp.VariancePop: rename_func("VAR_POP"),
484        exp.Xor: bool_xor_sql,
485        exp.Year: _day_month_year_sql,
486        exp.Unicode: rename_func("ASCII"),
487        exp.UnixToTime: _unix_to_time_sql,
488        exp.Levenshtein: _levenshtein_sql,
489        exp.JSONBObjectAgg: rename_func("JSONB_OBJECT_AGG"),
490        exp.CountIf: count_if_to_sum,
491        exp.FileFormatProperty: lambda self, e: f"USING {self.sql(e, 'this')}",
492        exp.TableSpaceProperty: lambda self, e: f"TABLESPACE {self.sql(e, 'this')}",
493    }
494
495    PROPERTIES_LOCATION = {
496        **generator.Generator.PROPERTIES_LOCATION,
497        exp.FileFormatProperty: exp.Properties.Location.POST_SCHEMA,
498        exp.OnCommitProperty: exp.Properties.Location.POST_WITH,
499        exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
500        exp.TableSpaceProperty: exp.Properties.Location.POST_WITH,
501        exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
502        exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
503    }
504
505    def with_properties(self, properties: exp.Properties) -> str:
506        with_properties = []
507        post_with = []
508        for prop in properties.expressions:
509            if isinstance(prop, (exp.OnCommitProperty, exp.TableSpaceProperty)):
510                post_with.append(prop)
511            else:
512                with_properties.append(prop)
513
514        post_with.sort(key=lambda prop: isinstance(prop, exp.TableSpaceProperty))
515        sql = super().with_properties(exp.Properties(expressions=with_properties))
516        post_sql = self.expressions(sqls=post_with, sep=" ", indent=False)
517        return sql + self.seg(post_sql, sep=" " if sql else "") if post_sql else sql
518
519    def _native_dayofweek_sql(self, expression: exp.DayOfWeek) -> str:
520        return self.sql(exp.Extract(this=exp.var("DOW"), expression=expression.this))
521
522    def extract_sql(self, expression: exp.Extract) -> str:
523        if not expression.args.get("date_part"):
524            return super().extract_sql(expression)
525
526        part = expression.this
527        name = self.DATE_PART_WITH_EXPRESSION
528        if isinstance(part, exp.Var):
529            name = "DATE_PART"
530            part = exp.Literal.string(part.name.lower())
531        return self.func(name, part, expression.expression)
532
533    def bytestring_sql(self, expression: exp.ByteString) -> str:
534        if not expression.args.get("is_bytes"):
535            return super().bytestring_sql(expression)
536
537        return self.func(
538            "DECODE",
539            exp.Literal.string(expression.this.encode("latin-1").hex()),
540            exp.Literal.string("hex"),
541        )
542
543    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
544        args = expression.expressions
545        pair = args[0] if len(args) == 1 else None
546        # Only the SQL/JSON spelling, JSON_OBJECTAGG, accepts these clauses.
547        if (
548            isinstance(pair, exp.FormatJson)
549            or expression.args.get("null_handling")
550            or expression.args.get("unique_keys") is not None
551            or expression.args.get("return_type")
552            or expression.args.get("encoding")
553        ):
554            return self._jsonobject_sql(expression)
555
556        if isinstance(pair, exp.JSONKeyValue):
557            args = [pair.this, pair.expression]
558        return self.func("JSON_OBJECT_AGG", *args)
559
560    def schemacommentproperty_sql(self, expression: exp.SchemaCommentProperty) -> str:
561        self.unsupported("Table comments are not supported in the CREATE statement")
562        return ""
563
564    def commentcolumnconstraint_sql(self, expression: exp.CommentColumnConstraint) -> str:
565        self.unsupported("Column comments are not supported in the CREATE statement")
566        return ""
567
568    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
569        # PostgreSQL places parameter modes BEFORE parameter name
570        param_constraint = expression.find(exp.InOutColumnConstraint)
571
572        if param_constraint:
573            mode_sql = self.sql(param_constraint)
574            param_constraint.pop()  # Remove to prevent double-rendering
575            base_sql = super().columndef_sql(expression, sep)
576            return f"{mode_sql} {base_sql}"
577
578        return super().columndef_sql(expression, sep)
579
580    def unnest_sql(self, expression: exp.Unnest) -> str:
581        if len(expression.expressions) == 1:
582            arg = expression.expressions[0]
583            if isinstance(arg, exp.GenerateDateArray):
584                generate_series: exp.Expr = exp.GenerateSeries(**arg.args)
585                if isinstance(expression.parent, (exp.From, exp.Join)):
586                    generate_series = (
587                        exp.select("value::date")
588                        .from_(exp.Table(this=generate_series).as_("_t", table=["value"]))
589                        .subquery(expression.args.get("alias") or "_unnested_generate_series")
590                    )
591                return self.sql(generate_series)
592
593            from sqlglot.optimizer.annotate_types import annotate_types
594
595            this = annotate_types(arg, dialect=self.dialect)
596            if this.is_type("array<json>"):
597                while isinstance(this, exp.Cast):
598                    this = this.this
599
600                arg_as_json = self.sql(exp.cast(this, exp.DType.JSON))
601                alias = self.sql(expression, "alias")
602                alias = f" AS {alias}" if alias else ""
603
604                if expression.args.get("offset"):
605                    self.unsupported("Unsupported JSON_ARRAY_ELEMENTS with offset")
606
607                return f"JSON_ARRAY_ELEMENTS({arg_as_json}){alias}"
608
609            # PostgreSQL before 16 requires an alias for subqueries in FROM.
610            if query := transforms.unnest_with_offset(expression, require_alias=True):
611                if isinstance(expression.parent, exp.Join):
612                    return self.sql(exp.Lateral(this=query))
613                return self.sql(query)
614
615        return super().unnest_sql(expression)
616
617    def bracket_sql(self, expression: exp.Bracket) -> str:
618        """Forms like ARRAY[1, 2, 3][3] aren't allowed; we need to wrap the ARRAY."""
619        if isinstance(expression.this, exp.Array):
620            expression.set("this", exp.paren(expression.this, copy=False))
621
622        return super().bracket_sql(expression)
623
624    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
625        this = self.sql(expression, "this")
626        expressions = [f"{self.sql(e)} @@ {this}" for e in expression.expressions]
627        sql = " OR ".join(expressions)
628        return f"({sql})" if len(expressions) > 1 else sql
629
630    def alterset_sql(self, expression: exp.AlterSet) -> str:
631        exprs = self.expressions(expression, flat=True)
632        exprs = f"({exprs})" if exprs else ""
633
634        access_method = self.sql(expression, "access_method")
635        access_method = f"ACCESS METHOD {access_method}" if access_method else ""
636        tablespace = self.sql(expression, "tablespace")
637        tablespace = f"TABLESPACE {tablespace}" if tablespace else ""
638        option = self.sql(expression, "option")
639
640        return f"SET {exprs}{access_method}{tablespace}{option}"
641
642    def datatype_sql(self, expression: exp.DataType) -> str:
643        if expression.is_type(exp.DType.ARRAY):
644            if expression.expressions:
645                values = self.expressions(expression, key="values", flat=True)
646                return f"{self.expressions(expression, flat=True)}[{values}]"
647            return "ARRAY"
648
649        if expression.is_type(exp.DType.ENUM):
650            return f"ENUM ({self.expressions(expression, flat=True)})"
651
652        if expression.is_type(exp.DType.DOUBLE, exp.DType.FLOAT) and expression.expressions:
653            # Postgres doesn't support precision for REAL and DOUBLE PRECISION types
654            return f"FLOAT({self.expressions(expression, flat=True)})"
655
656        return super().datatype_sql(expression)
657
658    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
659        this = expression.this
660
661        # Postgres casts DIV() to decimal for transpilation but when roundtripping it's superfluous
662        if (
663            isinstance(this, exp.IntDiv)
664            and exp.IntDiv in self.TRANSFORMS
665            and expression.to == exp.DType.DECIMAL.into_expr()
666        ):
667            return self.sql(this)
668
669        return super().cast_sql(expression, safe_prefix=safe_prefix)
670
671    def array_sql(self, expression: exp.Array) -> str:
672        exprs = expression.expressions
673        func_name = self.normalize_func("ARRAY")
674
675        if isinstance(seq_get(exprs, 0), exp.Query):
676            return f"{func_name}({self.sql(exprs[0])})"
677
678        return f"{func_name}{inline_array_sql(self, expression)}"
679
680    def struct_sql(self, expression: exp.Struct) -> str:
681        fields = expression.expressions
682
683        if any(isinstance(e, (exp.PropertyEQ, exp.Alias)) for e in fields):
684            self.unsupported("PostgreSQL does not support named structs")
685
686        return self.func(
687            "ROW",
688            *[e.expression if isinstance(e, exp.PropertyEQ) else e.unalias() for e in fields],
689        )
690
691    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
692        return f"GENERATED ALWAYS AS ({self.sql(expression, 'this')}) STORED"
693
694    def isascii_sql(self, expression: exp.IsAscii) -> str:
695        return f"({self.sql(expression.this)} ~ '^[[:ascii:]]*$')"
696
697    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
698        # https://www.postgresql.org/docs/current/functions-window.html
699        self.unsupported("PostgreSQL does not support IGNORE NULLS.")
700        return self.sql(expression.this)
701
702    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
703        # https://www.postgresql.org/docs/current/functions-window.html
704        self.unsupported("PostgreSQL does not support RESPECT NULLS.")
705        return self.sql(expression.this)
706
707    @unsupported_args("options")
708    def regexpfullmatch_sql(self, expression: exp.RegexpFullMatch) -> str:
709        pattern = expression.expression.unnest()
710        if not pattern.is_string or not _REGEXP_FULL_MATCH_METACHARS.isdisjoint(pattern.name):
711            self.unsupported(
712                "Only plain literal REGEXP_FULL_MATCH patterns translate to SIMILAR TO"
713            )
714
715        predicate = exp.SimilarTo(this=expression.this, expression=expression.expression)
716        return self.sql(exp.paren(predicate, copy=False))
717
718    # PostgreSQL reads adjacent +~ and ~+ as single operator names.
719    def pos_sql(self, expression: exp.Pos) -> str:
720        operand = self.sql(expression, "this")
721        return f"+ {operand}" if operand.startswith("~") else f"+{operand}"
722
723    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
724        operand = self.sql(expression, "this")
725        return f"~ {operand}" if operand.startswith("+") else f"~{operand}"
726
727    def regexplike_sql(self, expression: exp.RegexpLike) -> str:
728        flag = expression.args.get("flag")
729        if not flag:
730            return self.binary(expression, "~")
731
732        # Postgres has no flags argument for ~, only the case-insensitive ~* operator. Of the
733        # case flags, the last one wins, e.g. 'ic' is case-sensitive and 'ci' is not
734        flags = flag.name if flag.is_string else ""
735        if not flag.is_string or set(flags) - {"i", "c"}:
736            self.unsupported("Only the case flags 'i' and 'c' are supported for ~ in Postgres")
737
738        return self.binary(expression, "~*" if flags.rfind("i") > flags.rfind("c") else "~")
739
740    @unsupported_args("this")
741    def currentschema_sql(self, expression: exp.CurrentSchema) -> str:
742        return "CURRENT_SCHEMA"
743
744    def currenttime_sql(self, expression: exp.CurrentTime) -> str:
745        precision = expression.this
746        return self.func("CURRENT_TIME", precision) if precision else "CURRENT_TIME"
747
748    def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str:
749        # Other dialects can use this argument for a time zone instead of a precision.
750        precision = expression.this
751        if precision and precision.is_int:
752            return self.func("CURRENT_TIMESTAMP", precision)
753        return "CURRENT_TIMESTAMP"
754
755    def interval_sql(self, expression: exp.Interval) -> str:
756        unit = expression.text("unit").lower()
757
758        this = expression.this
759        if unit.startswith("quarter") and isinstance(this, exp.Literal):
760            # Postgres has no QUARTER unit and no exponents in interval strings
761            quarters = to_int(this.to_py())
762            if quarters is None:
763                self.unsupported("Postgres intervals need a whole number of quarters")
764            else:
765                this.replace(exp.Literal.string(quarters * 3))
766                expression.args["unit"].replace(exp.var("MONTH"))
767
768        return super().interval_sql(expression)
769
770    def placeholder_sql(self, expression: exp.Placeholder) -> str:
771        if expression.args.get("jdbc"):
772            return "?"
773
774        this = f"({expression.name})" if expression.this else ""
775        return f"{self.NAMED_PLACEHOLDER_TOKEN}{this}s"
776
777    def arraycontains_sql(self, expression: exp.ArrayContains) -> str:
778        # Convert DuckDB's LIST_CONTAINS(array, value) to PostgreSQL
779        # DuckDB behavior:
780        #   - LIST_CONTAINS([1,2,3], 2) -> true
781        #   - LIST_CONTAINS([1,2,3], 4) -> false
782        #   - LIST_CONTAINS([1,2,NULL], 4) -> false (not NULL)
783        #   - LIST_CONTAINS([1,2,3], NULL) -> NULL
784        #
785        # PostgreSQL equivalent: CASE WHEN value IS NULL THEN NULL
786        #                            ELSE COALESCE(value = ANY(array), FALSE) END
787        value = expression.expression
788        array = expression.this
789
790        coalesce_expr = exp.Coalesce(
791            this=value.eq(exp.Any(this=exp.paren(expression=array, copy=False))),
792            expressions=[exp.false()],
793        )
794
795        case_expr = (
796            exp.Case()
797            .when(exp.Is(this=value, expression=exp.null()), exp.null(), copy=False)
798            .else_(coalesce_expr, copy=False)
799        )
800
801        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 WHERE clause. 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
BARE_OPERATORS = {'<=>'}
DAYOFWEEK_ZERO_BASED = True
SELECT_KINDS = ()
VARIANCE_NAME = 'VAR_SAMP'
DATE_PART_WITH_EXPRESSION = 'DATE_PART'
TRY_SUPPORTED = False
SUPPORTS_DECODE_CASE = False
SUPPORTS_MULTI_ARG_CHR = False
AFTER_HAVING_MODIFIER_TRANSFORMS = {'windows': <function <lambda>>, 'qualify': <function <lambda>>}
SINGLE_STRING_INTERVAL = True
RENAME_TABLE_WITH_DB = False
LOCKING_READS_SUPPORTED = True
JOIN_HINTS = False
TABLE_HINTS = False
QUERY_HINTS = False
NVL2_SUPPORTED = False
PARAMETER_TOKEN = '$'
NAMED_PLACEHOLDER_TOKEN = '%'
TABLESAMPLE_SIZE_IS_ROWS = False
TABLESAMPLE_SEED_KEYWORD = 'REPEATABLE'
SUPPORTS_SELECT_INTO = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = True
SUPPORTS_UNLOGGED_TABLES = True
LIKE_PROPERTY_INSIDE_SCHEMA = True
MULTI_ARG_DISTINCT = False
CAN_IMPLEMENT_ARRAY_ANY = True
SUPPORTS_WINDOW_EXCLUDE = True
COPY_HAS_INTO_KEYWORD = False
ARRAY_CONCAT_IS_VAR_LEN = False
SUPPORTS_MEDIAN = False
ARRAY_SIZE_DIM_REQUIRED: bool | None = True
SUPPORTS_BETWEEN_FLAGS = True
INOUT_SEPARATOR = ''
def lateral_sql(self, expression: sqlglot.expressions.query.Lateral) -> str:
340    def lateral_sql(self, expression: exp.Lateral) -> str:
341        sql = super().lateral_sql(expression)
342
343        if expression.args.get("cross_apply") is not None:
344            sql = f"{sql} ON TRUE"
345
346        return sql
def arraysize_sql(self, expression: sqlglot.expressions.array.ArraySize) -> str:
348    def arraysize_sql(self, expression: exp.ArraySize) -> str:
349        # ARRAY_LENGTH(arr, 1) returns NULL for an empty array, whereas CARDINALITY returns 0
350        if not expression.expression:
351            return self.func("CARDINALITY", expression.this)
352
353        return super().arraysize_sql(expression)
def star_sql(self, expression: sqlglot.expressions.core.Star) -> str:
355    def star_sql(self, expression: exp.Star) -> str:
356        if self.STAR_EXCEPT == "EXCEPT" and expression.args.get("except_"):
357            self.unsupported("PostgreSQL does not support EXCEPT in the SELECT projection")
358
359        return super().star_sql(expression)
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 PostgresGenerator.<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.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.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.DateFromParts'>: <function rename_func.<locals>.<lambda>>, <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.string.Left'>: <function _left_right_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.string.Right'>: <function _left_right_sql>, <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.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'>}
def with_properties(self, properties: sqlglot.expressions.properties.Properties) -> str:
505    def with_properties(self, properties: exp.Properties) -> str:
506        with_properties = []
507        post_with = []
508        for prop in properties.expressions:
509            if isinstance(prop, (exp.OnCommitProperty, exp.TableSpaceProperty)):
510                post_with.append(prop)
511            else:
512                with_properties.append(prop)
513
514        post_with.sort(key=lambda prop: isinstance(prop, exp.TableSpaceProperty))
515        sql = super().with_properties(exp.Properties(expressions=with_properties))
516        post_sql = self.expressions(sqls=post_with, sep=" ", indent=False)
517        return sql + self.seg(post_sql, sep=" " if sql else "") if post_sql else sql
def extract_sql(self, expression: sqlglot.expressions.temporal.Extract) -> str:
522    def extract_sql(self, expression: exp.Extract) -> str:
523        if not expression.args.get("date_part"):
524            return super().extract_sql(expression)
525
526        part = expression.this
527        name = self.DATE_PART_WITH_EXPRESSION
528        if isinstance(part, exp.Var):
529            name = "DATE_PART"
530            part = exp.Literal.string(part.name.lower())
531        return self.func(name, part, expression.expression)
def bytestring_sql(self, expression: sqlglot.expressions.query.ByteString) -> str:
533    def bytestring_sql(self, expression: exp.ByteString) -> str:
534        if not expression.args.get("is_bytes"):
535            return super().bytestring_sql(expression)
536
537        return self.func(
538            "DECODE",
539            exp.Literal.string(expression.this.encode("latin-1").hex()),
540            exp.Literal.string("hex"),
541        )
def jsonobjectagg_sql(self, expression: sqlglot.expressions.json.JSONObjectAgg) -> str:
543    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
544        args = expression.expressions
545        pair = args[0] if len(args) == 1 else None
546        # Only the SQL/JSON spelling, JSON_OBJECTAGG, accepts these clauses.
547        if (
548            isinstance(pair, exp.FormatJson)
549            or expression.args.get("null_handling")
550            or expression.args.get("unique_keys") is not None
551            or expression.args.get("return_type")
552            or expression.args.get("encoding")
553        ):
554            return self._jsonobject_sql(expression)
555
556        if isinstance(pair, exp.JSONKeyValue):
557            args = [pair.this, pair.expression]
558        return self.func("JSON_OBJECT_AGG", *args)
def schemacommentproperty_sql( self, expression: sqlglot.expressions.properties.SchemaCommentProperty) -> str:
560    def schemacommentproperty_sql(self, expression: exp.SchemaCommentProperty) -> str:
561        self.unsupported("Table comments are not supported in the CREATE statement")
562        return ""
def commentcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.CommentColumnConstraint) -> str:
564    def commentcolumnconstraint_sql(self, expression: exp.CommentColumnConstraint) -> str:
565        self.unsupported("Column comments are not supported in the CREATE statement")
566        return ""
def columndef_sql( self, expression: sqlglot.expressions.query.ColumnDef, sep: str = ' ') -> str:
568    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
569        # PostgreSQL places parameter modes BEFORE parameter name
570        param_constraint = expression.find(exp.InOutColumnConstraint)
571
572        if param_constraint:
573            mode_sql = self.sql(param_constraint)
574            param_constraint.pop()  # Remove to prevent double-rendering
575            base_sql = super().columndef_sql(expression, sep)
576            return f"{mode_sql} {base_sql}"
577
578        return super().columndef_sql(expression, sep)
def unnest_sql(self, expression: sqlglot.expressions.array.Unnest) -> str:
580    def unnest_sql(self, expression: exp.Unnest) -> str:
581        if len(expression.expressions) == 1:
582            arg = expression.expressions[0]
583            if isinstance(arg, exp.GenerateDateArray):
584                generate_series: exp.Expr = exp.GenerateSeries(**arg.args)
585                if isinstance(expression.parent, (exp.From, exp.Join)):
586                    generate_series = (
587                        exp.select("value::date")
588                        .from_(exp.Table(this=generate_series).as_("_t", table=["value"]))
589                        .subquery(expression.args.get("alias") or "_unnested_generate_series")
590                    )
591                return self.sql(generate_series)
592
593            from sqlglot.optimizer.annotate_types import annotate_types
594
595            this = annotate_types(arg, dialect=self.dialect)
596            if this.is_type("array<json>"):
597                while isinstance(this, exp.Cast):
598                    this = this.this
599
600                arg_as_json = self.sql(exp.cast(this, exp.DType.JSON))
601                alias = self.sql(expression, "alias")
602                alias = f" AS {alias}" if alias else ""
603
604                if expression.args.get("offset"):
605                    self.unsupported("Unsupported JSON_ARRAY_ELEMENTS with offset")
606
607                return f"JSON_ARRAY_ELEMENTS({arg_as_json}){alias}"
608
609            # PostgreSQL before 16 requires an alias for subqueries in FROM.
610            if query := transforms.unnest_with_offset(expression, require_alias=True):
611                if isinstance(expression.parent, exp.Join):
612                    return self.sql(exp.Lateral(this=query))
613                return self.sql(query)
614
615        return super().unnest_sql(expression)
def bracket_sql(self, expression: sqlglot.expressions.core.Bracket) -> str:
617    def bracket_sql(self, expression: exp.Bracket) -> str:
618        """Forms like ARRAY[1, 2, 3][3] aren't allowed; we need to wrap the ARRAY."""
619        if isinstance(expression.this, exp.Array):
620            expression.set("this", exp.paren(expression.this, copy=False))
621
622        return super().bracket_sql(expression)

Forms like ARRAY[1, 2, 3][3] aren't allowed; we need to wrap the ARRAY.

def matchagainst_sql(self, expression: sqlglot.expressions.string.MatchAgainst) -> str:
624    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
625        this = self.sql(expression, "this")
626        expressions = [f"{self.sql(e)} @@ {this}" for e in expression.expressions]
627        sql = " OR ".join(expressions)
628        return f"({sql})" if len(expressions) > 1 else sql
def alterset_sql(self, expression: sqlglot.expressions.ddl.AlterSet) -> str:
630    def alterset_sql(self, expression: exp.AlterSet) -> str:
631        exprs = self.expressions(expression, flat=True)
632        exprs = f"({exprs})" if exprs else ""
633
634        access_method = self.sql(expression, "access_method")
635        access_method = f"ACCESS METHOD {access_method}" if access_method else ""
636        tablespace = self.sql(expression, "tablespace")
637        tablespace = f"TABLESPACE {tablespace}" if tablespace else ""
638        option = self.sql(expression, "option")
639
640        return f"SET {exprs}{access_method}{tablespace}{option}"
def datatype_sql(self, expression: sqlglot.expressions.datatypes.DataType) -> str:
642    def datatype_sql(self, expression: exp.DataType) -> str:
643        if expression.is_type(exp.DType.ARRAY):
644            if expression.expressions:
645                values = self.expressions(expression, key="values", flat=True)
646                return f"{self.expressions(expression, flat=True)}[{values}]"
647            return "ARRAY"
648
649        if expression.is_type(exp.DType.ENUM):
650            return f"ENUM ({self.expressions(expression, flat=True)})"
651
652        if expression.is_type(exp.DType.DOUBLE, exp.DType.FLOAT) and expression.expressions:
653            # Postgres doesn't support precision for REAL and DOUBLE PRECISION types
654            return f"FLOAT({self.expressions(expression, flat=True)})"
655
656        return super().datatype_sql(expression)
def cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
658    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
659        this = expression.this
660
661        # Postgres casts DIV() to decimal for transpilation but when roundtripping it's superfluous
662        if (
663            isinstance(this, exp.IntDiv)
664            and exp.IntDiv in self.TRANSFORMS
665            and expression.to == exp.DType.DECIMAL.into_expr()
666        ):
667            return self.sql(this)
668
669        return super().cast_sql(expression, safe_prefix=safe_prefix)
def array_sql(self, expression: sqlglot.expressions.array.Array) -> str:
671    def array_sql(self, expression: exp.Array) -> str:
672        exprs = expression.expressions
673        func_name = self.normalize_func("ARRAY")
674
675        if isinstance(seq_get(exprs, 0), exp.Query):
676            return f"{func_name}({self.sql(exprs[0])})"
677
678        return f"{func_name}{inline_array_sql(self, expression)}"
def struct_sql(self, expression: sqlglot.expressions.array.Struct) -> str:
680    def struct_sql(self, expression: exp.Struct) -> str:
681        fields = expression.expressions
682
683        if any(isinstance(e, (exp.PropertyEQ, exp.Alias)) for e in fields):
684            self.unsupported("PostgreSQL does not support named structs")
685
686        return self.func(
687            "ROW",
688            *[e.expression if isinstance(e, exp.PropertyEQ) else e.unalias() for e in fields],
689        )
def computedcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.ComputedColumnConstraint) -> str:
691    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
692        return f"GENERATED ALWAYS AS ({self.sql(expression, 'this')}) STORED"
def isascii_sql(self, expression: sqlglot.expressions.string.IsAscii) -> str:
694    def isascii_sql(self, expression: exp.IsAscii) -> str:
695        return f"({self.sql(expression.this)} ~ '^[[:ascii:]]*$')"
def ignorenulls_sql(self, expression: sqlglot.expressions.core.IgnoreNulls) -> str:
697    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
698        # https://www.postgresql.org/docs/current/functions-window.html
699        self.unsupported("PostgreSQL does not support IGNORE NULLS.")
700        return self.sql(expression.this)
def respectnulls_sql(self, expression: sqlglot.expressions.core.RespectNulls) -> str:
702    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
703        # https://www.postgresql.org/docs/current/functions-window.html
704        self.unsupported("PostgreSQL does not support RESPECT NULLS.")
705        return self.sql(expression.this)
@unsupported_args('options')
def regexpfullmatch_sql(self, expression: sqlglot.expressions.string.RegexpFullMatch) -> str:
707    @unsupported_args("options")
708    def regexpfullmatch_sql(self, expression: exp.RegexpFullMatch) -> str:
709        pattern = expression.expression.unnest()
710        if not pattern.is_string or not _REGEXP_FULL_MATCH_METACHARS.isdisjoint(pattern.name):
711            self.unsupported(
712                "Only plain literal REGEXP_FULL_MATCH patterns translate to SIMILAR TO"
713            )
714
715        predicate = exp.SimilarTo(this=expression.this, expression=expression.expression)
716        return self.sql(exp.paren(predicate, copy=False))
def pos_sql(self, expression: sqlglot.expressions.core.Pos) -> str:
719    def pos_sql(self, expression: exp.Pos) -> str:
720        operand = self.sql(expression, "this")
721        return f"+ {operand}" if operand.startswith("~") else f"+{operand}"
def bitwisenot_sql(self, expression: sqlglot.expressions.core.BitwiseNot) -> str:
723    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
724        operand = self.sql(expression, "this")
725        return f"~ {operand}" if operand.startswith("+") else f"~{operand}"
def regexplike_sql(self, expression: sqlglot.expressions.core.RegexpLike) -> str:
727    def regexplike_sql(self, expression: exp.RegexpLike) -> str:
728        flag = expression.args.get("flag")
729        if not flag:
730            return self.binary(expression, "~")
731
732        # Postgres has no flags argument for ~, only the case-insensitive ~* operator. Of the
733        # case flags, the last one wins, e.g. 'ic' is case-sensitive and 'ci' is not
734        flags = flag.name if flag.is_string else ""
735        if not flag.is_string or set(flags) - {"i", "c"}:
736            self.unsupported("Only the case flags 'i' and 'c' are supported for ~ in Postgres")
737
738        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:
740    @unsupported_args("this")
741    def currentschema_sql(self, expression: exp.CurrentSchema) -> str:
742        return "CURRENT_SCHEMA"
def currenttime_sql(self, expression: sqlglot.expressions.temporal.CurrentTime) -> str:
744    def currenttime_sql(self, expression: exp.CurrentTime) -> str:
745        precision = expression.this
746        return self.func("CURRENT_TIME", precision) if precision else "CURRENT_TIME"
def currenttimestamp_sql(self, expression: sqlglot.expressions.temporal.CurrentTimestamp) -> str:
748    def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str:
749        # Other dialects can use this argument for a time zone instead of a precision.
750        precision = expression.this
751        if precision and precision.is_int:
752            return self.func("CURRENT_TIMESTAMP", precision)
753        return "CURRENT_TIMESTAMP"
def interval_sql(self, expression: sqlglot.expressions.datatypes.Interval) -> str:
755    def interval_sql(self, expression: exp.Interval) -> str:
756        unit = expression.text("unit").lower()
757
758        this = expression.this
759        if unit.startswith("quarter") and isinstance(this, exp.Literal):
760            # Postgres has no QUARTER unit and no exponents in interval strings
761            quarters = to_int(this.to_py())
762            if quarters is None:
763                self.unsupported("Postgres intervals need a whole number of quarters")
764            else:
765                this.replace(exp.Literal.string(quarters * 3))
766                expression.args["unit"].replace(exp.var("MONTH"))
767
768        return super().interval_sql(expression)
def placeholder_sql(self, expression: sqlglot.expressions.core.Placeholder) -> str:
770    def placeholder_sql(self, expression: exp.Placeholder) -> str:
771        if expression.args.get("jdbc"):
772            return "?"
773
774        this = f"({expression.name})" if expression.this else ""
775        return f"{self.NAMED_PLACEHOLDER_TOKEN}{this}s"
def arraycontains_sql(self, expression: sqlglot.expressions.array.ArrayContains) -> str:
777    def arraycontains_sql(self, expression: exp.ArrayContains) -> str:
778        # Convert DuckDB's LIST_CONTAINS(array, value) to PostgreSQL
779        # DuckDB behavior:
780        #   - LIST_CONTAINS([1,2,3], 2) -> true
781        #   - LIST_CONTAINS([1,2,3], 4) -> false
782        #   - LIST_CONTAINS([1,2,NULL], 4) -> false (not NULL)
783        #   - LIST_CONTAINS([1,2,3], NULL) -> NULL
784        #
785        # PostgreSQL equivalent: CASE WHEN value IS NULL THEN NULL
786        #                            ELSE COALESCE(value = ANY(array), FALSE) END
787        value = expression.expression
788        array = expression.this
789
790        coalesce_expr = exp.Coalesce(
791            this=value.eq(exp.Any(this=exp.paren(expression=array, copy=False))),
792            expressions=[exp.false()],
793        )
794
795        case_expr = (
796            exp.Case()
797            .when(exp.Is(this=value, expression=exp.null()), exp.null(), copy=False)
798            .else_(coalesce_expr, copy=False)
799        )
800
801        return self.sql(case_expr)
Inherited Members
sqlglot.generator.Generator
Generator
NULL_ORDERING_SUPPORTED
WINDOW_FUNCS_WITH_NULL_ORDERING
WINDOW_FUNCS_REQUIRING_ORDER
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_SCHEMA_EVOLUTION_MIN_VERSION
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
SUPPORTS_MATCH_CONDITION
MATCH_CONDITION_IN_ON
QUERY_HINT_SEP
IS_BOOL_ALLOWED
CAST_TO_INT_ROUNDS
SAFE_INT_DIVISION
INT_DIV_OPERATOR
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_OPTIMIZE
SUPPORTS_EXECUTE_IMMEDIATE
SUPPORTS_CREATE_TABLE_LIKE
SUPPORTS_MODIFY_COLUMN
SUPPORTS_CHANGE_COLUMN
SUPPORTS_ALTER_COLUMN_NULLABILITY
SUPPORTS_ALTER_COLUMN_IF_EXISTS
SUPPORTS_NESTED_JSON_SELECT
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
DAYOFWEEK_NAME
VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE
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
tableargument_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
dayofweek_sql
extract_date_part
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
format_sql
formatjson_sql
formatphrase_sql
teradataconversion_sql
teradatatitle_sql
teradatanamed_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
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
strtotime_sql
strtodate_sql
parsedatetime_sql
currentdate_sql
collate_sql
command_sql
optimize_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
nestedjsonselect_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
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
variance_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
datetrunc_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
executeimmediate_sql
altermodifysqlsecurity_sql
usingproperty_sql
renameindex_sql