sqlglot.dialects.redshift API documentation

Edit on GitHub

# sqlglot.dialects.redshift

View Source

      1from __future__ import annotations
      2
      3import typing as t
      4
      5from sqlglot import exp, transforms
      6from sqlglot.dialects.dialect import rename_func
      7from sqlglot.dialects.postgres import Postgres
      8from sqlglot.helper import seq_get
      9from sqlglot.tokens import TokenType
     10
     11
     12class Redshift(Postgres):
     13    time_format = "'YYYY-MM-DD HH:MI:SS'"
     14    time_mapping = {
     15        **Postgres.time_mapping,  # type: ignore
     16        "MON": "%b",
     17        "HH": "%H",
     18    }
     19
     20    class Parser(Postgres.Parser):
     21        FUNCTIONS = {
     22            **Postgres.Parser.FUNCTIONS,  # type: ignore
     23            "DATEADD": lambda args: exp.DateAdd(
     24                this=seq_get(args, 2),
     25                expression=seq_get(args, 1),
     26                unit=seq_get(args, 0),
     27            ),
     28            "DATEDIFF": lambda args: exp.DateDiff(
     29                this=seq_get(args, 2),
     30                expression=seq_get(args, 1),
     31                unit=seq_get(args, 0),
     32            ),
     33            "DECODE": exp.Matches.from_arg_list,
     34            "NVL": exp.Coalesce.from_arg_list,
     35        }
     36
     37        CONVERT_TYPE_FIRST = True
     38
     39        def _parse_types(self, check_func: bool = False) -> t.Optional[exp.Expression]:
     40            this = super()._parse_types(check_func=check_func)
     41
     42            if (
     43                isinstance(this, exp.DataType)
     44                and this.this == exp.DataType.Type.VARCHAR
     45                and this.expressions
     46                and this.expressions[0] == exp.column("MAX")
     47            ):
     48                this.set("expressions", [exp.Var(this="MAX")])
     49
     50            return this
     51
     52    class Tokenizer(Postgres.Tokenizer):
     53        STRING_ESCAPES = ["\\"]
     54
     55        KEYWORDS = {
     56            **Postgres.Tokenizer.KEYWORDS,  # type: ignore
     57            "GEOMETRY": TokenType.GEOMETRY,
     58            "GEOGRAPHY": TokenType.GEOGRAPHY,
     59            "HLLSKETCH": TokenType.HLLSKETCH,
     60            "SUPER": TokenType.SUPER,
     61            "TIME": TokenType.TIMESTAMP,
     62            "TIMETZ": TokenType.TIMESTAMPTZ,
     63            "TOP": TokenType.TOP,
     64            "UNLOAD": TokenType.COMMAND,
     65            "VARBYTE": TokenType.VARBINARY,
     66        }
     67
     68    class Generator(Postgres.Generator):
     69        TYPE_MAPPING = {
     70            **Postgres.Generator.TYPE_MAPPING,  # type: ignore
     71            exp.DataType.Type.BINARY: "VARBYTE",
     72            exp.DataType.Type.VARBINARY: "VARBYTE",
     73            exp.DataType.Type.INT: "INTEGER",
     74        }
     75
     76        PROPERTIES_LOCATION = {
     77            **Postgres.Generator.PROPERTIES_LOCATION,  # type: ignore
     78            exp.LikeProperty: exp.Properties.Location.POST_WITH,
     79        }
     80
     81        TRANSFORMS = {
     82            **Postgres.Generator.TRANSFORMS,  # type: ignore
     83            **transforms.ELIMINATE_DISTINCT_ON,  # type: ignore
     84            exp.DateAdd: lambda self, e: self.func(
     85                "DATEADD", exp.var(e.text("unit") or "day"), e.expression, e.this
     86            ),
     87            exp.DateDiff: lambda self, e: self.func(
     88                "DATEDIFF", exp.var(e.text("unit") or "day"), e.expression, e.this
     89            ),
     90            exp.DistKeyProperty: lambda self, e: f"DISTKEY({e.name})",
     91            exp.DistStyleProperty: lambda self, e: self.naked_property(e),
     92            exp.Matches: rename_func("DECODE"),
     93            exp.SortKeyProperty: lambda self, e: f"{'COMPOUND ' if e.args['compound'] else ''}SORTKEY({self.format_args(*e.this)})",
     94        }
     95
     96        # Redshift uses the POW | POWER (expr1, expr2) syntax instead of expr1 ^ expr2 (postgres)
     97        TRANSFORMS.pop(exp.Pow)
     98
     99        def values_sql(self, expression: exp.Values) -> str:
    100            """
    101            Converts `VALUES...` expression into a series of unions.
    102
    103            Note: If you have a lot of unions then this will result in a large number of recursive statements to
    104            evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    105            very slow.
    106            """
    107            if not isinstance(expression.unnest().parent, exp.From):
    108                return super().values_sql(expression)
    109            rows = [tuple_exp.expressions for tuple_exp in expression.expressions]
    110            selects = []
    111            for i, row in enumerate(rows):
    112                if i == 0 and expression.alias:
    113                    row = [
    114                        exp.alias_(value, column_name)
    115                        for value, column_name in zip(row, expression.args["alias"].args["columns"])
    116                    ]
    117                selects.append(exp.Select(expressions=row))
    118            subquery_expression = selects[0]
    119            if len(selects) > 1:
    120                for select in selects[1:]:
    121                    subquery_expression = exp.union(subquery_expression, select, distinct=False)
    122            return self.subquery_sql(subquery_expression.subquery(expression.alias))
    123
    124        def with_properties(self, properties: exp.Properties) -> str:
    125            """Redshift doesn't have `WITH` as part of their with_properties so we remove it"""
    126            return self.properties(properties, prefix=" ", suffix="")
    127
    128        def renametable_sql(self, expression: exp.RenameTable) -> str:
    129            """Redshift only supports defining the table name itself (not the db) when renaming tables"""
    130            expression = expression.copy()
    131            target_table = expression.this
    132            for arg in target_table.args:
    133                if arg != "this":
    134                    target_table.set(arg, None)
    135            this = self.sql(expression, "this")
    136            return f"RENAME TO {this}"
    137
    138        def datatype_sql(self, expression: exp.DataType) -> str:
    139            """
    140            Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
    141            VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
    142            without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
    143            `TEXT` to `VARCHAR`.
    144            """
    145            if expression.this == exp.DataType.Type.TEXT:
    146                expression = expression.copy()
    147                expression.set("this", exp.DataType.Type.VARCHAR)
    148                precision = expression.args.get("expressions")
    149                if not precision:
    150                    expression.append("expressions", exp.Var(this="MAX"))
    151            return super().datatype_sql(expression)

