Edit on GitHub

sqlglot.generators.redshift

  1from __future__ import annotations
  2
  3
  4from sqlglot import exp, transforms
  5from sqlglot.dialects.dialect import (
  6    array_concat_sql,
  7    concat_to_dpipe_sql,
  8    concat_ws_to_dpipe_sql,
  9    date_delta_sql,
 10    generatedasidentitycolumnconstraint_sql,
 11    json_extract_segments,
 12    no_tablesample_sql,
 13    rename_func,
 14)
 15from sqlglot.generator import Generator
 16from sqlglot.generators.postgres import PostgresGenerator
 17from sqlglot.helper import seq_get
 18
 19
 20class RedshiftGenerator(PostgresGenerator):
 21    LOCKING_READS_SUPPORTED = False
 22    QUERY_HINTS = False
 23    VALUES_AS_TABLE = False
 24    TZ_TO_WITH_TIME_ZONE = True
 25    NVL2_SUPPORTED = True
 26    LAST_DAY_SUPPORTS_DATE_PART = False
 27    CAN_IMPLEMENT_ARRAY_ANY = False
 28    MULTI_ARG_DISTINCT = True
 29    COPY_PARAMS_ARE_WRAPPED = False
 30    HEX_FUNC = "TO_HEX"
 31    PARSE_JSON_NAME: str | None = "JSON_PARSE"
 32    ARRAY_CONCAT_IS_VAR_LEN = False
 33    SUPPORTS_CONVERT_TIMEZONE = True
 34    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
 35    SUPPORTS_MEDIAN = True
 36    ALTER_SET_TYPE = "TYPE"
 37    SUPPORTS_DECODE_CASE = True
 38    SUPPORTS_BETWEEN_FLAGS = False
 39    LIMIT_FETCH = "LIMIT"
 40    STAR_EXCEPT = "EXCLUDE"
 41    STAR_EXCLUDE_REQUIRES_DERIVED_TABLE = False
 42
 43    # Redshift doesn't have `WITH` as part of their with_properties so we remove it
 44    WITH_PROPERTIES_PREFIX = " "
 45
 46    TYPE_MAPPING = {
 47        **PostgresGenerator.TYPE_MAPPING,
 48        exp.DType.BINARY: "VARBYTE",
 49        exp.DType.BLOB: "VARBYTE",
 50        exp.DType.INT: "INTEGER",
 51        exp.DType.TIMETZ: "TIME",
 52        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
 53        exp.DType.VARBINARY: "VARBYTE",
 54        exp.DType.ROWVERSION: "VARBYTE",
 55    }
 56
 57    TRANSFORMS = {
 58        **{
 59            k: v
 60            for k, v in PostgresGenerator.TRANSFORMS.items()
 61            if k
 62            not in {
 63                exp.Pivot,
 64                exp.ParseJSON,
 65                exp.AnyValue,
 66                exp.LastDay,
 67                exp.SHA2,
 68                exp.Getbit,
 69                exp.Round,
 70            }
 71        },
 72        exp.ArrayConcat: array_concat_sql("ARRAY_CONCAT"),
 73        exp.Concat: concat_to_dpipe_sql,
 74        exp.ConcatWs: concat_ws_to_dpipe_sql,
 75        exp.ApproxDistinct: lambda self, e: f"APPROXIMATE COUNT(DISTINCT {self.sql(e, 'this')})",
 76        exp.CurrentTimestamp: lambda self, e: "SYSDATE" if e.args.get("sysdate") else "GETDATE()",
 77        exp.DateAdd: date_delta_sql("DATEADD"),
 78        exp.DateDiff: date_delta_sql("DATEDIFF"),
 79        exp.DistKeyProperty: lambda self, e: self.func("DISTKEY", e.this),
 80        exp.DistStyleProperty: lambda self, e: self.naked_property(e),
 81        exp.Explode: lambda self, e: self.explode_sql(e),
 82        exp.FarmFingerprint: rename_func("FARMFINGERPRINT64"),
 83        exp.FromBase: rename_func("STRTOL"),
 84        exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
 85        exp.JSONExtract: json_extract_segments("JSON_EXTRACT_PATH_TEXT"),
 86        exp.JSONExtractScalar: json_extract_segments("JSON_EXTRACT_PATH_TEXT"),
 87        exp.GroupConcat: rename_func("LISTAGG"),
 88        exp.Hex: lambda self, e: self.func("UPPER", self.func("TO_HEX", self.sql(e, "this"))),
 89        exp.RegexpExtract: rename_func("REGEXP_SUBSTR"),
 90        exp.Select: transforms.preprocess(
 91            [
 92                transforms.eliminate_window_clause,
 93                transforms.eliminate_distinct_on,
 94                transforms.eliminate_semi_and_anti_joins,
 95                transforms.unqualify_unnest,
 96                transforms.unnest_generate_date_array_using_recursive_cte,
 97            ]
 98        ),
 99        exp.SortKeyProperty: lambda self, e: (
100            f"{'COMPOUND ' if e.args['compound'] else ''}SORTKEY({self.format_args(*e.this)})"
101        ),
102        exp.StartsWith: lambda self, e: f"{self.sql(e.this)} LIKE {self.sql(e.expression)} || '%'",
103        exp.StringToArray: rename_func("SPLIT_TO_ARRAY"),
104        exp.TableSample: no_tablesample_sql,
105        exp.TsOrDsAdd: date_delta_sql("DATEADD"),
106        exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
107        exp.UnixToTime: lambda self, e: self._unix_to_time_sql(e),
108        exp.SHA2Digest: lambda self, e: self.func(
109            "SHA2", e.this, e.args.get("length") or exp.Literal.number(256)
110        ),
111    }
112
113    RESERVED_KEYWORDS = {
114        "aes128",
115        "aes256",
116        "all",
117        "allowoverwrite",
118        "analyse",
119        "analyze",
120        "and",
121        "any",
122        "array",
123        "as",
124        "asc",
125        "authorization",
126        "az64",
127        "backup",
128        "between",
129        "binary",
130        "blanksasnull",
131        "both",
132        "bytedict",
133        "bzip2",
134        "case",
135        "cast",
136        "check",
137        "collate",
138        "column",
139        "constraint",
140        "create",
141        "credentials",
142        "cross",
143        "current_date",
144        "current_time",
145        "current_timestamp",
146        "current_user",
147        "current_user_id",
148        "default",
149        "deferrable",
150        "deflate",
151        "defrag",
152        "delta",
153        "delta32k",
154        "desc",
155        "disable",
156        "distinct",
157        "do",
158        "else",
159        "emptyasnull",
160        "enable",
161        "encode",
162        "encrypt     ",
163        "encryption",
164        "end",
165        "except",
166        "explicit",
167        "false",
168        "for",
169        "foreign",
170        "freeze",
171        "from",
172        "full",
173        "globaldict256",
174        "globaldict64k",
175        "grant",
176        "group",
177        "gzip",
178        "having",
179        "identity",
180        "ignore",
181        "ilike",
182        "in",
183        "initially",
184        "inner",
185        "intersect",
186        "interval",
187        "into",
188        "is",
189        "isnull",
190        "join",
191        "leading",
192        "left",
193        "like",
194        "limit",
195        "localtime",
196        "localtimestamp",
197        "lun",
198        "luns",
199        "lzo",
200        "lzop",
201        "minus",
202        "mostly16",
203        "mostly32",
204        "mostly8",
205        "natural",
206        "new",
207        "not",
208        "notnull",
209        "null",
210        "nulls",
211        "off",
212        "offline",
213        "offset",
214        "oid",
215        "old",
216        "on",
217        "only",
218        "open",
219        "or",
220        "order",
221        "outer",
222        "overlaps",
223        "parallel",
224        "partition",
225        "percent",
226        "permissions",
227        "pivot",
228        "placing",
229        "primary",
230        "raw",
231        "readratio",
232        "recover",
233        "references",
234        "rejectlog",
235        "resort",
236        "respect",
237        "restore",
238        "right",
239        "select",
240        "session_user",
241        "similar",
242        "snapshot",
243        "some",
244        "sysdate",
245        "system",
246        "table",
247        "tag",
248        "tdes",
249        "text255",
250        "text32k",
251        "then",
252        "timestamp",
253        "to",
254        "top",
255        "trailing",
256        "true",
257        "truncatecolumns",
258        "type",
259        "union",
260        "unique",
261        "unnest",
262        "unpivot",
263        "user",
264        "using",
265        "verbose",
266        "wallet",
267        "when",
268        "where",
269        "with",
270        "without",
271    }
272
273    def unnest_sql(self, expression: exp.Unnest) -> str:
274        args = expression.expressions
275        num_args = len(args)
276
277        if num_args != 1:
278            self.unsupported(f"Unsupported number of arguments in UNNEST: {num_args}")
279            return ""
280
281        if isinstance(expression.find_ancestor(exp.From, exp.Join, exp.Select), exp.Select):
282            self.unsupported("Unsupported UNNEST when not used in FROM/JOIN clauses")
283            return ""
284
285        arg = self.sql(seq_get(args, 0))
286
287        alias = self.expressions(expression.args.get("alias"), key="columns", flat=True)
288        return f"{arg} AS {alias}" if alias else arg
289
290    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
291        if expression.is_type(exp.DType.JSON):
292            # Redshift doesn't support a JSON type, so casting to it is treated as a noop
293            return self.sql(expression, "this")
294
295        return super().cast_sql(expression, safe_prefix=safe_prefix)
296
297    def datatype_sql(self, expression: exp.DataType) -> str:
298        """
299        Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
300        VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
301        without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
302        `TEXT` to `VARCHAR`.
303        """
304        if expression.is_type("text"):
305            expression.set("this", exp.DType.VARCHAR)
306            precision = expression.args.get("expressions")
307
308            if not precision:
309                expression.append("expressions", exp.var("MAX"))
310
311        return super().datatype_sql(expression)
312
313    def alterset_sql(self, expression: exp.AlterSet) -> str:
314        exprs = self.expressions(expression, flat=True)
315        exprs = f" TABLE PROPERTIES ({exprs})" if exprs else ""
316        location = self.sql(expression, "location")
317        location = f" LOCATION {location}" if location else ""
318        file_format = self.expressions(expression, key="file_format", flat=True, sep=" ")
319        file_format = f" FILE FORMAT {file_format}" if file_format else ""
320
321        return f"SET{exprs}{location}{file_format}"
322
323    def array_sql(self, expression: exp.Array) -> str:
324        if expression.args.get("bracket_notation"):
325            return super().array_sql(expression)
326
327        return rename_func("ARRAY")(self, expression)
328
329    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
330        return Generator.ignorenulls_sql(self, expression)
331
332    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
333        return Generator.respectnulls_sql(self, expression)
334
335    def explode_sql(self, expression: exp.Explode) -> str:
336        self.unsupported("Unsupported EXPLODE() function")
337        return ""
338
339    def _unix_to_time_sql(self, expression: exp.UnixToTime) -> str:
340        scale = expression.args.get("scale")
341        this = self.sql(expression.this)
342
343        if scale is not None and scale != exp.UnixToTime.SECONDS and scale.is_int:
344            this = f"({this} / POWER(10, {scale.to_py()}))"
345
346        return f"(TIMESTAMP 'epoch' + {this} * INTERVAL '1 SECOND')"
class RedshiftGenerator(sqlglot.generators.postgres.PostgresGenerator):
 21class RedshiftGenerator(PostgresGenerator):
 22    LOCKING_READS_SUPPORTED = False
 23    QUERY_HINTS = False
 24    VALUES_AS_TABLE = False
 25    TZ_TO_WITH_TIME_ZONE = True
 26    NVL2_SUPPORTED = True
 27    LAST_DAY_SUPPORTS_DATE_PART = False
 28    CAN_IMPLEMENT_ARRAY_ANY = False
 29    MULTI_ARG_DISTINCT = True
 30    COPY_PARAMS_ARE_WRAPPED = False
 31    HEX_FUNC = "TO_HEX"
 32    PARSE_JSON_NAME: str | None = "JSON_PARSE"
 33    ARRAY_CONCAT_IS_VAR_LEN = False
 34    SUPPORTS_CONVERT_TIMEZONE = True
 35    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
 36    SUPPORTS_MEDIAN = True
 37    ALTER_SET_TYPE = "TYPE"
 38    SUPPORTS_DECODE_CASE = True
 39    SUPPORTS_BETWEEN_FLAGS = False
 40    LIMIT_FETCH = "LIMIT"
 41    STAR_EXCEPT = "EXCLUDE"
 42    STAR_EXCLUDE_REQUIRES_DERIVED_TABLE = False
 43
 44    # Redshift doesn't have `WITH` as part of their with_properties so we remove it
 45    WITH_PROPERTIES_PREFIX = " "
 46
 47    TYPE_MAPPING = {
 48        **PostgresGenerator.TYPE_MAPPING,
 49        exp.DType.BINARY: "VARBYTE",
 50        exp.DType.BLOB: "VARBYTE",
 51        exp.DType.INT: "INTEGER",
 52        exp.DType.TIMETZ: "TIME",
 53        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
 54        exp.DType.VARBINARY: "VARBYTE",
 55        exp.DType.ROWVERSION: "VARBYTE",
 56    }
 57
 58    TRANSFORMS = {
 59        **{
 60            k: v
 61            for k, v in PostgresGenerator.TRANSFORMS.items()
 62            if k
 63            not in {
 64                exp.Pivot,
 65                exp.ParseJSON,
 66                exp.AnyValue,
 67                exp.LastDay,
 68                exp.SHA2,
 69                exp.Getbit,
 70                exp.Round,
 71            }
 72        },
 73        exp.ArrayConcat: array_concat_sql("ARRAY_CONCAT"),
 74        exp.Concat: concat_to_dpipe_sql,
 75        exp.ConcatWs: concat_ws_to_dpipe_sql,
 76        exp.ApproxDistinct: lambda self, e: f"APPROXIMATE COUNT(DISTINCT {self.sql(e, 'this')})",
 77        exp.CurrentTimestamp: lambda self, e: "SYSDATE" if e.args.get("sysdate") else "GETDATE()",
 78        exp.DateAdd: date_delta_sql("DATEADD"),
 79        exp.DateDiff: date_delta_sql("DATEDIFF"),
 80        exp.DistKeyProperty: lambda self, e: self.func("DISTKEY", e.this),
 81        exp.DistStyleProperty: lambda self, e: self.naked_property(e),
 82        exp.Explode: lambda self, e: self.explode_sql(e),
 83        exp.FarmFingerprint: rename_func("FARMFINGERPRINT64"),
 84        exp.FromBase: rename_func("STRTOL"),
 85        exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
 86        exp.JSONExtract: json_extract_segments("JSON_EXTRACT_PATH_TEXT"),
 87        exp.JSONExtractScalar: json_extract_segments("JSON_EXTRACT_PATH_TEXT"),
 88        exp.GroupConcat: rename_func("LISTAGG"),
 89        exp.Hex: lambda self, e: self.func("UPPER", self.func("TO_HEX", self.sql(e, "this"))),
 90        exp.RegexpExtract: rename_func("REGEXP_SUBSTR"),
 91        exp.Select: transforms.preprocess(
 92            [
 93                transforms.eliminate_window_clause,
 94                transforms.eliminate_distinct_on,
 95                transforms.eliminate_semi_and_anti_joins,
 96                transforms.unqualify_unnest,
 97                transforms.unnest_generate_date_array_using_recursive_cte,
 98            ]
 99        ),
100        exp.SortKeyProperty: lambda self, e: (
101            f"{'COMPOUND ' if e.args['compound'] else ''}SORTKEY({self.format_args(*e.this)})"
102        ),
103        exp.StartsWith: lambda self, e: f"{self.sql(e.this)} LIKE {self.sql(e.expression)} || '%'",
104        exp.StringToArray: rename_func("SPLIT_TO_ARRAY"),
105        exp.TableSample: no_tablesample_sql,
106        exp.TsOrDsAdd: date_delta_sql("DATEADD"),
107        exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
108        exp.UnixToTime: lambda self, e: self._unix_to_time_sql(e),
109        exp.SHA2Digest: lambda self, e: self.func(
110            "SHA2", e.this, e.args.get("length") or exp.Literal.number(256)
111        ),
112    }
113
114    RESERVED_KEYWORDS = {
115        "aes128",
116        "aes256",
117        "all",
118        "allowoverwrite",
119        "analyse",
120        "analyze",
121        "and",
122        "any",
123        "array",
124        "as",
125        "asc",
126        "authorization",
127        "az64",
128        "backup",
129        "between",
130        "binary",
131        "blanksasnull",
132        "both",
133        "bytedict",
134        "bzip2",
135        "case",
136        "cast",
137        "check",
138        "collate",
139        "column",
140        "constraint",
141        "create",
142        "credentials",
143        "cross",
144        "current_date",
145        "current_time",
146        "current_timestamp",
147        "current_user",
148        "current_user_id",
149        "default",
150        "deferrable",
151        "deflate",
152        "defrag",
153        "delta",
154        "delta32k",
155        "desc",
156        "disable",
157        "distinct",
158        "do",
159        "else",
160        "emptyasnull",
161        "enable",
162        "encode",
163        "encrypt     ",
164        "encryption",
165        "end",
166        "except",
167        "explicit",
168        "false",
169        "for",
170        "foreign",
171        "freeze",
172        "from",
173        "full",
174        "globaldict256",
175        "globaldict64k",
176        "grant",
177        "group",
178        "gzip",
179        "having",
180        "identity",
181        "ignore",
182        "ilike",
183        "in",
184        "initially",
185        "inner",
186        "intersect",
187        "interval",
188        "into",
189        "is",
190        "isnull",
191        "join",
192        "leading",
193        "left",
194        "like",
195        "limit",
196        "localtime",
197        "localtimestamp",
198        "lun",
199        "luns",
200        "lzo",
201        "lzop",
202        "minus",
203        "mostly16",
204        "mostly32",
205        "mostly8",
206        "natural",
207        "new",
208        "not",
209        "notnull",
210        "null",
211        "nulls",
212        "off",
213        "offline",
214        "offset",
215        "oid",
216        "old",
217        "on",
218        "only",
219        "open",
220        "or",
221        "order",
222        "outer",
223        "overlaps",
224        "parallel",
225        "partition",
226        "percent",
227        "permissions",
228        "pivot",
229        "placing",
230        "primary",
231        "raw",
232        "readratio",
233        "recover",
234        "references",
235        "rejectlog",
236        "resort",
237        "respect",
238        "restore",
239        "right",
240        "select",
241        "session_user",
242        "similar",
243        "snapshot",
244        "some",
245        "sysdate",
246        "system",
247        "table",
248        "tag",
249        "tdes",
250        "text255",
251        "text32k",
252        "then",
253        "timestamp",
254        "to",
255        "top",
256        "trailing",
257        "true",
258        "truncatecolumns",
259        "type",
260        "union",
261        "unique",
262        "unnest",
263        "unpivot",
264        "user",
265        "using",
266        "verbose",
267        "wallet",
268        "when",
269        "where",
270        "with",
271        "without",
272    }
273
274    def unnest_sql(self, expression: exp.Unnest) -> str:
275        args = expression.expressions
276        num_args = len(args)
277
278        if num_args != 1:
279            self.unsupported(f"Unsupported number of arguments in UNNEST: {num_args}")
280            return ""
281
282        if isinstance(expression.find_ancestor(exp.From, exp.Join, exp.Select), exp.Select):
283            self.unsupported("Unsupported UNNEST when not used in FROM/JOIN clauses")
284            return ""
285
286        arg = self.sql(seq_get(args, 0))
287
288        alias = self.expressions(expression.args.get("alias"), key="columns", flat=True)
289        return f"{arg} AS {alias}" if alias else arg
290
291    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
292        if expression.is_type(exp.DType.JSON):
293            # Redshift doesn't support a JSON type, so casting to it is treated as a noop
294            return self.sql(expression, "this")
295
296        return super().cast_sql(expression, safe_prefix=safe_prefix)
297
298    def datatype_sql(self, expression: exp.DataType) -> str:
299        """
300        Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
301        VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
302        without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
303        `TEXT` to `VARCHAR`.
304        """
305        if expression.is_type("text"):
306            expression.set("this", exp.DType.VARCHAR)
307            precision = expression.args.get("expressions")
308
309            if not precision:
310                expression.append("expressions", exp.var("MAX"))
311
312        return super().datatype_sql(expression)
313
314    def alterset_sql(self, expression: exp.AlterSet) -> str:
315        exprs = self.expressions(expression, flat=True)
316        exprs = f" TABLE PROPERTIES ({exprs})" if exprs else ""
317        location = self.sql(expression, "location")
318        location = f" LOCATION {location}" if location else ""
319        file_format = self.expressions(expression, key="file_format", flat=True, sep=" ")
320        file_format = f" FILE FORMAT {file_format}" if file_format else ""
321
322        return f"SET{exprs}{location}{file_format}"
323
324    def array_sql(self, expression: exp.Array) -> str:
325        if expression.args.get("bracket_notation"):
326            return super().array_sql(expression)
327
328        return rename_func("ARRAY")(self, expression)
329
330    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
331        return Generator.ignorenulls_sql(self, expression)
332
333    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
334        return Generator.respectnulls_sql(self, expression)
335
336    def explode_sql(self, expression: exp.Explode) -> str:
337        self.unsupported("Unsupported EXPLODE() function")
338        return ""
339
340    def _unix_to_time_sql(self, expression: exp.UnixToTime) -> str:
341        scale = expression.args.get("scale")
342        this = self.sql(expression.this)
343
344        if scale is not None and scale != exp.UnixToTime.SECONDS and scale.is_int:
345            this = f"({this} / POWER(10, {scale.to_py()}))"
346
347        return f"(TIMESTAMP 'epoch' + {this} * INTERVAL '1 SECOND')"

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
LOCKING_READS_SUPPORTED = False
QUERY_HINTS = False
VALUES_AS_TABLE = False
TZ_TO_WITH_TIME_ZONE = True
NVL2_SUPPORTED = True
LAST_DAY_SUPPORTS_DATE_PART = False
CAN_IMPLEMENT_ARRAY_ANY = False
MULTI_ARG_DISTINCT = True
COPY_PARAMS_ARE_WRAPPED = False
HEX_FUNC = 'TO_HEX'
PARSE_JSON_NAME: str | None = 'JSON_PARSE'
ARRAY_CONCAT_IS_VAR_LEN = False
SUPPORTS_CONVERT_TIMEZONE = True
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
SUPPORTS_MEDIAN = True
ALTER_SET_TYPE = 'TYPE'
SUPPORTS_DECODE_CASE = True
SUPPORTS_BETWEEN_FLAGS = False
LIMIT_FETCH = 'LIMIT'
STAR_EXCEPT = 'EXCLUDE'
STAR_EXCLUDE_REQUIRES_DERIVED_TABLE = False
WITH_PROPERTIES_PREFIX = ' '
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'>: 'VARBYTE', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <DType.LONGBLOB: 'LONGBLOB'>: 'BLOB', <DType.TINYBLOB: 'TINYBLOB'>: 'BLOB', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'VARBYTE', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP', <DType.TINYINT: 'TINYINT'>: 'SMALLINT', <DType.FLOAT: 'FLOAT'>: 'REAL', <DType.DOUBLE: 'DOUBLE'>: 'DOUBLE PRECISION', <DType.BINARY: 'BINARY'>: 'VARBYTE', <DType.VARBINARY: 'VARBINARY'>: 'VARBYTE', <DType.DATETIME: 'DATETIME'>: 'TIMESTAMP', <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>: 'TIMESTAMP', <DType.INT: 'INT'>: 'INTEGER', <DType.TIMETZ: 'TIMETZ'>: 'TIME', <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>: '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.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.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.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.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.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayConcat'>: <function array_concat_sql.<locals>._array_concat_sql>, <class 'sqlglot.expressions.array.ArrayFilter'>: <function filter_array_using_unnest>, <class 'sqlglot.expressions.array.ArrayAppend'>: <function array_append_sql.<locals>._array_append_sql>, <class 'sqlglot.expressions.array.ArrayPrepend'>: <function array_append_sql.<locals>._array_append_sql>, <class 'sqlglot.expressions.math.BitwiseAndAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseOrAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseXor'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.math.BitwiseXorAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.ColumnDef'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.CurrentDate'>: <function no_paren_current_date_sql>, <class 'sqlglot.expressions.temporal.CurrentTimestamp'>: <function RedshiftGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentUser'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentVersion'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DateAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DateDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.temporal.DateSub'>: <function _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.array.Explode'>: <function RedshiftGenerator.<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.aggregate.GroupConcat'>: <function rename_func.<locals>.<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_segments.<locals>._json_extract_segments>, <class 'sqlglot.expressions.json.JSONExtractScalar'>: <function json_extract_segments.<locals>._json_extract_segments>, <class 'sqlglot.expressions.json.JSONBExtract'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONBExtractScalar'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContains'>: <function PostgresGenerator.<lambda>>, <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.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.functions.Rand'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.RegexpLike'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.string.RegexpILike'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.string.RegexpReplace'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.query.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.SHA2Digest'>: <function RedshiftGenerator.<lambda>>, <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.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_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TsOrDsDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.UnixToTime'>: <function RedshiftGenerator.<lambda>>, <class 'sqlglot.expressions.functions.Uuid'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimeToUnix'>: <function PostgresGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.VariancePop'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.Variance'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.Xor'>: <function bool_xor_sql>, <class 'sqlglot.expressions.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.string.Concat'>: <function concat_to_dpipe_sql>, <class 'sqlglot.expressions.string.ConcatWs'>: <function concat_ws_to_dpipe_sql>, <class 'sqlglot.expressions.core.ApproxDistinct'>: <function RedshiftGenerator.<lambda>>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <function RedshiftGenerator.<lambda>>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <function RedshiftGenerator.<lambda>>, <class 'sqlglot.expressions.string.FarmFingerprint'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.FromBase'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.constraints.GeneratedAsIdentityColumnConstraint'>: <function generatedasidentitycolumnconstraint_sql>, <class 'sqlglot.expressions.string.Hex'>: <function RedshiftGenerator.<lambda>>, <class 'sqlglot.expressions.string.RegexpExtract'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <function RedshiftGenerator.<lambda>>, <class 'sqlglot.expressions.string.StartsWith'>: <function RedshiftGenerator.<lambda>>, <class 'sqlglot.expressions.array.StringToArray'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.TableSample'>: <function no_tablesample_sql>}
RESERVED_KEYWORDS = {'off', 'delta', 'collate', 'current_date', 'as', 'recover', 'not', 'raw', 'table', 'lun', 'respect', 'snapshot', 'unnest', 'mostly16', 'primary', 'similar', 'luns', 'resort', 'union', 'without', 'localtime', 'gzip', 'between', 'when', 'localtimestamp', 'desc', 'system', 'interval', 'delta32k', 'text32k', 'lzop', 'to', 'true', 'session_user', 'natural', 'truncatecolumns', 'new', 'only', 'create', 'allowoverwrite', 'current_timestamp', 'offset', 'asc', 'references', 'is', 'placing', 'encryption', 'constraint', 'timestamp', 'array', 'order', 'for', 'leading', 'identity', 'any', 'globaldict64k', 'case', 'text255', 'binary', 'column', 'ilike', 'limit', 'offline', 'disable', 'like', 'isnull', 'grant', 'permissions', 'emptyasnull', 'then', 'outer', 'distinct', 'or', 'end', 'verbose', 'deferrable', 'select', 'authorization', 'rejectlog', 'notnull', 'deflate', 'join', 'parallel', 'else', 'overlaps', 'cast', 'ignore', 'current_time', 'aes128', 'where', 'left', 'mostly8', 'all', 'encrypt ', 'check', 'enable', 'partition', 'bytedict', 'analyze', 'foreign', 'some', 'aes256', 'null', 'false', 'lzo', 'bzip2', 'from', 'analyse', 'percent', 'current_user_id', 'both', 'on', 'mostly32', 'credentials', 'blanksasnull', 'defrag', 'inner', 'pivot', 'cross', 'open', 'globaldict256', 'user', 'initially', 'oid', 'with', 'right', 'default', 'into', 'top', 'sysdate', 'readratio', 'full', 'old', 'encode', 'do', 'type', 'having', 'current_user', 'intersect', 'nulls', 'and', 'explicit', 'group', 'using', 'unique', 'restore', 'trailing', 'tag', 'az64', 'tdes', 'minus', 'backup', 'freeze', 'except', 'wallet', 'in', 'unpivot'}
def unnest_sql(self, expression: sqlglot.expressions.array.Unnest) -> str:
274    def unnest_sql(self, expression: exp.Unnest) -> str:
275        args = expression.expressions
276        num_args = len(args)
277
278        if num_args != 1:
279            self.unsupported(f"Unsupported number of arguments in UNNEST: {num_args}")
280            return ""
281
282        if isinstance(expression.find_ancestor(exp.From, exp.Join, exp.Select), exp.Select):
283            self.unsupported("Unsupported UNNEST when not used in FROM/JOIN clauses")
284            return ""
285
286        arg = self.sql(seq_get(args, 0))
287
288        alias = self.expressions(expression.args.get("alias"), key="columns", flat=True)
289        return f"{arg} AS {alias}" if alias else arg
def cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
291    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
292        if expression.is_type(exp.DType.JSON):
293            # Redshift doesn't support a JSON type, so casting to it is treated as a noop
294            return self.sql(expression, "this")
295
296        return super().cast_sql(expression, safe_prefix=safe_prefix)
def datatype_sql(self, expression: sqlglot.expressions.datatypes.DataType) -> str:
298    def datatype_sql(self, expression: exp.DataType) -> str:
299        """
300        Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
301        VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
302        without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
303        `TEXT` to `VARCHAR`.
304        """
305        if expression.is_type("text"):
306            expression.set("this", exp.DType.VARCHAR)
307            precision = expression.args.get("expressions")
308
309            if not precision:
310                expression.append("expressions", exp.var("MAX"))
311
312        return super().datatype_sql(expression)

