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    CAST_TO_INT_ROUNDS = True
 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    PROPERTIES_LOCATION = {
 48        **PostgresGenerator.PROPERTIES_LOCATION,
 49        exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA,
 50        exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA,
 51        exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA,
 52    }
 53
 54    TYPE_MAPPING = {
 55        **PostgresGenerator.TYPE_MAPPING,
 56        exp.DType.BINARY: "VARBYTE",
 57        exp.DType.BLOB: "VARBYTE",
 58        exp.DType.INT: "INTEGER",
 59        exp.DType.TIMETZ: "TIME",
 60        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
 61        exp.DType.VARBINARY: "VARBYTE",
 62        exp.DType.ROWVERSION: "VARBYTE",
 63    }
 64
 65    TRANSFORMS = {
 66        **{
 67            k: v
 68            for k, v in PostgresGenerator.TRANSFORMS.items()
 69            if k
 70            not in {
 71                exp.Pivot,
 72                exp.ParseJSON,
 73                exp.AnyValue,
 74                exp.LastDay,
 75                exp.SHA2,
 76                exp.Getbit,
 77                exp.IntDiv,
 78                exp.Round,
 79                exp.TryCast,
 80            }
 81        },
 82        exp.ArrayConcat: array_concat_sql("ARRAY_CONCAT"),
 83        exp.Concat: concat_to_dpipe_sql,
 84        exp.ConcatWs: concat_ws_to_dpipe_sql,
 85        exp.ApproxDistinct: lambda self, e: f"APPROXIMATE COUNT(DISTINCT {self.sql(e, 'this')})",
 86        exp.CurrentTimestamp: lambda self, e: "SYSDATE" if e.args.get("sysdate") else "GETDATE()",
 87        exp.CurrentUserId: lambda *_: "CURRENT_USER_ID",
 88        exp.DateAdd: date_delta_sql("DATEADD"),
 89        exp.DateDiff: date_delta_sql("DATEDIFF"),
 90        exp.DistKeyProperty: lambda self, e: self.func("DISTKEY", e.this),
 91        exp.DistStyleProperty: lambda self, e: self.naked_property(e),
 92        exp.Explode: lambda self, e: self.explode_sql(e),
 93        exp.FarmFingerprint: rename_func("FARMFINGERPRINT64"),
 94        exp.FromBase: rename_func("STRTOL"),
 95        exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
 96        exp.JSONExtract: json_extract_segments("JSON_EXTRACT_PATH_TEXT"),
 97        exp.JSONExtractScalar: json_extract_segments("JSON_EXTRACT_PATH_TEXT"),
 98        exp.GroupConcat: rename_func("LISTAGG"),
 99        exp.Hex: lambda self, e: self.func("UPPER", self.func("TO_HEX", self.sql(e, "this"))),
100        exp.RegexpExtract: rename_func("REGEXP_SUBSTR"),
101        exp.Select: transforms.preprocess(
102            [
103                transforms.eliminate_window_clause,
104                transforms.eliminate_distinct_on,
105                transforms.eliminate_semi_and_anti_joins,
106                transforms.unqualify_unnest,
107                transforms.unnest_generate_date_array_using_recursive_cte,
108            ]
109        ),
110        exp.SortKeyProperty: lambda self, e: (
111            f"{'COMPOUND ' if e.args['compound'] else ''}SORTKEY({self.format_args(*e.this)})"
112        ),
113        exp.StartsWith: lambda self, e: f"{self.sql(e.this)} LIKE {self.sql(e.expression)} || '%'",
114        exp.StringToArray: rename_func("SPLIT_TO_ARRAY"),
115        exp.TableSample: no_tablesample_sql,
116        exp.TsOrDsAdd: date_delta_sql("DATEADD"),
117        exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
118        exp.UnixToTime: lambda self, e: self._unix_to_time_sql(e),
119        exp.SHA2Digest: lambda self, e: self.func(
120            "SHA2", e.this, e.args.get("length") or exp.Literal.number(256)
121        ),
122    }
123
124    RESERVED_KEYWORDS = {
125        "aes128",
126        "aes256",
127        "all",
128        "allowoverwrite",
129        "analyse",
130        "analyze",
131        "and",
132        "any",
133        "array",
134        "as",
135        "asc",
136        "authorization",
137        "az64",
138        "backup",
139        "between",
140        "binary",
141        "blanksasnull",
142        "both",
143        "bytedict",
144        "bzip2",
145        "case",
146        "cast",
147        "check",
148        "collate",
149        "column",
150        "constraint",
151        "create",
152        "credentials",
153        "cross",
154        "current_date",
155        "current_time",
156        "current_timestamp",
157        "current_user",
158        "current_user_id",
159        "default",
160        "deferrable",
161        "deflate",
162        "defrag",
163        "delta",
164        "delta32k",
165        "desc",
166        "disable",
167        "distinct",
168        "do",
169        "else",
170        "emptyasnull",
171        "enable",
172        "encode",
173        "encrypt     ",
174        "encryption",
175        "end",
176        "except",
177        "explicit",
178        "false",
179        "for",
180        "foreign",
181        "freeze",
182        "from",
183        "full",
184        "globaldict256",
185        "globaldict64k",
186        "grant",
187        "group",
188        "gzip",
189        "having",
190        "identity",
191        "ignore",
192        "ilike",
193        "in",
194        "initially",
195        "inner",
196        "intersect",
197        "interval",
198        "into",
199        "is",
200        "isnull",
201        "join",
202        "leading",
203        "left",
204        "like",
205        "limit",
206        "localtime",
207        "localtimestamp",
208        "lun",
209        "luns",
210        "lzo",
211        "lzop",
212        "minus",
213        "mostly16",
214        "mostly32",
215        "mostly8",
216        "natural",
217        "new",
218        "not",
219        "notnull",
220        "null",
221        "nulls",
222        "off",
223        "offline",
224        "offset",
225        "oid",
226        "old",
227        "on",
228        "only",
229        "open",
230        "or",
231        "order",
232        "outer",
233        "overlaps",
234        "parallel",
235        "partition",
236        "percent",
237        "permissions",
238        "pivot",
239        "placing",
240        "primary",
241        "raw",
242        "readratio",
243        "recover",
244        "references",
245        "rejectlog",
246        "resort",
247        "respect",
248        "restore",
249        "right",
250        "select",
251        "session_user",
252        "similar",
253        "snapshot",
254        "some",
255        "sysdate",
256        "system",
257        "table",
258        "tag",
259        "tdes",
260        "text255",
261        "text32k",
262        "then",
263        "timestamp",
264        "to",
265        "top",
266        "trailing",
267        "true",
268        "truncatecolumns",
269        "type",
270        "union",
271        "unique",
272        "unnest",
273        "unpivot",
274        "user",
275        "using",
276        "verbose",
277        "wallet",
278        "when",
279        "where",
280        "with",
281        "without",
282    }
283
284    def bytestring_sql(self, expression: exp.ByteString) -> str:
285        if not expression.args.get("is_bytes"):
286            return self.sql(exp.Literal.string(expression.this))
287
288        return self.func("FROM_HEX", exp.Literal.string(expression.this.encode("latin-1").hex()))
289
290    def stpoint_sql(self, expression: exp.StPoint) -> str:
291        # ST_POINT only accepts 2 args in Redshift; use ST_MAKEPOINT for 3 or 4 args
292        if expression.args.get("z") or expression.args.get("m"):
293            return self.func(
294                "ST_MAKEPOINT",
295                expression.this,
296                expression.expression,
297                expression.args.get("z"),
298                expression.args.get("m"),
299            )
300        return self.func("ST_POINT", expression.this, expression.expression)
301
302    def arraycontains_sql(self, expression: exp.ArrayContains) -> str:
303        return self.func(
304            "ARRAY_CONTAINS",
305            expression.this,
306            expression.expression,
307            expression.args.get("check_null"),
308        )
309
310    def objecttransform_sql(self, expression: exp.ObjectTransform) -> str:
311        this = self.sql(expression, "this")
312        keep = self.expressions(expression, key="keep", flat=True)
313        set_ = self.expressions(expression, key="set_", flat=True)
314        keep_sql = " KEEP " + keep if keep else ""
315        set_sql = " SET " + set_ if set_ else ""
316        return f"OBJECT_TRANSFORM({this}{keep_sql}{set_sql})"
317
318    def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str:
319        return "APPROXIMATE " + self.sql(
320            exp.WithinGroup(
321                this=exp.PercentileDisc(this=expression.args["quantile"]),
322                expression=exp.Order(expressions=[exp.Ordered(this=expression.this)]),
323            )
324        )
325
326    def unnest_sql(self, expression: exp.Unnest) -> str:
327        args = expression.expressions
328        num_args = len(args)
329
330        if num_args != 1:
331            self.unsupported(f"Unsupported number of arguments in UNNEST: {num_args}")
332            return ""
333
334        if isinstance(expression.find_ancestor(exp.From, exp.Join, exp.Select), exp.Select):
335            self.unsupported("Unsupported UNNEST when not used in FROM/JOIN clauses")
336            return ""
337
338        arg = self.sql(seq_get(args, 0))
339
340        alias = self.expressions(expression.args.get("alias"), key="columns", flat=True)
341        return f"{arg} AS {alias}" if alias else arg
342
343    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
344        if expression.is_type(exp.DType.JSON):
345            # Redshift doesn't support a JSON type, so casting to it is treated as a noop
346            return self.sql(expression, "this")
347
348        return super().cast_sql(expression, safe_prefix=safe_prefix)
349
350    def datatype_sql(self, expression: exp.DataType) -> str:
351        """
352        Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
353        VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
354        without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
355        `TEXT` to `VARCHAR`.
356        """
357        if expression.is_type("text"):
358            expression.set("this", exp.DType.VARCHAR)
359            precision = expression.args.get("expressions")
360
361            if not precision:
362                expression.append("expressions", exp.var("MAX"))
363
364        return super().datatype_sql(expression)
365
366    def alterset_sql(self, expression: exp.AlterSet) -> str:
367        exprs = self.expressions(expression, flat=True)
368        exprs = f" TABLE PROPERTIES ({exprs})" if exprs else ""
369        location = self.sql(expression, "location")
370        location = f" LOCATION {location}" if location else ""
371        file_format = self.expressions(expression, key="file_format", flat=True, sep=" ")
372        file_format = f" FILE FORMAT {file_format}" if file_format else ""
373
374        return f"SET{exprs}{location}{file_format}"
375
376    def array_sql(self, expression: exp.Array) -> str:
377        if expression.args.get("bracket_notation"):
378            return super().array_sql(expression)
379
380        return rename_func("ARRAY")(self, expression)
381
382    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
383        return Generator.ignorenulls_sql(self, expression)
384
385    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
386        return Generator.respectnulls_sql(self, expression)
387
388    def explode_sql(self, expression: exp.Explode) -> str:
389        self.unsupported("Unsupported EXPLODE() function")
390        return ""
391
392    def _unix_to_time_sql(self, expression: exp.UnixToTime) -> str:
393        scale = expression.args.get("scale")
394        this = self.sql(expression.this)
395
396        if scale is not None and scale != exp.UnixToTime.SECONDS and scale.is_int:
397            this = f"({this} / POWER(10, {scale.to_py()}))"
398
399        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    CAST_TO_INT_ROUNDS = True
 25    VALUES_AS_TABLE = False
 26    TZ_TO_WITH_TIME_ZONE = True
 27    NVL2_SUPPORTED = True
 28    LAST_DAY_SUPPORTS_DATE_PART = False
 29    CAN_IMPLEMENT_ARRAY_ANY = False
 30    MULTI_ARG_DISTINCT = True
 31    COPY_PARAMS_ARE_WRAPPED = False
 32    HEX_FUNC = "TO_HEX"
 33    PARSE_JSON_NAME: str | None = "JSON_PARSE"
 34    ARRAY_CONCAT_IS_VAR_LEN = False
 35    SUPPORTS_CONVERT_TIMEZONE = True
 36    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False
 37    SUPPORTS_MEDIAN = True
 38    ALTER_SET_TYPE = "TYPE"
 39    SUPPORTS_DECODE_CASE = True
 40    SUPPORTS_BETWEEN_FLAGS = False
 41    LIMIT_FETCH = "LIMIT"
 42    STAR_EXCEPT = "EXCLUDE"
 43    STAR_EXCLUDE_REQUIRES_DERIVED_TABLE = False
 44
 45    # Redshift doesn't have `WITH` as part of their with_properties so we remove it
 46    WITH_PROPERTIES_PREFIX = " "
 47
 48    PROPERTIES_LOCATION = {
 49        **PostgresGenerator.PROPERTIES_LOCATION,
 50        exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA,
 51        exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA,
 52        exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA,
 53    }
 54
 55    TYPE_MAPPING = {
 56        **PostgresGenerator.TYPE_MAPPING,
 57        exp.DType.BINARY: "VARBYTE",
 58        exp.DType.BLOB: "VARBYTE",
 59        exp.DType.INT: "INTEGER",
 60        exp.DType.TIMETZ: "TIME",
 61        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
 62        exp.DType.VARBINARY: "VARBYTE",
 63        exp.DType.ROWVERSION: "VARBYTE",
 64    }
 65
 66    TRANSFORMS = {
 67        **{
 68            k: v
 69            for k, v in PostgresGenerator.TRANSFORMS.items()
 70            if k
 71            not in {
 72                exp.Pivot,
 73                exp.ParseJSON,
 74                exp.AnyValue,
 75                exp.LastDay,
 76                exp.SHA2,
 77                exp.Getbit,
 78                exp.IntDiv,
 79                exp.Round,
 80                exp.TryCast,
 81            }
 82        },
 83        exp.ArrayConcat: array_concat_sql("ARRAY_CONCAT"),
 84        exp.Concat: concat_to_dpipe_sql,
 85        exp.ConcatWs: concat_ws_to_dpipe_sql,
 86        exp.ApproxDistinct: lambda self, e: f"APPROXIMATE COUNT(DISTINCT {self.sql(e, 'this')})",
 87        exp.CurrentTimestamp: lambda self, e: "SYSDATE" if e.args.get("sysdate") else "GETDATE()",
 88        exp.CurrentUserId: lambda *_: "CURRENT_USER_ID",
 89        exp.DateAdd: date_delta_sql("DATEADD"),
 90        exp.DateDiff: date_delta_sql("DATEDIFF"),
 91        exp.DistKeyProperty: lambda self, e: self.func("DISTKEY", e.this),
 92        exp.DistStyleProperty: lambda self, e: self.naked_property(e),
 93        exp.Explode: lambda self, e: self.explode_sql(e),
 94        exp.FarmFingerprint: rename_func("FARMFINGERPRINT64"),
 95        exp.FromBase: rename_func("STRTOL"),
 96        exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
 97        exp.JSONExtract: json_extract_segments("JSON_EXTRACT_PATH_TEXT"),
 98        exp.JSONExtractScalar: json_extract_segments("JSON_EXTRACT_PATH_TEXT"),
 99        exp.GroupConcat: rename_func("LISTAGG"),
100        exp.Hex: lambda self, e: self.func("UPPER", self.func("TO_HEX", self.sql(e, "this"))),
101        exp.RegexpExtract: rename_func("REGEXP_SUBSTR"),
102        exp.Select: transforms.preprocess(
103            [
104                transforms.eliminate_window_clause,
105                transforms.eliminate_distinct_on,
106                transforms.eliminate_semi_and_anti_joins,
107                transforms.unqualify_unnest,
108                transforms.unnest_generate_date_array_using_recursive_cte,
109            ]
110        ),
111        exp.SortKeyProperty: lambda self, e: (
112            f"{'COMPOUND ' if e.args['compound'] else ''}SORTKEY({self.format_args(*e.this)})"
113        ),
114        exp.StartsWith: lambda self, e: f"{self.sql(e.this)} LIKE {self.sql(e.expression)} || '%'",
115        exp.StringToArray: rename_func("SPLIT_TO_ARRAY"),
116        exp.TableSample: no_tablesample_sql,
117        exp.TsOrDsAdd: date_delta_sql("DATEADD"),
118        exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
119        exp.UnixToTime: lambda self, e: self._unix_to_time_sql(e),
120        exp.SHA2Digest: lambda self, e: self.func(
121            "SHA2", e.this, e.args.get("length") or exp.Literal.number(256)
122        ),
123    }
124
125    RESERVED_KEYWORDS = {
126        "aes128",
127        "aes256",
128        "all",
129        "allowoverwrite",
130        "analyse",
131        "analyze",
132        "and",
133        "any",
134        "array",
135        "as",
136        "asc",
137        "authorization",
138        "az64",
139        "backup",
140        "between",
141        "binary",
142        "blanksasnull",
143        "both",
144        "bytedict",
145        "bzip2",
146        "case",
147        "cast",
148        "check",
149        "collate",
150        "column",
151        "constraint",
152        "create",
153        "credentials",
154        "cross",
155        "current_date",
156        "current_time",
157        "current_timestamp",
158        "current_user",
159        "current_user_id",
160        "default",
161        "deferrable",
162        "deflate",
163        "defrag",
164        "delta",
165        "delta32k",
166        "desc",
167        "disable",
168        "distinct",
169        "do",
170        "else",
171        "emptyasnull",
172        "enable",
173        "encode",
174        "encrypt     ",
175        "encryption",
176        "end",
177        "except",
178        "explicit",
179        "false",
180        "for",
181        "foreign",
182        "freeze",
183        "from",
184        "full",
185        "globaldict256",
186        "globaldict64k",
187        "grant",
188        "group",
189        "gzip",
190        "having",
191        "identity",
192        "ignore",
193        "ilike",
194        "in",
195        "initially",
196        "inner",
197        "intersect",
198        "interval",
199        "into",
200        "is",
201        "isnull",
202        "join",
203        "leading",
204        "left",
205        "like",
206        "limit",
207        "localtime",
208        "localtimestamp",
209        "lun",
210        "luns",
211        "lzo",
212        "lzop",
213        "minus",
214        "mostly16",
215        "mostly32",
216        "mostly8",
217        "natural",
218        "new",
219        "not",
220        "notnull",
221        "null",
222        "nulls",
223        "off",
224        "offline",
225        "offset",
226        "oid",
227        "old",
228        "on",
229        "only",
230        "open",
231        "or",
232        "order",
233        "outer",
234        "overlaps",
235        "parallel",
236        "partition",
237        "percent",
238        "permissions",
239        "pivot",
240        "placing",
241        "primary",
242        "raw",
243        "readratio",
244        "recover",
245        "references",
246        "rejectlog",
247        "resort",
248        "respect",
249        "restore",
250        "right",
251        "select",
252        "session_user",
253        "similar",
254        "snapshot",
255        "some",
256        "sysdate",
257        "system",
258        "table",
259        "tag",
260        "tdes",
261        "text255",
262        "text32k",
263        "then",
264        "timestamp",
265        "to",
266        "top",
267        "trailing",
268        "true",
269        "truncatecolumns",
270        "type",
271        "union",
272        "unique",
273        "unnest",
274        "unpivot",
275        "user",
276        "using",
277        "verbose",
278        "wallet",
279        "when",
280        "where",
281        "with",
282        "without",
283    }
284
285    def bytestring_sql(self, expression: exp.ByteString) -> str:
286        if not expression.args.get("is_bytes"):
287            return self.sql(exp.Literal.string(expression.this))
288
289        return self.func("FROM_HEX", exp.Literal.string(expression.this.encode("latin-1").hex()))
290
291    def stpoint_sql(self, expression: exp.StPoint) -> str:
292        # ST_POINT only accepts 2 args in Redshift; use ST_MAKEPOINT for 3 or 4 args
293        if expression.args.get("z") or expression.args.get("m"):
294            return self.func(
295                "ST_MAKEPOINT",
296                expression.this,
297                expression.expression,
298                expression.args.get("z"),
299                expression.args.get("m"),
300            )
301        return self.func("ST_POINT", expression.this, expression.expression)
302
303    def arraycontains_sql(self, expression: exp.ArrayContains) -> str:
304        return self.func(
305            "ARRAY_CONTAINS",
306            expression.this,
307            expression.expression,
308            expression.args.get("check_null"),
309        )
310
311    def objecttransform_sql(self, expression: exp.ObjectTransform) -> str:
312        this = self.sql(expression, "this")
313        keep = self.expressions(expression, key="keep", flat=True)
314        set_ = self.expressions(expression, key="set_", flat=True)
315        keep_sql = " KEEP " + keep if keep else ""
316        set_sql = " SET " + set_ if set_ else ""
317        return f"OBJECT_TRANSFORM({this}{keep_sql}{set_sql})"
318
319    def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str:
320        return "APPROXIMATE " + self.sql(
321            exp.WithinGroup(
322                this=exp.PercentileDisc(this=expression.args["quantile"]),
323                expression=exp.Order(expressions=[exp.Ordered(this=expression.this)]),
324            )
325        )
326
327    def unnest_sql(self, expression: exp.Unnest) -> str:
328        args = expression.expressions
329        num_args = len(args)
330
331        if num_args != 1:
332            self.unsupported(f"Unsupported number of arguments in UNNEST: {num_args}")
333            return ""
334
335        if isinstance(expression.find_ancestor(exp.From, exp.Join, exp.Select), exp.Select):
336            self.unsupported("Unsupported UNNEST when not used in FROM/JOIN clauses")
337            return ""
338
339        arg = self.sql(seq_get(args, 0))
340
341        alias = self.expressions(expression.args.get("alias"), key="columns", flat=True)
342        return f"{arg} AS {alias}" if alias else arg
343
344    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
345        if expression.is_type(exp.DType.JSON):
346            # Redshift doesn't support a JSON type, so casting to it is treated as a noop
347            return self.sql(expression, "this")
348
349        return super().cast_sql(expression, safe_prefix=safe_prefix)
350
351    def datatype_sql(self, expression: exp.DataType) -> str:
352        """
353        Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
354        VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
355        without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
356        `TEXT` to `VARCHAR`.
357        """
358        if expression.is_type("text"):
359            expression.set("this", exp.DType.VARCHAR)
360            precision = expression.args.get("expressions")
361
362            if not precision:
363                expression.append("expressions", exp.var("MAX"))
364
365        return super().datatype_sql(expression)
366
367    def alterset_sql(self, expression: exp.AlterSet) -> str:
368        exprs = self.expressions(expression, flat=True)
369        exprs = f" TABLE PROPERTIES ({exprs})" if exprs else ""
370        location = self.sql(expression, "location")
371        location = f" LOCATION {location}" if location else ""
372        file_format = self.expressions(expression, key="file_format", flat=True, sep=" ")
373        file_format = f" FILE FORMAT {file_format}" if file_format else ""
374
375        return f"SET{exprs}{location}{file_format}"
376
377    def array_sql(self, expression: exp.Array) -> str:
378        if expression.args.get("bracket_notation"):
379            return super().array_sql(expression)
380
381        return rename_func("ARRAY")(self, expression)
382
383    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
384        return Generator.ignorenulls_sql(self, expression)
385
386    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
387        return Generator.respectnulls_sql(self, expression)
388
389    def explode_sql(self, expression: exp.Explode) -> str:
390        self.unsupported("Unsupported EXPLODE() function")
391        return ""
392
393    def _unix_to_time_sql(self, expression: exp.UnixToTime) -> str:
394        scale = expression.args.get("scale")
395        this = self.sql(expression.this)
396
397        if scale is not None and scale != exp.UnixToTime.SECONDS and scale.is_int:
398            this = f"({this} / POWER(10, {scale.to_py()}))"
399
400        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
CAST_TO_INT_ROUNDS = True
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 = ' '
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.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <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.POST_SCHEMA: 'POST_SCHEMA'>, <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'>}
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.ArrayContainedBy'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.AssumeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.BinaryColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApiProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.EndStatement'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HybridProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsTopKey'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.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.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 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.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.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.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.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.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.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.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>>, <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.functions.CurrentUserId'>: <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 = {'allowoverwrite', 'resort', 'inner', 'limit', 'similar', 'gzip', 'trailing', 'user', 'encryption', 'current_timestamp', 'default', 'using', 'table', 'authorization', 'ilike', 'az64', 'cross', 'except', 'defrag', 'natural', 'text255', 'initially', 'recover', 'lzo', 'offset', 'constraint', 'with', 'old', 'cast', 'sysdate', 'select', 'backup', 'rejectlog', 'or', 'mostly32', 'parallel', 'bzip2', 'delta', 'nulls', 'references', 'foreign', 'text32k', 'luns', 'for', 'and', 'deflate', 'encode', 'wallet', 'false', 'tag', 'leading', 'unpivot', 'encrypt ', 'new', 'both', 'partition', 'timestamp', 'ignore', 'system', 'true', 'type', 'some', 'end', 'analyze', 'full', 'outer', 'session_user', 'when', 'having', 'current_time', 'create', 'to', 'check', 'overlaps', 'placing', 'emptyasnull', 'bytedict', 'verbose', 'any', 'right', 'group', 'isnull', 'aes128', 'desc', 'deferrable', 'collate', 'interval', 'pivot', 'open', 'credentials', 'then', 'respect', 'restore', 'percent', 'aes256', 'is', 'oid', 'localtime', 'without', 'globaldict256', 'asc', 'null', 'delta32k', 'identity', 'grant', 'mostly8', 'off', 'current_user_id', 'between', 'offline', 'as', 'order', 'top', 'column', 'from', 'on', 'lzop', 'intersect', 'localtimestamp', 'join', 'left', 'blanksasnull', 'else', 'freeze', 'unnest', 'analyse', 'snapshot', 'enable', 'explicit', 'in', 'tdes', 'raw', 'primary', 'union', 'into', 'like', 'distinct', 'where', 'array', 'permissions', 'globaldict64k', 'current_user', 'readratio', 'notnull', 'mostly16', 'only', 'lun', 'disable', 'minus', 'binary', 'do', 'current_date', 'all', 'not', 'truncatecolumns', 'case', 'unique'}
def bytestring_sql(self, expression: sqlglot.expressions.query.ByteString) -> str:
285    def bytestring_sql(self, expression: exp.ByteString) -> str:
286        if not expression.args.get("is_bytes"):
287            return self.sql(exp.Literal.string(expression.this))
288
289        return self.func("FROM_HEX", exp.Literal.string(expression.this.encode("latin-1").hex()))
def stpoint_sql(self, expression: sqlglot.expressions.array.StPoint) -> str:
291    def stpoint_sql(self, expression: exp.StPoint) -> str:
292        # ST_POINT only accepts 2 args in Redshift; use ST_MAKEPOINT for 3 or 4 args
293        if expression.args.get("z") or expression.args.get("m"):
294            return self.func(
295                "ST_MAKEPOINT",
296                expression.this,
297                expression.expression,
298                expression.args.get("z"),
299                expression.args.get("m"),
300            )
301        return self.func("ST_POINT", expression.this, expression.expression)
def arraycontains_sql(self, expression: sqlglot.expressions.array.ArrayContains) -> str:
303    def arraycontains_sql(self, expression: exp.ArrayContains) -> str:
304        return self.func(
305            "ARRAY_CONTAINS",
306            expression.this,
307            expression.expression,
308            expression.args.get("check_null"),
309        )
def objecttransform_sql(self, expression: sqlglot.expressions.functions.ObjectTransform) -> str:
311    def objecttransform_sql(self, expression: exp.ObjectTransform) -> str:
312        this = self.sql(expression, "this")
313        keep = self.expressions(expression, key="keep", flat=True)
314        set_ = self.expressions(expression, key="set_", flat=True)
315        keep_sql = " KEEP " + keep if keep else ""
316        set_sql = " SET " + set_ if set_ else ""
317        return f"OBJECT_TRANSFORM({this}{keep_sql}{set_sql})"
def approxquantile_sql(self, expression: sqlglot.expressions.aggregate.ApproxQuantile) -> str:
319    def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str:
320        return "APPROXIMATE " + self.sql(
321            exp.WithinGroup(
322                this=exp.PercentileDisc(this=expression.args["quantile"]),
323                expression=exp.Order(expressions=[exp.Ordered(this=expression.this)]),
324            )
325        )
def unnest_sql(self, expression: sqlglot.expressions.array.Unnest) -> str:
327    def unnest_sql(self, expression: exp.Unnest) -> str:
328        args = expression.expressions
329        num_args = len(args)
330
331        if num_args != 1:
332            self.unsupported(f"Unsupported number of arguments in UNNEST: {num_args}")
333            return ""
334
335        if isinstance(expression.find_ancestor(exp.From, exp.Join, exp.Select), exp.Select):
336            self.unsupported("Unsupported UNNEST when not used in FROM/JOIN clauses")
337            return ""
338
339        arg = self.sql(seq_get(args, 0))
340
341        alias = self.expressions(expression.args.get("alias"), key="columns", flat=True)
342        return f"{arg} AS {alias}" if alias else arg
def cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
344    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
345        if expression.is_type(exp.DType.JSON):
346            # Redshift doesn't support a JSON type, so casting to it is treated as a noop
347            return self.sql(expression, "this")
348
349        return super().cast_sql(expression, safe_prefix=safe_prefix)
def datatype_sql(self, expression: sqlglot.expressions.datatypes.DataType) -> str:
351    def datatype_sql(self, expression: exp.DataType) -> str:
352        """
353        Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
354        VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
355        without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
356        `TEXT` to `VARCHAR`.
357        """
358        if expression.is_type("text"):
359            expression.set("this", exp.DType.VARCHAR)
360            precision = expression.args.get("expressions")
361
362            if not precision:
363                expression.append("expressions", exp.var("MAX"))
364
365        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:
367    def alterset_sql(self, expression: exp.AlterSet) -> str:
368        exprs = self.expressions(expression, flat=True)
369        exprs = f" TABLE PROPERTIES ({exprs})" if exprs else ""
370        location = self.sql(expression, "location")
371        location = f" LOCATION {location}" if location else ""
372        file_format = self.expressions(expression, key="file_format", flat=True, sep=" ")
373        file_format = f" FILE FORMAT {file_format}" if file_format else ""
374
375        return f"SET{exprs}{location}{file_format}"
def array_sql(self, expression: sqlglot.expressions.array.Array) -> str:
377    def array_sql(self, expression: exp.Array) -> str:
378        if expression.args.get("bracket_notation"):
379            return super().array_sql(expression)
380
381        return rename_func("ARRAY")(self, expression)
def ignorenulls_sql(self, expression: sqlglot.expressions.core.IgnoreNulls) -> str:
383    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
384        return Generator.ignorenulls_sql(self, expression)
def respectnulls_sql(self, expression: sqlglot.expressions.core.RespectNulls) -> str:
386    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
387        return Generator.respectnulls_sql(self, expression)
def explode_sql(self, expression: sqlglot.expressions.array.Explode) -> str:
389    def explode_sql(self, expression: exp.Explode) -> str:
390        self.unsupported("Unsupported EXPLODE() function")
391        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
MERGE_ALL_BY_NAME
INTERVAL_ALLOWS_PLURAL_FORM
AUTO_REFRESH_BARE_INTERVALS
LIMIT_ONLY_LITERALS
GROUPINGS_SEP
SUPPORTS_GROUPING_SETS_AS_SUFFIX
INDEX_ON
DIRECTED_JOINS
SUPPORTS_NEAREST_JOIN
QUERY_HINT_SEP
IS_BOOL_ALLOWED
SAFE_INT_DIVISION
DUPLICATE_KEY_UPDATE_WITH_SET
LIMIT_IS_TOP
RETURNING_END
EXTRACT_ALLOWS_QUOTES
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
SUPPORTS_TABLE_ALIAS_COLUMNS
SUPPORTS_NAMED_CTE_COLUMNS
UNPIVOT_ALIASES_ARE_IDENTIFIERS
PIVOT_ALIAS_WITH_AS
JSON_KEY_VALUE_PAIR_SEP
INSERT_OVERWRITE
SUPPORTS_CREATE_TABLE_LIKE
SUPPORTS_MODIFY_COLUMN
SUPPORTS_CHANGE_COLUMN
SUPPORTS_ALTER_COLUMN_NULLABILITY
SUPPORTS_ALTER_COLUMN_IF_EXISTS
JSON_PATH_BRACKETED_KEY_SUPPORTED
JSON_PATH_SINGLE_QUOTE_ESCAPE
JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
SUPPORTS_TO_NUMBER
SET_OP_MODIFIERS
SET_OP_LIMITS
SET_OP_PARENTHESIZED_OPERANDS
COPY_PARAMS_EQ_REQUIRED
SUPPORTS_UESCAPE
UNICODE_SUBSTITUTE
BYTE_STRING_FUNCTION
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
TYPE_PARAM_SETTINGS
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
MOD_OPERATOR
MOD_PAREN_PARENT_TYPES
ALTER_PARTITION_OPTIONS
SAFE_JSON_PATH_KEY_RE
SENTINEL_LINE_BREAK
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages
generate
preprocess
unsupported
sep
seg
sanitize_comment
maybe_comment
wrap
no_identify
normalize_func
indent
sql
uncache_sql
cache_sql
characterset_sql
column_parts
column_sql
pseudocolumn_sql
columnposition_sql
columnconstraint_sql
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
generatedasrowcolumnconstraint_sql
periodforsystemtimeconstraint_sql
notnullcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
inoutcolumnconstraint_sql
createable_sql
create_sql
sequenceproperties_sql
triggerproperties_sql
triggerreferencing_sql
triggerevent_sql
clone_sql
describe_sql
heredoc_sql
prepend_ctes
with_sql
cte_sql
tablealias_sql
bitstring_sql
hexstring_sql
unicodestring_sql
rawstring_sql
datatypeparam_sql
datatype_param_bound_limiter
directory_sql
delete_sql
drop_sql
set_operation
set_operations
fetch_sql
limitoptions_sql
filter_sql
per_sql
hint_sql
indexparameters_sql
index_sql
dynamicidentifier_sql
identifier_sql
hex_sql
lowerhex_sql
inputoutputformat_sql
national_sql
partition_sql
properties_sql
root_properties
properties
locate_properties
property_name
property_sql
uuidproperty_sql
likeproperty_sql
fallbackproperty_sql
journalproperty_sql
freespaceproperty_sql
checksumproperty_sql
mergeblockratioproperty_sql
moduleproperty_sql
datablocksizeproperty_sql
blockcompressionproperty_sql
isolatedloadingproperty_sql
partitionboundspec_sql
partitionedofproperty_sql
lockingproperty_sql
lockingstatement_sql
withdataproperty_sql
withsystemversioningproperty_sql
insert_sql
introducer_sql
kill_sql
pseudotype_sql
objectidentifier_sql
onconflict_sql
returning_sql
rowformatdelimitedproperty_sql
withtablehint_sql
indextablehint_sql
historicaldata_sql
table_parts
table_sql
tablefromrows_sql
tablesample_sql
pivot_sql
version_sql
tuple_sql
update_sql
values_sql
var_sql
into_sql
from_sql
groupingsets_sql
rollup_sql
rollupindex_sql
rollupproperty_sql
cube_sql
group_sql
having_sql
connectto_sql
disconnect_sql
connect_sql
prior_sql
join_sql
nearest_sql
lambda_sql
lateral_op
limit_sql
offset_sql
setitem_sql
set_sql
queryband_sql
pragma_sql
lock_sql
literal_sql
escape_str
loaddata_sql
null_sql
boolean_sql
booland_sql
boolor_sql
order_sql
withfill_sql
cluster_sql
clusterproperty_sql
distribute_sql
sort_sql
ordered_sql
matchrecognizemeasure_sql
matchrecognize_sql
query_modifiers
options_modifier
forclause_sql
queryoption_sql
offset_limit_modifiers
after_limit_modifiers
select_sql
schema_sql
schema_columns_sql
parameter_sql
sessionparameter_sql
subquery_sql
qualify_sql
prewhere_sql
where_sql
window_sql
partition_by_sql
partitionbyexcluding_sql
windowspec_sql
withingroup_sql
between_sql
bracket_offset_expressions
all_sql
any_sql
exists_sql
case_sql
constraint_sql
nextvaluefor_sql
extract_sql
trim_sql
convert_concat_args
concat_sql
concatws_sql
check_sql
foreignkey_sql
primarykey_sql
timeserieskey_sql
if_sql
jsonkeyvalue_sql
jsonpath_sql
json_path_part
formatjson_sql
formatphrase_sql
teradatatitle_sql
jsonarray_sql
jsonarrayagg_sql
jsoncolumndef_sql
jsonschema_sql
jsontable_sql
openjsoncolumndef_sql
openjson_sql
in_sql
in_unnest_op
return_sql
reference_sql
anonymous_sql
paren_sql
neg_sql
not_sql
alias_sql
pivotalias_sql
aliases_sql
atindex_sql
attimezone_sql
fromtimezone_sql
fromiso8601date_sql
fromiso8601timestamp_sql
fromiso8601timestampnanos_sql
add_sql
and_sql
or_sql
xor_sql
connector_sql
bitwiseand_sql
bitwiseleftshift_sql
bitwisenot_sql
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
strtotime_sql
strtodate_sql
parsedatetime_sql
currentdate_sql
collate_sql
command_sql
comment_sql
mergetreettlaction_sql
mergetreettl_sql
transaction_sql
commit_sql
rollback_sql
altercolumn_sql
modifycolumn_sql
alterindex_sql
alterdiststyle_sql
altersortkey_sql
alterrename_sql
renamecolumn_sql
alter_sql
altersession_sql
add_column_sql
droppartition_sql
dropprimarykey_sql
addconstraint_sql
replacecolumns_sql
addpartition_sql
distinct_sql
havingmax_sql
intdiv_sql
dpipe_sql
nullif_zero_divisor
div_sql
safedivide_sql
overlaps_sql
distance_sql
distancend_sql
dot_sql
eq_sql
propertyeq_sql
escape_sql
glob_sql
gt_sql
gte_sql
is_sql
like_sql
ilike_sql
match_sql
similarto_sql
lt_sql
lte_sql
mod_sql
mul_sql
neq_sql
nullsafeeq_sql
nullsafeneq_sql
sub_sql
trycast_sql
jsoncast_sql
try_sql
log_sql
use_sql
binary
ceil_floor
function_fallback_sql
function_name
func
format_args
too_wide
format_time
expressions
op_expressions
naked_property
tag_sql
token_sql
userdefinedfunction_sql
macrooverloads_sql
macrooverload_sql
joinhint_sql
kwarg_sql
when_sql
whens_sql
merge_sql
tochar_sql
tonumber_sql
dictproperty_sql
dictrange_sql
dictsubproperty_sql
aggregatekeyproperty_sql
duplicatekeyproperty_sql
uniquekeyproperty_sql
distributedbyproperty_sql
oncluster_sql
clusteredbyproperty_sql
anyvalue_sql
querytransform_sql
indexconstraintoption_sql
checkcolumnconstraint_sql
indexcolumnconstraint_sql
nvl2_sql
nthvalue_sql
comprehension_sql
columnprefix_sql
opclass_sql
predict_sql
generateembedding_sql
generatetext_sql
generatetable_sql
generatebool_sql
generateint_sql
generatedouble_sql
mltranslate_sql
mlforecast_sql
aiforecast_sql
featuresattime_sql
vectorsearch_sql
forin_sql
refresh_sql
toarray_sql
tsordstotime_sql
tsordstotimestamp_sql
tsordstodatetime_sql
tsordstodate_sql
unixdate_sql
lastday_sql
dateadd_sql
arrayinsert_sql
arrayany_sql
struct_sql
partitionrange_sql
truncatetable_sql
convert_sql
copyparameter_sql
credentials_sql
copy_sql
semicolon_sql
datadeletionproperty_sql
maskingpolicycolumnconstraint_sql
gapfill_sql
scope_resolution
scoperesolution_sql
parsejson_sql
rand_sql
changes_sql
pad_sql
summarize_sql
explodinggenerateseries_sql
converttimezone_sql
json_sql
jsonvalue_sql
skipjsoncolumn_sql
conditionalinsert_sql
multitableinserts_sql
oncondition_sql
jsonextractquote_sql
jsonexists_sql
min_sql
max_sql
arrayagg_sql
timeslice_sql
slice_sql
apply_sql
grant_sql
revoke_sql
grantprivilege_sql
grantprincipal_sql
columns_sql
overlay_sql
todouble_sql
string_sql
median_sql
overflowtruncatebehavior_sql
unixseconds_sql
arraysort_sql
arraysize_sql
attach_sql
detach_sql
attachoption_sql
watermarkcolumnconstraint_sql
encodeproperty_sql
includeproperty_sql
xmlelement_sql
xmlkeyvalueoption_sql
partitionbyrangeproperty_sql
partitionbyrangepropertydynamic_sql
unpivotcolumns_sql
analyzesample_sql
analyzestatistics_sql
analyzehistogram_sql
analyzedelete_sql
analyzelistchainedrows_sql
analyzevalidate_sql
analyze_sql
xmltable_sql
xmlnamespace_sql
export_sql
declare_sql
declareitem_sql
recursivewithsearch_sql
parameterizedagg_sql
anonymousaggfunc_sql
combinedaggfunc_sql
combinedparameterizedagg_sql
show_sql
install_sql
liststage_sql
get_put_sql
translatecharacters_sql
decodecase_sql
semanticview_sql
getextract_sql
datefromunixdate_sql
space_sql
buildproperty_sql
refreshtriggerproperty_sql
modelattribute_sql
directorystage_sql
uuid_sql
initcap_sql
localtime_sql
localtimestamp_sql
weekstart_name
weekstart_sql
chr_sql
weightstring_sql
block_sql
functionspecification_sql
storedprocedure_sql
ifblock_sql
casestatement_sql
whileblock_sql
loopblock_sql
repeatblock_sql
leave_sql
iterate_sql
execute_sql
executesql_sql
altermodifysqlsecurity_sql
usingproperty_sql
renameindex_sql
sqlglot.generators.postgres.PostgresGenerator
SELECT_KINDS
TRY_SUPPORTED
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
star_sql
with_properties
schemacommentproperty_sql
commentcolumnconstraint_sql
columndef_sql
bracket_sql
matchagainst_sql
computedcolumnconstraint_sql
isascii_sql
regexplike_sql
currentschema_sql
interval_sql
placeholder_sql