sqlglot.dialects.postgres API documentation

Edit on GitHub

# sqlglot.dialects.postgres

View Source

      1from __future__ import annotations
      2
      3from sqlglot import exp, generator, parser, tokens
      4from sqlglot.dialects.dialect import (
      5    Dialect,
      6    arrow_json_extract_scalar_sql,
      7    arrow_json_extract_sql,
      8    format_time_lambda,
      9    no_paren_current_date_sql,
     10    no_tablesample_sql,
     11    no_trycast_sql,
     12    rename_func,
     13    str_position_sql,
     14    trim_sql,
     15)
     16from sqlglot.helper import seq_get
     17from sqlglot.tokens import TokenType
     18from sqlglot.transforms import delegate, preprocess
     19
     20DATE_DIFF_FACTOR = {
     21    "MICROSECOND": " * 1000000",
     22    "MILLISECOND": " * 1000",
     23    "SECOND": "",
     24    "MINUTE": " / 60",
     25    "HOUR": " / 3600",
     26    "DAY": " / 86400",
     27}
     28
     29
     30def _date_add_sql(kind):
     31    def func(self, expression):
     32        from sqlglot.optimizer.simplify import simplify
     33
     34        this = self.sql(expression, "this")
     35        unit = self.sql(expression, "unit")
     36        expression = simplify(expression.args["expression"])
     37
     38        if not isinstance(expression, exp.Literal):
     39            self.unsupported("Cannot add non literal")
     40
     41        expression = expression.copy()
     42        expression.args["is_string"] = True
     43        return f"{this} {kind} {self.sql(exp.Interval(this=expression, unit=unit))}"
     44
     45    return func
     46
     47
     48def _date_diff_sql(self, expression):
     49    unit = expression.text("unit").upper()
     50    factor = DATE_DIFF_FACTOR.get(unit)
     51
     52    end = f"CAST({expression.this} AS TIMESTAMP)"
     53    start = f"CAST({expression.expression} AS TIMESTAMP)"
     54
     55    if factor is not None:
     56        return f"CAST(EXTRACT(epoch FROM {end} - {start}){factor} AS BIGINT)"
     57
     58    age = f"AGE({end}, {start})"
     59
     60    if unit == "WEEK":
     61        unit = f"EXTRACT(year FROM {age}) * 48 + EXTRACT(month FROM {age}) * 4 + EXTRACT(day FROM {age}) / 7"
     62    elif unit == "MONTH":
     63        unit = f"EXTRACT(year FROM {age}) * 12 + EXTRACT(month FROM {age})"
     64    elif unit == "QUARTER":
     65        unit = f"EXTRACT(year FROM {age}) * 4 + EXTRACT(month FROM {age}) / 3"
     66    elif unit == "YEAR":
     67        unit = f"EXTRACT(year FROM {age})"
     68    else:
     69        unit = age
     70
     71    return f"CAST({unit} AS BIGINT)"
     72
     73
     74def _substring_sql(self, expression):
     75    this = self.sql(expression, "this")
     76    start = self.sql(expression, "start")
     77    length = self.sql(expression, "length")
     78
     79    from_part = f" FROM {start}" if start else ""
     80    for_part = f" FOR {length}" if length else ""
     81
     82    return f"SUBSTRING({this}{from_part}{for_part})"
     83
     84
     85def _string_agg_sql(self, expression):
     86    expression = expression.copy()
     87    separator = expression.args.get("separator") or exp.Literal.string(",")
     88
     89    order = ""
     90    this = expression.this
     91    if isinstance(this, exp.Order):
     92        if this.this:
     93            this = this.this
     94            this.pop()
     95        order = self.sql(expression.this)  # Order has a leading space
     96
     97    return f"STRING_AGG({self.format_args(this, separator)}{order})"
     98
     99
    100def _datatype_sql(self, expression):
    101    if expression.this == exp.DataType.Type.ARRAY:
    102        return f"{self.expressions(expression, flat=True)}[]"
    103    return self.datatype_sql(expression)
    104
    105
    106def _auto_increment_to_serial(expression):
    107    auto = expression.find(exp.AutoIncrementColumnConstraint)
    108
    109    if auto:
    110        expression = expression.copy()
    111        expression.args["constraints"].remove(auto.parent)
    112        kind = expression.args["kind"]
    113
    114        if kind.this == exp.DataType.Type.INT:
    115            kind.replace(exp.DataType(this=exp.DataType.Type.SERIAL))
    116        elif kind.this == exp.DataType.Type.SMALLINT:
    117            kind.replace(exp.DataType(this=exp.DataType.Type.SMALLSERIAL))
    118        elif kind.this == exp.DataType.Type.BIGINT:
    119            kind.replace(exp.DataType(this=exp.DataType.Type.BIGSERIAL))
    120
    121    return expression
    122
    123
    124def _serial_to_generated(expression):
    125    kind = expression.args["kind"]
    126
    127    if kind.this == exp.DataType.Type.SERIAL:
    128        data_type = exp.DataType(this=exp.DataType.Type.INT)
    129    elif kind.this == exp.DataType.Type.SMALLSERIAL:
    130        data_type = exp.DataType(this=exp.DataType.Type.SMALLINT)
    131    elif kind.this == exp.DataType.Type.BIGSERIAL:
    132        data_type = exp.DataType(this=exp.DataType.Type.BIGINT)
    133    else:
    134        data_type = None
    135
    136    if data_type:
    137        expression = expression.copy()
    138        expression.args["kind"].replace(data_type)
    139        constraints = expression.args["constraints"]
    140        generated = exp.ColumnConstraint(kind=exp.GeneratedAsIdentityColumnConstraint(this=False))
    141        notnull = exp.ColumnConstraint(kind=exp.NotNullColumnConstraint())
    142        if notnull not in constraints:
    143            constraints.insert(0, notnull)
    144        if generated not in constraints:
    145            constraints.insert(0, generated)
    146
    147    return expression
    148
    149
    150def _generate_series(args):
    151    # The goal is to convert step values like '1 day' or INTERVAL '1 day' into INTERVAL '1' day
    152    step = seq_get(args, 2)
    153
    154    if step is None:
    155        # Postgres allows calls with just two arguments -- the "step" argument defaults to 1
    156        return exp.GenerateSeries.from_arg_list(args)
    157
    158    if step.is_string:
    159        args[2] = exp.to_interval(step.this)
    160    elif isinstance(step, exp.Interval) and not step.args.get("unit"):
    161        args[2] = exp.to_interval(step.this.this)
    162
    163    return exp.GenerateSeries.from_arg_list(args)
    164
    165
    166def _to_timestamp(args):
    167    # TO_TIMESTAMP accepts either a single double argument or (text, text)
    168    if len(args) == 1:
    169        # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TABLE
    170        return exp.UnixToTime.from_arg_list(args)
    171    # https://www.postgresql.org/docs/current/functions-formatting.html
    172    return format_time_lambda(exp.StrToTime, "postgres")(args)
    173
    174
    175class Postgres(Dialect):
    176    null_ordering = "nulls_are_large"
    177    time_format = "'YYYY-MM-DD HH24:MI:SS'"
    178    time_mapping = {
    179        "AM": "%p",
    180        "PM": "%p",
    181        "D": "%u",  # 1-based day of week
    182        "DD": "%d",  # day of month
    183        "DDD": "%j",  # zero padded day of year
    184        "FMDD": "%-d",  # - is no leading zero for Python; same for FM in postgres
    185        "FMDDD": "%-j",  # day of year
    186        "FMHH12": "%-I",  # 9
    187        "FMHH24": "%-H",  # 9
    188        "FMMI": "%-M",  # Minute
    189        "FMMM": "%-m",  # 1
    190        "FMSS": "%-S",  # Second
    191        "HH12": "%I",  # 09
    192        "HH24": "%H",  # 09
    193        "MI": "%M",  # zero padded minute
    194        "MM": "%m",  # 01
    195        "OF": "%z",  # utc offset
    196        "SS": "%S",  # zero padded second
    197        "TMDay": "%A",  # TM is locale dependent
    198        "TMDy": "%a",
    199        "TMMon": "%b",  # Sep
    200        "TMMonth": "%B",  # September
    201        "TZ": "%Z",  # uppercase timezone name
    202        "US": "%f",  # zero padded microsecond
    203        "WW": "%U",  # 1-based week of year
    204        "YY": "%y",  # 15
    205        "YYYY": "%Y",  # 2015
    206    }
    207
    208    class Tokenizer(tokens.Tokenizer):
    209        QUOTES = ["'", "$$"]
    210
    211        BIT_STRINGS = [("b'", "'"), ("B'", "'")]
    212        HEX_STRINGS = [("x'", "'"), ("X'", "'")]
    213        BYTE_STRINGS = [("e'", "'"), ("E'", "'")]
    214
    215        KEYWORDS = {
    216            **tokens.Tokenizer.KEYWORDS,
    217            "~~": TokenType.LIKE,
    218            "~~*": TokenType.ILIKE,
    219            "~*": TokenType.IRLIKE,
    220            "~": TokenType.RLIKE,
    221            "BEGIN": TokenType.COMMAND,
    222            "BEGIN TRANSACTION": TokenType.BEGIN,
    223            "BIGSERIAL": TokenType.BIGSERIAL,
    224            "CHARACTER VARYING": TokenType.VARCHAR,
    225            "COMMENT ON": TokenType.COMMAND,
    226            "DECLARE": TokenType.COMMAND,
    227            "DO": TokenType.COMMAND,
    228            "GRANT": TokenType.COMMAND,
    229            "HSTORE": TokenType.HSTORE,
    230            "JSONB": TokenType.JSONB,
    231            "REFRESH": TokenType.COMMAND,
    232            "REINDEX": TokenType.COMMAND,
    233            "RESET": TokenType.COMMAND,
    234            "REVOKE": TokenType.COMMAND,
    235            "SERIAL": TokenType.SERIAL,
    236            "SMALLSERIAL": TokenType.SMALLSERIAL,
    237            "TEMP": TokenType.TEMPORARY,
    238            "UUID": TokenType.UUID,
    239            "CSTRING": TokenType.PSEUDO_TYPE,
    240        }
    241
    242        SINGLE_TOKENS = {
    243            **tokens.Tokenizer.SINGLE_TOKENS,
    244            "$": TokenType.PARAMETER,
    245        }
    246
    247    class Parser(parser.Parser):
    248        STRICT_CAST = False
    249
    250        FUNCTIONS = {
    251            **parser.Parser.FUNCTIONS,  # type: ignore
    252            "NOW": exp.CurrentTimestamp.from_arg_list,
    253            "TO_TIMESTAMP": _to_timestamp,
    254            "TO_CHAR": format_time_lambda(exp.TimeToStr, "postgres"),
    255            "GENERATE_SERIES": _generate_series,
    256        }
    257
    258        BITWISE = {
    259            **parser.Parser.BITWISE,  # type: ignore
    260            TokenType.HASH: exp.BitwiseXor,
    261        }
    262
    263        FACTOR = {
    264            **parser.Parser.FACTOR,  # type: ignore
    265            TokenType.CARET: exp.Pow,
    266        }
    267
    268    class Generator(generator.Generator):
    269        LOCKING_READS_SUPPORTED = True
    270        PARAMETER_TOKEN = "$"
    271
    272        TYPE_MAPPING = {
    273            **generator.Generator.TYPE_MAPPING,  # type: ignore
    274            exp.DataType.Type.TINYINT: "SMALLINT",
    275            exp.DataType.Type.FLOAT: "REAL",
    276            exp.DataType.Type.DOUBLE: "DOUBLE PRECISION",
    277            exp.DataType.Type.BINARY: "BYTEA",
    278            exp.DataType.Type.VARBINARY: "BYTEA",
    279            exp.DataType.Type.DATETIME: "TIMESTAMP",
    280        }
    281
    282        TRANSFORMS = {
    283            **generator.Generator.TRANSFORMS,  # type: ignore
    284            exp.BitwiseXor: lambda self, e: self.binary(e, "#"),
    285            exp.ColumnDef: preprocess(
    286                [
    287                    _auto_increment_to_serial,
    288                    _serial_to_generated,
    289                ],
    290                delegate("columndef_sql"),
    291            ),
    292            exp.JSONExtract: arrow_json_extract_sql,
    293            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    294            exp.JSONBExtract: lambda self, e: self.binary(e, "#>"),
    295            exp.JSONBExtractScalar: lambda self, e: self.binary(e, "#>>"),
    296            exp.JSONBContains: lambda self, e: self.binary(e, "?"),
    297            exp.Pow: lambda self, e: self.binary(e, "^"),
    298            exp.CurrentDate: no_paren_current_date_sql,
    299            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    300            exp.DateAdd: _date_add_sql("+"),
    301            exp.DateSub: _date_add_sql("-"),
    302            exp.DateDiff: _date_diff_sql,
    303            exp.LogicalOr: rename_func("BOOL_OR"),
    304            exp.RegexpLike: lambda self, e: self.binary(e, "~"),
    305            exp.RegexpILike: lambda self, e: self.binary(e, "~*"),
    306            exp.StrPosition: str_position_sql,
    307            exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})",
    308            exp.Substring: _substring_sql,
    309            exp.TimeStrToTime: lambda self, e: f"CAST({self.sql(e, 'this')} AS TIMESTAMP)",
    310            exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})",
    311            exp.TableSample: no_tablesample_sql,
    312            exp.Trim: trim_sql,
    313            exp.TryCast: no_trycast_sql,
    314            exp.UnixToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')})",
    315            exp.DataType: _datatype_sql,
    316            exp.GroupConcat: _string_agg_sql,
    317            exp.Array: lambda self, e: f"{self.normalize_func('ARRAY')}({self.sql(e.expressions[0])})"
    318            if isinstance(seq_get(e.expressions, 0), exp.Select)
    319            else f"{self.normalize_func('ARRAY')}[{self.expressions(e, flat=True)}]",
    320        }