class Redshift(sqlglot.dialects.postgres.Postgres): View Source

     13class Redshift(Postgres):
     14    time_format = "'YYYY-MM-DD HH:MI:SS'"
     15    time_mapping = {
     16        **Postgres.time_mapping,  # type: ignore
     17        "MON": "%b",
     18        "HH": "%H",
     19    }
     20
     21    class Parser(Postgres.Parser):
     22        FUNCTIONS = {
     23            **Postgres.Parser.FUNCTIONS,  # type: ignore
     24            "DATEADD": lambda args: exp.DateAdd(
     25                this=seq_get(args, 2),
     26                expression=seq_get(args, 1),
     27                unit=seq_get(args, 0),
     28            ),
     29            "DATEDIFF": lambda args: exp.DateDiff(
     30                this=seq_get(args, 2),
     31                expression=seq_get(args, 1),
     32                unit=seq_get(args, 0),
     33            ),
     34            "DECODE": exp.Matches.from_arg_list,
     35            "NVL": exp.Coalesce.from_arg_list,
     36        }
     37
     38        CONVERT_TYPE_FIRST = True
     39
     40        def _parse_types(self, check_func: bool = False) -> t.Optional[exp.Expression]:
     41            this = super()._parse_types(check_func=check_func)
     42
     43            if (
     44                isinstance(this, exp.DataType)
     45                and this.this == exp.DataType.Type.VARCHAR
     46                and this.expressions
     47                and this.expressions[0] == exp.column("MAX")
     48            ):
     49                this.set("expressions", [exp.Var(this="MAX")])
     50
     51            return this
     52
     53    class Tokenizer(Postgres.Tokenizer):
     54        STRING_ESCAPES = ["\\"]
     55
     56        KEYWORDS = {
     57            **Postgres.Tokenizer.KEYWORDS,  # type: ignore
     58            "GEOMETRY": TokenType.GEOMETRY,
     59            "GEOGRAPHY": TokenType.GEOGRAPHY,
     60            "HLLSKETCH": TokenType.HLLSKETCH,
     61            "SUPER": TokenType.SUPER,
     62            "TIME": TokenType.TIMESTAMP,
     63            "TIMETZ": TokenType.TIMESTAMPTZ,
     64            "TOP": TokenType.TOP,
     65            "UNLOAD": TokenType.COMMAND,
     66            "VARBYTE": TokenType.VARBINARY,
     67        }
     68
     69    class Generator(Postgres.Generator):
     70        TYPE_MAPPING = {
     71            **Postgres.Generator.TYPE_MAPPING,  # type: ignore
     72            exp.DataType.Type.BINARY: "VARBYTE",
     73            exp.DataType.Type.VARBINARY: "VARBYTE",
     74            exp.DataType.Type.INT: "INTEGER",
     75        }
     76
     77        PROPERTIES_LOCATION = {
     78            **Postgres.Generator.PROPERTIES_LOCATION,  # type: ignore
     79            exp.LikeProperty: exp.Properties.Location.POST_WITH,
     80        }
     81
     82        TRANSFORMS = {
     83            **Postgres.Generator.TRANSFORMS,  # type: ignore
     84            **transforms.ELIMINATE_DISTINCT_ON,  # type: ignore
     85            exp.DateAdd: lambda self, e: self.func(
     86                "DATEADD", exp.var(e.text("unit") or "day"), e.expression, e.this
     87            ),
     88            exp.DateDiff: lambda self, e: self.func(
     89                "DATEDIFF", exp.var(e.text("unit") or "day"), e.expression, e.this
     90            ),
     91            exp.DistKeyProperty: lambda self, e: f"DISTKEY({e.name})",
     92            exp.DistStyleProperty: lambda self, e: self.naked_property(e),
     93            exp.Matches: rename_func("DECODE"),
     94            exp.SortKeyProperty: lambda self, e: f"{'COMPOUND ' if e.args['compound'] else ''}SORTKEY({self.format_args(*e.this)})",
     95        }
     96
     97        # Redshift uses the POW | POWER (expr1, expr2) syntax instead of expr1 ^ expr2 (postgres)
     98        TRANSFORMS.pop(exp.Pow)
     99
    100        def values_sql(self, expression: exp.Values) -> str:
    101            """
    102            Converts `VALUES...` expression into a series of unions.
    103
    104            Note: If you have a lot of unions then this will result in a large number of recursive statements to
    105            evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    106            very slow.
    107            """
    108            if not isinstance(expression.unnest().parent, exp.From):
    109                return super().values_sql(expression)
    110            rows = [tuple_exp.expressions for tuple_exp in expression.expressions]
    111            selects = []
    112            for i, row in enumerate(rows):
    113                if i == 0 and expression.alias:
    114                    row = [
    115                        exp.alias_(value, column_name)
    116                        for value, column_name in zip(row, expression.args["alias"].args["columns"])
    117                    ]
    118                selects.append(exp.Select(expressions=row))
    119            subquery_expression = selects[0]
    120            if len(selects) > 1:
    121                for select in selects[1:]:
    122                    subquery_expression = exp.union(subquery_expression, select, distinct=False)
    123            return self.subquery_sql(subquery_expression.subquery(expression.alias))
    124
    125        def with_properties(self, properties: exp.Properties) -> str:
    126            """Redshift doesn't have `WITH` as part of their with_properties so we remove it"""
    127            return self.properties(properties, prefix=" ", suffix="")
    128
    129        def renametable_sql(self, expression: exp.RenameTable) -> str:
    130            """Redshift only supports defining the table name itself (not the db) when renaming tables"""
    131            expression = expression.copy()
    132            target_table = expression.this
    133            for arg in target_table.args:
    134                if arg != "this":
    135                    target_table.set(arg, None)
    136            this = self.sql(expression, "this")
    137            return f"RENAME TO {this}"
    138
    139        def datatype_sql(self, expression: exp.DataType) -> str:
    140            """
    141            Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
    142            VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
    143            without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
    144            `TEXT` to `VARCHAR`.
    145            """
    146            if expression.this == exp.DataType.Type.TEXT:
    147                expression = expression.copy()
    148                expression.set("this", exp.DataType.Type.VARCHAR)
    149                precision = expression.args.get("expressions")
    150                if not precision:
    151                    expression.append("expressions", exp.Var(this="MAX"))
    152            return super().datatype_sql(expression)

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  get_or_raise
  format_time
  parse
  parse_into
  generate
  transpile
  tokenize
  parser
  generator

