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

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

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

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

    55    class Tokenizer(Postgres.Tokenizer):
    56        STRING_ESCAPES = ["\\"]
    57
    58        KEYWORDS = {
    59            **Postgres.Tokenizer.KEYWORDS,  # type: ignore
    60            "GEOMETRY": TokenType.GEOMETRY,
    61            "GEOGRAPHY": TokenType.GEOGRAPHY,
    62            "HLLSKETCH": TokenType.HLLSKETCH,
    63            "SUPER": TokenType.SUPER,
    64            "SYSDATE": TokenType.CURRENT_TIMESTAMP,
    65            "TIME": TokenType.TIMESTAMP,
    66            "TIMETZ": TokenType.TIMESTAMPTZ,
    67            "TOP": TokenType.TOP,
    68            "UNLOAD": TokenType.COMMAND,
    69            "VARBYTE": TokenType.VARBINARY,
    70        }
    71
    72        # Redshift allows # to appear as a table identifier prefix
    73        SINGLE_TOKENS = Postgres.Tokenizer.SINGLE_TOKENS.copy()
    74        SINGLE_TOKENS.pop("#")

##### Inherited Members

sqlglot.tokens.Tokenizer
  reset
  tokenize

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

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

    114        def values_sql(self, expression: exp.Values) -> str:
    115            """
    116            Converts `VALUES...` expression into a series of unions.
    117
    118            Note: If you have a lot of unions then this will result in a large number of recursive statements to
    119            evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    120            very slow.
    121            """
    122            if not isinstance(expression.unnest().parent, exp.From):
    123                return super().values_sql(expression)
    124            rows = [tuple_exp.expressions for tuple_exp in expression.expressions]
    125            selects = []
    126            for i, row in enumerate(rows):
    127                if i == 0 and expression.alias:
    128                    row = [
    129                        exp.alias_(value, column_name)
    130                        for value, column_name in zip(row, expression.args["alias"].args["columns"])
    131                    ]
    132                selects.append(exp.Select(expressions=row))
    133            subquery_expression = selects[0]
    134            if len(selects) > 1:
    135                for select in selects[1:]:
    136                    subquery_expression = exp.union(subquery_expression, select, distinct=False)
    137            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

    139        def with_properties(self, properties: exp.Properties) -> str:
    140            """Redshift doesn't have `WITH` as part of their with_properties so we remove it"""
    141            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

    143        def renametable_sql(self, expression: exp.RenameTable) -> str:
    144            """Redshift only supports defining the table name itself (not the db) when renaming tables"""
    145            expression = expression.copy()
    146            target_table = expression.this
    147            for arg in target_table.args:
    148                if arg != "this":
    149                    target_table.set(arg, None)
    150            this = self.sql(expression, "this")
    151            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

    153        def datatype_sql(self, expression: exp.DataType) -> str:
    154            """
    155            Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
    156            VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
    157            without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
    158            `TEXT` to `VARCHAR`.
    159            """
    160            if expression.this == exp.DataType.Type.TEXT:
    161                expression = expression.copy()
    162                expression.set("this", exp.DataType.Type.VARCHAR)
    163                precision = expression.args.get("expressions")
    164                if not precision:
    165                    expression.append("expressions", exp.Var(this="MAX"))
    166            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
  columnposition_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
  bytestring_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_sql
  inputoutputformat_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
  onconflict_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
  windowspec_sql
  withingroup_sql
  between_sql
  bracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  nextvaluefor_sql
  extract_sql
  trim_sql
  concat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  unique_sql
  if_sql
  matchagainst_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
  ilikeany_sql
  is_sql
  like_sql
  likeany_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