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

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

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

    25    class Parser(Postgres.Parser):
    26        FUNCTIONS = {
    27            **Postgres.Parser.FUNCTIONS,
    28            "DATEADD": lambda args: exp.DateAdd(
    29                this=exp.TsOrDsToDate(this=seq_get(args, 2)),
    30                expression=seq_get(args, 1),
    31                unit=seq_get(args, 0),
    32            ),
    33            "DATEDIFF": lambda args: exp.DateDiff(
    34                this=exp.TsOrDsToDate(this=seq_get(args, 2)),
    35                expression=exp.TsOrDsToDate(this=seq_get(args, 1)),
    36                unit=seq_get(args, 0),
    37            ),
    38            "NVL": exp.Coalesce.from_arg_list,
    39            "STRTOL": exp.FromBase.from_arg_list,
    40        }
    41
    42        CONVERT_TYPE_FIRST = True
    43
    44        def _parse_types(
    45            self, check_func: bool = False, schema: bool = False
    46        ) -> t.Optional[exp.Expression]:
    47            this = super()._parse_types(check_func=check_func, schema=schema)
    48
    49            if (
    50                isinstance(this, exp.DataType)
    51                and this.is_type("varchar")
    52                and this.expressions
    53                and this.expressions[0].this == exp.column("MAX")
    54            ):
    55                this.set("expressions", [exp.var("MAX")])
    56
    57            return this

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

###### Arguments:

- error_level: The desired error level. Default: ErrorLevel.IMMEDIATE
- error_message_context: Determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 100
- 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

##### 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

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

##### Inherited Members

sqlglot.tokens.Tokenizer
  reset
  tokenize
  peek

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

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

Generator converts a given syntax tree to the corresponding SQL string.

###### Arguments:

- pretty: Whether or not 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 or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether or not to normalize identifiers to lowercase. Default: False.
- pad: Determines the pad size in a formatted string. Default: 2.
- indent: Determines the indentation size in a formatted string. Default: 2.
- normalize_functions: Whether or not to normalize all 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: Determines whether or not 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 or not to preserve comments in the output SQL code. Default: True

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

    125        def values_sql(self, expression: exp.Values) -> str:
    126            """
    127            Converts `VALUES...` expression into a series of unions.
    128
    129            Note: If you have a lot of unions then this will result in a large number of recursive statements to
    130            evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    131            very slow.
    132            """
    133
    134            # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    135            if not expression.find_ancestor(exp.From, exp.Join):
    136                return super().values_sql(expression)
    137
    138            column_names = expression.alias and expression.args["alias"].columns
    139
    140            selects = []
    141            rows = [tuple_exp.expressions for tuple_exp in expression.expressions]
    142
    143            for i, row in enumerate(rows):
    144                if i == 0 and column_names:
    145                    row = [
    146                        exp.alias_(value, column_name)
    147                        for value, column_name in zip(row, column_names)
    148                    ]
    149
    150                selects.append(exp.Select(expressions=row))
    151
    152            subquery_expression: exp.Select | exp.Union = selects[0]
    153            if len(selects) > 1:
    154                for select in selects[1:]:
    155                    subquery_expression = exp.union(subquery_expression, select, distinct=False)
    156
    157            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

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

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

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

    163        def datatype_sql(self, expression: exp.DataType) -> str:
    164            """
    165            Redshift converts the `TEXT` data type to `VARCHAR(255)` by default when people more generally mean
    166            VARCHAR of max length which is `VARCHAR(max)` in Redshift. Therefore if we get a `TEXT` data type
    167            without precision we convert it to `VARCHAR(max)` and if it does have precision then we just convert
    168            `TEXT` to `VARCHAR`.
    169            """
    170            if expression.is_type("text"):
    171                expression = expression.copy()
    172                expression.set("this", exp.DataType.Type.VARCHAR)
    173                precision = expression.args.get("expressions")
    174
    175                if not precision:
    176                    expression.append("expressions", exp.var("MAX"))
    177
    178            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
  createable_sql
  create_sql
  clone_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  bytestring_sql
  rawstring_sql
  datatypesize_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
  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
  offset_limit_modifiers
  after_having_modifiers
  after_limit_modifiers
  select_sql
  schema_sql
  schema_columns_sql
  star_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
  safeconcat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  jsonobject_sql
  openjsoncolumndef_sql
  openjson_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
  mergetreettlaction_sql
  mergetreettl_sql
  transaction_sql
  commit_sql
  rollback_sql
  altercolumn_sql
  renametable_sql
  altertable_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  safedpipe_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
  dictproperty_sql
  dictrange_sql
  dictsubproperty_sql
  oncluster_sql