class Redshift.Parser(sqlglot.dialects.postgres.Postgres.Parser): View Source

    21    class Parser(Postgres.Parser):
    22        FUNCTIONS = {
    23            **Postgres.Parser.FUNCTIONS,  # type: ignore
    24            "DATEADD": lambda args: exp.DateAdd(
    25                this=seq_get(args, 2),
    26                expression=seq_get(args, 1),
    27                unit=seq_get(args, 0),
    28            ),
    29            "DATEDIFF": lambda args: exp.DateDiff(
    30                this=seq_get(args, 2),
    31                expression=seq_get(args, 1),
    32                unit=seq_get(args, 0),
    33            ),
    34            "DECODE": exp.Matches.from_arg_list,
    35            "NVL": exp.Coalesce.from_arg_list,
    36        }
    37
    38        CONVERT_TYPE_FIRST = True
    39
    40        def _parse_types(self, check_func: bool = False) -> t.Optional[exp.Expression]:
    41            this = super()._parse_types(check_func=check_func)
    42
    43            if (
    44                isinstance(this, exp.DataType)
    45                and this.this == exp.DataType.Type.VARCHAR
    46                and this.expressions
    47                and this.expressions[0] == exp.column("MAX")
    48            ):
    49                this.set("expressions", [exp.Var(this="MAX")])
    50
    51            return this

