pglast

PostgreSQL Languages AST and statements prettifier

author

Lele Gaifax

contact

lele@metapensiero.it

license

GNU General Public License version 3 or later

version

4

This is a Python 3 module that exposes the parse tree of a PostgreSQL statement (extracted by the almost standard PG parser repackaged as a standalone static library by libpg_query) as set of interconnected nodes, usually called an abstract syntax tree.

Introduction

At the lower level the module exposes several libpg_query functions:

  1. pglast.parser.parse_sql_json()

  2. pglast.parser.parse_sql_protobuf()

  3. pglast.parser.parse_plpgsql_json()

  4. pglast.parser.fingerprint()

  5. pglast.parser.scan()

  6. pglast.parser.split()

  7. pglast.parser.deparse_protobuf()

The first two take an SQL statement and return the correspondent parse tree respectively as a JSON encoded value and a Protobuf encoded value; the third function takes a PLpgSQL statement and returns the parse tree as JSON, the fourth returns an hash of the given statement that can be used to compare different SQLs, the fifth returns a sequence of tokens that compose a SQL statement, the sixth returns a sequence of the single statements and the last one accepts a Protobuf-serialized statement and reproduce the original SQL statement.

One more function, pglast.parser.parse_sql(), is similar to parse_sql_json() but instead of JSON returns the syntax tree represented by a hierarchy of instances of the classes implemented in the pglast.ast module.

On top of that, the module implements two serializations, one that transforms a Node into a raw textual representation and another that returns a prettified <pglast.stream.IndentedStream representation. The latter is exposed by the pgpp CLI tool, see the Command line section of the examples of usage.

Installation

As usual, the easiest way is with pip:

$ pip install pglast

Alternatively you can clone the repository:

$ git clone https://github.com/lelit/pglast.git --recursive

and install from there:

$ pip install ./pglast

Development

There is a set of makefiles implementing the most common operations, a make help will show a brief table of contents. A comprehensive test suite, based on pytest, covers nearly 99% of the source lines.

History

For a more detailed evolution steps see Changes.

Version 1

I needed a better SQL reformatter than the one implemented by sqlparse, and was annoyed by a few glitches (subselects in particular) that ruins the otherwise excellent job it does, considering that it is a generic library that tries to swallow many different SQL dialects.

When I found psqlparse I decided to try implementing a PostgreSQL focused tool: at the beginning it’s been easier than I feared, but I quickly hit some shortcomings in that implementation, so I opted for writing my own solution restarting from scratch, with the following goals:

  • target only Python 3.4+

  • target PostgreSQL 10+

  • use a more dynamic approach to represent the parse tree, with a twofold advantage:

    1. it is much less boring to code, because there’s no need to write one Python class for each PostgreSQL node tag

    2. the representation is version agnostic, it can be adapted to newer/older Elephants in a snap

  • allow exploration of parse tree in both directions, because I realized that some kinds of nodes require that knowledge to determine their textual representation

  • avoid introducing arbitrary renames of tags and attributes, so what you read in PostgreSQL documentation/sources is available without the hassle of guessing how a symbol has been mapped

  • use a zero copy approach, keeping the original parse tree returned from the underlying libpg_query functions and have each node just borrow a reference to its own subtree

Version 2

In late 2019, Ronan opened PR #62 against libpg_query, that reimplemented the build machinery of the library to make it easier (read, semi-automatic) to support PostgreSQL 12, and PR #36 to bring pglast in line.

Since that version of PostgreSQL inevitably introduced some backward incompatibilities, I bumped the major version of pglast to better reflect the fact.

This version only had some development releases, since PR #62 has been superseded.

Important

This version requires Python 3.6 or greater, due to usage of f-strings.

Version 3

In early 2021, Lukas put a considerable effort into evolving his library to target PostgreSQL 13. He introduced a richer protobuf-based AST serialization protocol, rewriting the underlying machinery so that the same code is used to generate either a JSON or a protobuf stream.

