Edit on GitHub

sqlglot.dialects.postgres

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

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"
class Postgres.Generator(sqlglot.generator.Generator):
283    class Generator(generator.Generator):
284        LOCKING_READS_SUPPORTED = True
285        PARAMETER_TOKEN = "$"
286
287        TYPE_MAPPING = {
288            **generator.Generator.TYPE_MAPPING,  # type: ignore
289            exp.DataType.Type.TINYINT: "SMALLINT",
290            exp.DataType.Type.FLOAT: "REAL",
291            exp.DataType.Type.DOUBLE: "DOUBLE PRECISION",
292            exp.DataType.Type.BINARY: "BYTEA",
293            exp.DataType.Type.VARBINARY: "BYTEA",
294            exp.DataType.Type.DATETIME: "TIMESTAMP",
295        }
296
297        TRANSFORMS = {
298            **generator.Generator.TRANSFORMS,  # type: ignore
299            exp.BitwiseXor: lambda self, e: self.binary(e, "#"),
300            exp.ColumnDef: preprocess(
301                [
302                    _auto_increment_to_serial,
303                    _serial_to_generated,
304                ],
305                delegate("columndef_sql"),
306            ),
307            exp.JSONExtract: arrow_json_extract_sql,
308            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
309            exp.JSONBExtract: lambda self, e: self.binary(e, "#>"),
310            exp.JSONBExtractScalar: lambda self, e: self.binary(e, "#>>"),
311            exp.JSONBContains: lambda self, e: self.binary(e, "?"),
312            exp.Pow: lambda self, e: self.binary(e, "^"),
313            exp.CurrentDate: no_paren_current_date_sql,
314            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
315            exp.DateAdd: _date_add_sql("+"),
316            exp.DateSub: _date_add_sql("-"),
317            exp.DateDiff: _date_diff_sql,
318            exp.LogicalOr: rename_func("BOOL_OR"),
319            exp.LogicalAnd: rename_func("BOOL_AND"),
320            exp.Max: max_or_greatest,
321            exp.Min: min_or_least,
322            exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"),
323            exp.ArrayContains: lambda self, e: self.binary(e, "@>"),
324            exp.ArrayContained: lambda self, e: self.binary(e, "<@"),
325            exp.RegexpLike: lambda self, e: self.binary(e, "~"),
326            exp.RegexpILike: lambda self, e: self.binary(e, "~*"),
327            exp.StrPosition: str_position_sql,
328            exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})",
329            exp.Substring: _substring_sql,
330            exp.TimestampTrunc: timestamptrunc_sql,
331            exp.TimeStrToTime: lambda self, e: f"CAST({self.sql(e, 'this')} AS TIMESTAMP)",
332            exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})",
333            exp.TableSample: no_tablesample_sql,
334            exp.ToChar: lambda self, e: self.function_fallback_sql(e),
335            exp.Trim: trim_sql,
336            exp.TryCast: no_trycast_sql,
337            exp.UnixToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')})",
338            exp.DataType: _datatype_sql,
339            exp.GroupConcat: _string_agg_sql,
340            exp.Array: lambda self, e: f"{self.normalize_func('ARRAY')}({self.sql(e.expressions[0])})"
341            if isinstance(seq_get(e.expressions, 0), exp.Select)
342            else f"{self.normalize_func('ARRAY')}[{self.expressions(e, flat=True)}]",
343        }
344
345        PROPERTIES_LOCATION = {
346            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
347            exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
348        }

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