Parser consumes a list of tokens produced by the `sqlglot.tokens.Tokenizer` and produces a parsed syntax tree.

###### Arguments:

- error_level: the desired error level. Default: ErrorLevel.RAISE
- error_message_context: determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 50.
- index_offset: Index offset for arrays eg ARRAY[0] vs ARRAY[1] as the head of a list. Default: 0
- alias_post_tablesample: If the table alias comes after tablesample. Default: False
- max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
- null_ordering: Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"

##### Inherited Members

sqlglot.parser.Parser
  Parser
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression

class Redshift.Tokenizer(sqlglot.dialects.postgres.Postgres.Tokenizer): View Source

    53    class Tokenizer(Postgres.Tokenizer):
    54        STRING_ESCAPES = ["\\"]
    55
    56        KEYWORDS = {
    57            **Postgres.Tokenizer.KEYWORDS,  # type: ignore
    58            "GEOMETRY": TokenType.GEOMETRY,
    59            "GEOGRAPHY": TokenType.GEOGRAPHY,
    60            "HLLSKETCH": TokenType.HLLSKETCH,
    61            "SUPER": TokenType.SUPER,
    62            "TIME": TokenType.TIMESTAMP,
    63            "TIMETZ": TokenType.TIMESTAMPTZ,
    64            "TOP": TokenType.TOP,
    65            "UNLOAD": TokenType.COMMAND,
    66            "VARBYTE": TokenType.VARBINARY,
    67        }

##### Inherited Members

sqlglot.tokens.Tokenizer
  reset
  tokenize