class Postgres(sqlglot.dialects.dialect.Dialect): View Source

    176class Postgres(Dialect):
    177    null_ordering = "nulls_are_large"
    178    time_format = "'YYYY-MM-DD HH24:MI:SS'"
    179    time_mapping = {
    180        "AM": "%p",
    181        "PM": "%p",
    182        "D": "%u",  # 1-based day of week
    183        "DD": "%d",  # day of month
    184        "DDD": "%j",  # zero padded day of year
    185        "FMDD": "%-d",  # - is no leading zero for Python; same for FM in postgres
    186        "FMDDD": "%-j",  # day of year
    187        "FMHH12": "%-I",  # 9
    188        "FMHH24": "%-H",  # 9
    189        "FMMI": "%-M",  # Minute
    190        "FMMM": "%-m",  # 1
    191        "FMSS": "%-S",  # Second
    192        "HH12": "%I",  # 09
    193        "HH24": "%H",  # 09
    194        "MI": "%M",  # zero padded minute
    195        "MM": "%m",  # 01
    196        "OF": "%z",  # utc offset
    197        "SS": "%S",  # zero padded second
    198        "TMDay": "%A",  # TM is locale dependent
    199        "TMDy": "%a",
    200        "TMMon": "%b",  # Sep
    201        "TMMonth": "%B",  # September
    202        "TZ": "%Z",  # uppercase timezone name
    203        "US": "%f",  # zero padded microsecond
    204        "WW": "%U",  # 1-based week of year
    205        "YY": "%y",  # 15
    206        "YYYY": "%Y",  # 2015
    207    }
    208
    209    class Tokenizer(tokens.Tokenizer):
    210        QUOTES = ["'", "$$"]
    211
    212        BIT_STRINGS = [("b'", "'"), ("B'", "'")]
    213        HEX_STRINGS = [("x'", "'"), ("X'", "'")]
    214        BYTE_STRINGS = [("e'", "'"), ("E'", "'")]
    215
    216        KEYWORDS = {
    217            **tokens.Tokenizer.KEYWORDS,
    218            "~~": TokenType.LIKE,
    219            "~~*": TokenType.ILIKE,
    220            "~*": TokenType.IRLIKE,
    221            "~": TokenType.RLIKE,
    222            "BEGIN": TokenType.COMMAND,
    223            "BEGIN TRANSACTION": TokenType.BEGIN,
    224            "BIGSERIAL": TokenType.BIGSERIAL,
    225            "CHARACTER VARYING": TokenType.VARCHAR,
    226            "COMMENT ON": TokenType.COMMAND,
    227            "DECLARE": TokenType.COMMAND,
    228            "DO": TokenType.COMMAND,
    229            "GRANT": TokenType.COMMAND,
    230            "HSTORE": TokenType.HSTORE,
    231            "JSONB": TokenType.JSONB,
    232            "REFRESH": TokenType.COMMAND,
    233            "REINDEX": TokenType.COMMAND,
    234            "RESET": TokenType.COMMAND,
    235            "REVOKE": TokenType.COMMAND,
    236            "SERIAL": TokenType.SERIAL,
    237            "SMALLSERIAL": TokenType.SMALLSERIAL,
    238            "TEMP": TokenType.TEMPORARY,
    239            "UUID": TokenType.UUID,
    240            "CSTRING": TokenType.PSEUDO_TYPE,
    241        }
    242
    243        SINGLE_TOKENS = {
    244            **tokens.Tokenizer.SINGLE_TOKENS,
    245            "$": TokenType.PARAMETER,
    246        }
    247
    248    class Parser(parser.Parser):
    249        STRICT_CAST = False
    250
    251        FUNCTIONS = {
    252            **parser.Parser.FUNCTIONS,  # type: ignore
    253            "NOW": exp.CurrentTimestamp.from_arg_list,
    254            "TO_TIMESTAMP": _to_timestamp,
    255            "TO_CHAR": format_time_lambda(exp.TimeToStr, "postgres"),
    256            "GENERATE_SERIES": _generate_series,
    257        }
    258
    259        BITWISE = {
    260            **parser.Parser.BITWISE,  # type: ignore
    261            TokenType.HASH: exp.BitwiseXor,
    262        }
    263
    264        FACTOR = {
    265            **parser.Parser.FACTOR,  # type: ignore
    266            TokenType.CARET: exp.Pow,
    267        }
    268
    269    class Generator(generator.Generator):
    270        LOCKING_READS_SUPPORTED = True
    271        PARAMETER_TOKEN = "$"
    272
    273        TYPE_MAPPING = {
    274            **generator.Generator.TYPE_MAPPING,  # type: ignore
    275            exp.DataType.Type.TINYINT: "SMALLINT",
    276            exp.DataType.Type.FLOAT: "REAL",
    277            exp.DataType.Type.DOUBLE: "DOUBLE PRECISION",
    278            exp.DataType.Type.BINARY: "BYTEA",
    279            exp.DataType.Type.VARBINARY: "BYTEA",
    280            exp.DataType.Type.DATETIME: "TIMESTAMP",
    281        }
    282
    283        TRANSFORMS = {
    284            **generator.Generator.TRANSFORMS,  # type: ignore
    285            exp.BitwiseXor: lambda self, e: self.binary(e, "#"),
    286            exp.ColumnDef: preprocess(
    287                [
    288                    _auto_increment_to_serial,
    289                    _serial_to_generated,
    290                ],
    291                delegate("columndef_sql"),
    292            ),
    293            exp.JSONExtract: arrow_json_extract_sql,
    294            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    295            exp.JSONBExtract: lambda self, e: self.binary(e, "#>"),
    296            exp.JSONBExtractScalar: lambda self, e: self.binary(e, "#>>"),
    297            exp.JSONBContains: lambda self, e: self.binary(e, "?"),
    298            exp.Pow: lambda self, e: self.binary(e, "^"),
    299            exp.CurrentDate: no_paren_current_date_sql,
    300            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    301            exp.DateAdd: _date_add_sql("+"),
    302            exp.DateSub: _date_add_sql("-"),
    303            exp.DateDiff: _date_diff_sql,
    304            exp.LogicalOr: rename_func("BOOL_OR"),
    305            exp.RegexpLike: lambda self, e: self.binary(e, "~"),
    306            exp.RegexpILike: lambda self, e: self.binary(e, "~*"),
    307            exp.StrPosition: str_position_sql,
    308            exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})",
    309            exp.Substring: _substring_sql,
    310            exp.TimeStrToTime: lambda self, e: f"CAST({self.sql(e, 'this')} AS TIMESTAMP)",
    311            exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})",
    312            exp.TableSample: no_tablesample_sql,
    313            exp.Trim: trim_sql,
    314            exp.TryCast: no_trycast_sql,
    315            exp.UnixToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')})",
    316            exp.DataType: _datatype_sql,
    317            exp.GroupConcat: _string_agg_sql,
    318            exp.Array: lambda self, e: f"{self.normalize_func('ARRAY')}({self.sql(e.expressions[0])})"
    319            if isinstance(seq_get(e.expressions, 0), exp.Select)
    320            else f"{self.normalize_func('ARRAY')}[{self.expressions(e, flat=True)}]",
    321        }