Redshift converts the TEXT data type to VARCHAR(255) by default when people more generally mean VARCHAR of max length which is VARCHAR(max) in Redshift. Therefore if we get a TEXT data type without precision we convert it to VARCHAR(max) and if it does have precision then we just convert TEXT to VARCHAR.

def alterset_sql(self, expression: sqlglot.expressions.ddl.AlterSet) -> str:
314    def alterset_sql(self, expression: exp.AlterSet) -> str:
315        exprs = self.expressions(expression, flat=True)
316        exprs = f" TABLE PROPERTIES ({exprs})" if exprs else ""
317        location = self.sql(expression, "location")
318        location = f" LOCATION {location}" if location else ""
319        file_format = self.expressions(expression, key="file_format", flat=True, sep=" ")
320        file_format = f" FILE FORMAT {file_format}" if file_format else ""
321
322        return f"SET{exprs}{location}{file_format}"
def array_sql(self, expression: sqlglot.expressions.array.Array) -> str:
324    def array_sql(self, expression: exp.Array) -> str:
325        if expression.args.get("bracket_notation"):
326            return super().array_sql(expression)
327
328        return rename_func("ARRAY")(self, expression)
def ignorenulls_sql(self, expression: sqlglot.expressions.core.IgnoreNulls) -> str:
330    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
331        return Generator.ignorenulls_sql(self, expression)
def respectnulls_sql(self, expression: sqlglot.expressions.core.RespectNulls) -> str:
333    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
334        return Generator.respectnulls_sql(self, expression)
def explode_sql(self, expression: sqlglot.expressions.array.Explode) -> str:
336    def explode_sql(self, expression: exp.Explode) -> str:
337        self.unsupported("Unsupported EXPLODE() function")
338        return ""
Inherited Members
sqlglot.generator.Generator
Generator
NULL_ORDERING_SUPPORTED
WINDOW_FUNCS_WITH_NULL_ORDERING
IGNORE_NULLS_IN_FUNC
IGNORE_NULLS_BEFORE_ORDER
WRAP_DERIVED_VALUES
CREATE_FUNCTION_RETURN_AS
MATCHED_BY_SOURCE
SUPPORTS_MERGE_WHERE
INTERVAL_ALLOWS_PLURAL_FORM
LIMIT_ONLY_LITERALS
GROUPINGS_SEP
INDEX_ON
DIRECTED_JOINS
QUERY_HINT_SEP
IS_BOOL_ALLOWED
DUPLICATE_KEY_UPDATE_WITH_SET
LIMIT_IS_TOP
RETURNING_END
EXTRACT_ALLOWS_QUOTES
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
UNNEST_WITH_ORDINALITY
AGGREGATE_FILTER_SUPPORTED
SEMI_ANTI_JOIN_WITH_SIDE
COMPUTED_COLUMN_WITH_TYPE
SUPPORTS_TABLE_COPY
TABLESAMPLE_REQUIRES_PARENS
TABLESAMPLE_KEYWORDS
TABLESAMPLE_WITH_METHOD
COLLATE_IS_FUNC
DATA_TYPE_SPECIFIERS_ALLOWED
ENSURE_BOOLS
CTE_RECURSIVE_KEYWORD_REQUIRED
SUPPORTS_SINGLE_ARG_CONCAT
SUPPORTS_TABLE_ALIAS_COLUMNS
UNPIVOT_ALIASES_ARE_IDENTIFIERS
JSON_KEY_VALUE_PAIR_SEP
INSERT_OVERWRITE
SUPPORTS_CREATE_TABLE_LIKE
JSON_PATH_BRACKETED_KEY_SUPPORTED
JSON_PATH_SINGLE_QUOTE_ESCAPE
SUPPORTS_TO_NUMBER
SET_OP_MODIFIERS
COPY_PARAMS_EQ_REQUIRED
UNICODE_SUBSTITUTE
QUOTE_JSON_PATH
PAD_FILL_PATTERN_IS_REQUIRED
SUPPORTS_EXPLODING_PROJECTIONS
SUPPORTS_UNIX_SECONDS
ALTER_SET_WRAPPED
NORMALIZE_EXTRACT_DATE_PARTS
ARRAY_SIZE_NAME
SUPPORTS_LIKE_QUANTIFIERS
MATCH_AGAINST_TABLE_PREFIX
SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD
DECLARE_DEFAULT_ASSIGNMENT
UPDATE_STATEMENT_SUPPORTS_FROM
SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY
UNSUPPORTED_TYPES
TIME_PART_SINGULARS
TOKEN_MAPPING
STRUCT_DELIMITER
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
WITH_SEPARATED_COMMENTS
EXCLUDE_COMMENTS
UNWRAPPED_INTERVAL_VALUES
PARAMETERIZABLE_TEXT_TYPES
EXPRESSIONS_WITHOUT_NESTED_CTES
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS
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
bytestring_sql
unicodestring_sql
rawstring_sql
datatypeparam_sql
directory_sql
delete_sql
drop_sql
set_operation
set_operations
fetch_sql
limitoptions_sql
filter_sql
hint_sql
indexparameters_sql
index_sql
identifier_sql
hex_sql
lowerhex_sql
inputoutputformat_sql
national_sql
partition_sql
properties_sql
root_properties
properties
with_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
withdataproperty_sql
withsystemversioningproperty_sql
insert_sql
introducer_sql
kill_sql
pseudotype_sql
objectidentifier_sql
onconflict_sql
returning_sql
rowformatdelimitedproperty_sql
withtablehint_sql
indextablehint_sql
historicaldata_sql
table_parts
table_sql
tablefromrows_sql
tablesample_sql
pivot_sql
version_sql
tuple_sql
update_sql
values_sql
var_sql
into_sql
from_sql
groupingsets_sql
rollup_sql
rollupindex_sql
rollupproperty_sql
cube_sql
group_sql
having_sql
connect_sql
prior_sql
join_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
distribute_sql
sort_sql
ordered_sql
matchrecognizemeasure_sql
matchrecognize_sql
query_modifiers
options_modifier
for_modifiers
queryoption_sql
offset_limit_modifiers
after_limit_modifiers
select_sql
schema_sql
schema_columns_sql
star_sql
parameter_sql
sessionparameter_sql
subquery_sql
qualify_sql
prewhere_sql
where_sql
window_sql
partition_by_sql
windowspec_sql
withingroup_sql
between_sql
bracket_offset_expressions
all_sql
any_sql
exists_sql
case_sql
constraint_sql
nextvaluefor_sql
extract_sql
trim_sql
convert_concat_args
concat_sql
concatws_sql
check_sql
foreignkey_sql
primarykey_sql
if_sql
jsonkeyvalue_sql
jsonpath_sql
json_path_part
formatjson_sql
formatphrase_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
add_sql
and_sql
or_sql
xor_sql
connector_sql
bitwiseand_sql
bitwiseleftshift_sql
bitwisenot_sql
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
strtotime_sql
currentdate_sql
collate_sql
command_sql
comment_sql
mergetreettlaction_sql
mergetreettl_sql
transaction_sql
commit_sql
rollback_sql
altercolumn_sql
alterindex_sql
alterdiststyle_sql
altersortkey_sql
alterrename_sql
renamecolumn_sql
alter_sql
altersession_sql
add_column_sql
droppartition_sql
addconstraint_sql
addpartition_sql
distinct_sql
havingmax_sql
intdiv_sql
dpipe_sql
div_sql
safedivide_sql
overlaps_sql
distance_sql
dot_sql
eq_sql
propertyeq_sql
escape_sql
glob_sql
gt_sql
gte_sql
is_sql
like_sql
ilike_sql
match_sql
similarto_sql
lt_sql
lte_sql
mod_sql
mul_sql
neq_sql
nullsafeeq_sql
nullsafeneq_sql
sub_sql
trycast_sql
jsoncast_sql
try_sql
log_sql
use_sql
binary
ceil_floor
function_fallback_sql
func
format_args
too_wide
format_time
expressions
op_expressions
naked_property
tag_sql
token_sql
userdefinedfunction_sql
joinhint_sql
kwarg_sql
when_sql
whens_sql
merge_sql
tochar_sql
tonumber_sql
dictproperty_sql
dictrange_sql
dictsubproperty_sql
duplicatekeyproperty_sql
uniquekeyproperty_sql
distributedbyproperty_sql
oncluster_sql
clusteredbyproperty_sql
anyvalue_sql
querytransform_sql
indexconstraintoption_sql
checkcolumnconstraint_sql
indexcolumnconstraint_sql
nvl2_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
arrayany_sql
struct_sql
partitionrange_sql
truncatetable_sql
convert_sql
copyparameter_sql
credentials_sql
copy_sql
semicolon_sql
datadeletionproperty_sql
maskingpolicycolumnconstraint_sql
gapfill_sql
scope_resolution
scoperesolution_sql
parsejson_sql
rand_sql
changes_sql
pad_sql
summarize_sql
explodinggenerateseries_sql
converttimezone_sql
json_sql
jsonvalue_sql
skipjsoncolumn_sql
conditionalinsert_sql
multitableinserts_sql
oncondition_sql
jsonextractquote_sql
jsonexists_sql
arrayagg_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
arraysize_sql
attach_sql
detach_sql
attachoption_sql
watermarkcolumnconstraint_sql
encodeproperty_sql
includeproperty_sql
xmlelement_sql
xmlkeyvalueoption_sql
partitionbyrangeproperty_sql
partitionbyrangepropertydynamic_sql
unpivotcolumns_sql
analyzesample_sql
analyzestatistics_sql
analyzehistogram_sql
analyzedelete_sql
analyzelistchainedrows_sql
analyzevalidate_sql
analyze_sql
xmltable_sql
xmlnamespace_sql
export_sql
declare_sql
declareitem_sql
recursivewithsearch_sql
parameterizedagg_sql
anonymousaggfunc_sql
combinedaggfunc_sql
combinedparameterizedagg_sql
show_sql
install_sql
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_sql
chr_sql
block_sql
storedprocedure_sql
ifblock_sql
whileblock_sql
execute_sql
executesql_sql
altermodifysqlsecurity_sql
usingproperty_sql
renameindex_sql
sqlglot.generators.postgres.PostgresGenerator
SELECT_KINDS
TRY_SUPPORTED
SUPPORTS_UESCAPE
AFTER_HAVING_MODIFIER_TRANSFORMS
SINGLE_STRING_INTERVAL
RENAME_TABLE_WITH_DB
JOIN_HINTS
TABLE_HINTS
PARAMETER_TOKEN
NAMED_PLACEHOLDER_TOKEN
TABLESAMPLE_SIZE_IS_ROWS
TABLESAMPLE_SEED_KEYWORD
SUPPORTS_SELECT_INTO
JSON_TYPE_REQUIRED_FOR_EXTRACTION
SUPPORTS_UNLOGGED_TABLES
LIKE_PROPERTY_INSIDE_SCHEMA
SUPPORTS_WINDOW_EXCLUDE
COPY_HAS_INTO_KEYWORD
ARRAY_SIZE_DIM_REQUIRED
INOUT_SEPARATOR
SUPPORTED_JSON_PATH_PARTS
lateral_sql
PROPERTIES_LOCATION
schemacommentproperty_sql
commentcolumnconstraint_sql
columndef_sql
bracket_sql
matchagainst_sql
computedcolumnconstraint_sql
isascii_sql
currentschema_sql
interval_sql
placeholder_sql
arraycontains_sql