class Redshift.Generator(sqlglot.dialects.postgres.Postgres.Generator): View Source

     69    class Generator(Postgres.Generator):
     70        TYPE_MAPPING = {
     71            **Postgres.Generator.TYPE_MAPPING,  # type: ignore
     72            exp.DataType.Type.BINARY: "VARBYTE",
     73            exp.DataType.Type.VARBINARY: "VARBYTE",
     74            exp.DataType.Type.INT: "INTEGER",
     75        }
     76
     77        PROPERTIES_LOCATION = {
     78            **Postgres.Generator.PROPERTIES_LOCATION,  # type: ignore
     79            exp.LikeProperty: exp.Properties.Location.POST_WITH,
     80        }
     81
     82        TRANSFORMS = {
     83            **Postgres.Generator.TRANSFORMS,  # type: ignore
     84            **transforms.ELIMINATE_DISTINCT_ON,  # type: ignore
     85            exp.DateAdd: lambda self, e: self.func(
     86                "DATEADD", exp.var(e.text("unit") or "day"), e.expression, e.this
     87            ),
     88            exp.DateDiff: lambda self, e: self.func(
     89                "DATEDIFF", exp.var(e.text("unit") or "day"), e.expression, e.this
     90            ),
     91            exp.DistKeyProperty: lambda self, e: f"DISTKEY({e.name})",
     92            exp.DistStyleProperty: lambda self, e: self.naked_property(e),
     93            exp.Matches: rename_func("DECODE"),
     94            exp.SortKeyProperty: lambda self, e: f"{'COMPOUND ' if e.args['compound'] else ''}SORTKEY({self.format_args(*e.this)})",
     95        }
     96
     97        # Redshift uses the POW | POWER (expr1, expr2) syntax instead of expr1 ^ expr2 (postgres)
     98        TRANSFORMS.pop(exp.Pow)
     99
    100        def values_sql(self, expression: exp.Values) -> str:
    101            """
    102            Converts `VALUES...` expression into a series of unions.
    103
    104            Note: If you have a lot of unions then this will result in a large number of recursive statements to
    105            evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    106            very slow.
    107            """
    108            if not isinstance(expression.unnest().parent, exp.From):
    109                return super().values_sql(expression)
    110            rows = [tuple_exp.expressions for tuple_exp in expression.expressions]
    111            selects = []
    112            for i, row in enumerate(rows):
    113                if i == 0 and expression.alias:
    114                    row = [
    115                        exp.alias_(value, column_name)
    116                        for value, column_name in zip(row, expression.args["alias"].args["columns"])
    117                    ]
    118                selects.append(exp.Select(expressions=row))
    119            subquery_expression = selects[0]
    120            if len(selects) > 1:
    121                for select in selects[1:]:
    122                    subquery_expression = exp.union(subquery_expression, select, distinct=False)
    123            return self.subquery_sql(subquery_expression.subquery(expression.alias))
    124
    125        def with_properties(self, properties: exp.Properties) -> str:
    126            """Redshift doesn't have `WITH` as part of their with_properties so we remove it"""
    127            return self.properties(properties, prefix=" ", suffix="")
    128
    129        def renametable_sql(self, expression: exp.RenameTable) -> str:
    130            """Redshift only supports defining the table name itself (not the db) when renaming tables"""
    131            expression = expression.copy()
    132            target_table = expression.this
    133            for arg in target_table.args:
    134                if arg != "this":
    135                    target_table.set(arg, None)
    136            this = self.sql(expression, "this")
    137            return f"RENAME TO {this}"
    138
    139        def datatype_sql(self, expression: exp.DataType) -> str:
    140            """
    141            Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
    142            VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
    143            without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
    144            `TEXT` to `VARCHAR`.
    145            """
    146            if expression.this == exp.DataType.Type.TEXT:
    147                expression = expression.copy()
    148                expression.set("this", exp.DataType.Type.VARCHAR)
    149                precision = expression.args.get("expressions")
    150                if not precision:
    151                    expression.append("expressions", exp.Var(this="MAX"))
    152            return super().datatype_sql(expression)

Generator interprets the given syntax tree and produces a SQL string as an output.

###### Arguments:

- time_mapping (dict): the dictionary of custom time mappings in which the key represents a python time format and the output the target time format
- time_trie (trie): a trie of the time_mapping keys
- pretty (bool): if set to True the returned string will be formatted. Default: False.
- quote_start (str): specifies which starting character to use to delimit quotes. Default: '.
- quote_end (str): specifies which ending character to use to delimit quotes. Default: '.
- identifier_start (str): specifies which starting character to use to delimit identifiers. Default: ".
- identifier_end (str): specifies which ending character to use to delimit identifiers. Default: ".
- identify (bool | str): 'always': always quote, 'safe': quote identifiers if they don't contain an upcase, True defaults to always.
- normalize (bool): if set to True all identifiers will lower cased
- string_escape (str): specifies a string escape character. Default: '.
- identifier_escape (str): specifies an identifier escape character. Default: ".
- pad (int): determines padding in a formatted string. Default: 2.
- indent (int): determines the size of indentation in a formatted string. Default: 4.
- unnest_column_only (bool): if true unnest table aliases are considered only as column aliases
- normalize_functions (str): normalize function names, "upper", "lower", or None Default: "upper"
- alias_post_tablesample (bool): if the table alias comes after tablesample Default: False
- unsupported_level (ErrorLevel): determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- null_ordering (str): Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
- max_unsupported (int): 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 (bool): if the the comma is leading or trailing in select statements Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether or not to preserve comments in the output SQL code. Default: True