Postgres()

##### Inherited Members

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

class Postgres.Tokenizer(sqlglot.tokens.Tokenizer): View Source

    209    class Tokenizer(tokens.Tokenizer):
    210        QUOTES = ["'", "$$"]
    211
    212        BIT_STRINGS = [("b'", "'"), ("B'", "'")]
    213        HEX_STRINGS = [("x'", "'"), ("X'", "'")]
    214        BYTE_STRINGS = [("e'", "'"), ("E'", "'")]
    215
    216        KEYWORDS = {
    217            **tokens.Tokenizer.KEYWORDS,
    218            "~~": TokenType.LIKE,
    219            "~~*": TokenType.ILIKE,
    220            "~*": TokenType.IRLIKE,
    221            "~": TokenType.RLIKE,
    222            "BEGIN": TokenType.COMMAND,
    223            "BEGIN TRANSACTION": TokenType.BEGIN,
    224            "BIGSERIAL": TokenType.BIGSERIAL,
    225            "CHARACTER VARYING": TokenType.VARCHAR,
    226            "COMMENT ON": TokenType.COMMAND,
    227            "DECLARE": TokenType.COMMAND,
    228            "DO": TokenType.COMMAND,
    229            "GRANT": TokenType.COMMAND,
    230            "HSTORE": TokenType.HSTORE,
    231            "JSONB": TokenType.JSONB,
    232            "REFRESH": TokenType.COMMAND,
    233            "REINDEX": TokenType.COMMAND,
    234            "RESET": TokenType.COMMAND,
    235            "REVOKE": TokenType.COMMAND,
    236            "SERIAL": TokenType.SERIAL,
    237            "SMALLSERIAL": TokenType.SMALLSERIAL,
    238            "TEMP": TokenType.TEMPORARY,
    239            "UUID": TokenType.UUID,
    240            "CSTRING": TokenType.PSEUDO_TYPE,
    241        }
    242
    243        SINGLE_TOKENS = {
    244            **tokens.Tokenizer.SINGLE_TOKENS,
    245            "$": TokenType.PARAMETER,
    246        }