The approach has obvious advantages, but unfortunately both formats come with different shortcomings, and I was not able to adapt pglast. The JSON serialization has changed in a way that it is not sufficient anymore to rebuild the original AST because some attributes now carry an implicit structure, that requires additional information to understand the content (see issue #82). OTOH, the Protobuf format is clumsy, at least on the Python side: the Google’s compiler creates a huge and unreadable module, while other implementations (see pyrobuf, cprotobuf and betterproto) suffer of different issues (see issue #210).

After several attempts, I decided to follow a more rewarding way and implement a native Python wrapper layer on top of PG parser’s nodes, pglast.ast.

Ronan and Hong helped a lot respectively with PR #72 and PR #77. Last but not least, https://bit.io/ kindly sponsored the project.

Version 4

The ultimate goal of this version is targeting PostgreSQL 14, exploiting the combined effort of Tessa Lisanti and Wolfgang Walther who upgraded libpg_query to the latest PG 14 parser that eventually has been finalized in the 14-latest branch.

While I was waiting for that to happen, I simplified the code getting rid of the wrapper classes. They were required in version 1, when pglast consumed the JSON-serialized parse tree emitted by libpg_query exposing those structures as generic Nodes distinguishable by their tag.

Version 3 retained them, although rewritten on top of the new concrete AST parser nodes, to make them aware of their ancestry, notion required by some printers to choose different representations.

Now the lineage is injected directly into the AST nodes by the printer machinery (cheaper than updating/computing it when setting/accessing each property) and all the printer functions receive one concrete AST node.

Changes
Version 4
4.4 (2023-08-24)
4.3 (2023-04-27)
4.2 (2023-02-27)
  • Handle special syntax required by SET TIME ZONE INTERVAL '-08:00' hour to minute

  • Fix mistype mapping of raw C “long” and “double” attributes, that were decorated with the wrong Python type

4.1 (2022-12-19)
  • Fix serialization glitches introduced by “Avoid overly abundancy of parentheses in expressions” (to be precise, by this commit)

4.0 (2022-12-12)
4.0.dev0 (2022-11-24)
  • Update libpg_query to 14-3.0.0

  • Avoid overly abundancy of parentheses in expressions

  • Prefer SELECT a FROM b LIMIT ALL to ... LIMIT NONE

Breaking changes
  • Target PostgreSQL 14

  • The wrapper classes used in previous versions, implemented in pglast.node, are gone: now everything works on top of the AST classes (issue #80)

  • The Ancestor class is not iterable anymore: it was an internal implementation facility, now moved to a _iter_members() method

Version 3
3.18 (2023-08-24)
  • Fix BooleanTest printer, enclosing expression within parens in more cases (issue #129)

  • Fix Constraint printer, avoiding repetition of “DEFERRABLE INITIALLY DEFERRED” on some kind of constraints (issue #130)

3.17 (2022-11-04)
  • Fix AlterSubscriptionStmt printer, handling “SET PUBLICATION” without options

3.16 (2022-11-03)
3.15 (2022-10-17)
  • Produce Python 3.11 wheels (PR #108), thanks to cibuildwheel 2.11.1 and to Bastien Gandouet

3.14 (2022-08-08)
  • Harden the way Visitor handle modifications to the AST (issue #107)

3.13 (2022-06-29)
3.12 (2022-06-19)
  • Rewrite the implementation of the referenced_relations() function, that was flawed with regard to CTEs handling (issue #106), thanks to Michal Charemza for providing his own version

  • Improve WithClause printer indentation

  • Fix minor whitespace related issues in a few printer functions

3.11 (2022-05-29)
  • Fix the Visitor class, it was ignoring nodes nested in sub-lists

  • Reduce the size of the generated parser by factoring out common code into helper functions

3.10 (2022-05-11)
3.9 (2022-02-24)
  • Fix bug handling node containing a location field, e.g. CreateTableSpaceStmt (issue #98)

  • Properly handle dereferenced array expression (issue #99)

  • Avoid improper “floatification” of literal integers (issue #100)

3.8 (2021-12-28)
  • Fix glitch in the AST extractor tool (issue #97)

  • Add Linux AArch64 wheel build support (PR #95), thanks to odidev

  • Fix type mismatch when using --remove-pg_catalog-from-functions (PR #93), thanks to Boris Zentner

3.7 (2021-10-13)
3.6 (2021-10-09)
  • Use latest libpg_query, to fix an error parsing PLpgSQL statements (issue #88)

3.5 (2021-09-26)
  • Forward the special_functions option to substream, when concatenating items (issue #89)

  • Fix representation of floating point numbers without decimal digits (issue #91)

  • Produce Python 3.10 wheels, thanks to cibuildwheel 2.1.2

  • Update libpg_query to 13-2.0.7

  • New option --remove-pg_catalog-from-functions on the command line tool (PR #90), thanks to Boris Zentner

  • Implement more special functions (PR #92), thanks to Boris Zentner

3.4 (2021-08-21)
  • Fix another packaging issue, that prevented recompilation from the sdist .tar.gz (issue #86), thanks to Christopher Brichford

3.3 (2021-07-04)
3.2 (2021-06-25)
  • Effectively include libpg_query’s vendored sources (issue #82)

3.1 (2021-06-25)
  • Fix packaging glitch (issue #82)

  • Build wheels also for macOS

  • Update libpg_query to 13-2.0.5

3.0 (2021-06-04)
  • Fix glitch in the RawStream, avoiding spurious space after an open parenthesis

  • Improve the Visitor class, to make it easier altering the original tree

  • Properly handle nested lists in the serialization of AST Node

3.0.dev2 (2021-05-22)
  • Fix bug in CreateStmt printer (issue #79)

  • Make it possible to pass also concrete ast.Nodes to RawStream`

Breaking changes
  • To reduce confusion, the printer module has been removed: print-specific stuff is now directly exposed by the printers subpackage while serialization classes are now in the new stream module

  • The default value for the safety_belt option of the printify() function is now False

3.0.dev1 (2021-05-16)
  • Fix AT_SetIdentity, AT_EnableReplicaTrig and AlterSubscriptionStmt printers

  • Improve AlterTSConfigType and IntoClause printers

  • New generic “visitor pattern” (issue #51) exemplified by a new referenced_relations() function (issue #66)

  • Refine printing of SQL comments

  • Implement AlterExtensionStmt printer

3.0.dev0 (2021-05-03)
  • Expose the new pg_query_scan() function as parser.scan()

  • Expose the pg_query_parse() function as parser.parse_sql_json()

  • Expose the new pg_query_parse_protobuf() function as parser.parse_sql_protobuf()

  • Expose the new pg_query_deparse_protobuf() function as parser.deparse_protobuf()

  • Honor the catalogname of a RangeVar if present (issue #71)

  • Cover almost all SQL statements, testing against the whole PostgreSQL regression suite (issue #68, PR #72 and PR #77), thanks to Ronan Dunklau and Hong Cheng

  • New rudimentary support for the preserve comments feature (issue #23)

Breaking changes
  • Target PostgreSQL 13

  • The pglast.parser module exposes all libpg_query entry points, even the new pg_query_deparse_protobuf() function that is basically equivalent to RawStream-based printer

  • The split() function is now based on the lower level pg_query_split_with_xxx() functions

  • The parse_sql() function returns native Python objects, not a JSON string as before: all PG nodes are now represented by subclasses of pglast.ast.Node, without exception, even Expr and Value are there. The latter impacts on pglast.node.Scalar: for example it now may contains a ast.Integer instance instead of a Python int

  • The pgpp --parse-tree output is a pprint represention of the AST, not a JSON string as before

  • The ParseError exception does not expose the location as an instance member anymore, although its still there, as the second argument (ie .args[1]); furthermore, its value now corresponds to the index in the original Unicode string, instead of the offset in the UTF-8 representation passed to the underlying C function

Version 2
2.0.dev3 (2021-02-20)
  • Handle INCLUDE clause in IndexStmt (PR #67), thanks to Ronan Dunklau

2.0.dev2 (2020-10-24)
  • Merge new fingerprint functionality from v1 (i.e. master) branch

2.0.dev1 (2020-09-26)
  • Require Python 3.6 or greater

  • Handle ALTER TYPE .. RENAME VALUE in AlterEnumStmt (PR #52), thanks to Ronan Dunklau

  • Add support for Create / Alter / Drop PROCEDURE (PR #48), thanks to Ronan Dunklau

  • Use Ronan’s fork of libpg_query, targeting PostgreSQL 12.1 (PR #36)

  • Change get_postgresql_version() to return a (major, minor) tuple (issue #38)

  • Handle ALTER TABLE ... ALTER COLUMN ... SET STORAGE ...

  • Handle PG12 materialized CTEs (issue #57)

  • Support column numbers in ALTER INDEX (PR #58), thanks to Ronan Dunklau

  • Handle SET LOGGED and SET UNLOGGED in ALTER TABLE (PR #59), thanks to Ronan Dunklau

  • Handle ALTER TYPE ... RENAME (PR #62), , thanks to Ronan Dunklau

Version 1
1.18 (2021-06-01)
  • Fix exclusion constraint printer (issue #81)

1.17 (2021-02-20)
  • Fix the generic case in the RenameStmt printer

1.16 (2021-02-20)
  • Promote to the stable state

  • Move the job of building and uploading binary wheels from TravisCI to GitHub Actions

1.15 (2021-02-19)
  • Fix IF EXISTS variant of RenameStmt printer (PR #70), thanks to Jonathan Mortensen

  • Update libpg_query to 10-1.0.5

1.14 (2020-10-24)
  • Produce Python 3.9 wheels, thanks to cibuildwheel 1.6.3

  • Expose the libpg_query’s fingerprint functionality (PR #64), thanks to Yiming Wang

1.13 (2020-09-26)
  • Handle SELECT FROM foo

1.12 (2020-06-08)
  • Double quote column names in the TYPE_FUNC_NAME_KEYWORDS set (issue #55)

  • Possibly wrap SELECT in UNION/INTERSECT between parens, when needed (issue #55)

1.11 (2020-05-08)
  • Fix A_Expr printer, when lexpr is missing (PR #54), thanks to Aiham

  • Support DISABLE ROW LEVEL SECURITY in AlterTableCmd (PR #49), thanks to Ronan Dunklau

  • Implement CreateOpClassStmt printer (PR #47), thanks to Ronan Dunklau

1.10 (2020-01-25)
  • Fix collation name printer (PR #44), thanks to Ronan Dunklau

  • Implement CreatePLangStmt printer (PR #42), thanks to Bennie Swart

  • Fix privileges printer (PR #41), thanks to Bennie Swart

  • Handle TRUNCATE event in CreateTrigStmt printer (PR #40), thanks to Bennie Swart

  • Fix function body dollar quoting (PR #39), thanks to Bennie Swart

1.9 (2019-12-20)
  • Prettier INSERT representation

1.8 (2019-12-07)
  • Prettier CASE representation

  • New option to emit a semicolon after the last statement (issue #24)

1.7 (2019-12-01)
  • Implement NotifyStmt printer

  • Implement RuleStmt printer, thanks to Gavin M. Roy for his PR #28

  • Fix RenameStmt, properly handling object name

  • Produce Python 3.8 wheels, thanks to cibuildwheel 1.0.0

  • Support ALTER TABLE RENAME CONSTRAINT (PR #35), thanks to Ronan Dunklau

1.6 (2019-09-04)
  • Fix issue with boolean expressions precedence (issue #29)

  • Implement BitString printer

  • Support LEAKPROOF option (PR #31), thanks to Ronan Dunklau

  • Support DEFERRABLE INITIALLY DEFERRED option (PR #32), thanks to Ronan Dunklau

1.5 (2019-06-04)
  • Fix issue with RETURNS SETOF functions, a more general solution than the one proposed by Ronan Dunklau (PR #22)

  • Allow more than one empty line between statements (PR #26), thanks to apnewberry

1.4 (2019-04-06)
  • Fix wrap of trigger’s WHEN expression (issue #18)

  • Support for variadic functions (PR #19), thanks to Ronan Dunklau

  • Support ORDER / LIMIT / OFFSET for set operations (PR #20), thanks to Ronan Dunklau

  • Implement ConstraintsSetStmt and improve VariableSetStmt printers

1.3 (2019-03-28)
  • Support CROSS JOIN and timezone modifiers on time and timestamp datatypes (PR #15), thanks to Ronan Dunklau

  • Many new printers and several enhancements (PR #14), thanks to Ronan Dunklau

  • Expose the package version as pglast.__version__ (issue #12)

1.2 (2019-02-13)
  • Implement new split() function (see PR #10)

  • Implement BooleanTest printer (issue #11)

1.1 (2018-07-20)
  • No visible changes, but now PyPI carries binary wheels for Python 3.7.

1.0 (2018-06-16)

Important

The name of the package has been changed from pg_query to pglast, to satisfy the request made by the author of libpg_query in issue #9.

This affects both the main repository on GitHub, that from now on is https://github.com/lelit/pglast, and the ReadTheDocs project that hosts the documentation, http://pglast.readthedocs.io/en/latest/.

I’m sorry for any inconvenience this may cause.

0.28 (2018-06-06)
  • Update libpg_query to 10-1.0.2

  • Support the ‘?’-style parameter placeholder variant allowed by libpg_query (details)

0.27 (2018-04-15)
  • Prettier JOINs representation, aligning them with the starting relation

0.26 (2018-04-03)
  • Fix cosmetic issue with ANY() and ALL()

0.25 (2018-03-31)
  • Fix issue in the safety belt check performed by pgpp (issue #4)

0.24 (2018-03-02)
  • Implement Null printer

0.23 (2017-12-28)
  • Implement some other DDL statements printers

  • New alternative style to print comma-separated-values lists, activated by a new --comma-at-eoln option on pgpp

0.22 (2017-12-03)
  • Implement TransactionStmt and almost all DROP xxx printers

0.21 (2017-11-22)
  • Implement NamedArgExpr printer

  • New alternative printers for a set of special functions, activated by a new --special-functions option on pgpp (issue #2)

0.20 (2017-11-21)
  • Handle special de-reference (A_Indirection) cases

0.19 (2017-11-16)
  • Fix serialization of column labels containing double quotes

  • Fix corner issues surfaced implementing some more DDL statement printers

0.18 (2017-11-14)
  • Fix endless loop due to sloppy conversion of command line option

  • Install the command line tool as pgpp

0.17 (2017-11-12)
  • Rename printers.sql to printers.dml (backward incompatibility)

  • List printer functions in the documentation, referencing the definition of related node type

  • Fix inconsistent spacing in JOIN condition inside a nested expression

  • Fix representation of unbound arrays

  • Fix representation of interval data type

  • Initial support for DDL statements

  • Fix representation of string literals containing single quotes

0.16 (2017-10-31)
  • Update libpg_query to 10-1.0.0

0.15 (2017-10-12)
  • Fix indentation of boolean expressions in SELECT’s targets (issue #3)

0.14 (2017-10-09)
  • Update to latest libpg_query’s 10-latest branch, targeting PostgreSQL 10.0 final

0.13 (2017-09-17)
  • Fix representation of subselects requiring surrounding parens

0.12 (2017-08-22)
  • New option --version on the command line tool

  • Better enums documentation

  • Release the GIL while calling libpg_query functions

0.11 (2017-08-11)
  • Nicer indentation for JOINs, making OUTER JOINs stand out

  • Minor tweaks to lists rendering, with less spurious whitespaces

  • New option --no-location on the command line tool

0.10 (2017-08-11)
  • Support Python 3.4 and Python 3.5 as well as Python 3.6

0.9 (2017-08-10)
  • Fix spacing before the $ character

  • Handle type modifiers

  • New option --plpgsql on the command line tool, just for fun

0.8 (2017-08-10)
  • Add enums subpackages to the documentation with references to their related headers

  • New compact_lists_margin option to produce a more compact representation when possible (see issue #1)

0.7 (2017-08-10)
  • Fix sdist including the Sphinx documentation

0.6 (2017-08-10)
  • New option --parse-tree on the command line tool to show just the parse tree

  • Sphinx documentation, available online

0.5 (2017-08-09)
  • Handle some more cases when a name must be double-quoted

  • Complete the serialization of the WindowDef node, handling its frame options

0.4 (2017-08-09)
  • Expose the actual PostgreSQL version the underlying libpg_query libray is built on thru a new get_postgresql_version() function

  • New option safety_belt for the prettify() function, to protect the innocents

  • Handle serialization of CoalesceExpr and MinMaxExpr

0.3 (2017-08-07)
  • Handle serialization of ParamRef nodes

  • Expose a prettify() helper function

0.2 (2017-08-07)
  • Test coverage at 99%

  • First attempt at automatic wheel upload to PyPI, let’s see…

0.1 (2017-08-07)
  • First release (“Hi daddy!”, as my soul would tag it)

Examples of usage

Here are some example of how the module can be used.

AST level

The lowest level is a Python wrapper around each parse node returned by the PostgreSQL parser. Each node is represented by a corresponding Python class in the module pglast.ast — Python classes representing PG parser nodes.

Parse an SQL statement and get its AST root node

The function parse_sql() returns a tuple containing one or more RawStmt instances:

>>> from pglast import parse_sql
>>> root = parse_sql('select 1')
>>> print(root)
(<RawStmt stmt=<SelectStmt targetList=(<ResTarget val=<A_Const val=<Integer val=1>>>,) ...,)

The textual representation of a parse node carries all its not None attributes, recursively.

You can obtain the accepted attributes of any node by iterating it:

>>> rawstmt = root[0]
>>> print(tuple(rawstmt))
('stmt', 'stmt_location', 'stmt_len')
>>> from pglast import ast
>>> stmt = rawstmt.stmt
>>> assert isinstance(stmt, ast.SelectStmt)

Each node is also a callable, to serialize it into a hierarchy of elementary Python values such as dictionaries and tuples:

>>> from pprint import pprint
>>> pprint(stmt(depth=2, skip_none=True))
{'@': 'SelectStmt',
 'all': False,
 'groupDistinct': False,
 'limitOption': {'#': 'LimitOption',
                 'name': 'LIMIT_OPTION_DEFAULT',
                 'value': 0},
 'op': {'#': 'SetOperation', 'name': 'SETOP_NONE', 'value': 0},
 'targetList': ({'@': 'ResTarget', 'location': 7, 'val': …},)}

As you can see, each node is serialized to a dictionary containing at least on special key, @, with the tag name of the node; lists of nodes are converted to tuples, and Enum instances to a dictionary with a special # key carrying the name of data type, and two other keys name and value respectively with the name and value of the enum value.

Nodes can be compared to each other, and are considered equal when all their attributes match, ignoring those semantically irrelevant:

>>> other_stmt = parse_sql('select /* something here */ 1')[0].stmt
>>> print(other_stmt(depth=2, skip_none=True))
{'@': 'SelectStmt', 'targetList': ({'@': 'ResTarget', 'val': …, 'location': 28},), ...}
>>> stmt == other_stmt
True
Altering a node

Any attribute of a node is alterable, and some check is done on the assigned value:

>>> print(stmt.all)
False
>>> stmt.all = True
>>> print(stmt.all)
True
>>> stmt.all = "foo"
Traceback (most recent call last):
  ...
ValueError: Bad value for attribute SelectStmt.all, expected (<class 'bool'>, <class 'int'>), got <class 'str'>: 'foo'

Enum attributes can be set to either a plain string, which is looked up in the related class, or to a dictionary:

>>> stmt.limitOption = 'LIMIT_OPTION_COUNT'
>>> pprint(stmt(depth=1, skip_none=True))
{'@': 'SelectStmt',
 'all': True,
 'groupDistinct': False,
 'limitOption': {'#': 'LimitOption', 'name': 'LIMIT_OPTION_COUNT', 'value': 1},
 'op': {'#': 'SetOperation', 'name': 'SETOP_NONE', 'value': 0},
 'targetList': (…,)}
>>> stmt.limitOption = {'#': 'LimitOption', 'name': 'LIMIT_OPTION_WITH_TIES'}
>>> pprint(stmt(depth=1, skip_none=True))
{'@': 'SelectStmt',
 'all': True,
 'groupDistinct': False,
 'limitOption': {'#': 'LimitOption',
                 'name': 'LIMIT_OPTION_WITH_TIES',
                 'value': 2},
 'op': {'#': 'SetOperation', 'name': 'SETOP_NONE', 'value': 0},
 'targetList': (…,)}

Either way, assigning the wrong value raises an exception:

>>> stmt.limitOption = 'foo'
Traceback (most recent call last):
  ...
ValueError: Bad value for attribute SelectStmt.limitOption, (<class 'int'>, <class 'str'>, <class 'dict'>, <enum 'LimitOption'>), got 'foo'
>>> stmt.limitOption = {'#': 'JoinType', 'name': 'JOIN_INNER'}
Traceback (most recent call last):
  ...
ValueError: Bad value for attribute SelectStmt.limitOption, expected a (<class 'int'>, <class 'str'>, <class 'dict'>, <enum 'LimitOption'>), got {'#': 'JoinType', 'name': 'JOIN_INNER'}
Creating a node

You can easily create a new node in the usual way, possibly passing any recognized attribute as a parameter to the constructor:

>>> print(ast.SelectStmt())
<SelectStmt>
>>> print(ast.SelectStmt(all=1))
<SelectStmt all=True>
>>> ast.SelectStmt(non_existing_attribute=None)
Traceback (most recent call last):
  ...
TypeError: __init__() got an unexpected keyword argument 'non_existing_attribute'
>>> ast.SelectStmt(all="foo")
Traceback (most recent call last):
  ...
ValueError: Bad value for attribute SelectStmt.all, expected (<class 'bool'>, <class 'int'>), got <class 'str'>: 'foo'

Alternatively, you can pass a single dictionary as argument, with the special @ key valued with the correct node name:

>>> print(ast.SelectStmt({'@': 'SelectStmt', 'all': True}))
<SelectStmt all=True>
>>> print(ast.SelectStmt({'@': 'RawStmt', 'all': True}))
Traceback (most recent call last):
  ...
ValueError: Bad argument, wrong "@" value, expected 'SelectStmt', got 'RawStmt'

This basically means that you can reconstruct a syntax tree from the result of calling a node:

>>> clone = ast.SelectStmt(stmt())
>>> clone is stmt
False
>>> clone == stmt
True
Programmatically reformat a SQL statement
The easy way

The prettify() takes a textual SQL statement and returns its equivalent once reprinted with a focus on readability.

>>> from pglast import prettify
>>> print(prettify('delete from sometable where value is null'))
DELETE FROM sometable
WHERE value IS NULL
>>> print(prettify('select a,b,c from sometable where value is null'))
SELECT a
     , b
     , c
FROM sometable
WHERE value IS NULL
>>> print(prettify('select a,b,c from sometable'
...                ' where value is null or value = 1',
...                comma_at_eoln=True))
SELECT a,
       b,
       c
FROM sometable
WHERE value IS NULL
   OR value = 1
Under the cover

The function above is a simple wrapper to the IndentedStream class, that extends pglast.stream.RawStream adding a bit a aesthetic sense.

>>> from pglast.stream import IndentedStream, RawStream
>>> print(IndentedStream(comma_at_eoln=True)('select a,b,c from sometable'))
SELECT a,
       b,
       c
FROM sometable
>>> print(IndentedStream()('select foo from bar'))
SELECT foo
FROM bar
>>> sql = 'select a.x, b.y from a join b on a.bid = b.id'
>>> astnode = parse_sql(sql)[0].stmt
>>> astnode
<SelectStmt targetList=(<ResTarget val=<ColumnRef fields=(<String val='a'>, <String val='x'>)>>...
>>> print(RawStream()(astnode.fromClause))
a INNER JOIN b ON a.bid = b.id
Visit or modify the AST tree
>>> from collections import Counter
>>> from pglast.visitors import Visitor
>>>
>>> class Stats(Visitor):
...     def __call__(self, node):
...         self.counters = Counter()
...         super().__call__(node)
...         return self.counters
...
...     def visit(self, ancestors, node):
...         self.counters.update((node.__class__.__name__,))
...
>>> stats = Stats()
>>> print(stats(parse_sql('select 1')))
Counter({'RawStmt': 1, 'SelectStmt': 1, 'ResTarget': 1, 'A_Const': 1, 'Integer': 1})
>>> class NoisyVisitor(Visitor):
...     def visit(self, ancestors, node):
...         print(ancestors, ':', node(depth=0, skip_none=True))
...
>>> visitor = NoisyVisitor()
>>> visitor(parse_sql('select a, b from c'))
ROOT → 0 : {'@': 'RawStmt', 'stmt': …, 'stmt_location': 0, 'stmt_len': 0}
ROOT → 0 → stmt : {'@': 'SelectStmt', 'targetList': …, 'fromClause': …, ...
ROOT → 0 → stmt → targetList → 0 : {'@': 'ResTarget', 'val': …, 'location': 7}
ROOT → 0 → stmt → targetList → 1 : {'@': 'ResTarget', 'val': …, 'location': 10}
ROOT → 0 → stmt → fromClause → 0 : {'@': 'RangeVar', 'relname': 'c', 'inh': True, ...
ROOT → 0 → stmt → targetList → 0 → val : {'@': 'ColumnRef', 'fields': …, 'location': 7}
ROOT → 0 → stmt → targetList → 1 → val : {'@': 'ColumnRef', 'fields': …, 'location': 10}
ROOT → 0 → stmt → targetList → 0 → val → fields → 0 : {'@': 'String', 'val': 'a'}
ROOT → 0 → stmt → targetList → 1 → val → fields → 0 : {'@': 'String', 'val': 'b'}
(<RawStmt stmt=<SelectStmt ...
>>> from pglast import enums
>>> from pglast.visitors import Delete
>>>
>>> class DropNullConstraint(Visitor):
...     def visit_Constraint(self, ancestors, node):
...         if node.contype == enums.ConstrType.CONSTR_NULL:
...             return Delete
...
>>> raw = parse_sql('create table foo (a integer null, b integer not null)')
>>> DropNullConstraint()(raw)
(<RawStmt stmt=<CreateStmt ...
>>> print(RawStream()(raw))
CREATE TABLE foo (a integer, b integer NOT NULL)
Customize a node printer
>>> sql = 'update translations set italian=$2 where word=$1'
>>> print(prettify(sql))
UPDATE translations
SET italian = $2
WHERE word = $1
>>> from pglast.printers import node_printer
>>> @node_printer(ast.ParamRef, override=True)
... def replace_param_ref(node, output):
...     output.write(repr(args[node.number - 1]))
...
>>> args = ['Hello', 'Ciao']
>>> print(prettify(sql, safety_belt=False))
UPDATE translations
SET italian = 'Ciao'
WHERE word = 'Hello'
Iterate over each statement

By default, the split() function uses the parser to do its job:

>>> from pglast import split
>>> for statement in split('select 1; select 2'):
...     print(statement)
...
select 1
select 2

and thus it raises an error if the statement contains errors:

>>> split('select 1 from; select 2')
Traceback (most recent call last):
  ...
pglast.parser.ParseError: syntax error at or near ";", at location 14

In this case, you can use a variant that uses the lexical scanner instead:

>>> for statement in split('select 1 from; select 2', with_parser=False):
...     print(statement)
...
select 1 from
select 2

Command line

Reformat a SQL statement
$ echo "select a,b,c from sometable" | pgpp
SELECT a
     , b
     , c
FROM sometable

$ pgpp -S "select a, case when a=1 then 'singular' else 'plural' end from test"
SELECT a
     , CASE
         WHEN (a = 1)
           THEN 'singular'
         ELSE 'plural'
       END
FROM test

$ echo 'update "table" set value=123 where value is null' | pgpp
UPDATE "table"
SET value = 123
WHERE value IS NULL

$ echo "
insert into t (id, description)
values (1, 'this is short enough'),
       (2, 'this is too long, and will be splitted')" | pgpp -s 20
INSERT INTO t (id, description)
VALUES (1, 'this is short enough')
     , (2, 'this is too long, an'
           'd will be splitted')
Get a more compact representation
$ pgpp --compact 30 -S "select a,b,c from st where a='longvalue1' and b='longvalue2'"
SELECT a, b, c
FROM st
WHERE (a = 'longvalue1')
  AND (b = 'longvalue2')

$ pgpp --compact 60 -S "select a,b,c from st where a='longvalue1' and b='longvalue2'"
SELECT a, b, c
FROM st
WHERE (a = 'longvalue1') AND (b = 'longvalue2')
Obtain the parse tree of a SQL statement
$ pgpp --parse-tree --statement "select 1"
[{'@': 'RawStmt',
  'stmt': {'@': 'SelectStmt',
           'all': False,
           'limitOption': <LimitOption.LIMIT_OPTION_DEFAULT: 0>,
           'op': <SetOperation.SETOP_NONE: 0>,
           'targetList': ({'@': 'ResTarget',
                           'location': 7,
                           'val': {'@': 'A_Const',
                                   'location': 7,
                                   'val': {'@': 'Integer', 'val': 1}}},)},
  'stmt_len': 0,
  'stmt_location': 0}]
Preserve comments
$ pgpp --preserve-comments -S "/* Header */ select 1"
/* Header */ SELECT 1

$ echo -e "--what?\nselect foo\n--where?\nfrom bar" | pgpp -C
--what?
SELECT foo
FROM
   --where?
bar

$ echo -e "--what?\nselect foo\n/*where?*/from bar\n--end" | pgpp -C
--what?
SELECT foo
FROM
   /*where?*/ bar
--end

Note

Preserving comments is always hard and far from a perfect science: not all AST nodes carry their exact location, so it is not possible to differentiate between SELECT * /*comment*/ FROM foo and SELECT * FROM /*comment*/ foo.

Functions vs SQL syntax
$ pgpp -S "select extract(hour from t1.modtime) from t1"
SELECT pg_catalog.date_part('hour', t1.modtime)
FROM t1

$ pgpp --special-functions -S "select extract(hour from t1.modtime) from t1"
SELECT EXTRACT(HOUR FROM t1.modtime)
FROM t1

$ echo "
select substring('123',2,3),
       regexp_split_to_array('x,x,x', ','),
       btrim('xxx'), trim('xxx'),
       POSITION('hour' in trim(substring('xyz hour ',1,6)))
" | pgpp
SELECT pg_catalog.substring('123', 2, 3)
     , regexp_split_to_array('x,x,x', ',')
     , btrim('xxx')
     , pg_catalog.btrim('xxx')
     , pg_catalog.position(pg_catalog.btrim(pg_catalog.substring('xyz hour ', 1, 6))
                         , 'hour')

$ echo "
select substring('123',2,3),
       regexp_split_to_array('x,x,x', ','),
       btrim('xxx'), trim('xxx'),
       POSITION('hour' in trim(substring('xyz hour ',1,6)))
" | pgpp -f --remove-pg_catalog-from-functions
SELECT substring('123', 2, 3)
     , regexp_split_to_array('x,x,x', ',')
     , btrim('xxx')
     , btrim('xxx')
     , pg_catalog.position(btrim(substring('xyz hour ', 1, 6))
                         , 'hour')

API documentation

This chapter briefly explains some implementation detail.

exception pglast.Error

Top level error exception.

pglast.__author__ = 'Lele Gaifax <lele@metapensiero.it>'

Package’s author.

pglast.__version__ = 'v4.4'

Package’s version.

pglast.prettify(statement, safety_belt=False, preserve_comments=False, **options)

Render given statement into a prettified format.

Parameters
  • statement (str) – the SQL statement(s)

  • safety_belt (bool) – whether to perform a safe check against bugs in pglast’s serialization

  • preserve_comments (bool) – whether comments shall be preserved, defaults to not

  • **options – any keyword option accepted by IndentedStream constructor

Returns

a string with the equivalent prettified statement(s)

When safety_belt is True, the resulting statement is parsed again and its AST compared with the original statement: if they don’t match, a warning is emitted and the original statement is returned. By default it is False, so no double check is done.

pglast.split(stmts, with_parser=True, only_slices=False)

Split the given stmts string into a sequence of the single SQL statements.

By default this uses the parser to perform the job; when with_parser is False the scanner variant is used, indicated when the statements may contain parse errors.

When only_slices is True, return a sequence of slice instances, one for each statement, instead of statements text.

NB: leading and trailing whitespace are removed from the statements.

pglast.parser — The interface with libpg_query

This module is a C extension written in Cython that exposes a few functions from the underlying libpg_query library it links against.

pglast.parser.LONG_MAX

The highest integer that can be stored in a C long variable: it is used as a marker, for example in PG’s FetchStmt.howMany, that uses the constant FETCH_ALL.

exception pglast.parser.ParseError

Exception representing the error state returned by the parser.

exception pglast.parser.DeparseError

Exception representing the error state returned by the deparser.

pglast.parser.deparse_protobuf(buffer)
Parameters

buffer (bytes) – a Protobuf buffer

Returns

str

Return the SQL statement from the given buffer argument, something generated by parse_sql_protobuf().

pglast.parser.fingerprint(query)
Parameters

query (str) – The SQL statement

Returns

str

Fingerprint the given query, a string with the SQL statement(s), and return a hash digest that can identify similar queries. For similar queries that are different only because of the queried object or formatting, the returned digest will be the same.

pglast.parser.get_postgresql_version()
Returns

a tuple

Return the PostgreSQL version as a tuple (major, minor, patch).

pglast.parser.parse_sql(query)
Parameters

query (str) – The SQL statement

Returns

tuple

Parse the given query, a string with the SQL statement(s), and return the corresponding parse tree as a tuple of pglast.ast.RawStmt instances.

pglast.parser.parse_sql_json(query)
Parameters

query (str) – The SQL statement

Returns

str

Parse the given query, a string with the SQL statement(s), and return the libpg_query‘s JSON-serialized parse tree.

pglast.parser.parse_sql_protobuf(query)
Parameters

query (str) – The SQL statement

Returns

bytes

Parse the given query, a string with the SQL statement(s), and return the libpg_query‘s Protobuf-serialized parse tree.

pglast.parser.parse_plpgsql_json(query)
Parameters

query (str) – The PLpgSQL statement

Returns

str

Parse the given query, a string with the plpgsql statement(s), and return the libpg_query‘s JSON-serialized parse tree.

pglast.parser.scan(query)
Parameters

query (str) – The SQL statement

Returns

sequence of tuples

Split the given query into its tokens. Each token is a namedtuple with the following slots:

startint

the index of the start of the token

endint

the index of the end of the token

namestr

the name of the offset

keywordstr

the keyword kind

pglast.parser.split(query, with_parser=True, only_slices=False)
Parameters
  • query (str) – The SQL statement

  • with_parser (bool) – Whether to use the parser or the scanner

  • only_slices (bool) – Return slices instead of statement’s text

Returns

tuple

Split the given stmts string into a sequence of the single SQL statements.

By default this uses the parser to perform the job; when with_parser is False the scanner variant is used, indicated when the statements may contain parse errors.

When only_slices is True, return a sequence of slice instances, one for each statement, instead of statements text.

Note

Leading and trailing whitespace are removed from the statements.

pglast.ast — Python classes representing PG parser nodes

The module implements a set of data classes, one for each C structure defined in several PostgreSQL headers, primarily those in the include/nodes/ directory.

The pglast.ast.Node is an abstract class that implements the common behaviour of all the concrete classes. In particular any node can be compared with another instance, is able to serialize itself and can be altered.

class pglast.ast.Node(data)

Base class for all AST nodes.

__call__(depth=None, ellipsis=…, skip_none=False)

Serialize the node as a structure made of simple Python data-types.

Parameters
  • depth (None or int) – if not None, the maximum depth to reach

  • ellipsis – the marker value that will be used to replace cut-off branch

  • skip_none (bool) – whether None-valued attributes should be elided

  • enum_name (bool) – whether Enums will be rendered as their name only

Returns

a dict instance

This performs a top-down recursive visit to the whole AST tree: each Node instance becomes a dictionary with a special @ key carrying the node type, lists becomes tuples and Enum instances become dictionaries with a special # key carrying the enum name.

__eq__(other)

Compare two nodes, returning True if they are considered equivalent.

This is mainly an helper method used by tests: for this reason, two nodes are considered equal when all their attributes match, ignoring positional ones such as location, stmt_len and stmt_location.

__repr__()

Build a representation of the whole node and its subtree, for debug.

__setattr__(name, value)

Validate the given value and if acceptable assign it to the name attribute.

This tries to coerce the given value accordingly with the ctype of the attribute, raising opportune exception when that is not possible.

class pglast.ast.Value(value=None)

Abstract super class, representing PG’s Value union type.

class pglast.ast.BitString(value=None)

Implement the T_BitString variant of the Value union.

class pglast.ast.Float(value=None)

Implement the T_Float variant of the Value union.

class pglast.ast.Integer(value=None)

Implement the T_Integer variant of the Value union.

class pglast.ast.Null(value=None)

Implement the T_Null variant of the Value union.

class pglast.ast.String(value=None)

Implement the T_String variant of the Value union.

class pglast.ast.A_ArrayExpr(elements=None, location=None)

Wrapper for the homonymous parser node.

elements: tuple

Array element expressions

location: int

Token location, or -1 if unknown

class pglast.ast.A_Const(val=None, location=None)

Wrapper for the homonymous parser node.

val: Value

Value (includes type info, see value.h)

location: int

Token location, or -1 if unknown

class pglast.ast.A_Expr(kind=None, name=None, lexpr=None, rexpr=None, location=None)

Wrapper for the homonymous parser node.

kind: A_Expr_Kind
name: tuple

Possibly-qualified name of operator

lexpr: Node

Left argument, or NULL if none

rexpr: Node

Right argument, or NULL if none

location: int

Token location, or -1 if unknown

class pglast.ast.A_Indices(is_slice=None, lidx=None, uidx=None)

Wrapper for the homonymous parser node.

is_slice: bool

True if slice (i.e., colon present)

lidx: Node

Slice lower bound, if any

uidx: Node

Subscript, or slice upper bound if any

class pglast.ast.A_Indirection(arg=None, indirection=None)

Wrapper for the homonymous parser node.

arg: Node

The thing being selected from

indirection: tuple

Subscripts and/or field names and/or *

class pglast.ast.A_Star

Wrapper for the homonymous parser node.

class pglast.ast.AccessPriv(priv_name=None, cols=None)

Wrapper for the homonymous parser node.

priv_name: str

String name of privilege

cols: tuple

List of Value strings

class pglast.ast.Aggref(aggargtypes=None, aggdirectargs=None, args=None, aggorder=None, aggdistinct=None, aggfilter=None, aggstar=None, aggvariadic=None, aggkind=None, agglevelsup=None, aggsplit=None, aggno=None, aggtransno=None, location=None)

Wrapper for the homonymous parser node.

aggargtypes: tuple

Type Oids of direct and aggregated args

aggdirectargs: tuple

Direct arguments, if an ordered-set agg

args: tuple

Aggregated arguments and sort expressions

aggorder: tuple

ORDER BY (list of SortGroupClause)

aggdistinct: tuple

DISTINCT (list of SortGroupClause)

aggfilter: Expr*

FILTER expression, if any

aggstar: bool

True if argument list was really ‘*’

aggvariadic: bool

True if variadic arguments have been combined into an array last argument

aggkind: str

Aggregate kind (see pg_aggregate.h)

agglevelsup: Index

> 0 if agg belongs to outer query

aggsplit: AggSplit

Expected agg-splitting mode of parent Agg

aggno: int

Unique ID within the Agg node

aggtransno: int

Unique ID of transition state in the Agg

location: int

Token location, or -1 if unknown

class pglast.ast.Alias(aliasname=None, colnames=None)

Wrapper for the homonymous parser node.

aliasname: str

Aliased rel name (never qualified)

colnames: tuple

Optional list of column aliases

class pglast.ast.AlterCollationStmt(collname=None)

Wrapper for the homonymous parser node.

collname: tuple
class pglast.ast.AlterDatabaseSetStmt(dbname=None, setstmt=None)

Wrapper for the homonymous parser node.

dbname: str

Database name

setstmt: VariableSetStmt*

SET or RESET subcommand

class pglast.ast.AlterDatabaseStmt(dbname=None, options=None)

Wrapper for the homonymous parser node.

dbname: str

Name of database to alter

options: tuple

List of DefElem nodes

class pglast.ast.AlterDefaultPrivilegesStmt(options=None, action=None)

Wrapper for the homonymous parser node.

options: tuple

List of DefElem

action: GrantStmt*

GRANT/REVOKE action (with objects=NIL)

class pglast.ast.AlterDomainStmt(subtype=None, typeName=None, name=None, def_=None, behavior=None, missing_ok=None)

Wrapper for the homonymous parser node.

subtype: str
  • T = alter column default

  • N = alter column drop not null

  • O = alter column set not null

  • C = add constraint

  • X = drop constraint

typeName: tuple

Domain to work on

name: str

Column or constraint name to act on

def_: Node

Definition of default or constraint

behavior: DropBehavior

RESTRICT or CASCADE for DROP cases

missing_ok: bool

Skip error if missing?

class pglast.ast.AlterEnumStmt(typeName=None, oldVal=None, newVal=None, newValNeighbor=None, newValIsAfter=None, skipIfNewValExists=None)

Wrapper for the homonymous parser node.

typeName: tuple

Qualified name (list of Value strings)

oldVal: str

Old enum value’s name, if renaming

newVal: str

New enum value’s name

newValNeighbor: str

Neighboring enum value, if specified

newValIsAfter: bool

Place new enum value after neighbor?

skipIfNewValExists: bool

No error if new already exists?

class pglast.ast.AlterEventTrigStmt(trigname=None, tgenabled=None)

Wrapper for the homonymous parser node.

trigname: str

TRIGGER’s name

tgenabled: str

Trigger’s firing configuration WRT session_replication_role

class pglast.ast.AlterExtensionContentsStmt(extname=None, action=None, objtype=None, object=None)

Wrapper for the homonymous parser node.

extname: str

Extension’s name

action: int

+1 = add object, -1 = drop object

objtype: ObjectType

Object’s type

object: Node

Qualified name of the object

class pglast.ast.AlterExtensionStmt(extname=None, options=None)

Wrapper for the homonymous parser node.

extname: str
options: tuple

List of DefElem nodes

class pglast.ast.AlterFdwStmt(fdwname=None, func_options=None, options=None)

Wrapper for the homonymous parser node.

fdwname: str

Foreign-data wrapper name

func_options: tuple

HANDLER/VALIDATOR options

options: tuple

Generic options to FDW

class pglast.ast.AlterForeignServerStmt(servername=None, version=None, options=None, has_version=None)

Wrapper for the homonymous parser node.

servername: str

Server name

version: str

Optional server version

options: tuple

Generic options to server

has_version: bool

Version specified

class pglast.ast.AlterFunctionStmt(objtype=None, func=None, actions=None)

Wrapper for the homonymous parser node.

objtype: ObjectType
func: ObjectWithArgs*

Name and args of function

actions: tuple

List of DefElem

class pglast.ast.AlterObjectDependsStmt(objectType=None, relation=None, object=None, extname=None, remove=None)

Wrapper for the homonymous parser node.

objectType: ObjectType

OBJECT_FUNCTION, OBJECT_TRIGGER, etc

relation: RangeVar*

In case a table is involved

object: Node

Name of the object

extname: Value*

Extension name

remove: bool

Set true to remove dep rather than add

class pglast.ast.AlterObjectSchemaStmt(objectType=None, relation=None, object=None, newschema=None, missing_ok=None)

Wrapper for the homonymous parser node.

objectType: ObjectType

OBJECT_TABLE, OBJECT_TYPE, etc

relation: RangeVar*

In case it’s a table

object: Node

In case it’s some other object

newschema: str

The new schema

missing_ok: bool

Skip error if missing?

class pglast.ast.AlterOpFamilyStmt(opfamilyname=None, amname=None, isDrop=None, items=None)

Wrapper for the homonymous parser node.

opfamilyname: tuple

Qualified name (list of Value strings)

amname: str

Name of index AM opfamily is for

isDrop: bool

ADD or DROP the items?

items: tuple

List of CreateOpClassItem nodes

class pglast.ast.AlterOperatorStmt(opername=None, options=None)

Wrapper for the homonymous parser node.

opername: ObjectWithArgs*

Operator name and argument types

options: tuple

List of DefElem nodes

class pglast.ast.AlterOwnerStmt(objectType=None, relation=None, object=None, newowner=None)

Wrapper for the homonymous parser node.

objectType: ObjectType

OBJECT_TABLE, OBJECT_TYPE, etc

relation: RangeVar*

In case it’s a table

object: Node

In case it’s some other object

newowner: RoleSpec*

The new owner

class pglast.ast.AlterPolicyStmt(policy_name=None, table=None, roles=None, qual=None, with_check=None)

Wrapper for the homonymous parser node.

policy_name: str

Policy’s name

table: RangeVar*

The table name the policy applies to

roles: tuple

The roles associated with the policy

qual: Node

The policy’s condition

with_check: Node

The policy’s WITH CHECK condition.

class pglast.ast.AlterPublicationStmt(pubname=None, options=None, tables=None, for_all_tables=None, tableAction=None)

Wrapper for the homonymous parser node.

pubname: str

Name of the publication

options: tuple

List of DefElem nodes

tables: tuple

List of tables to add/drop

for_all_tables: bool

Special publication for all tables in db

tableAction: DefElemAction

What action to perform with the tables

class pglast.ast.AlterRoleSetStmt(role=None, database=None, setstmt=None)

Wrapper for the homonymous parser node.

role: RoleSpec*

Role

database: str

Database name, or NULL

setstmt: VariableSetStmt*

SET or RESET subcommand

class pglast.ast.AlterRoleStmt(role=None, options=None, action=None)

Wrapper for the homonymous parser node.

role: RoleSpec*

Role

options: tuple

List of DefElem nodes

action: int

+1 = add members, -1 = drop members

class pglast.ast.AlterSeqStmt(sequence=None, options=None, for_identity=None, missing_ok=None)

Wrapper for the homonymous parser node.

sequence: RangeVar*

The sequence to alter

options: tuple
for_identity: bool
missing_ok: bool

Skip error if a role is missing?

class pglast.ast.AlterStatsStmt(defnames=None, stxstattarget=None, missing_ok=None)

Wrapper for the homonymous parser node.

defnames: tuple

Qualified name (list of Value strings)

stxstattarget: int

Statistics target

missing_ok: bool

Skip error if statistics object is missing

class pglast.ast.AlterSubscriptionStmt(kind=None, subname=None, conninfo=None, publication=None, options=None)

Wrapper for the homonymous parser node.

kind: AlterSubscriptionType

ALTER_SUBSCRIPTION_OPTIONS, etc

subname: str

Name of the subscription

conninfo: str

Connection string to publisher

publication: tuple

One or more publication to subscribe to

options: tuple

List of DefElem nodes

class pglast.ast.AlterSystemStmt(setstmt=None)

Wrapper for the homonymous parser node.

setstmt: VariableSetStmt*

SET subcommand

class pglast.ast.AlterTSConfigurationStmt(kind=None, cfgname=None, tokentype=None, dicts=None, override=None, replace=None, missing_ok=None)

Wrapper for the homonymous parser node.

kind: AlterTSConfigType

ALTER_TSCONFIG_ADD_MAPPING, etc

cfgname: tuple

Qualified name (list of Value strings)

tokentype: tuple

List of Value strings

dicts: tuple

List of list of Value strings

override: bool

If true - remove old variant

replace: bool

If true - replace dictionary by another

missing_ok: bool

For DROP - skip error if missing?

class pglast.ast.AlterTSDictionaryStmt(dictname=None, options=None)

Wrapper for the homonymous parser node.

dictname: tuple

Qualified name (list of Value strings)

options: tuple

List of DefElem nodes

class pglast.ast.AlterTableCmd(subtype=None, name=None, num=None, newowner=None, def_=None, behavior=None, missing_ok=None, recurse=None)

Wrapper for the homonymous parser node.

subtype: AlterTableType

Type of table alteration to apply

name: str

Column, constraint, or trigger to act on, or tablespace

num: int16

Attribute number for columns referenced by number

newowner: RoleSpec*
def_: Node

Definition of new column, index, constraint, or parent table

behavior: DropBehavior

RESTRICT or CASCADE for DROP cases

missing_ok: bool

Skip error if missing?

recurse: bool

Exec-time recursion

class pglast.ast.AlterTableMoveAllStmt(orig_tablespacename=None, objtype=None, roles=None, new_tablespacename=None, nowait=None)

Wrapper for the homonymous parser node.

orig_tablespacename: str
objtype: ObjectType

Object type to move

roles: tuple

List of roles to move objects of

new_tablespacename: str
nowait: bool
class pglast.ast.AlterTableSpaceOptionsStmt(tablespacename=None, options=None, isReset=None)

Wrapper for the homonymous parser node.

tablespacename: str
options: tuple
isReset: bool
class pglast.ast.AlterTableStmt(relation=None, cmds=None, objtype=None, missing_ok=None)

Wrapper for the homonymous parser node.

relation: RangeVar*

Table to work on

cmds: tuple

List of subcommands

objtype: ObjectType

Type of object

missing_ok: bool

Skip error if table missing

class pglast.ast.AlterTypeStmt(typeName=None, options=None)

Wrapper for the homonymous parser node.

typeName: tuple

Type name (possibly qualified)

options: tuple

List of DefElem nodes

class pglast.ast.AlterUserMappingStmt(user=None, servername=None, options=None)

Wrapper for the homonymous parser node.

user: RoleSpec*

User role

servername: str

Server name

options: tuple

Generic options to server

class pglast.ast.AlternativeSubPlan(subplans=None)

Wrapper for the homonymous parser node.

subplans: tuple

SubPlan(s) with equivalent results

class pglast.ast.ArrayCoerceExpr(arg=None, elemexpr=None, resulttypmod=None, coerceformat=None, location=None)

Wrapper for the homonymous parser node.

arg: Expr*

Input expression (yields an array)

elemexpr: Expr*

Expression representing per-element work

resulttypmod: int32

Output typmod (also element typmod)

coerceformat: CoercionForm

How to display this node

location: int

Token location, or -1 if unknown

class pglast.ast.ArrayExpr(elements=None, multidims=None, location=None)

Wrapper for the homonymous parser node.

elements: tuple

The array elements or sub-arrays

multidims: bool

True if elements are sub-arrays

location: int

Token location, or -1 if unknown

class pglast.ast.BoolExpr(boolop=None, args=None, location=None)

Wrapper for the homonymous parser node.

boolop: BoolExprType
args: tuple

Arguments to this expression

location: int

Token location, or -1 if unknown

class pglast.ast.BooleanTest(arg=None, booltesttype=None, location=None)

Wrapper for the homonymous parser node.

arg: Expr*

Input expression

booltesttype: BoolTestType

Test type

location: int

Token location, or -1 if unknown

class pglast.ast.CTECycleClause(cycle_col_list=None, cycle_mark_column=None, cycle_mark_value=None, cycle_mark_default=None, cycle_path_column=None, location=None, cycle_mark_typmod=None)

Wrapper for the homonymous parser node.

cycle_col_list: tuple
cycle_mark_column: str
cycle_mark_value: Node
cycle_mark_default: Node
cycle_path_column: str
location: int
cycle_mark_typmod: int
class pglast.ast.CTESearchClause(search_col_list=None, search_breadth_first=None, search_seq_column=None, location=None)

Wrapper for the homonymous parser node.

search_col_list: tuple
search_breadth_first: bool
search_seq_column: str
location: int
class pglast.ast.CallContext(atomic=None)

Wrapper for the homonymous parser node.

atomic: bool
class pglast.ast.CallStmt(funccall=None, funcexpr=None, outargs=None)

Wrapper for the homonymous parser node.

funccall: FuncCall*

From the parser

funcexpr: FuncExpr*

Transformed call, with only input args

outargs: tuple

Transformed output-argument expressions

class pglast.ast.CaseExpr(arg=None, args=None, defresult=None, location=None)

Wrapper for the homonymous parser node.

arg: Expr*

Implicit equality comparison argument

args: tuple

The arguments (list of WHEN clauses)

defresult: Expr*

The default result (ELSE clause)

location: int

Token location, or -1 if unknown

class pglast.ast.CaseTestExpr(typeMod=None)

Wrapper for the homonymous parser node.

typeMod: int32

Typemod for substituted value

class pglast.ast.CaseWhen(expr=None, result=None, location=None)

Wrapper for the homonymous parser node.

expr: Expr*

Condition expression

result: Expr*

Substitution result

location: int

Token location, or -1 if unknown

class pglast.ast.CheckPointStmt

Wrapper for the homonymous parser node.

class pglast.ast.ClosePortalStmt(portalname=None)

Wrapper for the homonymous parser node.

portalname: str

Name of the portal (cursor)

class pglast.ast.ClusterStmt(relation=None, indexname=None, params=None)

Wrapper for the homonymous parser node.

relation: RangeVar*

Relation being indexed, or NULL if all

indexname: str

Original index defined

params: tuple

List of DefElem nodes

class pglast.ast.CoalesceExpr(args=None, location=None)

Wrapper for the homonymous parser node.

args: tuple

The arguments

location: int

Token location, or -1 if unknown

class pglast.ast.CoerceToDomain(arg=None, resulttypmod=None, coercionformat=None, location=None)

Wrapper for the homonymous parser node.

arg: Expr*

Input expression

resulttypmod: int32

Output typmod (currently always -1)

coercionformat: CoercionForm

How to display this node

location: int

Token location, or -1 if unknown

class pglast.ast.CoerceToDomainValue(typeMod=None, location=None)

Wrapper for the homonymous parser node.

typeMod: int32

Typemod for substituted value

location: int

Token location, or -1 if unknown

class pglast.ast.CoerceViaIO(arg=None, coerceformat=None, location=None)

Wrapper for the homonymous parser node.

arg: Expr*

Input expression

coerceformat: CoercionForm

How to display this node

location: int

Token location, or -1 if unknown

class pglast.ast.CollateClause(arg=None, collname=None, location=None)

Wrapper for the homonymous parser node.

arg: Node

Input expression

collname: tuple

Possibly-qualified collation name

location: int

Token location, or -1 if unknown

class pglast.ast.CollateExpr(arg=None, location=None)

Wrapper for the homonymous parser node.

arg: Expr*

Input expression

location: int

Token location, or -1 if unknown

class pglast.ast.ColumnDef(colname=None, typeName=None, compression=None, inhcount=None, is_local=None, is_not_null=None, is_from_type=None, storage=None, raw_default=None, cooked_default=None, identity=None, identitySequence=None, generated=None, collClause=None, constraints=None, fdwoptions=None, location=None)

Wrapper for the homonymous parser node.

colname: str

Name of column

typeName: TypeName*

Type of column

compression: str

Compression method for column

inhcount: int

Number of times column is inherited

is_local: bool

Column has local (non-inherited) def’n

is_not_null: bool

NOT NULL constraint specified?

is_from_type: bool

Column definition came from table type

storage: str

Attstorage setting, or 0 for default

raw_default: Node

Default value (untransformed parse tree)

cooked_default: Node

Default value (transformed expr tree)

identity: str

Attidentity setting

identitySequence: RangeVar*

To store identity sequence name for ALTER TABLE … ADD COLUMN

generated: str

Attgenerated setting

collClause: CollateClause*

Untransformed COLLATE spec, if any

constraints: tuple

Other constraints on column

fdwoptions: tuple

Per-column FDW options

location: int

Parse location, or -1 if none/unknown

class pglast.ast.ColumnRef(fields=None, location=None)

Wrapper for the homonymous parser node.

fields: tuple

Field names (Value strings) or A_Star

location: int

Token location, or -1 if unknown

class pglast.ast.CommentStmt(objtype=None, object=None, comment=None)

Wrapper for the homonymous parser node.

objtype: ObjectType

Object’s type

object: Node

Qualified name of the object

comment: str

Comment to insert, or NULL to remove

class pglast.ast.CommonTableExpr(ctename=None, aliascolnames=None, ctematerialized=None, ctequery=None, search_clause=None, cycle_clause=None, location=None, cterecursive=None, cterefcount=None, ctecolnames=None, ctecoltypes=None, ctecoltypmods=None, ctecolcollations=None)

Wrapper for the homonymous parser node.

ctename: str

Query name (never qualified)

aliascolnames: tuple

Optional list of column names

ctematerialized: CTEMaterialize

Is this an optimization fence?

ctequery: Node

The CTE’s subquery

search_clause: CTESearchClause*
cycle_clause: CTECycleClause*
location: int

Token location, or -1 if unknown

cterecursive: bool

Is this CTE actually recursive?

cterefcount: int

Number of RTEs referencing this CTE (excluding internal self-references)

ctecolnames: tuple

List of output column names

ctecoltypes: tuple

OID list of output column type OIDs

ctecoltypmods: tuple

Integer list of output column typmods

ctecolcollations: tuple

OID list of column collation OIDs

class pglast.ast.CompositeTypeStmt(typevar=None, coldeflist=None)

Wrapper for the homonymous parser node.

typevar: RangeVar*

The composite type to be created

coldeflist: tuple

List of ColumnDef nodes

class pglast.ast.Constraint(contype=None, conname=None, deferrable=None, initdeferred=None, location=None, is_no_inherit=None, raw_expr=None, cooked_expr=None, generated_when=None, keys=None, including=None, exclusions=None, options=None, indexname=None, indexspace=None, reset_default_tblspc=None, access_method=None, where_clause=None, pktable=None, fk_attrs=None, pk_attrs=None, fk_matchtype=None, fk_upd_action=None, fk_del_action=None, old_conpfeqop=None, skip_validation=None, initially_valid=None)

Wrapper for the homonymous parser node.

contype: ConstrType
conname: str

Constraint name, or NULL if unnamed

deferrable: bool

DEFERRABLE?

initdeferred: bool

INITIALLY DEFERRED?

location: int

Token location, or -1 if unknown

is_no_inherit: bool

Is constraint non-inheritable?

raw_expr: Node

Expr, as untransformed parse tree

cooked_expr: str

Expr, as nodeToString representation

generated_when: str

ALWAYS or BY DEFAULT

keys: tuple

String nodes naming referenced key column(s)

including: tuple

String nodes naming referenced nonkey column(s)

exclusions: tuple

List of (IndexElem, operator name) pairs

options: tuple

Options from WITH clause

indexname: str

Existing index to use; otherwise NULL

indexspace: str

Index tablespace; NULL for default

reset_default_tblspc: bool

Reset default_tablespace prior to creating the index

access_method: str

Index access method; NULL for default

where_clause: Node

Partial index predicate

pktable: RangeVar*

Primary key table

fk_attrs: tuple

Attributes of foreign key

pk_attrs: tuple

Corresponding attrs in PK table

fk_matchtype: str

FULL, PARTIAL, SIMPLE

fk_upd_action: str

ON UPDATE action

fk_del_action: str

ON DELETE action

old_conpfeqop: tuple

Pg_constraint.conpfeqop of my former self

skip_validation: bool

Skip validation of existing rows?

initially_valid: bool

Mark the new constraint as valid?

class pglast.ast.ConstraintsSetStmt(constraints=None, deferred=None)

Wrapper for the homonymous parser node.

constraints: tuple

List of names as RangeVars

deferred: bool
class pglast.ast.ConvertRowtypeExpr(arg=None, convertformat=None, location=None)

Wrapper for the homonymous parser node.

arg: Expr*

Input expression

convertformat: CoercionForm

How to display this node

location: int

Token location, or -1 if unknown

class pglast.ast.CopyStmt(relation=None, query=None, attlist=None, is_from=None, is_program=None, filename=None, options=None, whereClause=None)

Wrapper for the homonymous parser node.

relation: RangeVar*

The relation to copy

query: Node

The query (SELECT or DML statement with RETURNING) to copy, as a raw parse tree

attlist: tuple

List of column names (as Strings), or NIL for all columns

is_from: bool

TO or FROM

is_program: bool

Is ‘filename’ a program to popen?

filename: str

Filename, or NULL for STDIN/STDOUT

options: tuple

List of DefElem nodes

whereClause: Node

WHERE condition (or NULL)

class pglast.ast.CreateAmStmt(amname=None, handler_name=None, amtype=None)

Wrapper for the homonymous parser node.

amname: str

Access method name

handler_name: tuple

Handler function name

amtype: str

Type of access method

class pglast.ast.CreateCastStmt(sourcetype=None, targettype=None, func=None, context=None, inout=None)

Wrapper for the homonymous parser node.

sourcetype: TypeName*
targettype: TypeName*
func: ObjectWithArgs*
context: CoercionContext
inout: bool
class pglast.ast.CreateConversionStmt(conversion_name=None, for_encoding_name=None, to_encoding_name=None, func_name=None, def_=None)

Wrapper for the homonymous parser node.

conversion_name: tuple

Name of the conversion

for_encoding_name: str

Source encoding name

to_encoding_name: str

Destination encoding name

func_name: tuple

Qualified conversion function name

def_: bool

Is this a default conversion?

class pglast.ast.CreateDomainStmt(domainname=None, typeName=None, collClause=None, constraints=None)

Wrapper for the homonymous parser node.

domainname: tuple

Qualified name (list of Value strings)

typeName: TypeName*

The base type

collClause: CollateClause*

Untransformed COLLATE spec, if any

constraints: tuple

Constraints (list of Constraint nodes)

class pglast.ast.CreateEnumStmt(typeName=None, vals=None)

Wrapper for the homonymous parser node.

typeName: tuple

Qualified name (list of Value strings)

vals: tuple

Enum values (list of Value strings)

class pglast.ast.CreateEventTrigStmt(trigname=None, eventname=None, whenclause=None, funcname=None)

Wrapper for the homonymous parser node.

trigname: str

TRIGGER’s name

eventname: str

Event’s identifier

whenclause: tuple

List of DefElems indicating filtering

funcname: tuple

Qual. name of function to call

class pglast.ast.CreateExtensionStmt(extname=None, if_not_exists=None, options=None)

Wrapper for the homonymous parser node.

extname: str
if_not_exists: bool

Just do nothing if it already exists?

options: tuple

List of DefElem nodes

class pglast.ast.CreateFdwStmt(fdwname=None, func_options=None, options=None)

Wrapper for the homonymous parser node.

fdwname: str

Foreign-data wrapper name

func_options: tuple

HANDLER/VALIDATOR options

options: tuple

Generic options to FDW

class pglast.ast.CreateForeignServerStmt(servername=None, servertype=None, version=None, fdwname=None, if_not_exists=None, options=None)

Wrapper for the homonymous parser node.

servername: str

Server name

servertype: str

Optional server type

version: str

Optional server version

fdwname: str

FDW name

if_not_exists: bool

Just do nothing if it already exists?

options: tuple

Generic options to server

class pglast.ast.CreateForeignTableStmt(base=None, servername=None, options=None)

Wrapper for the homonymous parser node.

base: CreateStmt
servername: str
options: tuple
class pglast.ast.CreateFunctionStmt(is_procedure=None, replace=None, funcname=None, parameters=None, returnType=None, options=None, sql_body=None)

Wrapper for the homonymous parser node.

is_procedure: bool

It’s really CREATE PROCEDURE

replace: bool

T => replace if already exists

funcname: tuple

Qualified name of function to create

parameters: tuple

A list of FunctionParameter

returnType: TypeName*

The return type

options: tuple

A list of DefElem

sql_body: Node
class pglast.ast.CreateOpClassItem(itemtype=None, name=None, number=None, order_family=None, class_args=None, storedtype=None)

Wrapper for the homonymous parser node.

itemtype: int

See codes above

name: ObjectWithArgs*

Operator or function name and args

number: int

Strategy num or support proc num

order_family: tuple

Only used for ordering operators

class_args: tuple

Amproclefttype/amprocrighttype or amoplefttype/amoprighttype

storedtype: TypeName*

Datatype stored in index

class pglast.ast.CreateOpClassStmt(opclassname=None, opfamilyname=None, amname=None, datatype=None, items=None, isDefault=None)

Wrapper for the homonymous parser node.

opclassname: tuple

Qualified name (list of Value strings)

opfamilyname: tuple

Qualified name (ditto); NIL if omitted

amname: str

Name of index AM opclass is for

datatype: TypeName*

Datatype of indexed column

items: tuple

List of CreateOpClassItem nodes

isDefault: bool

Should be marked as default for type?

class pglast.ast.CreateOpFamilyStmt(opfamilyname=None, amname=None)

Wrapper for the homonymous parser node.

opfamilyname: tuple

Qualified name (list of Value strings)

amname: str

Name of index AM opfamily is for

class pglast.ast.CreatePLangStmt(replace=None, plname=None, plhandler=None, plinline=None, plvalidator=None, pltrusted=None)

Wrapper for the homonymous parser node.

replace: bool

T => replace if already exists

plname: str

PL name

plhandler: tuple

PL call handler function (qual. name)

plinline: tuple

Optional inline function (qual. name)

plvalidator: tuple

Optional validator function (qual. name)

pltrusted: bool

PL is trusted

class pglast.ast.CreatePolicyStmt(policy_name=None, table=None, cmd_name=None, permissive=None, roles=None, qual=None, with_check=None)

Wrapper for the homonymous parser node.

policy_name: str

Policy’s name

table: RangeVar*

The table name the policy applies to

cmd_name: str

The command name the policy applies to

permissive: bool

Restrictive or permissive policy

roles: tuple

The roles associated with the policy

qual: Node

The policy’s condition

with_check: Node

The policy’s WITH CHECK condition.

class pglast.ast.CreatePublicationStmt(pubname=None, options=None, tables=None, for_all_tables=None)

Wrapper for the homonymous parser node.

pubname: str

Name of the publication

options: tuple

List of DefElem nodes

tables: tuple

Optional list of tables to add

for_all_tables: bool

Special publication for all tables in db

class pglast.ast.CreateRangeStmt(typeName=None, params=None)

Wrapper for the homonymous parser node.

typeName: tuple

Qualified name (list of Value strings)

params: tuple

Range parameters (list of DefElem)

class pglast.ast.CreateRoleStmt(stmt_type=None, role=None, options=None)

Wrapper for the homonymous parser node.

stmt_type: RoleStmtType

ROLE/USER/GROUP

role: str

Role name

options: tuple

List of DefElem nodes

class pglast.ast.CreateSchemaStmt(schemaname=None, authrole=None, schemaElts=None, if_not_exists=None)

Wrapper for the homonymous parser node.

schemaname: str

The name of the schema to create

authrole: RoleSpec*

The owner of the created schema

schemaElts: tuple

Schema components (list of parsenodes)

if_not_exists: bool

Just do nothing if schema already exists?

class pglast.ast.CreateSeqStmt(sequence=None, options=None, for_identity=None, if_not_exists=None)

Wrapper for the homonymous parser node.

sequence: RangeVar*

The sequence to create

options: tuple
for_identity: bool
if_not_exists: bool

Just do nothing if it already exists?

class pglast.ast.CreateStatsStmt(defnames=None, stat_types=None, exprs=None, relations=None, stxcomment=None, transformed=None, if_not_exists=None)

Wrapper for the homonymous parser node.

defnames: tuple

Qualified name (list of Value strings)

stat_types: tuple

Stat types (list of Value strings)

exprs: tuple

Expressions to build statistics on

relations: tuple

Rels to build stats on (list of RangeVar)

stxcomment: str

Comment to apply to stats, or NULL

transformed: bool

True when transformStatsStmt is finished

if_not_exists: bool

Do nothing if stats name already exists

class pglast.ast.CreateStmt(relation=None, tableElts=None, inhRelations=None, partbound=None, partspec=None, ofTypename=None, constraints=None, options=None, oncommit=None, tablespacename=None, accessMethod=None, if_not_exists=None)

Wrapper for the homonymous parser node.

relation: RangeVar*

Relation to create

tableElts: tuple

Column definitions (list of ColumnDef)

inhRelations: tuple

Relations to inherit from (list of RangeVar)

partbound: PartitionBoundSpec*

FOR VALUES clause

partspec: PartitionSpec*

PARTITION BY clause

ofTypename: TypeName*

OF typename

constraints: tuple

Constraints (list of Constraint nodes)

options: tuple

Options from WITH clause

oncommit: OnCommitAction

What do we do at COMMIT?

tablespacename: str

Table space to use, or NULL

accessMethod: str

Table access method

if_not_exists: bool

Just do nothing if it already exists?

class pglast.ast.CreateSubscriptionStmt(subname=None, conninfo=None, publication=None, options=None)

Wrapper for the homonymous parser node.

subname: str

Name of the subscription

conninfo: str

Connection string to publisher

publication: tuple

One or more publication to subscribe to

options: tuple

List of DefElem nodes

class pglast.ast.CreateTableAsStmt(query=None, into=None, objtype=None, is_select_into=None, if_not_exists=None)

Wrapper for the homonymous parser node.

query: Node

The query (see comments above)

into: IntoClause*

Destination table

objtype: ObjectType

OBJECT_TABLE or OBJECT_MATVIEW

is_select_into: bool

It was written as SELECT INTO

if_not_exists: bool

Just do nothing if it already exists?

class pglast.ast.CreateTableSpaceStmt(tablespacename=None, owner=None, location=None, options=None)

Wrapper for the homonymous parser node.

tablespacename: str
owner: RoleSpec*
location: str
options: tuple
class pglast.ast.CreateTransformStmt(replace=None, type_name=None, lang=None, fromsql=None, tosql=None)

Wrapper for the homonymous parser node.

replace: bool
type_name: TypeName*
lang: str
fromsql: ObjectWithArgs*
tosql: ObjectWithArgs*
class pglast.ast.CreateTrigStmt(replace=None, isconstraint=None, trigname=None, relation=None, funcname=None, args=None, row=None, timing=None, events=None, columns=None, whenClause=None, transitionRels=None, deferrable=None, initdeferred=None, constrrel=None)

Wrapper for the homonymous parser node.

replace: bool

Replace trigger if already exists

isconstraint: bool

This is a constraint trigger

trigname: str

TRIGGER’s name

relation: RangeVar*

Relation trigger is on

funcname: tuple

Qual. name of function to call

args: tuple

List of (T_String) Values or NIL

row: bool

ROW/STATEMENT

timing: int16

BEFORE, AFTER, or INSTEAD

events: int16

“OR” of INSERT/UPDATE/DELETE/TRUNCATE

columns: tuple

Column names, or NIL for all columns

whenClause: Node

Qual expression, or NULL if none

transitionRels: tuple

TriggerTransition nodes, or NIL if none

deferrable: bool

[NOT] DEFERRABLE

initdeferred: bool

INITIALLY {DEFERRED|IMMEDIATE}

constrrel: RangeVar*

Opposite relation, if RI trigger

class pglast.ast.CreateUserMappingStmt(user=None, servername=None, if_not_exists=None, options=None)

Wrapper for the homonymous parser node.

user: RoleSpec*

User role

servername: str

Server name

if_not_exists: bool

Just do nothing if it already exists?

options: tuple

Generic options to server

class pglast.ast.CreatedbStmt(dbname=None, options=None)

Wrapper for the homonymous parser node.

dbname: str

Name of database to create

options: tuple

List of DefElem nodes

class pglast.ast.CurrentOfExpr(cvarno=None, cursor_name=None, cursor_param=None)

Wrapper for the homonymous parser node.

cvarno: Index

RT index of target relation

cursor_name: str

Name of referenced cursor, or NULL

cursor_param: int

Refcursor parameter number, or 0

class pglast.ast.DeallocateStmt(name=None)

Wrapper for the homonymous parser node.

name: str

The name of the plan to remove

class pglast.ast.DeclareCursorStmt(portalname=None, options=None, query=None)

Wrapper for the homonymous parser node.

portalname: str

Name of the portal (cursor)

options: int

Bitmask of options (see above)

query: Node

The query (see comments above)

class pglast.ast.DefElem(defnamespace=None, defname=None, arg=None, defaction=None, location=None)

Wrapper for the homonymous parser node.

defnamespace: str

NULL if unqualified name

defname: str
arg: Node

A (Value *) or a (TypeName *)

defaction: DefElemAction

Unspecified action, or SET/ADD/DROP

location: int

Token location, or -1 if unknown

class pglast.ast.DefineStmt(kind=None, oldstyle=None, defnames=None, args=None, definition=None, if_not_exists=None, replace=None)

Wrapper for the homonymous parser node.

kind: ObjectType

Aggregate, operator, type

oldstyle: bool

Hack to signal old CREATE AGG syntax

defnames: tuple

Qualified name (list of Value strings)

args: tuple

A list of TypeName (if needed)

definition: tuple

A list of DefElem

if_not_exists: bool

Just do nothing if it already exists?

replace: bool

Replace if already exists?

class pglast.ast.DeleteStmt(relation=None, usingClause=None, whereClause=None, returningList=None, withClause=None)

Wrapper for the homonymous parser node.

relation: RangeVar*

Relation to delete from

usingClause: tuple

Optional using clause for more tables

whereClause: Node

Qualifications

returningList: tuple

List of expressions to return

withClause: WithClause*

WITH clause

class pglast.ast.DiscardStmt(target=None)

Wrapper for the homonymous parser node.

target: DiscardMode
class pglast.ast.DoStmt(args=None)

Wrapper for the homonymous parser node.

args: tuple

List of DefElem nodes

class pglast.ast.DropOwnedStmt(roles=None, behavior=None)

Wrapper for the homonymous parser node.

roles: tuple
behavior: DropBehavior
class pglast.ast.DropRoleStmt(roles=None, missing_ok=None)

Wrapper for the homonymous parser node.

roles: tuple

List of roles to remove

missing_ok: bool

Skip error if a role is missing?

class pglast.ast.DropStmt(objects=None, removeType=None, behavior=None, missing_ok=None, concurrent=None)

Wrapper for the homonymous parser node.

objects: tuple

List of names

removeType: ObjectType

Object type

behavior: DropBehavior

RESTRICT or CASCADE behavior

missing_ok: bool

Skip error if object is missing?

concurrent: bool

Drop index concurrently?

class pglast.ast.DropSubscriptionStmt(subname=None, missing_ok=None, behavior=None)

Wrapper for the homonymous parser node.

subname: str

Name of the subscription

missing_ok: bool

Skip error if missing?

behavior: DropBehavior

RESTRICT or CASCADE behavior

class pglast.ast.DropTableSpaceStmt(tablespacename=None, missing_ok=None)

Wrapper for the homonymous parser node.

tablespacename: str
missing_ok: bool

Skip error if missing?

class pglast.ast.DropUserMappingStmt(user=None, servername=None, missing_ok=None)

Wrapper for the homonymous parser node.

user: RoleSpec*

User role

servername: str

Server name

missing_ok: bool

Ignore missing mappings

class pglast.ast.DropdbStmt(dbname=None, missing_ok=None, options=None)

Wrapper for the homonymous parser node.

dbname: str

Database to drop

missing_ok: bool

Skip error if db is missing?

options: tuple

Currently only FORCE is supported

class pglast.ast.ExecuteStmt(name=None, params=None)

Wrapper for the homonymous parser node.

name: str

The name of the plan to execute

params: tuple

Values to assign to parameters

class pglast.ast.ExplainStmt(query=None, options=None)

Wrapper for the homonymous parser node.

query: Node

The query (see comments above)

options: tuple

List of DefElem nodes

class pglast.ast.FetchStmt(direction=None, howMany=None, portalname=None, ismove=None)

Wrapper for the homonymous parser node.

direction: FetchDirection
howMany: long

Number of rows, or position argument

portalname: str

Name of portal (cursor)

ismove: bool

True if MOVE

class pglast.ast.FieldSelect(arg=None, fieldnum=None, resulttypmod=None)

Wrapper for the homonymous parser node.

arg: Expr*

Input expression

fieldnum: AttrNumber

Attribute number of field to extract

resulttypmod: int32

Output typmod (usually -1)

class pglast.ast.FieldStore(arg=None, newvals=None, fieldnums=None)

Wrapper for the homonymous parser node.

arg: Expr*

Input tuple value

newvals: tuple

New value(s) for field(s)

fieldnums: tuple

Integer list of field attnums

class pglast.ast.FromExpr(fromlist=None, quals=None)

Wrapper for the homonymous parser node.

fromlist: tuple

List of join subtrees

quals: Node

Qualifiers on join, if any

class pglast.ast.FuncCall(funcname=None, args=None, agg_order=None, agg_filter=None, over=None, agg_within_group=None, agg_star=None, agg_distinct=None, func_variadic=None, funcformat=None, location=None)

Wrapper for the homonymous parser node.

funcname: tuple

Qualified name of function

args: tuple

The arguments (list of exprs)

agg_order: tuple

ORDER BY (list of SortBy)

agg_filter: Node

FILTER clause, if any

over: WindowDef*

OVER clause, if any

agg_within_group: bool

ORDER BY appeared in WITHIN GROUP

agg_star: bool

Argument was really ‘*’

agg_distinct: bool

Arguments were labeled DISTINCT

func_variadic: bool

Last argument was labeled VARIADIC

funcformat: CoercionForm

How to display this node

location: int

Token location, or -1 if unknown

class pglast.ast.FuncExpr(funcretset=None, funcvariadic=None, funcformat=None, args=None, location=None)

Wrapper for the homonymous parser node.

funcretset: bool

True if function returns set

funcvariadic: bool

True if variadic arguments have been combined into an array last argument

funcformat: CoercionForm

How to display this function call

args: tuple

Arguments to the function

location: int

Token location, or -1 if unknown

class pglast.ast.FunctionParameter(name=None, argType=None, mode=None, defexpr=None)

Wrapper for the homonymous parser node.

name: str

Parameter name, or NULL if not given

argType: TypeName*

TypeName for parameter type

mode: FunctionParameterMode

IN/OUT/etc

defexpr: Node

Raw default expr, or NULL if not given

class pglast.ast.GrantRoleStmt(granted_roles=None, grantee_roles=None, is_grant=None, admin_opt=None, grantor=None, behavior=None)

Wrapper for the homonymous parser node.

granted_roles: tuple

List of roles to be granted/revoked

grantee_roles: tuple

List of member roles to add/delete

is_grant: bool

True = GRANT, false = REVOKE

admin_opt: bool

With admin option

grantor: RoleSpec*

Set grantor to other than current role

behavior: DropBehavior

Drop behavior (for REVOKE)

class pglast.ast.GrantStmt(is_grant=None, targtype=None, objtype=None, objects=None, privileges=None, grantees=None, grant_option=None, grantor=None, behavior=None)

Wrapper for the homonymous parser node.

is_grant: bool

True = GRANT, false = REVOKE

targtype: GrantTargetType

Type of the grant target

objtype: ObjectType

Kind of object being operated on

objects: tuple

List of RangeVar nodes, ObjectWithArgs nodes, or plain names (as Value strings)

privileges: tuple

List of AccessPriv nodes

grantees: tuple

List of RoleSpec nodes

grant_option: bool

Grant or revoke grant option

grantor: RoleSpec*
behavior: DropBehavior

Drop behavior (for REVOKE)

class pglast.ast.GroupingFunc(args=None, refs=None, cols=None, agglevelsup=None, location=None)

Wrapper for the homonymous parser node.

args: tuple

Arguments, not evaluated but kept for benefit of EXPLAIN etc.

refs: tuple

Ressortgrouprefs of arguments

cols: tuple

Actual column positions set by planner

agglevelsup: Index

Same as Aggref.agglevelsup

location: int

Token location

class pglast.ast.GroupingSet(kind=None, content=None, location=None)

Wrapper for the homonymous parser node.

kind: GroupingSetKind
content: tuple
location: int
class pglast.ast.ImportForeignSchemaStmt(server_name=None, remote_schema=None, local_schema=None, list_type=None, table_list=None, options=None)

Wrapper for the homonymous parser node.

server_name: str

FDW server name

remote_schema: str

Remote schema name to query

local_schema: str

Local schema to create objects in

list_type: ImportForeignSchemaType

Type of table list

table_list: tuple

List of RangeVar

options: tuple

List of options to pass to FDW

class pglast.ast.IndexElem(name=None, expr=None, indexcolname=None, collation=None, opclass=None, opclassopts=None, ordering=None, nulls_ordering=None)

Wrapper for the homonymous parser node.

name: str

Name of attribute to index, or NULL

expr: Node

Expression to index, or NULL

indexcolname: str

Name for index column; NULL = default

collation: tuple

Name of collation; NIL = default

opclass: tuple

Name of desired opclass; NIL = default

opclassopts: tuple

Opclass-specific options, or NIL

ordering: SortByDir

ASC/DESC/default

nulls_ordering: SortByNulls

FIRST/LAST/default

class pglast.ast.IndexStmt(idxname=None, relation=None, accessMethod=None, tableSpace=None, indexParams=None, indexIncludingParams=None, options=None, whereClause=None, excludeOpNames=None, idxcomment=None, oldCreateSubid=None, oldFirstRelfilenodeSubid=None, unique=None, primary=None, isconstraint=None, deferrable=None, initdeferred=None, transformed=None, concurrent=None, if_not_exists=None, reset_default_tblspc=None)

Wrapper for the homonymous parser node.

idxname: str

Name of new index, or NULL for default

relation: RangeVar*

Relation to build index on

accessMethod: str

Name of access method (eg. btree)

tableSpace: str

Tablespace, or NULL for default

indexParams: tuple

Columns to index: a list of IndexElem

indexIncludingParams: tuple

Additional columns to index: a list of IndexElem

options: tuple

WITH clause options: a list of DefElem

whereClause: Node

Qualification (partial-index predicate)

excludeOpNames: tuple

Exclusion operator names, or NIL if none

idxcomment: str

Comment to apply to index, or NULL

oldCreateSubid: SubTransactionId

Rd_createSubid of oldNode

oldFirstRelfilenodeSubid: SubTransactionId

Rd_firstRelfilenodeSubid of oldNode

unique: bool

Is index unique?

primary: bool

Is index a primary key?

isconstraint: bool

Is it for a pkey/unique constraint?

deferrable: bool

Is the constraint DEFERRABLE?

initdeferred: bool

Is the constraint INITIALLY DEFERRED?

transformed: bool

True when transformIndexStmt is finished

concurrent: bool

Should this be a concurrent index build?

if_not_exists: bool

Just do nothing if index already exists?

reset_default_tblspc: bool

Reset default_tablespace prior to executing

class pglast.ast.InferClause(indexElems=None, whereClause=None, conname=None, location=None)

Wrapper for the homonymous parser node.

indexElems: tuple

IndexElems to infer unique index

whereClause: Node

Qualification (partial-index predicate)

conname: str

Constraint name, or NULL if unnamed

location: int

Token location, or -1 if unknown

class pglast.ast.InferenceElem(expr=None)

Wrapper for the homonymous parser node.

expr: Node

Expression to infer from, or NULL

class pglast.ast.InlineCodeBlock(source_text=None, langIsTrusted=None, atomic=None)

Wrapper for the homonymous parser node.

source_text: str

Source text of anonymous code block

langIsTrusted: bool

Trusted property of the language

atomic: bool

Atomic execution context

class pglast.ast.InsertStmt(relation=None, cols=None, selectStmt=None, onConflictClause=None, returningList=None, withClause=None, override=None)

Wrapper for the homonymous parser node.

relation: RangeVar*

Relation to insert into

cols: tuple

Optional: names of the target columns

selectStmt: Node

The source SELECT/VALUES, or NULL

onConflictClause: OnConflictClause*

ON CONFLICT clause

returningList: tuple

List of expressions to return

withClause: WithClause*

WITH clause

override: OverridingKind

OVERRIDING clause

class pglast.ast.IntoClause(rel=None, colNames=None, accessMethod=None, options=None, onCommit=None, tableSpaceName=None, viewQuery=None, skipData=None)

Wrapper for the homonymous parser node.

rel: RangeVar*

Target relation name

colNames: tuple

Column names to assign, or NIL

accessMethod: str

Table access method

options: tuple

Options from WITH clause

onCommit: OnCommitAction

What do we do at COMMIT?

tableSpaceName: str

Table space to use, or NULL

viewQuery: Node

Materialized view’s SELECT query

skipData: bool

True for WITH NO DATA

class pglast.ast.JoinExpr(jointype=None, isNatural=None, larg=None, rarg=None, usingClause=None, join_using_alias=None, quals=None, alias=None, rtindex=None)

Wrapper for the homonymous parser node.

jointype: JoinType

Type of join

isNatural: bool

Natural join? Will need to shape table

larg: Node

Left subtree

rarg: Node

Right subtree

usingClause: tuple

USING clause, if any (list of String)

join_using_alias: Alias*

Alias attached to USING clause, if any

quals: Node

Qualifiers on join, if any

alias: Alias*

User-written alias clause, if any

rtindex: int

RT index assigned for join, or 0

class pglast.ast.ListenStmt(conditionname=None)

Wrapper for the homonymous parser node.

conditionname: str

Condition name to listen on

class pglast.ast.LoadStmt(filename=None)

Wrapper for the homonymous parser node.

filename: str

File to load

class pglast.ast.LockStmt(relations=None, mode=None, nowait=None)

Wrapper for the homonymous parser node.

relations: tuple

Relations to lock

mode: int

Lock mode

nowait: bool

No wait mode

class pglast.ast.LockingClause(lockedRels=None, strength=None, waitPolicy=None)

Wrapper for the homonymous parser node.

lockedRels: tuple

FOR [KEY] UPDATE/SHARE relations

strength: LockClauseStrength
waitPolicy: LockWaitPolicy

NOWAIT and SKIP LOCKED

class pglast.ast.MinMaxExpr(op=None, args=None, location=None)

Wrapper for the homonymous parser node.

op: MinMaxOp

Function to execute

args: tuple

The arguments

location: int

Token location, or -1 if unknown

class pglast.ast.MultiAssignRef(source=None, colno=None, ncolumns=None)

Wrapper for the homonymous parser node.

source: Node

The row-valued expression

colno: int

Column number for this target (1..n)

ncolumns: int

Number of targets in the construct

class pglast.ast.NamedArgExpr(arg=None, name=None, argnumber=None, location=None)

Wrapper for the homonymous parser node.

arg: Expr*

The argument expression

name: str

The name

argnumber: int

Argument’s number in positional notation

location: int

Argument name location, or -1 if unknown

class pglast.ast.NotifyStmt(conditionname=None, payload=None)

Wrapper for the homonymous parser node.

conditionname: str

Condition name to notify

payload: str

The payload string, or NULL if none

class pglast.ast.NullTest(arg=None, nulltesttype=None, argisrow=None, location=None)

Wrapper for the homonymous parser node.

arg: Expr*

Input expression

nulltesttype: NullTestType

IS NULL, IS NOT NULL

argisrow: bool

T to perform field-by-field null checks

location: int

Token location, or -1 if unknown

class pglast.ast.ObjectWithArgs(objname=None, objargs=None, objfuncargs=None, args_unspecified=None)

Wrapper for the homonymous parser node.

objname: tuple

Qualified name of function/operator

objargs: tuple

List of Typename nodes (input args only)

objfuncargs: tuple

List of FunctionParameter nodes

args_unspecified: bool

Argument list was omitted?

class pglast.ast.OnConflictClause(action=None, infer=None, targetList=None, whereClause=None, location=None)

Wrapper for the homonymous parser node.

action: OnConflictAction

DO NOTHING or UPDATE?

infer: InferClause*

Optional index inference clause

targetList: tuple

The target list (of ResTarget)

whereClause: Node

Qualifications

location: int

Token location, or -1 if unknown

class pglast.ast.OnConflictExpr(action=None, arbiterElems=None, arbiterWhere=None, onConflictSet=None, onConflictWhere=None, exclRelIndex=None, exclRelTlist=None)

Wrapper for the homonymous parser node.

action: OnConflictAction

DO NOTHING or UPDATE?

arbiterElems: tuple

Unique index arbiter list (of InferenceElem’s)

arbiterWhere: Node

Unique index arbiter WHERE clause

onConflictSet: tuple

List of ON CONFLICT SET TargetEntrys

onConflictWhere: Node

Qualifiers to restrict UPDATE to

exclRelIndex: int

RT index of ‘excluded’ relation

exclRelTlist: tuple

Tlist of the EXCLUDED pseudo relation

class pglast.ast.OpExpr(opretset=None, args=None, location=None)

Wrapper for the homonymous parser node.

opretset: bool

True if operator returns set

args: tuple

Arguments to the operator (1 or 2)

location: int

Token location, or -1 if unknown

class pglast.ast.PLAssignStmt(name=None, indirection=None, nnames=None, val=None, location=None)

Wrapper for the homonymous parser node.

name: str

Initial column name

indirection: tuple

Subscripts and field names, if any

nnames: int

Number of names to use in ColumnRef

val: SelectStmt*

The PL/pgSQL expression to assign

location: int

Name’s token location, or -1 if unknown

class pglast.ast.Param(paramkind=None, paramid=None, paramtypmod=None, location=None)

Wrapper for the homonymous parser node.

paramkind: ParamKind

Kind of parameter. See above

paramid: int

Numeric ID for parameter

paramtypmod: int32

Typmod value, if known

location: int

Token location, or -1 if unknown

class pglast.ast.ParamRef(number=None, location=None)

Wrapper for the homonymous parser node.

number: int

The number of the parameter

location: int

Token location, or -1 if unknown

class pglast.ast.PartitionBoundSpec(strategy=None, is_default=None, modulus=None, remainder=None, listdatums=None, lowerdatums=None, upperdatums=None, location=None)

Wrapper for the homonymous parser node.

strategy: str

See PARTITION_STRATEGY codes above

is_default: bool

Is it a default partition bound?

modulus: int
remainder: int
listdatums: tuple

List of Consts (or A_Consts in raw tree)

lowerdatums: tuple

List of PartitionRangeDatums

upperdatums: tuple

List of PartitionRangeDatums

location: int

Token location, or -1 if unknown

class pglast.ast.PartitionCmd(name=None, bound=None, concurrent=None)

Wrapper for the homonymous parser node.

name: RangeVar*

Name of partition to attach/detach

bound: PartitionBoundSpec*

FOR VALUES, if attaching

concurrent: bool
class pglast.ast.PartitionElem(name=None, expr=None, collation=None, opclass=None, location=None)

Wrapper for the homonymous parser node.

name: str

Name of column to partition on, or NULL

expr: Node

Expression to partition on, or NULL

collation: tuple

Name of collation; NIL = default

opclass: tuple

Name of desired opclass; NIL = default

location: int

Token location, or -1 if unknown

class pglast.ast.PartitionRangeDatum(kind=None, value=None, location=None)

Wrapper for the homonymous parser node.

kind: PartitionRangeDatumKind
value: Node

Const (or A_Const in raw tree), if kind is PARTITION_RANGE_DATUM_VALUE, else NULL

location: int

Token location, or -1 if unknown

class pglast.ast.PartitionSpec(strategy=None, partParams=None, location=None)

Wrapper for the homonymous parser node.

strategy: str

Partitioning strategy (‘hash’, ‘list’ or ‘range’)

partParams: tuple

List of PartitionElems

location: int

Token location, or -1 if unknown

class pglast.ast.PrepareStmt(name=None, argtypes=None, query=None)

Wrapper for the homonymous parser node.

name: str

Name of plan, arbitrary

argtypes: tuple

Types of parameters (List of TypeName)

query: Node

The query itself (as a raw parsetree)

class pglast.ast.Query(commandType=None, querySource=None, queryId=None, canSetTag=None, utilityStmt=None, resultRelation=None, hasAggs=None, hasWindowFuncs=None, hasTargetSRFs=None, hasSubLinks=None, hasDistinctOn=None, hasRecursive=None, hasModifyingCTE=None, hasForUpdate=None, hasRowSecurity=None, isReturn=None, cteList=None, rtable=None, jointree=None, targetList=None, override=None, onConflict=None, returningList=None, groupClause=None, groupDistinct=None, groupingSets=None, havingQual=None, windowClause=None, distinctClause=None, sortClause=None, limitOffset=None, limitCount=None, limitOption=None, rowMarks=None, setOperations=None, constraintDeps=None, withCheckOptions=None, stmt_location=None, stmt_len=None)

Wrapper for the homonymous parser node.

commandType: CmdType

Select|insert|update|delete|utility

querySource: QuerySource

Where did I come from?

queryId: uint64

Query identifier (can be set by plugins)

canSetTag: bool

Do I set the command result tag?

utilityStmt: Node

Non-null if commandType == CMD_UTILITY

resultRelation: int

Rtable index of target relation for INSERT/UPDATE/DELETE; 0 for SELECT

hasAggs: bool

Has aggregates in tlist or havingQual

hasWindowFuncs: bool

Has window functions in tlist

hasTargetSRFs: bool

Has set-returning functions in tlist

Has subquery SubLink

hasDistinctOn: bool

DistinctClause is from DISTINCT ON

hasRecursive: bool

WITH RECURSIVE was specified

hasModifyingCTE: bool

Has INSERT/UPDATE/DELETE in WITH

hasForUpdate: bool

FOR [KEY] UPDATE/SHARE was specified

hasRowSecurity: bool

Rewriter has applied some RLS policy

isReturn: bool

Is a RETURN statement

cteList: tuple

WITH list (of CommonTableExpr’s)

rtable: tuple

List of range table entries

jointree: FromExpr*

Table join tree (FROM and WHERE clauses)

targetList: tuple

Target list (of TargetEntry)

override: OverridingKind

OVERRIDING clause

onConflict: OnConflictExpr*

ON CONFLICT DO [NOTHING | UPDATE]

returningList: tuple

Return-values list (of TargetEntry)

groupClause: tuple

A list of SortGroupClause’s

groupDistinct: bool

Is the group by clause distinct?

groupingSets: tuple

A list of GroupingSet’s if present

havingQual: Node

Qualifications applied to groups

windowClause: tuple

A list of WindowClause’s

distinctClause: tuple

A list of SortGroupClause’s

sortClause: tuple

A list of SortGroupClause’s

limitOffset: Node

# of result tuples to skip (int8 expr)

limitCount: Node

# of result tuples to return (int8 expr)

limitOption: LimitOption

Limit type

rowMarks: tuple

A list of RowMarkClause’s

setOperations: Node

Set-operation tree if this is top level of a UNION/INTERSECT/EXCEPT query

constraintDeps: tuple

A list of pg_constraint OIDs that the query depends on to be semantically valid

withCheckOptions: tuple

A list of WithCheckOption’s (added during rewrite)

stmt_location: int

Start location, or -1 if unknown

stmt_len: int

Length in bytes; 0 means “rest of string”

class pglast.ast.RangeFunction(lateral=None, ordinality=None, is_rowsfrom=None, functions=None, alias=None, coldeflist=None)

Wrapper for the homonymous parser node.

lateral: bool

Does it have LATERAL prefix?

ordinality: bool

Does it have WITH ORDINALITY suffix?

is_rowsfrom: bool

Is result of ROWS FROM() syntax?

functions: tuple

Per-function information, see above

alias: Alias*

Table alias & optional column aliases

coldeflist: tuple

List of ColumnDef nodes to describe result of function returning RECORD

class pglast.ast.RangeSubselect(lateral=None, subquery=None, alias=None)

Wrapper for the homonymous parser node.

lateral: bool

Does it have LATERAL prefix?

subquery: Node

The untransformed sub-select clause

alias: Alias*

Table alias & optional column aliases

class pglast.ast.RangeTableFunc(lateral=None, docexpr=None, rowexpr=None, namespaces=None, columns=None, alias=None, location=None)

Wrapper for the homonymous parser node.

lateral: bool

Does it have LATERAL prefix?

docexpr: Node

Document expression

rowexpr: Node

Row generator expression

namespaces: tuple

List of namespaces as ResTarget

columns: tuple

List of RangeTableFuncCol

alias: Alias*

Table alias & optional column aliases

location: int

Token location, or -1 if unknown

class pglast.ast.RangeTableFuncCol(colname=None, typeName=None, for_ordinality=None, is_not_null=None, colexpr=None, coldefexpr=None, location=None)

Wrapper for the homonymous parser node.

colname: str

Name of generated column

typeName: TypeName*

Type of generated column

for_ordinality: bool

Does it have FOR ORDINALITY?

is_not_null: bool

Does it have NOT NULL?

colexpr: Node

Column filter expression

coldefexpr: Node

Column default value expression

location: int

Token location, or -1 if unknown

class pglast.ast.RangeTableSample(relation=None, method=None, args=None, repeatable=None, location=None)

Wrapper for the homonymous parser node.

relation: Node

Relation to be sampled

method: tuple

Sampling method name (possibly qualified)

args: tuple

Argument(s) for sampling method

repeatable: Node

REPEATABLE expression, or NULL if none

location: int

Method name location, or -1 if unknown

class pglast.ast.RangeTblEntry(rtekind=None, relkind=None, rellockmode=None, tablesample=None, subquery=None, security_barrier=None, jointype=None, joinmergedcols=None, joinaliasvars=None, joinleftcols=None, joinrightcols=None, join_using_alias=None, functions=None, funcordinality=None, tablefunc=None, values_lists=None, ctename=None, ctelevelsup=None, self_reference=None, coltypes=None, coltypmods=None, colcollations=None, enrname=None, enrtuples=None, alias=None, eref=None, lateral=None, inh=None, inFromCl=None, requiredPerms=None, selectedCols=None, insertedCols=None, updatedCols=None, extraUpdatedCols=None, securityQuals=None)

Wrapper for the homonymous parser node.

rtekind: RTEKind
relkind: str

Relation kind (see pg_class.relkind)

rellockmode: int

Lock level that query requires on the rel

tablesample: TableSampleClause*

Sampling info, or NULL

subquery: Query*

The sub-query

security_barrier: bool

Is from security_barrier view?

jointype: JoinType

Type of join

joinmergedcols: int

Number of merged (JOIN USING) columns

joinaliasvars: tuple

List of alias-var expansions

joinleftcols: tuple

Left-side input column numbers

joinrightcols: tuple

Right-side input column numbers

join_using_alias: Alias*
functions: tuple

List of RangeTblFunction nodes

funcordinality: bool

Is this called WITH ORDINALITY?

tablefunc: TableFunc*
values_lists: tuple

List of expression lists

ctename: str

Name of the WITH list item

ctelevelsup: Index

Number of query levels up

self_reference: bool

Is this a recursive self-reference?

coltypes: tuple

OID list of column type OIDs

coltypmods: tuple

Integer list of column typmods

colcollations: tuple

OID list of column collation OIDs

enrname: str

Name of ephemeral named relation

enrtuples: double

Estimated or actual from caller

alias: Alias*

User-written alias clause, if any

eref: Alias*

Expanded reference names

lateral: bool

Subquery, function, or values is LATERAL?

inh: bool

Inheritance requested?

inFromCl: bool

Present in FROM clause?

requiredPerms: AclMode

Bitmask of required access permissions

selectedCols: Bitmapset*

Columns needing SELECT permission

insertedCols: Bitmapset*

Columns needing INSERT permission

updatedCols: Bitmapset*

Columns needing UPDATE permission

extraUpdatedCols: Bitmapset*

Generated columns being updated

securityQuals: tuple

Security barrier quals to apply, if any

class pglast.ast.RangeTblFunction(funcexpr=None, funccolcount=None, funccolnames=None, funccoltypes=None, funccoltypmods=None, funccolcollations=None, funcparams=None)

Wrapper for the homonymous parser node.

funcexpr: Node

Expression tree for func call

funccolcount: int

Number of columns it contributes to RTE

funccolnames: tuple

Column names (list of String)

funccoltypes: tuple

OID list of column type OIDs

funccoltypmods: tuple

Integer list of column typmods

funccolcollations: tuple

OID list of column collation OIDs

funcparams: Bitmapset*

PARAM_EXEC Param IDs affecting this func

class pglast.ast.RangeTblRef(rtindex=None)

Wrapper for the homonymous parser node.

rtindex: int
class pglast.ast.RangeVar(catalogname=None, schemaname=None, relname=None, inh=None, relpersistence=None, alias=None, location=None)

Wrapper for the homonymous parser node.

catalogname: str

The catalog (database) name, or NULL

schemaname: str

The schema name, or NULL

relname: str

The relation/sequence name

inh: bool

Expand rel by inheritance? recursively act on children?

relpersistence: str

See RELPERSISTENCE_* in pg_class.h

alias: Alias*

Table alias & optional column aliases

location: int

Token location, or -1 if unknown

class pglast.ast.RawStmt(stmt=None, stmt_location=None, stmt_len=None)

Wrapper for the homonymous parser node.

stmt: Node

Raw parse tree

stmt_location: int

Start location, or -1 if unknown

stmt_len: int

Length in bytes; 0 means “rest of string”

class pglast.ast.ReassignOwnedStmt(roles=None, newrole=None)

Wrapper for the homonymous parser node.

roles: tuple
newrole: RoleSpec*
class pglast.ast.RefreshMatViewStmt(concurrent=None, skipData=None, relation=None)

Wrapper for the homonymous parser node.

concurrent: bool

Allow concurrent access?

skipData: bool

True for WITH NO DATA

relation: RangeVar*

Relation to insert into

class pglast.ast.ReindexStmt(kind=None, relation=None, name=None, params=None)

Wrapper for the homonymous parser node.

kind: ReindexObjectType

REINDEX_OBJECT_INDEX, REINDEX_OBJECT_TABLE, etc.

relation: RangeVar*

Table or index to reindex

name: str

Name of database to reindex

params: tuple

List of DefElem nodes

class pglast.ast.RelabelType(arg=None, resulttypmod=None, relabelformat=None, location=None)

Wrapper for the homonymous parser node.

arg: Expr*

Input expression

resulttypmod: int32

Output typmod (usually -1)

relabelformat: CoercionForm

How to display this node

location: int

Token location, or -1 if unknown

class pglast.ast.RenameStmt(renameType=None, relationType=None, relation=None, object=None, subname=None, newname=None, behavior=None, missing_ok=None)

Wrapper for the homonymous parser node.

renameType: ObjectType

OBJECT_TABLE, OBJECT_COLUMN, etc

relationType: ObjectType

If column name, associated relation type

relation: RangeVar*

In case it’s a table

object: Node

In case it’s some other object

subname: str

Name of contained object (column, rule, trigger, etc)

newname: str

The new name

behavior: DropBehavior

RESTRICT or CASCADE behavior

missing_ok: bool

Skip error if missing?

class pglast.ast.ReplicaIdentityStmt(identity_type=None, name=None)

Wrapper for the homonymous parser node.

identity_type: str
name: str
class pglast.ast.ResTarget(name=None, indirection=None, val=None, location=None)

Wrapper for the homonymous parser node.

name: str

Column name or NULL

indirection: tuple

Subscripts, field names, and ‘*’, or NIL

val: Node

The value expression to compute or assign

location: int

Token location, or -1 if unknown

class pglast.ast.ReturnStmt(returnval=None)

Wrapper for the homonymous parser node.

returnval: Node
class pglast.ast.RoleSpec(roletype=None, rolename=None, location=None)

Wrapper for the homonymous parser node.

roletype: RoleSpecType

Type of this rolespec

rolename: str

Filled only for ROLESPEC_CSTRING

location: int

Token location, or -1 if unknown

class pglast.ast.RowCompareExpr(rctype=None, opnos=None, opfamilies=None, inputcollids=None, largs=None, rargs=None)

Wrapper for the homonymous parser node.

rctype: RowCompareType

LT LE GE or GT, never EQ or NE

opnos: tuple

OID list of pairwise comparison ops

opfamilies: tuple

OID list of containing operator families

inputcollids: tuple

OID list of collations for comparisons

largs: tuple

The left-hand input arguments

rargs: tuple

The right-hand input arguments

class pglast.ast.RowExpr(args=None, row_format=None, colnames=None, location=None)

Wrapper for the homonymous parser node.

args: tuple

The fields

row_format: CoercionForm

How to display this node

colnames: tuple

List of String, or NIL

location: int

Token location, or -1 if unknown

class pglast.ast.RowMarkClause(rti=None, strength=None, waitPolicy=None, pushedDown=None)

Wrapper for the homonymous parser node.

rti: Index

Range table index of target relation

strength: LockClauseStrength
waitPolicy: LockWaitPolicy

NOWAIT and SKIP LOCKED

pushedDown: bool

Pushed down from higher query level?

class pglast.ast.RuleStmt(relation=None, rulename=None, whereClause=None, event=None, instead=None, actions=None, replace=None)

Wrapper for the homonymous parser node.

relation: RangeVar*

Relation the rule is for

rulename: str

Name of the rule

whereClause: Node

Qualifications

event: CmdType

SELECT, INSERT, etc

instead: bool

Is a ‘do instead’?

actions: tuple

The action statements

replace: bool

OR REPLACE

class pglast.ast.SQLValueFunction(op=None, typmod=None, location=None)

Wrapper for the homonymous parser node.

op: SQLValueFunctionOp

Which function this is

typmod: int32
location: int

Token location, or -1 if unknown

class pglast.ast.ScalarArrayOpExpr(useOr=None, args=None, location=None)

Wrapper for the homonymous parser node.

useOr: bool

True for ANY, false for ALL

args: tuple

The scalar and array operands

location: int

Token location, or -1 if unknown

class pglast.ast.SecLabelStmt(objtype=None, object=None, provider=None, label=None)

Wrapper for the homonymous parser node.

objtype: ObjectType

Object’s type

object: Node

Qualified name of the object

provider: str

Label provider (or NULL)

label: str

New security label to be assigned

class pglast.ast.SelectStmt(distinctClause=None, intoClause=None, targetList=None, fromClause=None, whereClause=None, groupClause=None, groupDistinct=None, havingClause=None, windowClause=None, valuesLists=None, sortClause=None, limitOffset=None, limitCount=None, limitOption=None, lockingClause=None, withClause=None, op=None, all=None, larg=None, rarg=None)

Wrapper for the homonymous parser node.

distinctClause: tuple

NULL, list of DISTINCT ON exprs, or lcons(NIL,NIL) for all (SELECT DISTINCT)

intoClause: IntoClause*

Target for SELECT INTO

targetList: tuple

The target list (of ResTarget)

fromClause: tuple

The FROM clause

whereClause: Node

WHERE qualification

groupClause: tuple

GROUP BY clauses

groupDistinct: bool

Is this GROUP BY DISTINCT?

havingClause: Node

HAVING conditional-expression

windowClause: tuple

WINDOW window_name AS (…), …

valuesLists: tuple

Untransformed list of expression lists

sortClause: tuple

Sort clause (a list of SortBy’s)

limitOffset: Node

# of result tuples to skip

limitCount: Node

# of result tuples to return

limitOption: LimitOption

Limit type

lockingClause: tuple

FOR UPDATE (list of LockingClause’s)

withClause: WithClause*

WITH clause

op: SetOperation

Type of set op

all: bool

ALL specified?

larg: SelectStmt*

Left child

rarg: SelectStmt*

Right child

class pglast.ast.SetOperationStmt(op=None, all=None, larg=None, rarg=None, colTypes=None, colTypmods=None, colCollations=None, groupClauses=None)

Wrapper for the homonymous parser node.

op: SetOperation

Type of set op

all: bool

ALL specified?

larg: Node

Left child

rarg: Node

Right child

colTypes: tuple

OID list of output column type OIDs

colTypmods: tuple

Integer list of output column typmods

colCollations: tuple

OID list of output column collation OIDs

groupClauses: tuple

A list of SortGroupClause’s

class pglast.ast.SetToDefault(typeMod=None, location=None)

Wrapper for the homonymous parser node.

typeMod: int32

Typemod for substituted value

location: int

Token location, or -1 if unknown

class pglast.ast.SortBy(node=None, sortby_dir=None, sortby_nulls=None, useOp=None, location=None)

Wrapper for the homonymous parser node.

node: Node

Expression to sort on

sortby_dir: SortByDir

ASC/DESC/USING/default

sortby_nulls: SortByNulls

NULLS FIRST/LAST

useOp: tuple

Name of op to use, if SORTBY_USING

location: int

Operator location, or -1 if none/unknown

class pglast.ast.SortGroupClause(tleSortGroupRef=None, nulls_first=None, hashable=None)

Wrapper for the homonymous parser node.

tleSortGroupRef: Index

Reference into targetlist

nulls_first: bool

Do NULLs come before normal values?

hashable: bool

Can eqop be implemented by hashing?

class pglast.ast.StatsElem(name=None, expr=None)

Wrapper for the homonymous parser node.

name: str

Name of attribute to index, or NULL

expr: Node

Expression to index, or NULL

Wrapper for the homonymous parser node.

subLinkType: SubLinkType
subLinkId: int

ID (1..n); 0 if not MULTIEXPR

testexpr: Node

Outer-query test for ALL/ANY/ROWCOMPARE

operName: tuple

Originally specified operator name

subselect: Node

Subselect as Query* or raw parsetree

location: int

Token location, or -1 if unknown

class pglast.ast.SubPlan(subLinkType=None, testexpr=None, paramIds=None, plan_id=None, plan_name=None, firstColTypmod=None, useHashTable=None, unknownEqFalse=None, parallel_safe=None, setParam=None, parParam=None, args=None, startup_cost=None, per_call_cost=None)

Wrapper for the homonymous parser node.

subLinkType: SubLinkType
testexpr: Node

OpExpr or RowCompareExpr expression tree

paramIds: tuple

IDs of Params embedded in the above

plan_id: int

Index (from 1) in PlannedStmt.subplans

plan_name: str

A name assigned during planning

firstColTypmod: int32

Typmod of first column of subplan result

useHashTable: bool

True to store subselect output in a hash table (implies we are doing “IN”)

unknownEqFalse: bool

True if it’s okay to return FALSE when the spec result is UNKNOWN; this allows much simpler handling of null values

parallel_safe: bool

Is the subplan parallel-safe?

setParam: tuple

Initplan subqueries have to set these Params for parent plan

parParam: tuple

Indices of input Params from parent plan

args: tuple

Exprs to pass as parParam values

startup_cost: Cost

One-time setup cost

per_call_cost: Cost

Cost for each subplan evaluation

class pglast.ast.SubscriptingRef(reftypmod=None, refupperindexpr=None, reflowerindexpr=None, refexpr=None, refassgnexpr=None)

Wrapper for the homonymous parser node.

reftypmod: int32

Typmod of the result

refupperindexpr: tuple

Expressions that evaluate to upper container indexes

reflowerindexpr: tuple

Expressions that evaluate to lower container indexes, or NIL for single container element

refexpr: Expr*

The expression that evaluates to a container value

refassgnexpr: Expr*

Expression for the source value, or NULL if fetch

class pglast.ast.TableFunc(ns_uris=None, ns_names=None, docexpr=None, rowexpr=None, colnames=None, coltypes=None, coltypmods=None, colcollations=None, colexprs=None, coldefexprs=None, notnulls=None, ordinalitycol=None, location=None)

Wrapper for the homonymous parser node.

ns_uris: tuple

List of namespace URI expressions

ns_names: tuple

List of namespace names or NULL

docexpr: Node

Input document expression

rowexpr: Node

Row filter expression

colnames: tuple

Column names (list of String)

coltypes: tuple

OID list of column type OIDs

coltypmods: tuple

Integer list of column typmods

colcollations: tuple

OID list of column collation OIDs

colexprs: tuple

List of column filter expressions

coldefexprs: tuple

List of column default expressions

notnulls: Bitmapset*

Nullability flag for each output column

ordinalitycol: int

Counts from 0; -1 if none specified

location: int

Token location, or -1 if unknown

class pglast.ast.TableLikeClause(relation=None, options=None)

Wrapper for the homonymous parser node.

relation: RangeVar*
options: bits32

OR of TableLikeOption flags

class pglast.ast.TableSampleClause(args=None, repeatable=None)

Wrapper for the homonymous parser node.

args: tuple

Tablesample argument expression(s)

repeatable: Expr*

REPEATABLE expression, or NULL if none

class pglast.ast.TargetEntry(expr=None, resno=None, resname=None, ressortgroupref=None, resorigcol=None, resjunk=None)

Wrapper for the homonymous parser node.

expr: Expr*

Expression to evaluate

resno: AttrNumber

Attribute number (see notes above)

resname: str

Name of the column (could be NULL)

ressortgroupref: Index

Nonzero if referenced by a sort/group clause

resorigcol: AttrNumber

Column’s number in source table

resjunk: bool

Set to true to eliminate the attribute from final target list

class pglast.ast.TransactionStmt(kind=None, options=None, savepoint_name=None, gid=None, chain=None)

Wrapper for the homonymous parser node.

kind: TransactionStmtKind
options: tuple

For BEGIN/START commands

savepoint_name: str

For savepoint commands

gid: str

For two-phase-commit related commands

chain: bool

AND CHAIN option

class pglast.ast.TriggerTransition(name=None, isNew=None, isTable=None)

Wrapper for the homonymous parser node.

name: str
isNew: bool
isTable: bool
class pglast.ast.TruncateStmt(relations=None, restart_seqs=None, behavior=None)

Wrapper for the homonymous parser node.

relations: tuple

Relations (RangeVars) to be truncated

restart_seqs: bool

Restart owned sequences?

behavior: DropBehavior

RESTRICT or CASCADE behavior

class pglast.ast.TypeCast(arg=None, typeName=None, location=None)

Wrapper for the homonymous parser node.

arg: Node

The expression being casted

typeName: TypeName*

The target type

location: int

Token location, or -1 if unknown

class pglast.ast.TypeName(names=None, setof=None, pct_type=None, typmods=None, typemod=None, arrayBounds=None, location=None)

Wrapper for the homonymous parser node.

names: tuple

Qualified name (list of Value strings)

setof: bool

Is a set?

pct_type: bool

%TYPE specified?

typmods: tuple

Type modifier expression(s)

typemod: int32

Prespecified type modifier

arrayBounds: tuple

Array bounds

location: int

Token location, or -1 if unknown

class pglast.ast.UnlistenStmt(conditionname=None)

Wrapper for the homonymous parser node.

conditionname: str

Name to unlisten on, or NULL for all

class pglast.ast.UpdateStmt(relation=None, targetList=None, whereClause=None, fromClause=None, returningList=None, withClause=None)

Wrapper for the homonymous parser node.

relation: RangeVar*

Relation to update

targetList: tuple

The target list (of ResTarget)

whereClause: Node

Qualifications

fromClause: tuple

Optional from clause for more tables

returningList: tuple

List of expressions to return

withClause: WithClause*

WITH clause

class pglast.ast.VacuumRelation(relation=None, va_cols=None)

Wrapper for the homonymous parser node.

relation: RangeVar*

Table name to process, or NULL

va_cols: tuple

List of column names, or NIL for all

class pglast.ast.VacuumStmt(options=None, rels=None, is_vacuumcmd=None)

Wrapper for the homonymous parser node.

options: tuple

List of DefElem nodes

rels: tuple

List of VacuumRelation, or NIL for all

is_vacuumcmd: bool

True for VACUUM, false for ANALYZE

class pglast.ast.Var(varno=None, varattno=None, vartypmod=None, varlevelsup=None, varnosyn=None, varattnosyn=None, location=None)

Wrapper for the homonymous parser node.

varno: Index

Index of this var’s relation in the range table, or INNER_VAR/OUTER_VAR/INDEX_VAR

varattno: AttrNumber

Attribute number of this var, or zero for all attrs (“whole-row Var”)

vartypmod: int32

Pg_attribute typmod value

varlevelsup: Index

For subquery variables referencing outer relations; 0 in a normal var, >0 means N levels up

varnosyn: Index

Syntactic relation index (0 if unknown)

varattnosyn: AttrNumber

Syntactic attribute number

location: int

Token location, or -1 if unknown

class pglast.ast.VariableSetStmt(kind=None, name=None, args=None, is_local=None)

Wrapper for the homonymous parser node.

kind: VariableSetKind
name: str

Variable to be set

args: tuple

List of A_Const nodes

is_local: bool

SET LOCAL?

class pglast.ast.VariableShowStmt(name=None)

Wrapper for the homonymous parser node.

name: str
class pglast.ast.ViewStmt(view=None, aliases=None, query=None, replace=None, options=None, withCheckOption=None)

Wrapper for the homonymous parser node.

view: RangeVar*

The view to be created

aliases: tuple

Target column names

query: Node

The SELECT query (as a raw parse tree)

replace: bool

Replace an existing view?

options: tuple

Options from WITH clause

withCheckOption: ViewCheckOption

WITH CHECK OPTION

class pglast.ast.WindowClause(name=None, refname=None, partitionClause=None, orderClause=None, frameOptions=None, startOffset=None, endOffset=None, inRangeAsc=None, inRangeNullsFirst=None, winref=None, copiedOrder=None)

Wrapper for the homonymous parser node.

name: str

Window name (NULL in an OVER clause)

refname: str

Referenced window name, if any

partitionClause: tuple

PARTITION BY list

orderClause: tuple

ORDER BY list

frameOptions: int

Frame_clause options, see WindowDef

startOffset: Node

Expression for starting bound, if any

endOffset: Node

Expression for ending bound, if any

inRangeAsc: bool

Use ASC sort order for in_range tests?

inRangeNullsFirst: bool

Nulls sort first for in_range tests?

winref: Index

ID referenced by window functions

copiedOrder: bool

Did we copy orderClause from refname?

class pglast.ast.WindowDef(name=None, refname=None, partitionClause=None, orderClause=None, frameOptions=None, startOffset=None, endOffset=None, location=None)

Wrapper for the homonymous parser node.

name: str

Window’s own name

refname: str

Referenced window name, if any

partitionClause: tuple

PARTITION BY expression list

orderClause: tuple

ORDER BY (list of SortBy)

frameOptions: int

Frame_clause options, see below

startOffset: Node

Expression for starting bound, if any

endOffset: Node

Expression for ending bound, if any

location: int

Parse location, or -1 if none/unknown

class pglast.ast.WindowFunc(args=None, aggfilter=None, winref=None, winstar=None, winagg=None, location=None)

Wrapper for the homonymous parser node.

args: tuple

Arguments to the window function

aggfilter: Expr*

FILTER expression, if any

winref: Index

Index of associated WindowClause

winstar: bool

True if argument list was really ‘*’

winagg: bool

Is function a simple aggregate?

location: int

Token location, or -1 if unknown

class pglast.ast.WithCheckOption(kind=None, relname=None, polname=None, qual=None, cascaded=None)

Wrapper for the homonymous parser node.

kind: WCOKind

Kind of WCO

relname: str

Name of relation that specified the WCO

polname: str

Name of RLS policy being checked

qual: Node

Constraint qual to check

cascaded: bool

True for a cascaded WCO on a view

class pglast.ast.WithClause(ctes=None, recursive=None, location=None)

Wrapper for the homonymous parser node.

ctes: tuple

List of CommonTableExprs

recursive: bool

True = WITH RECURSIVE

location: int

Token location, or -1 if unknown

class pglast.ast.XmlExpr(op=None, name=None, named_args=None, arg_names=None, args=None, xmloption=None, typmod=None, location=None)

Wrapper for the homonymous parser node.

op: XmlExprOp

Xml function ID

name: str

Name in xml(NAME foo …) syntaxes

named_args: tuple

Non-XML expressions for xml_attributes

arg_names: tuple

Parallel list of Value strings

args: tuple

List of expressions

xmloption: XmlOptionType

DOCUMENT or CONTENT

typmod: int32
location: int

Token location, or -1 if unknown

class pglast.ast.XmlSerialize(xmloption=None, expr=None, typeName=None, location=None)

Wrapper for the homonymous parser node.

xmloption: XmlOptionType

DOCUMENT or CONTENT

expr: Node
typeName: TypeName*
location: int

Token location, or -1 if unknown

pglast.enums — Enumerated constants

This module contains all the constants that are used to give a meaning to some scalar values of the various kinds of nodes, extracted automatically from the PostgreSQL headers.

From include/catalog
pglast.enums.pg_am — Constants extracted from pg_am.h
pglast.enums.pg_am.AmNameIndexId

See here for details.

pglast.enums.pg_am.AmOidIndexId

See here for details.

pglast.enums.pg_am.AMTYPE_INDEX

See here for details.

pglast.enums.pg_am.AMTYPE_TABLE

See here for details.

pglast.enums.pg_attribute — Constants extracted from pg_attribute.h
pglast.enums.pg_attribute.AttributeRelidNameIndexId

See here for details.

pglast.enums.pg_attribute.AttributeRelidNumIndexId

See here for details.

pglast.enums.pg_attribute.ATTRIBUTE_IDENTITY_ALWAYS

See here for details.

pglast.enums.pg_attribute.ATTRIBUTE_IDENTITY_BY_DEFAULT

See here for details.

pglast.enums.pg_attribute.ATTRIBUTE_GENERATED_STORED

See here for details.

pglast.enums.pg_class — Constants extracted from pg_class.h
pglast.enums.pg_class.ClassOidIndexId

See here for details.

pglast.enums.pg_class.ClassNameNspIndexId

See here for details.

pglast.enums.pg_class.ClassTblspcRelfilenodeIndexId

See here for details.

pglast.enums.pg_class.RELKIND_RELATION

See here for details.

pglast.enums.pg_class.RELKIND_INDEX

See here for details.

pglast.enums.pg_class.RELKIND_SEQUENCE

See here for details.

pglast.enums.pg_class.RELKIND_TOASTVALUE

See here for details.

pglast.enums.pg_class.RELKIND_VIEW

See here for details.

pglast.enums.pg_class.RELKIND_MATVIEW

See here for details.

pglast.enums.pg_class.RELKIND_COMPOSITE_TYPE

See here for details.

pglast.enums.pg_class.RELKIND_FOREIGN_TABLE

See here for details.

pglast.enums.pg_class.RELKIND_PARTITIONED_TABLE

See here for details.

pglast.enums.pg_class.RELKIND_PARTITIONED_INDEX

See here for details.

pglast.enums.pg_class.RELPERSISTENCE_PERMANENT

See here for details.

pglast.enums.pg_class.RELPERSISTENCE_UNLOGGED

See here for details.

pglast.enums.pg_class.RELPERSISTENCE_TEMP

See here for details.

pglast.enums.pg_class.REPLICA_IDENTITY_DEFAULT

See here for details.

pglast.enums.pg_class.REPLICA_IDENTITY_NOTHING

See here for details.

pglast.enums.pg_class.REPLICA_IDENTITY_FULL

See here for details.

pglast.enums.pg_class.REPLICA_IDENTITY_INDEX

See here for details.

pglast.enums.pg_trigger — Constants extracted from pg_trigger.h
pglast.enums.pg_trigger.TriggerConstraintIndexId

See here for details.

pglast.enums.pg_trigger.TriggerRelidNameIndexId

See here for details.

pglast.enums.pg_trigger.TriggerOidIndexId

See here for details.

pglast.enums.pg_trigger.TRIGGER_TYPE_ROW

See here for details.

pglast.enums.pg_trigger.TRIGGER_TYPE_BEFORE

See here for details.

pglast.enums.pg_trigger.TRIGGER_TYPE_INSERT

See here for details.

pglast.enums.pg_trigger.TRIGGER_TYPE_DELETE

See here for details.

pglast.enums.pg_trigger.TRIGGER_TYPE_UPDATE

See here for details.

pglast.enums.pg_trigger.TRIGGER_TYPE_TRUNCATE

See here for details.

pglast.enums.pg_trigger.TRIGGER_TYPE_INSTEAD

See here for details.

pglast.enums.pg_trigger.TRIGGER_TYPE_STATEMENT

See here for details.

pglast.enums.pg_trigger.TRIGGER_TYPE_AFTER

See here for details.

From include/nodes
pglast.enums.lockoptions — Constants extracted from lockoptions.h
class pglast.enums.lockoptions.LockClauseStrength

Corresponds to the LockClauseStrength enum.

LCS_NONE
LCS_FORKEYSHARE
LCS_FORSHARE
LCS_FORNOKEYUPDATE
LCS_FORUPDATE
class pglast.enums.lockoptions.LockTupleMode

Corresponds to the LockTupleMode enum.

LockTupleKeyShare
LockTupleShare
LockTupleNoKeyExclusive
LockTupleExclusive
class pglast.enums.lockoptions.LockWaitPolicy

Corresponds to the LockWaitPolicy enum.

LockWaitBlock
LockWaitSkip
LockWaitError
pglast.enums.nodes — Constants extracted from nodes.h
class pglast.enums.nodes.AggSplit

Corresponds to the AggSplit enum.

AGGSPLIT_SIMPLE
AGGSPLIT_INITIAL_SERIAL
AGGSPLIT_FINAL_DESERIAL
class pglast.enums.nodes.AggStrategy

Corresponds to the AggStrategy enum.

AGG_PLAIN
AGG_SORTED
AGG_HASHED
AGG_MIXED
class pglast.enums.nodes.CmdType

Corresponds to the CmdType enum.

CMD_UNKNOWN
CMD_SELECT
CMD_UPDATE
CMD_INSERT
CMD_DELETE
CMD_UTILITY
CMD_NOTHING
class pglast.enums.nodes.JoinType

Corresponds to the JoinType enum.

JOIN_INNER
JOIN_LEFT
JOIN_FULL
JOIN_RIGHT
JOIN_SEMI
JOIN_ANTI
JOIN_UNIQUE_OUTER
JOIN_UNIQUE_INNER
class pglast.enums.nodes.LimitOption

Corresponds to the LimitOption enum.

LIMIT_OPTION_DEFAULT
LIMIT_OPTION_COUNT
LIMIT_OPTION_WITH_TIES
class pglast.enums.nodes.NodeTag

Corresponds to the NodeTag enum.

T_Invalid
T_IndexInfo
T_ExprContext
T_ProjectionInfo
T_JunkFilter
T_OnConflictSetState
T_ResultRelInfo
T_EState
T_TupleTableSlot
T_Plan
T_Result
T_ProjectSet
T_ModifyTable
T_Append
T_MergeAppend
T_RecursiveUnion
T_BitmapAnd
T_BitmapOr
T_Scan
T_SeqScan
T_SampleScan
T_IndexScan
T_IndexOnlyScan
T_BitmapIndexScan
T_BitmapHeapScan
T_TidScan
T_TidRangeScan
T_SubqueryScan
T_FunctionScan
T_ValuesScan
T_TableFuncScan
T_CteScan
T_NamedTuplestoreScan
T_WorkTableScan
T_ForeignScan
T_CustomScan
T_Join
T_NestLoop
T_MergeJoin
T_HashJoin
T_Material
T_Memoize
T_Sort
T_IncrementalSort
T_Group
T_Agg
T_WindowAgg
T_Unique
T_Gather
T_GatherMerge
T_Hash
T_SetOp
T_LockRows
T_Limit
T_NestLoopParam
T_PlanRowMark
T_PartitionPruneInfo
T_PartitionedRelPruneInfo
T_PartitionPruneStepOp
T_PartitionPruneStepCombine
T_PlanInvalItem
T_PlanState
T_ResultState
T_ProjectSetState
T_ModifyTableState
T_AppendState
T_MergeAppendState
T_RecursiveUnionState
T_BitmapAndState
T_BitmapOrState
T_ScanState
T_SeqScanState
T_SampleScanState
T_IndexScanState
T_IndexOnlyScanState
T_BitmapIndexScanState
T_BitmapHeapScanState
T_TidScanState
T_TidRangeScanState
T_SubqueryScanState
T_FunctionScanState
T_TableFuncScanState
T_ValuesScanState
T_CteScanState
T_NamedTuplestoreScanState
T_WorkTableScanState
T_ForeignScanState
T_CustomScanState
T_JoinState
T_NestLoopState
T_MergeJoinState
T_HashJoinState
T_MaterialState
T_MemoizeState
T_SortState
T_IncrementalSortState
T_GroupState
T_AggState
T_WindowAggState
T_UniqueState
T_GatherState
T_GatherMergeState
T_HashState
T_SetOpState
T_LockRowsState
T_LimitState
T_Alias
T_RangeVar
T_TableFunc
T_Expr
T_Var
T_Const
T_Param
T_Aggref
T_GroupingFunc
T_WindowFunc
T_SubscriptingRef
T_FuncExpr
T_NamedArgExpr
T_OpExpr
T_DistinctExpr
T_NullIfExpr
T_ScalarArrayOpExpr
T_BoolExpr
T_SubPlan
T_AlternativeSubPlan
T_FieldSelect
T_FieldStore
T_RelabelType
T_CoerceViaIO
T_ArrayCoerceExpr
T_ConvertRowtypeExpr
T_CollateExpr
T_CaseExpr
T_CaseWhen
T_CaseTestExpr
T_ArrayExpr
T_RowExpr
T_RowCompareExpr
T_CoalesceExpr
T_MinMaxExpr
T_SQLValueFunction
T_XmlExpr
T_NullTest
T_BooleanTest
T_CoerceToDomain
T_CoerceToDomainValue
T_SetToDefault
T_CurrentOfExpr
T_NextValueExpr
T_InferenceElem
T_TargetEntry
T_RangeTblRef
T_JoinExpr
T_FromExpr
T_OnConflictExpr
T_IntoClause
T_ExprState
T_WindowFuncExprState
T_SetExprState
T_SubPlanState
T_DomainConstraintState
T_PlannerInfo
T_PlannerGlobal
T_RelOptInfo
T_IndexOptInfo
T_ForeignKeyOptInfo
T_ParamPathInfo
T_Path
T_IndexPath
T_BitmapHeapPath
T_BitmapAndPath
T_BitmapOrPath
T_TidPath
T_TidRangePath
T_SubqueryScanPath
T_ForeignPath
T_CustomPath
T_NestPath
T_MergePath
T_HashPath
T_AppendPath
T_MergeAppendPath
T_GroupResultPath
T_MaterialPath
T_MemoizePath
T_UniquePath
T_GatherPath
T_GatherMergePath
T_ProjectionPath
T_ProjectSetPath
T_SortPath
T_IncrementalSortPath
T_GroupPath
T_UpperUniquePath
T_AggPath
T_GroupingSetsPath
T_MinMaxAggPath
T_WindowAggPath
T_SetOpPath
T_RecursiveUnionPath
T_LockRowsPath
T_ModifyTablePath
T_LimitPath
T_EquivalenceClass
T_EquivalenceMember
T_PathKey
T_PathTarget
T_RestrictInfo
T_IndexClause
T_PlaceHolderVar
T_SpecialJoinInfo
T_AppendRelInfo
T_RowIdentityVarInfo
T_PlaceHolderInfo
T_MinMaxAggInfo
T_PlannerParamItem
T_RollupData
T_GroupingSetData
T_StatisticExtInfo
T_MemoryContext
T_AllocSetContext
T_SlabContext
T_GenerationContext
T_Value
T_Integer
T_Float
T_String
T_BitString
T_Null
T_List
T_IntList
T_OidList
T_ExtensibleNode
T_RawStmt
T_Query
T_PlannedStmt
T_InsertStmt
T_DeleteStmt
T_UpdateStmt
T_SelectStmt
T_ReturnStmt
T_PLAssignStmt
T_AlterTableStmt
T_AlterTableCmd
T_AlterDomainStmt
T_SetOperationStmt
T_GrantStmt
T_GrantRoleStmt
T_AlterDefaultPrivilegesStmt
T_ClosePortalStmt
T_ClusterStmt
T_CopyStmt
T_CreateStmt
T_DefineStmt
T_DropStmt
T_TruncateStmt
T_CommentStmt
T_FetchStmt
T_IndexStmt
T_CreateFunctionStmt
T_AlterFunctionStmt
T_DoStmt
T_RenameStmt
T_RuleStmt
T_NotifyStmt
T_ListenStmt
T_UnlistenStmt
T_TransactionStmt
T_ViewStmt
T_LoadStmt
T_CreateDomainStmt
T_CreatedbStmt
T_DropdbStmt
T_VacuumStmt
T_ExplainStmt
T_CreateTableAsStmt
T_CreateSeqStmt
T_AlterSeqStmt
T_VariableSetStmt
T_VariableShowStmt
T_DiscardStmt
T_CreateTrigStmt
T_CreatePLangStmt
T_CreateRoleStmt
T_AlterRoleStmt
T_DropRoleStmt
T_LockStmt
T_ConstraintsSetStmt
T_ReindexStmt
T_CheckPointStmt
T_CreateSchemaStmt
T_AlterDatabaseStmt
T_AlterDatabaseSetStmt
T_AlterRoleSetStmt
T_CreateConversionStmt
T_CreateCastStmt
T_CreateOpClassStmt
T_CreateOpFamilyStmt
T_AlterOpFamilyStmt
T_PrepareStmt
T_ExecuteStmt
T_DeallocateStmt
T_DeclareCursorStmt
T_CreateTableSpaceStmt
T_DropTableSpaceStmt
T_AlterObjectDependsStmt
T_AlterObjectSchemaStmt
T_AlterOwnerStmt
T_AlterOperatorStmt
T_AlterTypeStmt
T_DropOwnedStmt
T_ReassignOwnedStmt
T_CompositeTypeStmt
T_CreateEnumStmt
T_CreateRangeStmt
T_AlterEnumStmt
T_AlterTSDictionaryStmt
T_AlterTSConfigurationStmt
T_CreateFdwStmt
T_AlterFdwStmt
T_CreateForeignServerStmt
T_AlterForeignServerStmt
T_CreateUserMappingStmt
T_AlterUserMappingStmt
T_DropUserMappingStmt
T_AlterTableSpaceOptionsStmt
T_AlterTableMoveAllStmt
T_SecLabelStmt
T_CreateForeignTableStmt
T_ImportForeignSchemaStmt
T_CreateExtensionStmt
T_AlterExtensionStmt
T_AlterExtensionContentsStmt
T_CreateEventTrigStmt
T_AlterEventTrigStmt
T_RefreshMatViewStmt
T_ReplicaIdentityStmt
T_AlterSystemStmt
T_CreatePolicyStmt
T_AlterPolicyStmt
T_CreateTransformStmt
T_CreateAmStmt
T_CreatePublicationStmt
T_AlterPublicationStmt
T_CreateSubscriptionStmt
T_AlterSubscriptionStmt
T_DropSubscriptionStmt
T_CreateStatsStmt
T_AlterCollationStmt
T_CallStmt
T_AlterStatsStmt
T_A_Expr
T_ColumnRef
T_ParamRef
T_A_Const
T_FuncCall
T_A_Star
T_A_Indices
T_A_Indirection
T_A_ArrayExpr
T_ResTarget
T_MultiAssignRef
T_TypeCast
T_CollateClause
T_SortBy
T_WindowDef
T_RangeSubselect
T_RangeFunction
T_RangeTableSample
T_RangeTableFunc
T_RangeTableFuncCol
T_TypeName
T_ColumnDef
T_IndexElem
T_StatsElem
T_Constraint
T_DefElem
T_RangeTblEntry
T_RangeTblFunction
T_TableSampleClause
T_WithCheckOption
T_SortGroupClause
T_GroupingSet
T_WindowClause
T_ObjectWithArgs
T_AccessPriv
T_CreateOpClassItem
T_TableLikeClause
T_FunctionParameter
T_LockingClause
T_RowMarkClause
T_XmlSerialize
T_WithClause
T_InferClause
T_OnConflictClause
T_CTESearchClause
T_CTECycleClause
T_CommonTableExpr
T_RoleSpec
T_TriggerTransition
T_PartitionElem
T_PartitionSpec
T_PartitionBoundSpec
T_PartitionRangeDatum
T_PartitionCmd
T_VacuumRelation
T_IdentifySystemCmd
T_BaseBackupCmd
T_CreateReplicationSlotCmd
T_DropReplicationSlotCmd
T_StartReplicationCmd
T_TimeLineHistoryCmd
T_SQLCmd
T_TriggerData
T_EventTriggerData
T_ReturnSetInfo
T_WindowObjectData
T_TIDBitmap
T_InlineCodeBlock
T_FdwRoutine
T_IndexAmRoutine
T_TableAmRoutine
T_TsmRoutine
T_ForeignKeyCacheInfo
T_CallContext
T_SupportRequestSimplify
T_SupportRequestSelectivity
T_SupportRequestCost
T_SupportRequestRows
T_SupportRequestIndexCondition
class pglast.enums.nodes.OnConflictAction

Corresponds to the OnConflictAction enum.

ONCONFLICT_NONE
ONCONFLICT_NOTHING
ONCONFLICT_UPDATE
class pglast.enums.nodes.SetOpCmd

Corresponds to the SetOpCmd enum.

SETOPCMD_INTERSECT
SETOPCMD_INTERSECT_ALL
SETOPCMD_EXCEPT
SETOPCMD_EXCEPT_ALL
class pglast.enums.nodes.SetOpStrategy

Corresponds to the SetOpStrategy enum.

SETOP_SORTED
SETOP_HASHED
pglast.enums.nodes.AGGSPLITOP_COMBINE

See here for details.

pglast.enums.nodes.AGGSPLITOP_SKIPFINAL

See here for details.

pglast.enums.nodes.AGGSPLITOP_SERIALIZE

See here for details.

pglast.enums.nodes.AGGSPLITOP_DESERIALIZE

See here for details.

pglast.enums.parsenodes — Constants extracted from parsenodes.h
class pglast.enums.parsenodes.A_Expr_Kind

Corresponds to the A_Expr_Kind enum.

AEXPR_OP
AEXPR_OP_ANY
AEXPR_OP_ALL
AEXPR_DISTINCT
AEXPR_NOT_DISTINCT
AEXPR_NULLIF
AEXPR_IN
AEXPR_LIKE
AEXPR_ILIKE
AEXPR_SIMILAR
AEXPR_BETWEEN
AEXPR_NOT_BETWEEN
AEXPR_BETWEEN_SYM
AEXPR_NOT_BETWEEN_SYM
class pglast.enums.parsenodes.AlterSubscriptionType

Corresponds to the AlterSubscriptionType enum.

ALTER_SUBSCRIPTION_OPTIONS
ALTER_SUBSCRIPTION_CONNECTION
ALTER_SUBSCRIPTION_SET_PUBLICATION
ALTER_SUBSCRIPTION_ADD_PUBLICATION
ALTER_SUBSCRIPTION_DROP_PUBLICATION
ALTER_SUBSCRIPTION_REFRESH
ALTER_SUBSCRIPTION_ENABLED
class pglast.enums.parsenodes.AlterTSConfigType

Corresponds to the AlterTSConfigType enum.

ALTER_TSCONFIG_ADD_MAPPING
ALTER_TSCONFIG_ALTER_MAPPING_FOR_TOKEN
ALTER_TSCONFIG_REPLACE_DICT
ALTER_TSCONFIG_REPLACE_DICT_FOR_TOKEN
ALTER_TSCONFIG_DROP_MAPPING
class pglast.enums.parsenodes.AlterTableType

Corresponds to the AlterTableType enum.

AT_AddColumn
AT_AddColumnRecurse
AT_AddColumnToView
AT_ColumnDefault
AT_CookedColumnDefault
AT_DropNotNull
AT_SetNotNull
AT_DropExpression
AT_CheckNotNull
AT_SetStatistics
AT_SetOptions
AT_ResetOptions
AT_SetStorage
AT_SetCompression
AT_DropColumn
AT_DropColumnRecurse
AT_AddIndex
AT_ReAddIndex
AT_AddConstraint
AT_AddConstraintRecurse
AT_ReAddConstraint
AT_ReAddDomainConstraint
AT_AlterConstraint
AT_ValidateConstraint
AT_ValidateConstraintRecurse
AT_AddIndexConstraint
AT_DropConstraint
AT_DropConstraintRecurse
AT_ReAddComment
AT_AlterColumnType
AT_AlterColumnGenericOptions
AT_ChangeOwner
AT_ClusterOn
AT_DropCluster
AT_SetLogged
AT_SetUnLogged
AT_DropOids
AT_SetTableSpace
AT_SetRelOptions
AT_ResetRelOptions
AT_ReplaceRelOptions
AT_EnableTrig
AT_EnableAlwaysTrig
AT_EnableReplicaTrig
AT_DisableTrig
AT_EnableTrigAll
AT_DisableTrigAll
AT_EnableTrigUser
AT_DisableTrigUser
AT_EnableRule
AT_EnableAlwaysRule
AT_EnableReplicaRule
AT_DisableRule
AT_AddInherit
AT_DropInherit
AT_AddOf
AT_DropOf
AT_ReplicaIdentity
AT_EnableRowSecurity
AT_DisableRowSecurity
AT_ForceRowSecurity
AT_NoForceRowSecurity
AT_GenericOptions
AT_AttachPartition
AT_DetachPartition
AT_DetachPartitionFinalize
AT_AddIdentity
AT_SetIdentity
AT_DropIdentity
AT_ReAddStatistics
class pglast.enums.parsenodes.CTEMaterialize

Corresponds to the CTEMaterialize enum.

CTEMaterializeDefault
CTEMaterializeAlways
CTEMaterializeNever
class pglast.enums.parsenodes.ConstrType

Corresponds to the ConstrType enum.

CONSTR_NULL
CONSTR_NOTNULL
CONSTR_DEFAULT
CONSTR_IDENTITY
CONSTR_GENERATED
CONSTR_CHECK
CONSTR_PRIMARY
CONSTR_UNIQUE
CONSTR_EXCLUSION
CONSTR_FOREIGN
CONSTR_ATTR_DEFERRABLE
CONSTR_ATTR_NOT_DEFERRABLE
CONSTR_ATTR_DEFERRED
CONSTR_ATTR_IMMEDIATE
class pglast.enums.parsenodes.DefElemAction

Corresponds to the DefElemAction enum.

DEFELEM_UNSPEC
DEFELEM_SET
DEFELEM_ADD
DEFELEM_DROP
class pglast.enums.parsenodes.DiscardMode

Corresponds to the DiscardMode enum.

DISCARD_ALL
DISCARD_PLANS
DISCARD_SEQUENCES
DISCARD_TEMP
class pglast.enums.parsenodes.DropBehavior

Corresponds to the DropBehavior enum.

DROP_RESTRICT
DROP_CASCADE
class pglast.enums.parsenodes.FetchDirection

Corresponds to the FetchDirection enum.

FETCH_FORWARD
FETCH_BACKWARD
FETCH_ABSOLUTE
FETCH_RELATIVE
class pglast.enums.parsenodes.FunctionParameterMode

Corresponds to the FunctionParameterMode enum.

FUNC_PARAM_IN
FUNC_PARAM_OUT
FUNC_PARAM_INOUT
FUNC_PARAM_VARIADIC
FUNC_PARAM_TABLE
FUNC_PARAM_DEFAULT
class pglast.enums.parsenodes.GrantTargetType

Corresponds to the GrantTargetType enum.

ACL_TARGET_OBJECT
ACL_TARGET_ALL_IN_SCHEMA
ACL_TARGET_DEFAULTS
class pglast.enums.parsenodes.GroupingSetKind

Corresponds to the GroupingSetKind enum.

GROUPING_SET_EMPTY
GROUPING_SET_SIMPLE
GROUPING_SET_ROLLUP
GROUPING_SET_CUBE
GROUPING_SET_SETS
class pglast.enums.parsenodes.ImportForeignSchemaType

Corresponds to the ImportForeignSchemaType enum.

FDW_IMPORT_SCHEMA_ALL
FDW_IMPORT_SCHEMA_LIMIT_TO
FDW_IMPORT_SCHEMA_EXCEPT
class pglast.enums.parsenodes.ObjectType

Corresponds to the ObjectType enum.

OBJECT_ACCESS_METHOD
OBJECT_AGGREGATE
OBJECT_AMOP
OBJECT_AMPROC
OBJECT_ATTRIBUTE
OBJECT_CAST
OBJECT_COLUMN
OBJECT_COLLATION
OBJECT_CONVERSION
OBJECT_DATABASE
OBJECT_DEFAULT
OBJECT_DEFACL
OBJECT_DOMAIN
OBJECT_DOMCONSTRAINT
OBJECT_EVENT_TRIGGER
OBJECT_EXTENSION
OBJECT_FDW
OBJECT_FOREIGN_SERVER
OBJECT_FOREIGN_TABLE
OBJECT_FUNCTION
OBJECT_INDEX
OBJECT_LANGUAGE
OBJECT_LARGEOBJECT
OBJECT_MATVIEW
OBJECT_OPCLASS
OBJECT_OPERATOR
OBJECT_OPFAMILY
OBJECT_POLICY
OBJECT_PROCEDURE
OBJECT_PUBLICATION
OBJECT_PUBLICATION_REL
OBJECT_ROLE
OBJECT_ROUTINE
OBJECT_RULE
OBJECT_SCHEMA
OBJECT_SEQUENCE
OBJECT_SUBSCRIPTION
OBJECT_STATISTIC_EXT
OBJECT_TABCONSTRAINT
OBJECT_TABLE
OBJECT_TABLESPACE
OBJECT_TRANSFORM
OBJECT_TRIGGER
OBJECT_TSCONFIGURATION
OBJECT_TSDICTIONARY
OBJECT_TSPARSER
OBJECT_TSTEMPLATE
OBJECT_TYPE
OBJECT_USER_MAPPING
OBJECT_VIEW
class pglast.enums.parsenodes.OverridingKind

Corresponds to the OverridingKind enum.

OVERRIDING_NOT_SET
OVERRIDING_USER_VALUE
OVERRIDING_SYSTEM_VALUE
class pglast.enums.parsenodes.PartitionRangeDatumKind

Corresponds to the PartitionRangeDatumKind enum.

PARTITION_RANGE_DATUM_MINVALUE
PARTITION_RANGE_DATUM_VALUE
PARTITION_RANGE_DATUM_MAXVALUE
class pglast.enums.parsenodes.QuerySource

Corresponds to the QuerySource enum.

QSRC_ORIGINAL
QSRC_PARSER
QSRC_INSTEAD_RULE
QSRC_QUAL_INSTEAD_RULE
QSRC_NON_INSTEAD_RULE
class pglast.enums.parsenodes.RTEKind

Corresponds to the RTEKind enum.

RTE_RELATION
RTE_SUBQUERY
RTE_JOIN
RTE_FUNCTION
RTE_TABLEFUNC
RTE_VALUES
RTE_CTE
RTE_NAMEDTUPLESTORE
RTE_RESULT
class pglast.enums.parsenodes.ReindexObjectType

Corresponds to the ReindexObjectType enum.

REINDEX_OBJECT_INDEX
REINDEX_OBJECT_TABLE
REINDEX_OBJECT_SCHEMA
REINDEX_OBJECT_SYSTEM
REINDEX_OBJECT_DATABASE
class pglast.enums.parsenodes.RoleSpecType

Corresponds to the RoleSpecType enum.

ROLESPEC_CSTRING
ROLESPEC_CURRENT_ROLE
ROLESPEC_CURRENT_USER
ROLESPEC_SESSION_USER
ROLESPEC_PUBLIC
class pglast.enums.parsenodes.RoleStmtType

Corresponds to the RoleStmtType enum.

ROLESTMT_ROLE
ROLESTMT_USER
ROLESTMT_GROUP
class pglast.enums.parsenodes.SetOperation

Corresponds to the SetOperation enum.

SETOP_NONE
SETOP_UNION
SETOP_INTERSECT
SETOP_EXCEPT
class pglast.enums.parsenodes.SetQuantifier

Corresponds to the SetQuantifier enum.

SET_QUANTIFIER_DEFAULT
SET_QUANTIFIER_ALL
SET_QUANTIFIER_DISTINCT
class pglast.enums.parsenodes.SortByDir

Corresponds to the SortByDir enum.

SORTBY_DEFAULT
SORTBY_ASC
SORTBY_DESC
SORTBY_USING
class pglast.enums.parsenodes.SortByNulls

Corresponds to the SortByNulls enum.

SORTBY_NULLS_DEFAULT
SORTBY_NULLS_FIRST
SORTBY_NULLS_LAST
class pglast.enums.parsenodes.TableLikeOption

Corresponds to the TableLikeOption enum.

CREATE_TABLE_LIKE_COMMENTS
CREATE_TABLE_LIKE_COMPRESSION
CREATE_TABLE_LIKE_CONSTRAINTS
CREATE_TABLE_LIKE_DEFAULTS
CREATE_TABLE_LIKE_GENERATED
CREATE_TABLE_LIKE_IDENTITY
CREATE_TABLE_LIKE_INDEXES
CREATE_TABLE_LIKE_STATISTICS
CREATE_TABLE_LIKE_STORAGE
CREATE_TABLE_LIKE_ALL
class pglast.enums.parsenodes.TransactionStmtKind

Corresponds to the TransactionStmtKind enum.

TRANS_STMT_BEGIN
TRANS_STMT_START
TRANS_STMT_COMMIT
TRANS_STMT_ROLLBACK
TRANS_STMT_SAVEPOINT
TRANS_STMT_RELEASE
TRANS_STMT_ROLLBACK_TO
TRANS_STMT_PREPARE
TRANS_STMT_COMMIT_PREPARED
TRANS_STMT_ROLLBACK_PREPARED
class pglast.enums.parsenodes.VariableSetKind

Corresponds to the VariableSetKind enum.

VAR_SET_VALUE
VAR_SET_DEFAULT
VAR_SET_CURRENT
VAR_SET_MULTI
VAR_RESET
VAR_RESET_ALL
class pglast.enums.parsenodes.ViewCheckOption

Corresponds to the ViewCheckOption enum.

NO_CHECK_OPTION
LOCAL_CHECK_OPTION
CASCADED_CHECK_OPTION
class pglast.enums.parsenodes.WCOKind

Corresponds to the WCOKind enum.

WCO_VIEW_CHECK
WCO_RLS_INSERT_CHECK
WCO_RLS_UPDATE_CHECK
WCO_RLS_CONFLICT_CHECK
pglast.enums.parsenodes.ACL_INSERT

See here for details.

pglast.enums.parsenodes.ACL_SELECT

See here for details.

pglast.enums.parsenodes.ACL_UPDATE

See here for details.

pglast.enums.parsenodes.ACL_DELETE

See here for details.

pglast.enums.parsenodes.ACL_TRUNCATE

See here for details.

pglast.enums.parsenodes.ACL_REFERENCES

See here for details.

pglast.enums.parsenodes.ACL_TRIGGER

See here for details.

pglast.enums.parsenodes.ACL_EXECUTE

See here for details.

pglast.enums.parsenodes.ACL_USAGE

See here for details.

pglast.enums.parsenodes.ACL_CREATE

See here for details.

pglast.enums.parsenodes.ACL_CREATE_TEMP

See here for details.

pglast.enums.parsenodes.ACL_CONNECT

See here for details.

pglast.enums.parsenodes.N_ACL_RIGHTS

See here for details.

pglast.enums.parsenodes.ACL_NO_RIGHTS

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_NONDEFAULT

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_RANGE

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_ROWS

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_GROUPS

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_BETWEEN

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_START_UNBOUNDED_PRECEDING

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_END_UNBOUNDED_PRECEDING

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_START_UNBOUNDED_FOLLOWING

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_END_UNBOUNDED_FOLLOWING

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_START_CURRENT_ROW

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_END_CURRENT_ROW

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_START_OFFSET_PRECEDING

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_END_OFFSET_PRECEDING

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_START_OFFSET_FOLLOWING

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_END_OFFSET_FOLLOWING

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_EXCLUDE_CURRENT_ROW

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_EXCLUDE_GROUP

See here for details.

pglast.enums.parsenodes.FRAMEOPTION_EXCLUDE_TIES

See here for details.

pglast.enums.parsenodes.PARTITION_STRATEGY_HASH

See here for details.

pglast.enums.parsenodes.PARTITION_STRATEGY_LIST

See here for details.

pglast.enums.parsenodes.PARTITION_STRATEGY_RANGE

See here for details.

pglast.enums.parsenodes.FKCONSTR_ACTION_NOACTION

See here for details.

pglast.enums.parsenodes.FKCONSTR_ACTION_RESTRICT

See here for details.

pglast.enums.parsenodes.FKCONSTR_ACTION_CASCADE

See here for details.

pglast.enums.parsenodes.FKCONSTR_ACTION_SETNULL

See here for details.

pglast.enums.parsenodes.FKCONSTR_ACTION_SETDEFAULT

See here for details.

pglast.enums.parsenodes.FKCONSTR_MATCH_FULL

See here for details.

pglast.enums.parsenodes.FKCONSTR_MATCH_PARTIAL

See here for details.

pglast.enums.parsenodes.FKCONSTR_MATCH_SIMPLE

See here for details.

pglast.enums.parsenodes.OPCLASS_ITEM_OPERATOR

See here for details.

pglast.enums.parsenodes.OPCLASS_ITEM_FUNCTION

See here for details.

pglast.enums.parsenodes.OPCLASS_ITEM_STORAGETYPE

See here for details.

pglast.enums.parsenodes.CURSOR_OPT_BINARY

See here for details.

pglast.enums.parsenodes.CURSOR_OPT_SCROLL

See here for details.

pglast.enums.parsenodes.CURSOR_OPT_NO_SCROLL

See here for details.

pglast.enums.parsenodes.CURSOR_OPT_INSENSITIVE

See here for details.

pglast.enums.parsenodes.CURSOR_OPT_ASENSITIVE

See here for details.

pglast.enums.parsenodes.CURSOR_OPT_HOLD

See here for details.

pglast.enums.parsenodes.CURSOR_OPT_FAST_PLAN

See here for details.

pglast.enums.parsenodes.CURSOR_OPT_GENERIC_PLAN

See here for details.

pglast.enums.parsenodes.CURSOR_OPT_CUSTOM_PLAN

See here for details.

pglast.enums.parsenodes.CURSOR_OPT_PARALLEL_OK

See here for details.

pglast.enums.parsenodes.FETCH_ALL

See here for details.

pglast.enums.primnodes — Constants extracted from primnodes.h
class pglast.enums.primnodes.BoolExprType

Corresponds to the BoolExprType enum.

AND_EXPR
OR_EXPR
NOT_EXPR
class pglast.enums.primnodes.BoolTestType

Corresponds to the BoolTestType enum.

IS_TRUE
IS_NOT_TRUE
IS_FALSE
IS_NOT_FALSE
IS_UNKNOWN
IS_NOT_UNKNOWN
class pglast.enums.primnodes.CoercionContext

Corresponds to the CoercionContext enum.

COERCION_IMPLICIT
COERCION_ASSIGNMENT
COERCION_PLPGSQL
COERCION_EXPLICIT
class pglast.enums.primnodes.CoercionForm

Corresponds to the CoercionForm enum.

COERCE_EXPLICIT_CALL
COERCE_EXPLICIT_CAST
COERCE_IMPLICIT_CAST
COERCE_SQL_SYNTAX
class pglast.enums.primnodes.MinMaxOp

Corresponds to the MinMaxOp enum.

IS_GREATEST
IS_LEAST
class pglast.enums.primnodes.NullTestType

Corresponds to the NullTestType enum.

IS_NULL
IS_NOT_NULL
class pglast.enums.primnodes.OnCommitAction

Corresponds to the OnCommitAction enum.

ONCOMMIT_NOOP
ONCOMMIT_PRESERVE_ROWS
ONCOMMIT_DELETE_ROWS
ONCOMMIT_DROP
class pglast.enums.primnodes.ParamKind

Corresponds to the ParamKind enum.

PARAM_EXTERN
PARAM_EXEC
PARAM_MULTIEXPR
class pglast.enums.primnodes.RowCompareType

Corresponds to the RowCompareType enum.

ROWCOMPARE_LT
ROWCOMPARE_LE
ROWCOMPARE_EQ
ROWCOMPARE_GE
ROWCOMPARE_GT
ROWCOMPARE_NE
class pglast.enums.primnodes.SQLValueFunctionOp

Corresponds to the SQLValueFunctionOp enum.

SVFOP_CURRENT_DATE
SVFOP_CURRENT_TIME
SVFOP_CURRENT_TIME_N
SVFOP_CURRENT_TIMESTAMP
SVFOP_CURRENT_TIMESTAMP_N
SVFOP_LOCALTIME
SVFOP_LOCALTIME_N
SVFOP_LOCALTIMESTAMP
SVFOP_LOCALTIMESTAMP_N
SVFOP_CURRENT_ROLE
SVFOP_CURRENT_USER
SVFOP_USER
SVFOP_SESSION_USER
SVFOP_CURRENT_CATALOG
SVFOP_CURRENT_SCHEMA
class pglast.enums.primnodes.SubLinkType

Corresponds to the SubLinkType enum.

class pglast.enums.primnodes.XmlExprOp

Corresponds to the XmlExprOp enum.

IS_XMLCONCAT
IS_XMLELEMENT
IS_XMLFOREST
IS_XMLPARSE
IS_XMLPI
IS_XMLROOT
IS_XMLSERIALIZE
IS_DOCUMENT
class pglast.enums.primnodes.XmlOptionType

Corresponds to the XmlOptionType enum.

XMLOPTION_DOCUMENT
XMLOPTION_CONTENT
pglast.enums.primnodes.INNER_VAR

See here for details.

pglast.enums.primnodes.OUTER_VAR

See here for details.

pglast.enums.primnodes.INDEX_VAR

See here for details.

pglast.enums.primnodes.ROWID_VAR

See here for details.

From include/storage
pglast.enums.lockdefs — Constants extracted from lockdefs.h
pglast.enums.lockdefs.NoLock

See here for details.

pglast.enums.lockdefs.AccessShareLock

See here for details.

pglast.enums.lockdefs.RowShareLock

See here for details.

pglast.enums.lockdefs.RowExclusiveLock

See here for details.

pglast.enums.lockdefs.ShareUpdateExclusiveLock

See here for details.

pglast.enums.lockdefs.ShareLock

See here for details.

pglast.enums.lockdefs.ShareRowExclusiveLock

See here for details.

pglast.enums.lockdefs.ExclusiveLock

See here for details.

pglast.enums.lockdefs.AccessExclusiveLock

See here for details.

pglast.enums.lockdefs.MaxLockMode

See here for details.

From include/utils
pglast.enums.xml — Constants extracted from xml.h
class pglast.enums.xml.PgXmlStrictness

Corresponds to the PgXmlStrictness enum.

PG_XML_STRICTNESS_LEGACY
PG_XML_STRICTNESS_WELLFORMED
PG_XML_STRICTNESS_ALL
class pglast.enums.xml.XmlBinaryType

Corresponds to the XmlBinaryType enum.

XMLBINARY_BASE64
XMLBINARY_HEX
class pglast.enums.xml.XmlStandaloneType

Corresponds to the XmlStandaloneType enum.

XML_STANDALONE_YES
XML_STANDALONE_NO
XML_STANDALONE_NO_VALUE
XML_STANDALONE_OMITTED

pglast.keywords — Various kinds of PostgreSQL keywords

This module contains the set of PostgreSQL keywords grouped by their characteristic.

pglast.keywords.COL_NAME_KEYWORDS
pglast.keywords.RESERVED_KEYWORDS
pglast.keywords.TYPE_FUNC_NAME_KEYWORDS
pglast.keywords.UNRESERVED_KEYWORDS

pglast.stream — The serialization machinery

class pglast.stream.OutputStream

A stream that has a concept of a pending separator between consecutive writes.

maybe_write_space(nextc=None, _special_chars={'"', '$', "'", '*', '+', '-', '/', '<', '=', '>', '@', '_'})

Emit a space when needed.

Parameters

nextc – either None or the next character that will be written

Returns

the number of characters written to the stream

If the last character written was neither a space nor an open parentheses, and nextc is either None or a special character, then emit a single whitespace.

separator()

Possibly insert a single whitespace character before next output.

When the last character written is not a space, set the pending_separator flag to True: the next call to write() will prepend a single whitespace to its argument if that begins with an alphanumeric character.

show(where=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>)

Emit current stream content, by default to stderr, to aid debugging.

swrite(s)

Shortcut for self.maybe_write_space(s[0]); self.write(s).

swrites(s)

Shortcut for self.swrite(s); self.separator().

write(s)

Emit string s.

Parameters

s (str) – the string to emit

Returns

the number of characters written to the stream

When s is not empty and pending_separator is True and the first character of s is alphanumeric, emit a single whitespace before writing out s and then reset pending_separator to False.

writes(s)

Shortcut for self.write(s); self.separator().

class pglast.stream.RawStream(separate_statements=1, special_functions=False, comma_at_eoln=False, semicolon_after_last_statement=False, comments=None, remove_pg_catalog_from_functions=False)

Basic SQL parse tree writer.

Parameters
  • separate_statements (int) – 1 by default, tells how many empty lines should separate statements

  • special_functions (bool) – False by default, when True some functions are treated in a special way and emitted as equivalent constructs

  • comma_at_eoln (bool) – False by default, when True put the comma right after each item instead of at the beginning of the next item line

  • semicolon_after_last_statement (bool) – False by default, when True add a semicolon after the last statement, otherwise it is emitted only as a separator between multiple statements

  • comments – optional sequence of tuples with the comments extracted from the statement

  • remove_pg_catalog_from_functions (bool) – False by default, when True remove the pg_catalog schema from functions

This augments OutputStream and implements the basic machinery needed to serialize the parse tree produced by parse_sql() back to a textual representation, without any adornment.

__call__(sql, plpgsql=False)

Main entry point: execute print_node() on each statement in sql.

Parameters
  • sql – the SQL statement

  • plpgsql (bool) – whether sql is really a plpgsql statement

Returns

a string with the equivalent SQL obtained by serializing the syntax tree

The sql statement may be either a str containing the SQL in textual form, or a concrete ast.Node instance or a tuple of them.

dedent()

Do nothing, shall be overridden by the prettifier subclass.

expression(need_parens)

Create a context manager usable to conditionally wrap something within parentheses.

Parameters

need_parens (bool) – whether to emit opening and closing parentheses

This method used to be used for subexpressions, but now is used to emit almost anything that goes within parentheses.

get_printer_for_function(name)

Look for a specific printer for function name in SPECIAL_FUNCTIONS.

Parameters

name (str) – the qualified name of the function

Returns

either None or a callable

When the option special_functions is True, return the printer function associated with name, if present. In all other cases return None.

indent(amount=0, relative=True)

Do nothing, shall be overridden by the prettifier subclass.

newline()

Emit a single whitespace, shall be overridden by the prettifier subclass.

print_comment(comment)

Print the given comment, unconditionally in the C syntax, joining all lines.

print_list(nodes, sep=',', relative_indent=None, standalone_items=None, are_names=False, is_symbol=False, item_needs_parens=None)

Execute print_node() on all the nodes, separating them with sep.

Parameters
  • nodes – a sequence of Node instances

  • sep (str) – the separator between them

  • relative_indent (bool) – if given, the relative amount of indentation to apply before the first item, by default computed automatically from the length of the separator sep

  • standalone_items (bool) – whether a newline will be emitted before each item

  • are_names (bool) – whether the nodes are actually names, which possibly require to be enclosed between double-quotes

  • is_symbol (bool) – whether the nodes are actually a symbol such as an operator name, in which case the last one must be printed verbatim (e.g. "MySchema".===)

  • item_needs_parens – either None or a callable

print_lists(lists, sep=',', relative_indent=None, standalone_items=None, are_names=False, sublist_open='(', sublist_close=')', sublist_sep=',', sublist_relative_indent=None)

Execute print_list() on all the lists items.

Parameters
  • lists – a sequence of sequences of Node instances

  • sep (str) – passed as is to print_list()

  • relative_indent (bool) – passed as is to print_list()

  • standalone_items (bool) – passed as is to print_list()

  • are_names (bool) – passed as is to print_list()

  • sublist_open (str) – the string that will be emitted before each sublist

  • sublist_close (str) – the string that will be emitted after each sublist

  • sublist_sep (str) – the separator between them each sublist

  • sublist_relative_indent (bool) – if given, the relative amount of indentation to apply before the first sublist, by default computed automatically from the length of the separator sublist_sep

print_name(nodes, sep='.')

Helper method, execute print_node() or print_list() as needed.

print_node(node, is_name=False, is_symbol=False)

Lookup the specific printer for the given node and execute it.

Parameters
  • node – an instance of Node

  • is_name (bool) – whether this is a name of something, that may need to be double quoted

  • is_symbol (bool) – whether this is the name of an operator, should not be double quoted

print_symbol(nodes, sep='.')

Helper method, execute print_node() or print_list() as needed.

push_indent(amount=0, relative=True)

Create a no-op context manager, shall be overridden by the prettifier subclass.

show(where=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>)

Emit also current expression_level and a “pointer” showing current_column.

space(count=1)

Emit a single whitespace, shall be overridden by the prettifier subclass.

write_quoted_string(s)

Emit the string s as a single-quoted literal constant.

class pglast.stream.IndentedStream(compact_lists_margin=None, split_string_literals_threshold=None, **options)

Indented SQL parse tree writer.

Parameters
  • compact_lists_margin (int) – an integer value that, if given, is used to print lists on a single line, when they do not exceed the given margin on the right

  • split_string_literals_threshold (int) – an integer value that, if given, is used as the threshold beyond that a string literal gets splitted in successive chunks of that length

  • **options – other options accepted by RawStream

This augments RawStream to emit a prettified representation of a parse tree.

dedent()

Pop the indentation level from the stack and set current_indent to that.

indent(amount=0, relative=True)

Push current indentation level to the stack, then set it adding amount to the current_column if relative is True otherwise to current_indent.

newline()

Emit a newline.

print_comment(comment)

Print the given comment, unconditionally in the C syntax, joining all lines.

print_list(nodes, sep=',', relative_indent=None, standalone_items=None, are_names=False, is_symbol=False, item_needs_parens=None)

Execute print_node() on all the nodes, separating them with sep.

Parameters
  • nodes – a sequence of Node instances

  • sep (str) – the separator between them

  • relative_indent (bool) – if given, the relative amount of indentation to apply before the first item, by default computed automatically from the length of the separator sep

  • standalone_items (bool) – whether a newline will be emitted before each item

  • are_names (bool) – whether the nodes are actually names, which possibly require to be enclosed between double-quotes

  • is_symbol (bool) – whether the nodes are actually an operator name, in which case the last one must be printed verbatim (such as "MySchema".===)

push_indent(amount=0, relative=True)

Create a context manager that calls indent() and dedent() around a block of code.

This is just an helper to simplify code that adjusts the indentation level:

with output.push_indent(4):
    # code that emits something with the new indentation
show(where=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>)

Emit also current_indent and indentation_stack.

space(count=1)

Emit consecutive spaces.

write(s)

Write string s to the stream, adjusting the current_column accordingly.

Parameters

s (str) – the string to emit

Returns

the number of characters written to the stream

If s is a newline character (\n) set current_column to 0. Otherwise when current_column is 0 and current_indent is greater than 0 emit a number of whitespaces before emitting s, to indent it as expected.

write_quoted_string(s)

Emit the string s possibly splitted in successive chunks.

When the split_string_literals_threshold option is greater than 0 and the length of s exceeds that value, split the string into multiple chunks.

pglast.printers — Specialized printer functions

This module implements the specialized functions that define how a particular Node will be serialized.

pglast.printers.NODE_PRINTERS = {<class 'pglast.ast.AccessPriv'>: <function access_priv>, <class 'pglast.ast.AlterCollationStmt'>: <function alter_collation_stmt>, <class 'pglast.ast.AlterDatabaseStmt'>: <function alter_database_stmt>, <class 'pglast.ast.AlterDatabaseSetStmt'>: <function alter_database_set_stmt>, <class 'pglast.ast.AlterExtensionStmt'>: <function alter_extension_stmt>, (<class 'pglast.ast.AlterExtensionStmt'>, <class 'pglast.ast.DefElem'>): <function alter_extension_stmt_def_elem>, <class 'pglast.ast.AlterExtensionContentsStmt'>: <function alter_extension_contents_stmt>, <class 'pglast.ast.AlterEnumStmt'>: <function alter_enum_stmt>, <class 'pglast.ast.AlterDefaultPrivilegesStmt'>: <function alter_default_privileges_stmt>, <class 'pglast.ast.AlterFunctionStmt'>: <function alter_function_stmt>, <class 'pglast.ast.AlterObjectSchemaStmt'>: <function alter_object_schema_stmt>, <class 'pglast.ast.AlterOperatorStmt'>: <function alter_operator_stmt>, (<class 'pglast.ast.AlterOperatorStmt'>, <class 'pglast.ast.DefElem'>): <function alter_operator_stmt_def_elem>, <class 'pglast.ast.AlterOpFamilyStmt'>: <function alter_op_family_stmt>, <class 'pglast.ast.AlterOwnerStmt'>: <function alter_owner_stmt>, <class 'pglast.ast.AlterPolicyStmt'>: <function alter_policy_stmt>, <class 'pglast.ast.AlterRoleStmt'>: <function alter_role_stmt>, <class 'pglast.ast.AlterSeqStmt'>: <function alter_seq_stmt>, <class 'pglast.ast.AlterTableStmt'>: <function alter_table_stmt>, (<class 'pglast.ast.AlterTableStmt'>, <class 'pglast.ast.RangeVar'>): <function range_var>, <class 'pglast.ast.AlterTableCmd'>: <function alter_table_cmd>, (<class 'pglast.ast.AlterTableCmd'>, <class 'pglast.ast.DefElem'>): <function alter_table_cmd_def_elem>, (<class 'pglast.ast.CreatePublicationStmt'>, <class 'pglast.ast.DefElem'>): <function alter_table_cmd_def_elem>, (<class 'pglast.ast.CreateStmt'>, <class 'pglast.ast.DefElem'>): <function alter_table_cmd_def_elem>, (<class 'pglast.ast.IndexStmt'>, <class 'pglast.ast.DefElem'>): <function alter_table_cmd_def_elem>, (<class 'pglast.ast.IntoClause'>, <class 'pglast.ast.DefElem'>): <function alter_table_cmd_def_elem>, <class 'pglast.ast.AlterTSConfigurationStmt'>: <function alter_ts_configuration_stmt>, <class 'pglast.ast.AlterTSDictionaryStmt'>: <function alter_ts_dictionary_stmt>, <class 'pglast.ast.AlterStatsStmt'>: <function alter_stats_stmt>, <class 'pglast.ast.AlterSubscriptionStmt'>: <function alter_subscription_stmt>, <class 'pglast.ast.AlterPublicationStmt'>: <function alter_publication_stmt>, <class 'pglast.ast.AlterFdwStmt'>: <function alter_fdw_stmt>, (<class 'pglast.ast.AlterFdwStmt'>, <class 'pglast.ast.DefElem'>): <function alter_fdw_stmt_def_elem>, <class 'pglast.ast.AlterForeignServerStmt'>: <function alter_foreign_server_stmt>, <class 'pglast.ast.AlterUserMappingStmt'>: <function alter_user_mapping_stmt>, <class 'pglast.ast.AlterRoleSetStmt'>: <function alter_role_set_stmt>, <class 'pglast.ast.AlterDomainStmt'>: <function alter_domain_stmt>, <class 'pglast.ast.AlterEventTrigStmt'>: <function alter_event_trig_stmt>, <class 'pglast.ast.AlterTypeStmt'>: <function alter_type_stmt>, <class 'pglast.ast.CheckPointStmt'>: <function check_point_stmt>, <class 'pglast.ast.ClusterStmt'>: <function cluster_stmt>, <class 'pglast.ast.ColumnDef'>: <function column_def>, <class 'pglast.ast.CommentStmt'>: <function comment_stmt>, <class 'pglast.ast.CompositeTypeStmt'>: <function composite_type_stmt>, (<class 'pglast.ast.CompositeTypeStmt'>, <class 'pglast.ast.RangeVar'>): <function composite_type_stmt_range_var>, <class 'pglast.ast.Constraint'>: <function constraint>, <class 'pglast.ast.CreateAmStmt'>: <function create_am_stmt>, <class 'pglast.ast.CreatedbStmt'>: <function create_db_stmt>, (<class 'pglast.ast.CreatedbStmt'>, <class 'pglast.ast.DefElem'>): <function create_db_stmt_def_elem>, <class 'pglast.ast.CreateCastStmt'>: <function create_cast_stmt>, <class 'pglast.ast.CreateConversionStmt'>: <function create_conversion_stmt>, <class 'pglast.ast.CreateDomainStmt'>: <function create_domain_stmt>, <class 'pglast.ast.CreateEnumStmt'>: <function create_enum_stmt>, <class 'pglast.ast.CreateEventTrigStmt'>: <function create_event_trig_stmt>, (<class 'pglast.ast.CreateEventTrigStmt'>, <class 'pglast.ast.DefElem'>): <function create_event_trig_stmt_def_elem>, <class 'pglast.ast.CreateExtensionStmt'>: <function create_extension_stmt>, (<class 'pglast.ast.CreateExtensionStmt'>, <class 'pglast.ast.DefElem'>): <function create_extension_stmt_def_elem>, <class 'pglast.ast.CreateFdwStmt'>: <function create_fdw_stmt>, (<class 'pglast.ast.ColumnDef'>, <class 'pglast.ast.DefElem'>): <function create_fdw_stmt_def_elem>, (<class 'pglast.ast.CreateUserMappingStmt'>, <class 'pglast.ast.DefElem'>): <function create_fdw_stmt_def_elem>, (<class 'pglast.ast.CreateFdwStmt'>, <class 'pglast.ast.DefElem'>): <function create_fdw_stmt_def_elem>, <class 'pglast.ast.CreateForeignServerStmt'>: <function create_foreign_server_stmt>, <class 'pglast.ast.CreateForeignTableStmt'>: <function create_foreign_table_stmt>, (<class 'pglast.ast.CreateForeignTableStmt'>, <class 'pglast.ast.DefElem'>): <function create_foreign_table_stmt_def_elem>, (<class 'pglast.ast.CreateForeignServerStmt'>, <class 'pglast.ast.DefElem'>): <function create_foreign_table_stmt_def_elem>, <class 'pglast.ast.CreateFunctionStmt'>: <function create_function_stmt>, (<class 'pglast.ast.AlterFunctionStmt'>, <class 'pglast.ast.DefElem'>): <function create_function_option>, (<class 'pglast.ast.CreateFunctionStmt'>, <class 'pglast.ast.DefElem'>): <function create_function_option>, (<class 'pglast.ast.DoStmt'>, <class 'pglast.ast.DefElem'>): <function create_function_option>, <class 'pglast.ast.CreateOpClassStmt'>: <function create_opclass_stmt>, <class 'pglast.ast.CreateOpClassItem'>: <function create_opclass_item>, <class 'pglast.ast.CreateOpFamilyStmt'>: <function create_op_family_stmt>, <class 'pglast.ast.CreatePLangStmt'>: <function create_plang_stmt>, <class 'pglast.ast.CreatePolicyStmt'>: <function create_policy_stmt>, <class 'pglast.ast.CreatePublicationStmt'>: <function create_publication_stmt>, (<class 'pglast.ast.CreatePublicationStmt'>, <class 'pglast.ast.RangeVar'>): <function create_publication_stmt_range_var>, <class 'pglast.ast.CreateRangeStmt'>: <function create_range_stmt>, <class 'pglast.ast.CreateRoleStmt'>: <function create_role_stmt>, (<class 'pglast.ast.AlterRoleStmt'>, <class 'pglast.ast.DefElem'>): <function create_or_alter_role_option>, (<class 'pglast.ast.CreateRoleStmt'>, <class 'pglast.ast.DefElem'>): <function create_or_alter_role_option>, <class 'pglast.ast.CreateSchemaStmt'>: <function create_schema_stmt>, <class 'pglast.ast.CreateSeqStmt'>: <function create_seq_stmt>, (<class 'pglast.ast.Constraint'>, <class 'pglast.ast.DefElem'>): <function create_seq_stmt_def_elem>, (<class 'pglast.ast.CreateSeqStmt'>, <class 'pglast.ast.DefElem'>): <function create_seq_stmt_def_elem>, (<class 'pglast.ast.AlterSeqStmt'>, <class 'pglast.ast.DefElem'>): <function create_seq_stmt_def_elem>, <class 'pglast.ast.CreateStatsStmt'>: <function create_stats_stmt>, <class 'pglast.ast.CreateStmt'>: <function create_stmt>, <class 'pglast.ast.CreateTableAsStmt'>: <function create_table_as_stmt>, <class 'pglast.ast.CreateTableSpaceStmt'>: <function create_table_space_stmt>, <class 'pglast.ast.CreateTrigStmt'>: <function create_trig_stmt>, (<class 'pglast.ast.AlterSubscriptionStmt'>, <class 'pglast.ast.DefElem'>): <function create_subscription_stmt_stmt_def_elem>, (<class 'pglast.ast.CreateSubscriptionStmt'>, <class 'pglast.ast.DefElem'>): <function create_subscription_stmt_stmt_def_elem>, <class 'pglast.ast.CreateSubscriptionStmt'>: <function create_subscription_stmt>, <class 'pglast.ast.CurrentOfExpr'>: <function current_of_expr>, <class 'pglast.ast.CreateTransformStmt'>: <function create_transform_stmt>, <class 'pglast.ast.ClosePortalStmt'>: <function close_portal_stmt>, <class 'pglast.ast.CreateUserMappingStmt'>: <function create_user_mapping_stmt>, <class 'pglast.ast.DeallocateStmt'>: <function deallocate_stmt>, <class 'pglast.ast.DefineStmt'>: <function define_stmt>, <class 'pglast.ast.DefElem'>: <function def_elem>, (<class 'pglast.ast.DefineStmt'>, <class 'pglast.ast.DefElem'>): <function define_stmt_def_elem>, <class 'pglast.ast.DiscardStmt'>: <function discard_stmt>, <class 'pglast.ast.DoStmt'>: <function do_stmt>, <class 'pglast.ast.DropdbStmt'>: <function drop_db_stmt>, <class 'pglast.ast.DropOwnedStmt'>: <function drop_owned_stmt>, <class 'pglast.ast.DropRoleStmt'>: <function drop_role_stmt>, <class 'pglast.ast.DropStmt'>: <function drop_stmt>, <class 'pglast.ast.DropSubscriptionStmt'>: <function drop_subscription_stmt>, <class 'pglast.ast.DropTableSpaceStmt'>: <function drop_table_space_stmt>, <class 'pglast.ast.DropUserMappingStmt'>: <function drop_user_mapping_stmt>, <class 'pglast.ast.FunctionParameter'>: <function function_parameter>, <class 'pglast.ast.GrantStmt'>: <function grant_stmt>, <class 'pglast.ast.GrantRoleStmt'>: <function grant_role_stmt>, <class 'pglast.ast.ImportForeignSchemaStmt'>: <function import_foreign_schema_stmt>, <class 'pglast.ast.IndexStmt'>: <function index_stmt>, <class 'pglast.ast.LockStmt'>: <function lock_stmt>, <class 'pglast.ast.NotifyStmt'>: <function notify_stmt>, <class 'pglast.ast.ObjectWithArgs'>: <function object_with_args>, (<class 'pglast.ast.AlterObjectSchemaStmt'>, <class 'pglast.ast.ObjectWithArgs'>): <function alter_object_schema_stmt_object_with_args>, (<class 'pglast.ast.AlterOperatorStmt'>, <class 'pglast.ast.ObjectWithArgs'>): <function alter_operator_stmt_object_with_args>, (<class 'pglast.ast.AlterOwnerStmt'>, <class 'pglast.ast.ObjectWithArgs'>): <function alter_owner_stmt_object_with_args>, (<class 'pglast.ast.CommentStmt'>, <class 'pglast.ast.ObjectWithArgs'>): <function comment_stmt_object_with_args>, (<class 'pglast.ast.DropStmt'>, <class 'pglast.ast.ObjectWithArgs'>): <function drop_stmt_object_with_args>, <class 'pglast.ast.PartitionBoundSpec'>: <function partition_bound_spec>, <class 'pglast.ast.PartitionCmd'>: <function partition_cmd>, <class 'pglast.ast.PartitionElem'>: <function partition_elem>, <class 'pglast.ast.PartitionRangeDatum'>: <function partition_range_datum>, <class 'pglast.ast.PartitionSpec'>: <function partition_spec>, <class 'pglast.ast.ReindexStmt'>: <function reindex_stmt>, (<class 'pglast.ast.ReindexStmt'>, <class 'pglast.ast.DefElem'>): <function reindex_stmt_def_elem>, <class 'pglast.ast.RenameStmt'>: <function rename_stmt>, (<class 'pglast.ast.RenameStmt'>, <class 'pglast.ast.RangeVar'>): <function rename_stmt_range_var>, <class 'pglast.ast.ReplicaIdentityStmt'>: <function replica_identity_stmt>, <class 'pglast.ast.RoleSpec'>: <function role_spec>, <class 'pglast.ast.RuleStmt'>: <function rule_stmt_printer>, <class 'pglast.ast.RefreshMatViewStmt'>: <function refresh_mat_view_stmt>, <class 'pglast.ast.ReassignOwnedStmt'>: <function reassign_owned_stmt>, <class 'pglast.ast.ReturnStmt'>: <function return_stmt>, <class 'pglast.ast.SecLabelStmt'>: <function sec_label_stmt>, <class 'pglast.ast.StatsElem'>: <function stats_elem>, <class 'pglast.ast.TableLikeClause'>: <function table_like_clause>, <class 'pglast.ast.TriggerTransition'>: <function trigger_transition>, <class 'pglast.ast.VacuumStmt'>: <function vacuum_stmt>, (<class 'pglast.ast.VacuumStmt'>, <class 'pglast.ast.DefElem'>): <function vacuum_stmt_def_elem>, <class 'pglast.ast.VacuumRelation'>: <function vacuum_relation>, <class 'pglast.ast.VariableSetStmt'>: <function variable_set_stmt>, <class 'pglast.ast.VariableShowStmt'>: <function variable_show_statement>, <class 'pglast.ast.ViewStmt'>: <function view_stmt>, (<class 'pglast.ast.ViewStmt'>, <class 'pglast.ast.DefElem'>): <function view_stmt_def_elem>, <class 'pglast.ast.A_ArrayExpr'>: <function a_array_expr>, <class 'pglast.ast.A_Const'>: <function a_const>, <class 'pglast.ast.A_Expr'>: <function a_expr>, <class 'pglast.ast.A_Indices'>: <function a_indices>, <class 'pglast.ast.A_Indirection'>: <function a_indirection>, (<class 'pglast.ast.A_Indirection'>, <class 'pglast.ast.A_Star'>): <function a_indirection_a_star>, (<class 'pglast.ast.A_Indirection'>, <class 'pglast.ast.ColumnRef'>): <function a_indirection_column_ref>, (<class 'pglast.ast.A_Indirection'>, <class 'pglast.ast.FuncCall'>): <function a_indirection_func_call>, (<class 'pglast.ast.A_Indirection'>, <class 'pglast.ast.String'>): <function a_indirection_field>, <class 'pglast.ast.A_Star'>: <function a_star>, <class 'pglast.ast.Alias'>: <function alias>, <class 'pglast.ast.BitString'>: <function bitstring>, <class 'pglast.ast.BoolExpr'>: <function bool_expr>, <class 'pglast.ast.BooleanTest'>: <function boolean_test>, <class 'pglast.ast.CallStmt'>: <function call_stmt>, <class 'pglast.ast.CaseExpr'>: <function case_expr>, <class 'pglast.ast.CaseWhen'>: <function case_when>, <class 'pglast.ast.CoalesceExpr'>: <function coalesce_expr>, <class 'pglast.ast.CollateClause'>: <function collate_clause>, <class 'pglast.ast.ColumnRef'>: <function column_ref>, <class 'pglast.ast.CTECycleClause'>: <function cte_cycle_clause>, (<class 'pglast.ast.CTECycleClause'>, <class 'pglast.ast.TypeCast'>): <function cte_cycle_clause_type_cast>, <class 'pglast.ast.CTESearchClause'>: <function cte_search_clause>, <class 'pglast.ast.CommonTableExpr'>: <function common_table_expr>, <class 'pglast.ast.ConstraintsSetStmt'>: <function constraints_set_stmt>, <class 'pglast.ast.CopyStmt'>: <function copy_stmt>, (<class 'pglast.ast.CopyStmt'>, <class 'pglast.ast.DefElem'>): <function copy_stmt_def_elem>, <class 'pglast.ast.DeclareCursorStmt'>: <function declare_cursor_stmt>, <class 'pglast.ast.DeleteStmt'>: <function delete_stmt>, <class 'pglast.ast.ExecuteStmt'>: <function execute_stmt>, <class 'pglast.ast.ExplainStmt'>: <function explain_stmt>, (<class 'pglast.ast.ExplainStmt'>, <class 'pglast.ast.DefElem'>): <function explain_stmt_def_elem>, <class 'pglast.ast.FetchStmt'>: <function fetch_stmt>, <class 'pglast.ast.Float'>: <function float>, <class 'pglast.ast.FuncCall'>: <function func_call>, (<class 'pglast.ast.FuncCall'>, <class 'pglast.ast.WindowDef'>): <function func_call_window_def>, <class 'pglast.ast.GroupingSet'>: <function grouping_set>, <class 'pglast.ast.GroupingFunc'>: <function grouping_func>, <class 'pglast.ast.IndexElem'>: <function index_elem>, <class 'pglast.ast.InferClause'>: <function infer_clause>, <class 'pglast.ast.Integer'>: <function integer>, <class 'pglast.ast.InsertStmt'>: <function insert_stmt>, <class 'pglast.ast.IntoClause'>: <function into_clause>, <class 'pglast.ast.JoinExpr'>: <function join_expr>, <class 'pglast.ast.LockingClause'>: <function locking_clause>, <class 'pglast.ast.ListenStmt'>: <function listen_stmt>, <class 'pglast.ast.MinMaxExpr'>: <function min_max_expr>, <class 'pglast.ast.MultiAssignRef'>: <function multi_assign_ref>, <class 'pglast.ast.NamedArgExpr'>: <function named_arg_expr>, <class 'pglast.ast.Null'>: <function null>, <class 'pglast.ast.NullTest'>: <function null_test>, <class 'pglast.ast.ParamRef'>: <function param_ref>, <class 'pglast.ast.PrepareStmt'>: <function prepare_stmt>, <class 'pglast.ast.OnConflictClause'>: <function on_conflict_clause>, <class 'pglast.ast.RangeFunction'>: <function range_function>, <class 'pglast.ast.RangeSubselect'>: <function range_subselect>, <class 'pglast.ast.RangeTableFunc'>: <function range_table_func>, (<class 'pglast.ast.RangeTableFunc'>, <class 'pglast.ast.ResTarget'>): <function range_table_func_res_target>, <class 'pglast.ast.RangeTableFuncCol'>: <function range_table_func_col>, <class 'pglast.ast.RangeVar'>: <function range_var>, <class 'pglast.ast.RangeTableSample'>: <function range_table_sample>, <class 'pglast.ast.RawStmt'>: <function raw_stmt>, <class 'pglast.ast.ResTarget'>: <function res_target>, <class 'pglast.ast.RowExpr'>: <function row_expr>, <class 'pglast.ast.SelectStmt'>: <function select_stmt>, <class 'pglast.ast.SetToDefault'>: <function set_to_default>, <class 'pglast.ast.SortBy'>: <function sort_by>, <class 'pglast.ast.SQLValueFunction'>: <function sql_value_function>, <class 'pglast.ast.String'>: <function string>, <class 'pglast.ast.SubLink'>: <function sub_link>, <class 'pglast.ast.TransactionStmt'>: <function transaction_stmt>, (<class 'pglast.ast.TransactionStmt'>, <class 'pglast.ast.DefElem'>): <function transaction_stmt_def_elem>, <class 'pglast.ast.TruncateStmt'>: <function truncate_stmt>, <class 'pglast.ast.TypeCast'>: <function type_cast>, <class 'pglast.ast.TypeName'>: <function type_name>, (<class 'pglast.ast.VariableSetStmt'>, <class 'pglast.ast.TypeCast'>): <function variable_set_stmt_type_cast>, <class 'pglast.ast.UpdateStmt'>: <function update_stmt>, <class 'pglast.ast.UnlistenStmt'>: <function unlisten_stmt>, <class 'pglast.ast.WithClause'>: <function with_clause>, <class 'pglast.ast.WindowDef'>: <function window_def>, (<class 'pglast.ast.OnConflictClause'>, <class 'pglast.ast.ResTarget'>): <function update_stmt_res_target>, (<class 'pglast.ast.UpdateStmt'>, <class 'pglast.ast.ResTarget'>): <function update_stmt_res_target>, <class 'pglast.ast.XmlExpr'>: <function xml_expr>, <class 'pglast.ast.XmlSerialize'>: <function xml_serialize>}

Registry of specialized node printers, keyed by their class.

pglast.printers.SPECIAL_FUNCTIONS = {'pg_catalog.btrim': <function btrim>, 'pg_catalog.extract': <function extract>, 'pg_catalog.ltrim': <function ltrim>, 'pg_catalog.normalize': <function normalize>, 'pg_catalog.overlaps': <function overlaps>, 'pg_catalog.overlay': <function overlay>, 'pg_catalog.pg_collation_for': <function pg_collation_for>, 'pg_catalog.position': <function position>, 'pg_catalog.rtrim': <function rtrim>, 'pg_catalog.substring': <function substring>, 'pg_catalog.timezone': <function timezone>, 'pg_catalog.xmlexists': <function xmlexists>}

Registry of specialized function printers, keyed by their qualified name.

exception pglast.printers.PrinterAlreadyPresentError

Exception raised trying to register another function for a tag already present.

pglast.printers.get_printer_for_node(node)

Get specific printer implementation for given node.

If there is a more specific printer for it, when it’s inside a particular ancestor, return that instead.

pglast.printers.node_printer(*nodes, override=False)

Decorator to register a specific printer implementation for a (set of) nodes.

Parameters
  • *nodes – a list of one or two items

  • override (bool) – when True the function will be registered even if already present in the NODE_PRINTERS registry

When nodes contains a single item then the decorated function is the generic one, and it will be registered in NODE_PRINTERS with that key alone. Otherwise it must contain two elements: the first may be either a scalar value or a sequence of parent nodes, and the function will be registered under the key (parent, node).

pglast.printers.special_function(name, override=False)

Decorator to declare a particular PostgreSQL function name as special, with a specific printer.

Parameters
  • name (str) – the qualified name of the PG function

  • override (bool) – when True the function will be registered even if already present in the SPECIAL_FUNCTIONS registry

pglast.printers.ddl — DDL printer functions
pglast.printers.ddl.access_priv(node, output)

Pretty print a node of type AccessPriv to the output stream.

pglast.printers.ddl.alter_collation_stmt(node, output)

Pretty print a node of type AlterCollationStmt to the output stream.

pglast.printers.ddl.alter_database_stmt(node, output)

Pretty print a node of type AlterDatabaseStmt to the output stream.

pglast.printers.ddl.alter_database_set_stmt(node, output)

Pretty print a node of type AlterDatabaseSetStmt to the output stream.

pglast.printers.ddl.alter_extension_stmt(node, output)

Pretty print a node of type AlterExtensionStmt to the output stream.

pglast.printers.ddl.alter_extension_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a AlterExtensionStmt, to the output stream.

pglast.printers.ddl.alter_extension_contents_stmt(node, output)

Pretty print a node of type AlterExtensionContentsStmt to the output stream.

pglast.printers.ddl.alter_enum_stmt(node, output)

Pretty print a node of type AlterEnumStmt to the output stream.

pglast.printers.ddl.alter_default_privileges_stmt(node, output)

Pretty print a node of type AlterDefaultPrivilegesStmt to the output stream.

pglast.printers.ddl.alter_function_stmt(node, output)

Pretty print a node of type AlterFunctionStmt to the output stream.

pglast.printers.ddl.alter_object_schema_stmt(node, output)

Pretty print a node of type AlterObjectSchemaStmt to the output stream.

pglast.printers.ddl.alter_operator_stmt(node, output)

Pretty print a node of type AlterOperatorStmt to the output stream.

pglast.printers.ddl.alter_operator_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a AlterOperatorStmt, to the output stream.

pglast.printers.ddl.alter_op_family_stmt(node, output)

Pretty print a node of type AlterOpFamilyStmt to the output stream.

pglast.printers.ddl.alter_owner_stmt(node, output)

Pretty print a node of type AlterOwnerStmt to the output stream.

pglast.printers.ddl.alter_policy_stmt(node, output)

Pretty print a node of type AlterPolicyStmt to the output stream.

pglast.printers.ddl.alter_role_stmt(node, output)

Pretty print a node of type AlterRoleStmt to the output stream.

pglast.printers.ddl.alter_seq_stmt(node, output)

Pretty print a node of type AlterSeqStmt to the output stream.

pglast.printers.ddl.alter_table_stmt(node, output)

Pretty print a node of type AlterTableStmt to the output stream.

pglast.printers.ddl.range_var(node, output)

Pretty print a node of type RangeVar, when it is inside a AlterTableStmt, to the output stream.

pglast.printers.ddl.alter_table_cmd(node, output)

Pretty print a node of type AlterTableCmd to the output stream.

pglast.printers.ddl.alter_table_cmd_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a AlterTableCmd or a CreatePublicationStmt or a CreateStmt or a IndexStmt or a IntoClause, to the output stream.

pglast.printers.ddl.alter_ts_configuration_stmt(node, output)

Pretty print a node of type AlterTSConfigurationStmt to the output stream.

pglast.printers.ddl.alter_ts_dictionary_stmt(node, output)

Pretty print a node of type AlterTSDictionaryStmt to the output stream.

pglast.printers.ddl.alter_stats_stmt(node, output)

Pretty print a node of type AlterStatsStmt to the output stream.

pglast.printers.ddl.alter_subscription_stmt(node, output)

Pretty print a node of type AlterSubscriptionStmt to the output stream.

pglast.printers.ddl.alter_publication_stmt(node, output)

Pretty print a node of type AlterPublicationStmt to the output stream.

pglast.printers.ddl.alter_fdw_stmt(node, output)

Pretty print a node of type AlterFdwStmt to the output stream.

pglast.printers.ddl.alter_fdw_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a AlterFdwStmt, to the output stream.

pglast.printers.ddl.alter_foreign_server_stmt(node, output)

Pretty print a node of type AlterForeignServerStmt to the output stream.

pglast.printers.ddl.alter_user_mapping_stmt(node, output)

Pretty print a node of type AlterUserMappingStmt to the output stream.

pglast.printers.ddl.alter_role_set_stmt(node, output)

Pretty print a node of type AlterRoleSetStmt to the output stream.

pglast.printers.ddl.alter_domain_stmt(node, output)

Pretty print a node of type AlterDomainStmt to the output stream.

pglast.printers.ddl.alter_event_trig_stmt(node, output)

Pretty print a node of type AlterEventTrigStmt to the output stream.

pglast.printers.ddl.alter_type_stmt(node, output)

Pretty print a node of type AlterTypeStmt to the output stream.

pglast.printers.ddl.check_point_stmt(node, output)

Pretty print a node of type CheckPointStmt to the output stream.

pglast.printers.ddl.cluster_stmt(node, output)

Pretty print a node of type ClusterStmt to the output stream.

pglast.printers.ddl.column_def(node, output)

Pretty print a node of type ColumnDef to the output stream.

pglast.printers.ddl.comment_stmt(node, output)

Pretty print a node of type CommentStmt to the output stream.

pglast.printers.ddl.composite_type_stmt(node, output)

Pretty print a node of type CompositeTypeStmt to the output stream.

pglast.printers.ddl.composite_type_stmt_range_var(node, output)

Pretty print a node of type RangeVar, when it is inside a CompositeTypeStmt, to the output stream.

pglast.printers.ddl.constraint(node, output)

Pretty print a node of type Constraint to the output stream.

pglast.printers.ddl.create_am_stmt(node, output)

Pretty print a node of type CreateAmStmt to the output stream.

pglast.printers.ddl.create_db_stmt(node, output)

Pretty print a node of type CreatedbStmt to the output stream.

pglast.printers.ddl.create_db_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a CreatedbStmt, to the output stream.

pglast.printers.ddl.create_cast_stmt(node, output)

Pretty print a node of type CreateCastStmt to the output stream.

pglast.printers.ddl.create_conversion_stmt(node, output)

Pretty print a node of type CreateConversionStmt to the output stream.

pglast.printers.ddl.create_domain_stmt(node, output)

Pretty print a node of type CreateDomainStmt to the output stream.

pglast.printers.ddl.create_enum_stmt(node, output)

Pretty print a node of type CreateEnumStmt to the output stream.

pglast.printers.ddl.create_event_trig_stmt(node, output)

Pretty print a node of type CreateEventTrigStmt to the output stream.

pglast.printers.ddl.create_event_trig_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a CreateEventTrigStmt, to the output stream.

pglast.printers.ddl.create_extension_stmt(node, output)

Pretty print a node of type CreateExtensionStmt to the output stream.

pglast.printers.ddl.create_extension_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a CreateExtensionStmt, to the output stream.

pglast.printers.ddl.create_fdw_stmt(node, output)

Pretty print a node of type CreateFdwStmt to the output stream.

pglast.printers.ddl.create_fdw_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a ColumnDef or a CreateUserMappingStmt or a CreateFdwStmt, to the output stream.

pglast.printers.ddl.create_foreign_server_stmt(node, output)

Pretty print a node of type CreateForeignServerStmt to the output stream.

pglast.printers.ddl.create_foreign_table_stmt(node, output)

Pretty print a node of type CreateForeignTableStmt to the output stream.

pglast.printers.ddl.create_foreign_table_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a CreateForeignTableStmt or a CreateForeignServerStmt, to the output stream.

pglast.printers.ddl.create_function_stmt(node, output)

Pretty print a node of type CreateFunctionStmt to the output stream.

pglast.printers.ddl.create_function_option(node, output)

Pretty print a node of type DefElem, when it is inside a AlterFunctionStmt or a CreateFunctionStmt or a DoStmt, to the output stream.

pglast.printers.ddl.create_opclass_stmt(node, output)

Pretty print a node of type CreateOpClassStmt to the output stream.

pglast.printers.ddl.create_opclass_item(node, output)

Pretty print a node of type CreateOpClassItem to the output stream.

pglast.printers.ddl.create_op_family_stmt(node, output)

Pretty print a node of type CreateOpFamilyStmt to the output stream.

pglast.printers.ddl.create_plang_stmt(node, output)

Pretty print a node of type CreatePLangStmt to the output stream.

pglast.printers.ddl.create_policy_stmt(node, output)

Pretty print a node of type CreatePolicyStmt to the output stream.

pglast.printers.ddl.create_publication_stmt(node, output)

Pretty print a node of type CreatePublicationStmt to the output stream.

pglast.printers.ddl.create_publication_stmt_range_var(node, output)

Pretty print a node of type RangeVar, when it is inside a CreatePublicationStmt, to the output stream.

pglast.printers.ddl.create_range_stmt(node, output)

Pretty print a node of type CreateRangeStmt to the output stream.

pglast.printers.ddl.create_role_stmt(node, output)

Pretty print a node of type CreateRoleStmt to the output stream.

pglast.printers.ddl.create_or_alter_role_option(node, output)

Pretty print a node of type DefElem, when it is inside a AlterRoleStmt or a CreateRoleStmt, to the output stream.

pglast.printers.ddl.create_schema_stmt(node, output)

Pretty print a node of type CreateSchemaStmt to the output stream.

pglast.printers.ddl.create_seq_stmt(node, output)

Pretty print a node of type CreateSeqStmt to the output stream.

pglast.printers.ddl.create_seq_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a Constraint or a CreateSeqStmt or a AlterSeqStmt, to the output stream.

pglast.printers.ddl.create_stats_stmt(node, output)

Pretty print a node of type CreateStatsStmt to the output stream.

pglast.printers.ddl.create_stmt(node, output)

Pretty print a node of type CreateStmt to the output stream.

pglast.printers.ddl.create_table_as_stmt(node, output)

Pretty print a node of type CreateTableAsStmt to the output stream.

pglast.printers.ddl.create_table_space_stmt(node, output)

Pretty print a node of type CreateTableSpaceStmt to the output stream.

pglast.printers.ddl.create_trig_stmt(node, output)

Pretty print a node of type CreateTrigStmt to the output stream.

pglast.printers.ddl.create_subscription_stmt_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a AlterSubscriptionStmt or a CreateSubscriptionStmt, to the output stream.

pglast.printers.ddl.create_subscription_stmt(node, output)

Pretty print a node of type CreateSubscriptionStmt to the output stream.

pglast.printers.ddl.current_of_expr(node, output)

Pretty print a node of type CurrentOfExpr to the output stream.

pglast.printers.ddl.create_transform_stmt(node, output)

Pretty print a node of type CreateTransformStmt to the output stream.

pglast.printers.ddl.close_portal_stmt(node, output)

Pretty print a node of type ClosePortalStmt to the output stream.

pglast.printers.ddl.create_user_mapping_stmt(node, output)

Pretty print a node of type CreateUserMappingStmt to the output stream.

pglast.printers.ddl.deallocate_stmt(node, output)

Pretty print a node of type DeallocateStmt to the output stream.

pglast.printers.ddl.define_stmt(node, output)

Pretty print a node of type DefineStmt to the output stream.

pglast.printers.ddl.def_elem(node, output)

Pretty print a node of type DefElem to the output stream.

pglast.printers.ddl.define_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a DefineStmt, to the output stream.

pglast.printers.ddl.discard_stmt(node, output)

Pretty print a node of type DiscardStmt to the output stream.

pglast.printers.ddl.do_stmt(node, output)

Pretty print a node of type DoStmt to the output stream.

pglast.printers.ddl.drop_db_stmt(node, output)

Pretty print a node of type DropdbStmt to the output stream.

pglast.printers.ddl.drop_owned_stmt(node, output)

Pretty print a node of type DropOwnedStmt to the output stream.

pglast.printers.ddl.drop_role_stmt(node, output)

Pretty print a node of type DropRoleStmt to the output stream.

pglast.printers.ddl.drop_stmt(node, output)

Pretty print a node of type DropStmt to the output stream.

pglast.printers.ddl.drop_subscription_stmt(node, output)

Pretty print a node of type DropSubscriptionStmt to the output stream.

pglast.printers.ddl.drop_table_space_stmt(node, output)

Pretty print a node of type DropTableSpaceStmt to the output stream.

pglast.printers.ddl.drop_user_mapping_stmt(node, output)

Pretty print a node of type DropUserMappingStmt to the output stream.

pglast.printers.ddl.function_parameter(node, output)

Pretty print a node of type FunctionParameter to the output stream.

pglast.printers.ddl.grant_stmt(node, output)

Pretty print a node of type GrantStmt to the output stream.

pglast.printers.ddl.grant_role_stmt(node, output)

Pretty print a node of type GrantRoleStmt to the output stream.

pglast.printers.ddl.import_foreign_schema_stmt(node, output)

Pretty print a node of type ImportForeignSchemaStmt to the output stream.

pglast.printers.ddl.index_stmt(node, output)

Pretty print a node of type IndexStmt to the output stream.

pglast.printers.ddl.lock_stmt(node, output)

Pretty print a node of type LockStmt to the output stream.

pglast.printers.ddl.notify_stmt(node, output)

Pretty print a node of type NotifyStmt to the output stream.

pglast.printers.ddl.object_with_args(node, output)

Pretty print a node of type ObjectWithArgs to the output stream.

pglast.printers.ddl.alter_object_schema_stmt_object_with_args(node, output)

Pretty print a node of type ObjectWithArgs, when it is inside a AlterObjectSchemaStmt, to the output stream.

pglast.printers.ddl.alter_operator_stmt_object_with_args(node, output)

Pretty print a node of type ObjectWithArgs, when it is inside a AlterOperatorStmt, to the output stream.

pglast.printers.ddl.alter_owner_stmt_object_with_args(node, output)

Pretty print a node of type ObjectWithArgs, when it is inside a AlterOwnerStmt, to the output stream.

pglast.printers.ddl.comment_stmt_object_with_args(node, output)

Pretty print a node of type ObjectWithArgs, when it is inside a CommentStmt, to the output stream.

pglast.printers.ddl.drop_stmt_object_with_args(node, output)

Pretty print a node of type ObjectWithArgs, when it is inside a DropStmt, to the output stream.

pglast.printers.ddl.partition_bound_spec(node, output)

Pretty print a node of type PartitionBoundSpec to the output stream.

pglast.printers.ddl.partition_cmd(node, output)

Pretty print a node of type PartitionCmd to the output stream.

pglast.printers.ddl.partition_elem(node, output)

Pretty print a node of type PartitionElem to the output stream.

pglast.printers.ddl.partition_range_datum(node, output)

Pretty print a node of type PartitionRangeDatum to the output stream.

pglast.printers.ddl.partition_spec(node, output)

Pretty print a node of type PartitionSpec to the output stream.

pglast.printers.ddl.reindex_stmt(node, output)

Pretty print a node of type ReindexStmt to the output stream.

pglast.printers.ddl.reindex_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a ReindexStmt, to the output stream.

pglast.printers.ddl.rename_stmt(node, output)

Pretty print a node of type RenameStmt to the output stream.

pglast.printers.ddl.rename_stmt_range_var(node, output)

Pretty print a node of type RangeVar, when it is inside a RenameStmt, to the output stream.

pglast.printers.ddl.replica_identity_stmt(node, output)

Pretty print a node of type ReplicaIdentityStmt to the output stream.

pglast.printers.ddl.role_spec(node, output)

Pretty print a node of type RoleSpec to the output stream.

pglast.printers.ddl.rule_stmt_printer(node, output)

Pretty print a node of type RuleStmt to the output stream.

pglast.printers.ddl.refresh_mat_view_stmt(node, output)

Pretty print a node of type RefreshMatViewStmt to the output stream.

pglast.printers.ddl.reassign_owned_stmt(node, output)

Pretty print a node of type ReassignOwnedStmt to the output stream.

pglast.printers.ddl.return_stmt(node, output)

Pretty print a node of type ReturnStmt to the output stream.

pglast.printers.ddl.sec_label_stmt(node, output)

Pretty print a node of type SecLabelStmt to the output stream.

pglast.printers.ddl.stats_elem(node, output)

Pretty print a node of type StatsElem to the output stream.

pglast.printers.ddl.table_like_clause(node, output)

Pretty print a node of type TableLikeClause to the output stream.

pglast.printers.ddl.trigger_transition(node, output)

Pretty print a node of type TriggerTransition to the output stream.

pglast.printers.ddl.vacuum_stmt(node, output)

Pretty print a node of type VacuumStmt to the output stream.

pglast.printers.ddl.vacuum_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a VacuumStmt, to the output stream.

pglast.printers.ddl.vacuum_relation(node, output)

Pretty print a node of type VacuumRelation to the output stream.

pglast.printers.ddl.variable_set_stmt(node, output)

Pretty print a node of type VariableSetStmt to the output stream.

pglast.printers.ddl.variable_show_statement(node, output)

Pretty print a node of type VariableShowStmt to the output stream.

pglast.printers.ddl.view_stmt(node, output)

Pretty print a node of type ViewStmt to the output stream.

pglast.printers.ddl.view_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a ViewStmt, to the output stream.

pglast.printers.dml — DML printer functions
pglast.printers.dml.a_array_expr(node, output)

Pretty print a node of type A_ArrayExpr to the output stream.

pglast.printers.dml.a_const(node, output)

Pretty print a node of type A_Const to the output stream.

pglast.printers.dml.a_expr(node, output)

Pretty print a node of type A_Expr to the output stream.

pglast.printers.dml.a_indices(node, output)

Pretty print a node of type A_Indices to the output stream.

pglast.printers.dml.a_indirection(node, output)

Pretty print a node of type A_Indirection to the output stream.

pglast.printers.dml.a_indirection_a_star(node, output)

Pretty print a node of type A_Star, when it is inside a A_Indirection, to the output stream.

pglast.printers.dml.a_indirection_column_ref(node, output)

Pretty print a node of type ColumnRef, when it is inside a A_Indirection, to the output stream.

pglast.printers.dml.a_indirection_func_call(node, output)

Pretty print a node of type FuncCall, when it is inside a A_Indirection, to the output stream.

pglast.printers.dml.a_indirection_field(node, output)

Pretty print a node of type String, when it is inside a A_Indirection, to the output stream.

pglast.printers.dml.a_star(node, output)

Pretty print a node of type A_Star to the output stream.

pglast.printers.dml.alias(node, output)

Pretty print a node of type Alias to the output stream.

pglast.printers.dml.bitstring(node, output)

Pretty print a node of type BitString to the output stream.

pglast.printers.dml.bool_expr(node, output)

Pretty print a node of type BoolExpr to the output stream.

pglast.printers.dml.boolean_test(node, output)

Pretty print a node of type BooleanTest to the output stream.

pglast.printers.dml.call_stmt(node, output)

Pretty print a node of type CallStmt to the output stream.

pglast.printers.dml.case_expr(node, output)

Pretty print a node of type CaseExpr to the output stream.

pglast.printers.dml.case_when(node, output)

Pretty print a node of type CaseWhen to the output stream.

pglast.printers.dml.coalesce_expr(node, output)

Pretty print a node of type CoalesceExpr to the output stream.

pglast.printers.dml.collate_clause(node, output)

Pretty print a node of type CollateClause to the output stream.

pglast.printers.dml.column_ref(node, output)

Pretty print a node of type ColumnRef to the output stream.

pglast.printers.dml.cte_cycle_clause(node, output)

Pretty print a node of type CTECycleClause to the output stream.

pglast.printers.dml.cte_cycle_clause_type_cast(node, output)

Pretty print a node of type TypeCast, when it is inside a CTECycleClause, to the output stream.

pglast.printers.dml.cte_search_clause(node, output)

Pretty print a node of type CTESearchClause to the output stream.

pglast.printers.dml.common_table_expr(node, output)

Pretty print a node of type CommonTableExpr to the output stream.

pglast.printers.dml.constraints_set_stmt(node, output)

Pretty print a node of type ConstraintsSetStmt to the output stream.

pglast.printers.dml.copy_stmt(node, output)

Pretty print a node of type CopyStmt to the output stream.

pglast.printers.dml.copy_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a CopyStmt, to the output stream.

pglast.printers.dml.declare_cursor_stmt(node, output)

Pretty print a node of type DeclareCursorStmt to the output stream.

pglast.printers.dml.delete_stmt(node, output)

Pretty print a node of type DeleteStmt to the output stream.

pglast.printers.dml.execute_stmt(node, output)

Pretty print a node of type ExecuteStmt to the output stream.

pglast.printers.dml.explain_stmt(node, output)

Pretty print a node of type ExplainStmt to the output stream.

pglast.printers.dml.explain_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a ExplainStmt, to the output stream.

pglast.printers.dml.fetch_stmt(node, output)

Pretty print a node of type FetchStmt to the output stream.

pglast.printers.dml.float(node, output)

Pretty print a node of type Float to the output stream.

pglast.printers.dml.func_call(node, output)

Pretty print a node of type FuncCall to the output stream.

pglast.printers.dml.func_call_window_def(node, output)

Pretty print a node of type WindowDef, when it is inside a FuncCall, to the output stream.

pglast.printers.dml.grouping_set(node, output)

Pretty print a node of type GroupingSet to the output stream.

pglast.printers.dml.grouping_func(node, output)

Pretty print a node of type GroupingFunc to the output stream.

pglast.printers.dml.index_elem(node, output)

Pretty print a node of type IndexElem to the output stream.

pglast.printers.dml.infer_clause(node, output)

Pretty print a node of type InferClause to the output stream.

pglast.printers.dml.integer(node, output)

Pretty print a node of type Integer to the output stream.

pglast.printers.dml.insert_stmt(node, output)

Pretty print a node of type InsertStmt to the output stream.

pglast.printers.dml.into_clause(node, output)

Pretty print a node of type IntoClause to the output stream.

pglast.printers.dml.join_expr(node, output)

Pretty print a node of type JoinExpr to the output stream.

pglast.printers.dml.locking_clause(node, output)

Pretty print a node of type LockingClause to the output stream.

pglast.printers.dml.listen_stmt(node, output)

Pretty print a node of type ListenStmt to the output stream.

pglast.printers.dml.min_max_expr(node, output)

Pretty print a node of type MinMaxExpr to the output stream.

pglast.printers.dml.multi_assign_ref(node, output)

Pretty print a node of type MultiAssignRef to the output stream.

pglast.printers.dml.named_arg_expr(node, output)

Pretty print a node of type NamedArgExpr to the output stream.

pglast.printers.dml.null(node, output)

Pretty print a node of type Null to the output stream.

pglast.printers.dml.null_test(node, output)

Pretty print a node of type NullTest to the output stream.

pglast.printers.dml.param_ref(node, output)

Pretty print a node of type ParamRef to the output stream.

pglast.printers.dml.prepare_stmt(node, output)

Pretty print a node of type PrepareStmt to the output stream.

pglast.printers.dml.on_conflict_clause(node, output)

Pretty print a node of type OnConflictClause to the output stream.

pglast.printers.dml.range_function(node, output)

Pretty print a node of type RangeFunction to the output stream.

pglast.printers.dml.range_subselect(node, output)

Pretty print a node of type RangeSubselect to the output stream.

pglast.printers.dml.range_table_func(node, output)

Pretty print a node of type RangeTableFunc to the output stream.

pglast.printers.dml.range_table_func_res_target(node, output)

Pretty print a node of type ResTarget, when it is inside a RangeTableFunc, to the output stream.

pglast.printers.dml.range_table_func_col(node, output)

Pretty print a node of type RangeTableFuncCol to the output stream.

pglast.printers.dml.range_var(node, output)

Pretty print a node of type RangeVar to the output stream.

pglast.printers.dml.range_table_sample(node, output)

Pretty print a node of type RangeTableSample to the output stream.

pglast.printers.dml.raw_stmt(node, output)

Pretty print a node of type RawStmt to the output stream.

pglast.printers.dml.res_target(node, output)

Pretty print a node of type ResTarget to the output stream.

pglast.printers.dml.row_expr(node, output)

Pretty print a node of type RowExpr to the output stream.

pglast.printers.dml.select_stmt(node, output)

Pretty print a node of type SelectStmt to the output stream.

pglast.printers.dml.set_to_default(node, output)

Pretty print a node of type SetToDefault to the output stream.

pglast.printers.dml.sort_by(node, output)

Pretty print a node of type SortBy to the output stream.

pglast.printers.dml.sql_value_function(node, output)

Pretty print a node of type SQLValueFunction to the output stream.

pglast.printers.dml.string(node, output)

Pretty print a node of type String to the output stream.

Pretty print a node of type SubLink to the output stream.

pglast.printers.dml.transaction_stmt(node, output)

Pretty print a node of type TransactionStmt to the output stream.

pglast.printers.dml.transaction_stmt_def_elem(node, output)

Pretty print a node of type DefElem, when it is inside a TransactionStmt, to the output stream.

pglast.printers.dml.truncate_stmt(node, output)

Pretty print a node of type TruncateStmt to the output stream.

pglast.printers.dml.type_cast(node, output)

Pretty print a node of type TypeCast to the output stream.

pglast.printers.dml.type_name(node, output)

Pretty print a node of type TypeName to the output stream.

pglast.printers.dml.variable_set_stmt_type_cast(node, output)

Pretty print a node of type TypeCast, when it is inside a VariableSetStmt, to the output stream.

pglast.printers.dml.update_stmt(node, output)

Pretty print a node of type UpdateStmt to the output stream.

pglast.printers.dml.unlisten_stmt(node, output)

Pretty print a node of type UnlistenStmt to the output stream.

pglast.printers.dml.with_clause(node, output)

Pretty print a node of type WithClause to the output stream.

pglast.printers.dml.window_def(node, output)

Pretty print a node of type WindowDef to the output stream.

pglast.printers.dml.update_stmt_res_target(node, output)

Pretty print a node of type ResTarget, when it is inside a OnConflictClause or a UpdateStmt, to the output stream.

pglast.printers.dml.xml_expr(node, output)

Pretty print a node of type XmlExpr to the output stream.

pglast.printers.dml.xml_serialize(node, output)

Pretty print a node of type XmlSerialize to the output stream.

pglast.printers.sfuncs — Special function printers

The PostgreSQL parser translates some SQL constructs into function calls, for example the expression EXTRACT(YEAR FROM date_column) is represented the same as pg_catalog.date_part('year', date_column).

This module declares some of those equivalences, implementing alternative printers that will be used when the option special_functions of the output stream is set to True.

pglast.printers.sfuncs.btrim(node, output)

Emit function pg_catalog.btrim('  abc  ') as trim(BOTH FROM '  abc  ') and pg_catalog.btrim('xxabcxx', 'x') as trim(BOTH 'x' FROM 'xxabcxx').

pglast.printers.sfuncs.extract(node, output)

Emit function pg_catalog.extract(field, timestamp) as EXTRACT(field FROM timestamp)..

pglast.printers.sfuncs.ltrim(node, output)

Emit function pg_catalog.ltrim('  abc  ') as trim(LEADING FROM '  abc  ') and pg_catalog.ltrim('xxabcxx', 'x') as trim(LEADING 'x' FROM 'xxabcxx').

pglast.printers.sfuncs.normalize(node, output)

Emit function pg_catalog.normalize(a) as normalize(x) and function pg_catalog.normalize('a','b') as normalize('a', b).

pglast.printers.sfuncs.overlaps(node, output)

Emit function pg_catalog.overlaps(a, b, c, d) as (a, b) OVERLAPS (c, d).

pglast.printers.sfuncs.overlay(node, output)

Emit function pg_catalog.overlay('Txxxxas','hom', 2, 4) as overlay('Txxxxas' PLACING 'hom' FROM 2 FOR 4).”

pglast.printers.sfuncs.pg_collation_for(node, output)

Emit function pg_catalog.pg_collation_for(x) as COLLATION FOR (x).

pglast.printers.sfuncs.position(node, output)

Emit function pg_catalog.position('abcd', 'a') as position('a' IN 'abcd').

pglast.printers.sfuncs.rtrim(node, output)

Emit function pg_catalog.rtrim('  abc  ') as trim(TRAILING FROM '  abc  ') and pg_catalog.rtrim('xxabcxx', 'x') as trim(TRAILING 'x' FROM 'xxabcxx')

pglast.printers.sfuncs.substring(node, output)

Emit function pg_catalog.substring('Txxxxas', 2, 4) as substring('Txxxxas' FROM 2 FOR 4) and pg_catalog.substring('blabla', 2) as substring('blabla' FROM 2).

pglast.printers.sfuncs.timezone(node, output)

Emit function pg_catalog.timezone(tz, timestamp) as timestamp AT TIME ZONE tz.

pglast.printers.sfuncs.xmlexists(node, output)

Emit function pg_catalog.xmlexists(x, y) as xmlexists(x PASSING BY REF y).

pglast.visitors — Other ways to inspect and manipulate the AST

class pglast.visitors.Action

Abstract action singleton.

class pglast.visitors.ActionMeta

Metaclass used to implement action singleton.

class pglast.visitors.Add

Marker used to tell the iterator to insert nodes in the current sequence.

class pglast.visitors.Ancestor(parent=None, node=None, member=None)

Simple object to keep track of the node’s ancestors while it’s being visited.

Parameters
  • parent (Ancestor) – the parent of the new instance

  • node – the tracked object

  • member – either the name of the attribute or the index in the sequence that points to the tracked object in the parent container

An instance of this class represent a particular ancestor in the hierarchy chain: it carries a reference that points to the higher item in the chain, the associated ast.Node instance and a member, either the attribute name or sequential index in the parent node: the latter happens when the parent node is actually a tuple, not an Node instance.

Accessing an instance with a positive index returns the nth node up in the hierarchy.

When applied (using the @ operator) to an ast.Node instance will traverse that node returning the leaf one corresponding to the whole chain.

Example:

>>> tree = parse_sql('select 1')
>>> root = Ancestor()
>>> root
ROOT
>>> root@tree is tree
True
>>> root[0] is None
True
>>> select_stmt_path = root / (tree, 0) / (tree[0], 'stmt')
>>> select_stmt_path
ROOT → 0 → stmt
>>> select_stmt_path@tree is tree[0].stmt
True
>>> select_stmt_path[0] is tree[0]
True
>>> columns_path = (select_stmt_path
...                 / (tree[0].stmt, 'targetList'))
>>> first_col_path = (columns_path
...                   / (tree[0].stmt.targetList[0], 0))
>>> first_col_path
ROOT → 0 → stmt → targetList → 0
>>> first_col_path[0]
<ResTarget val=<A_Const val=<Integer val=1>>>
>>> first_col_path[1] is columns_path[0]
True

As said, the node is not always a ast.Node, but may be a tuple, possibly containing subtuples, for example the functions slot of RangeFunction that is a tuple of tuples, each containing a FuncCall and possibly other values:

>>> tree = parse_sql('SELECT * FROM ROWS'
...                  ' FROM (generate_series(10,11),'
...                  '       get_users())')
>>> class VerboseVisitor(Visitor):
...   all_ancestors = []
...   def visit(self, ancestors, node):
...     print(f'{len(self.all_ancestors):2d}.',
...           "node:", type(node).__name__,
...           "ancestor:", type(ancestors.node).__name__)
...     self.all_ancestors.append(ancestors)
>>> VerboseVisitor()(tree)
 0. node: RawStmt ancestor: tuple
 1. node: SelectStmt ancestor: RawStmt
 2. node: ResTarget ancestor: tuple
 3. node: RangeFunction ancestor: tuple
 4. node: ColumnRef ancestor: ResTarget
 5. node: A_Star ancestor: tuple
 6. node: FuncCall ancestor: tuple
 7. node: FuncCall ancestor: tuple
 8. node: String ancestor: tuple
 9. node: A_Const ancestor: tuple
10. node: A_Const ancestor: tuple
11. node: String ancestor: tuple
12. node: Integer ancestor: A_Const
13. node: Integer ancestor: A_Const
...

To find the closest ancestor that is actually pointing to an AST node you may use the abs() function:

>>> range_function = tree[0].stmt.fromClause[0]
>>> gen_series_funccall = range_function.functions[0][0]
>>> gen_series_funccall
<FuncCall funcname=(<String val='generate_series'>,) ...>
>>> generate_series_ancestry = VerboseVisitor.all_ancestors[6]
>>> generate_series_ancestry@tree is gen_series_funccall
True
>>> abs(generate_series_ancestry).node is range_function
True

As an aid to visitors that apply changes to the AST, there are two methods, update() and apply(), that takes care of the different cases, when node is an AST instance or instead it’s a tuple (or subtuple); the former does not directly change the AST tree, but postpones that when the latter is called.

apply()

Apply the pending change, if any, to the actual node.

find_nearest(cls)

Find the nearest ancestor with a node of the given cls.

update(new_value)

Set new_value as a pending change to the tracked node.

class pglast.visitors.Continue

Marker used to tell the iterator to keep going.

class pglast.visitors.Delete

Marker used to tell the iterator to delete current node.

class pglast.visitors.ReferencedRelations(cte_names=None, skip_with_clause=None)

Concrete implementation of the referenced_relations() function.

Parameters
  • cte_names (set) – the set of surrounding CTE names

  • skip_with_clause (WithClause) – skip this clause, when specified

Calling an instance of this class will return a set of the names of the relations referenced by the given node.

visit_RangeVar(ancestors, node)

Collect relation names, taking into account defined CTE names

class pglast.visitors.Skip

Marker used to tell the iterator to not descend into the current node.

class pglast.visitors.Visitor

Base class implementing the visitor pattern.

To use it, you shall write a subclass that implements a set of particular named methods, specifically visit_XYZ where XYZ is the name of a class name defined in the pglast.ast module.

Instances of this class are callables and accept either a ast.Node instance or a sequence of instances, typically the result of parse_sql. The argument will be traversed in a breadth first order and each Node instance will be passed to the corresponding visit_XYZ method if it is implemented, falling back to the default visit method. If none of them are defined, the node will be ignored.

The visit_XYZ methods receive two arguments: the ancestry chain of the node, an instance of Ancestor and the Node instance itself. The methods may return either None, an action or a new node that will replace the original one.

iterate(node)

Iterate thru node’s AST using a breadth-first traversing.

Parameters

node – either a ast.Node instance or a tuple of those

This is a generator, that yields Node instances together with their ancestors chain as it finds them while traversing the tree.

visit = None

The default visit method for any node without a specific one. When None, nothing happens.

pglast.visitors.referenced_relations(stmt)

Return the set of relation names referenced in the given stmt.

Parameters

stmt – either a string containing the SQL statement or a ast.Node instance

Returns

a set of strings, the names of the relations

Example:

>>> referenced_relations('WITH q1(x,y) AS (SELECT 1,2)'
...                      ' SELECT * FROM q1, q2')
{'q2'}

Indices and tables