def values_sql(self, expression: sqlglot.expressions.Values) -> str: View Source

    100        def values_sql(self, expression: exp.Values) -> str:
    101            """
    102            Converts `VALUES...` expression into a series of unions.
    103
    104            Note: If you have a lot of unions then this will result in a large number of recursive statements to
    105            evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    106            very slow.
    107            """
    108            if not isinstance(expression.unnest().parent, exp.From):
    109                return super().values_sql(expression)
    110            rows = [tuple_exp.expressions for tuple_exp in expression.expressions]
    111            selects = []
    112            for i, row in enumerate(rows):
    113                if i == 0 and expression.alias:
    114                    row = [
    115                        exp.alias_(value, column_name)
    116                        for value, column_name in zip(row, expression.args["alias"].args["columns"])
    117                    ]
    118                selects.append(exp.Select(expressions=row))
    119            subquery_expression = selects[0]
    120            if len(selects) > 1:
    121                for select in selects[1:]:
    122                    subquery_expression = exp.union(subquery_expression, select, distinct=False)
    123            return self.subquery_sql(subquery_expression.subquery(expression.alias))

Converts `VALUES...` expression into a series of unions.

Note: If you have a lot of unions then this will result in a large number of recursive statements to evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be very slow.

def with_properties(self, properties: sqlglot.expressions.Properties) -> str: View Source

    125        def with_properties(self, properties: exp.Properties) -> str:
    126            """Redshift doesn't have `WITH` as part of their with_properties so we remove it"""
    127            return self.properties(properties, prefix=" ", suffix="")

Redshift doesn't have `WITH` as part of their with_properties so we remove it

def renametable_sql(self, expression: sqlglot.expressions.RenameTable) -> str: View Source

    129        def renametable_sql(self, expression: exp.RenameTable) -> str:
    130            """Redshift only supports defining the table name itself (not the db) when renaming tables"""
    131            expression = expression.copy()
    132            target_table = expression.this
    133            for arg in target_table.args:
    134                if arg != "this":
    135                    target_table.set(arg, None)
    136            this = self.sql(expression, "this")
    137            return f"RENAME TO {this}"

Redshift only supports defining the table name itself (not the db) when renaming tables

def datatype_sql(self, expression: sqlglot.expressions.DataType) -> str: View Source

    139        def datatype_sql(self, expression: exp.DataType) -> str:
    140            """
    141            Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
    142            VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
    143            without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
    144            `TEXT` to `VARCHAR`.
    145            """
    146            if expression.this == exp.DataType.Type.TEXT:
    147                expression = expression.copy()
    148                expression.set("this", exp.DataType.Type.VARCHAR)
    149                precision = expression.args.get("expressions")
    150                if not precision:
    151                    expression.append("expressions", exp.Var(this="MAX"))
    152            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`.

##### Inherited Members

sqlglot.generator.Generator
  Generator
  generate
  unsupported
  sep
  seg
  pad_comment
  maybe_comment
  wrap
  no_identify
  normalize_func
  indent
  sql
  uncache_sql
  cache_sql
  characterset_sql
  column_sql
  columndef_sql
  columnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  create_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  locate_properties
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  afterjournalproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  pseudotype_sql
  returning_sql
  rowformatdelimitedproperty_sql
  table_sql
  tablesample_sql
  pivot_sql
  tuple_sql
  update_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  join_sql
  lambda_sql
  lateral_sql
  limit_sql
  offset_sql
  setitem_sql
  set_sql
  pragma_sql
  lock_sql
  literal_sql
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  select_sql
  schema_sql
  star_sql
  structkwarg_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  window_spec_sql
  withingroup_sql
  between_sql
  bracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  extract_sql
  trim_sql
  concat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  unique_sql
  if_sql
  jsonkeyvalue_sql
  jsonobject_sql
  in_sql
  in_unnest_op
  interval_sql
  return_sql
  reference_sql
  anonymous_sql
  paren_sql
  neg_sql
  not_sql
  alias_sql
  aliases_sql
  attimezone_sql
  add_sql
  and_sql
  connector_sql
  bitwiseand_sql
  bitwiseleftshift_sql
  bitwisenot_sql
  bitwiseor_sql
  bitwiserightshift_sql
  bitwisexor_sql
  cast_sql
  currentdate_sql
  collate_sql
  command_sql
  comment_sql
  transaction_sql
  commit_sql
  rollback_sql
  altercolumn_sql
  altertable_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  is_sql
  like_sql
  similarto_sql
  lt_sql
  lte_sql
  mod_sql
  mul_sql
  neq_sql
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  use_sql
  binary
  function_fallback_sql
  func
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  set_operation
  tag_sql
  token_sql
  userdefinedfunction_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql
  tochar_sql