##### Inherited Members

sqlglot.tokens.Tokenizer
  Tokenizer
  reset
  tokenize

class Postgres.Parser(sqlglot.parser.Parser): View Source

    248    class Parser(parser.Parser):
    249        STRICT_CAST = False
    250
    251        FUNCTIONS = {
    252            **parser.Parser.FUNCTIONS,  # type: ignore
    253            "NOW": exp.CurrentTimestamp.from_arg_list,
    254            "TO_TIMESTAMP": _to_timestamp,
    255            "TO_CHAR": format_time_lambda(exp.TimeToStr, "postgres"),
    256            "GENERATE_SERIES": _generate_series,
    257        }
    258
    259        BITWISE = {
    260            **parser.Parser.BITWISE,  # type: ignore
    261            TokenType.HASH: exp.BitwiseXor,
    262        }
    263
    264        FACTOR = {
    265            **parser.Parser.FACTOR,  # type: ignore
    266            TokenType.CARET: exp.Pow,
    267        }

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 Postgres.Generator(sqlglot.generator.Generator): View Source

    269    class Generator(generator.Generator):
    270        LOCKING_READS_SUPPORTED = True
    271        PARAMETER_TOKEN = "$"
    272
    273        TYPE_MAPPING = {
    274            **generator.Generator.TYPE_MAPPING,  # type: ignore
    275            exp.DataType.Type.TINYINT: "SMALLINT",
    276            exp.DataType.Type.FLOAT: "REAL",
    277            exp.DataType.Type.DOUBLE: "DOUBLE PRECISION",
    278            exp.DataType.Type.BINARY: "BYTEA",
    279            exp.DataType.Type.VARBINARY: "BYTEA",
    280            exp.DataType.Type.DATETIME: "TIMESTAMP",
    281        }
    282
    283        TRANSFORMS = {
    284            **generator.Generator.TRANSFORMS,  # type: ignore
    285            exp.BitwiseXor: lambda self, e: self.binary(e, "#"),
    286            exp.ColumnDef: preprocess(
    287                [
    288                    _auto_increment_to_serial,
    289                    _serial_to_generated,
    290                ],
    291                delegate("columndef_sql"),
    292            ),
    293            exp.JSONExtract: arrow_json_extract_sql,
    294            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    295            exp.JSONBExtract: lambda self, e: self.binary(e, "#>"),
    296            exp.JSONBExtractScalar: lambda self, e: self.binary(e, "#>>"),
    297            exp.JSONBContains: lambda self, e: self.binary(e, "?"),
    298            exp.Pow: lambda self, e: self.binary(e, "^"),
    299            exp.CurrentDate: no_paren_current_date_sql,
    300            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    301            exp.DateAdd: _date_add_sql("+"),
    302            exp.DateSub: _date_add_sql("-"),
    303            exp.DateDiff: _date_diff_sql,
    304            exp.LogicalOr: rename_func("BOOL_OR"),
    305            exp.RegexpLike: lambda self, e: self.binary(e, "~"),
    306            exp.RegexpILike: lambda self, e: self.binary(e, "~*"),
    307            exp.StrPosition: str_position_sql,
    308            exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})",
    309            exp.Substring: _substring_sql,
    310            exp.TimeStrToTime: lambda self, e: f"CAST({self.sql(e, 'this')} AS TIMESTAMP)",
    311            exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})",
    312            exp.TableSample: no_tablesample_sql,
    313            exp.Trim: trim_sql,
    314            exp.TryCast: no_trycast_sql,
    315            exp.UnixToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')})",
    316            exp.DataType: _datatype_sql,
    317            exp.GroupConcat: _string_agg_sql,
    318            exp.Array: lambda self, e: f"{self.normalize_func('ARRAY')}({self.sql(e.expressions[0])})"
    319            if isinstance(seq_get(e.expressions, 0), exp.Select)
    320            else f"{self.normalize_func('ARRAY')}[{self.expressions(e, flat=True)}]",
    321        }

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): if set to True all identifiers will be delimited by the corresponding character.
- 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

##### 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
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  create_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  datatype_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
  with_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
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  pseudotype_sql
  rowformatdelimitedproperty_sql
  table_sql
  tablesample_sql
  pivot_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  join_sql
  lambda_sql
  lateral_sql
  limit_sql
  offset_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
  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
  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
  div_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