pglast¶
PostgreSQL Languages AST and statements prettifier¶
- author
Lele Gaifax
- contact
- license
- version
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:
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 SQL
s, 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:
it is much less boring to code, because there’s no need to write one Python class for each PostgreSQL node tag
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.
Changes¶
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)
Fix
AlterSubscriptionStmt
printer, handling “SET PUBLICATION” without options
Update libpg_query to 13-2.2.0
Harden the way
Visitor
handle modifications to the AST (issue #107)
Update libpg_query to 13-2.1.2
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 versionImprove
WithClause
printer indentationFix minor whitespace related issues in a few printer functions
Fix the
Visitor
class, it was ignoring nodes nested in sub-listsReduce the size of the generated parser by factoring out common code into helper functions
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)
Update libpg_query to 13-2.1.0
Use latest libpg_query, to fix an error parsing
PLpgSQL
statements (issue #88)
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.2Update libpg_query to 13-2.0.7
New option
--remove-pg_catalog-from-functions
on the command line tool (PR #90), thanks to Boris ZentnerImplement more special functions (PR #92), thanks to Boris Zentner
Fix another packaging issue, that prevented recompilation from the sdist
.tar.gz
(issue #86), thanks to Christopher Brichford
Update libpg_query to 13-2.0.6
Effectively include libpg_query’s vendored sources (issue #82)
Fix glitch in the
RawStream
, avoiding spurious space after an open parenthesisImprove the
Visitor
class, to make it easier altering the original treeProperly handle nested lists in the serialization of AST Node
Fix bug in
CreateStmt
printer (issue #79)Make it possible to pass also concrete
ast.Node
s toRawStream`
To reduce confusion, the
printer
module has been removed: print-specific stuff is now directly exposed by theprinters
subpackage while serialization classes are now in the newstream
moduleThe default value for the
safety_belt
option of theprintify()
function is nowFalse
Fix
AT_SetIdentity
,AT_EnableReplicaTrig
andAlterSubscriptionStmt
printersImprove
AlterTSConfigType
andIntoClause
printersNew generic “visitor pattern” (issue #51) exemplified by a new
referenced_relations()
function (issue #66)Refine printing of SQL comments
Implement
AlterExtensionStmt
printer
Expose the new
pg_query_scan()
function asparser.scan()
Expose the
pg_query_parse()
function asparser.parse_sql_json()
Expose the new
pg_query_parse_protobuf()
function asparser.parse_sql_protobuf()
Expose the new
pg_query_deparse_protobuf()
function asparser.deparse_protobuf()
Honor the
catalogname
of aRangeVar
if present (issue #71)Cover almost all
SQL
statements, testing against the wholePostgreSQL
regression suite (issue #68, PR #72 and PR #77), thanks to Ronan Dunklau and Hong ChengNew rudimentary support for the preserve comments feature (issue #23)
Target PostgreSQL 13
The
pglast.parser
module exposes alllibpg_query
entry points, even the newpg_query_deparse_protobuf()
function that is basically equivalent toRawStream
-based printerThe
split()
function is now based on the lower levelpg_query_split_with_xxx()
functionsThe
parse_sql()
function returns native Python objects, not aJSON
string as before: all PG nodes are now represented by subclasses ofpglast.ast.Node
, without exception, evenExpr
andValue
are there. The latter impacts onpglast.node.Scalar
: for example it now may contains aast.Integer
instance instead of a Pythonint
The
pgpp --parse-tree
output is a pprint represention of theAST
, not aJSON
string as beforeThe
ParseError
exception does not expose thelocation
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 theUTF-8
representation passed to the underlying C function
Handle
INCLUDE
clause inIndexStmt
(PR #67), thanks to Ronan Dunklau
Merge new
fingerprint
functionality fromv1
(i.e.master
) branch
Require Python 3.6 or greater
Handle
ALTER TYPE .. RENAME VALUE
inAlterEnumStmt
(PR #52), thanks to Ronan DunklauAdd 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 DunklauHandle
SET LOGGED
andSET UNLOGGED
inALTER TABLE
(PR #59), thanks to Ronan DunklauHandle
ALTER TYPE ... RENAME
(PR #62), , thanks to Ronan Dunklau
Fix exclusion constraint printer (issue #81)
Fix the generic case in the
RenameStmt
printer
Promote to the stable state
Move the job of building and uploading binary wheels from TravisCI to GitHub Actions
Fix
IF EXISTS
variant ofRenameStmt
printer (PR #70), thanks to Jonathan MortensenUpdate libpg_query to 10-1.0.5
Produce Python 3.9 wheels, thanks to
cibuildwheel
1.6.3Expose the
libpg_query
’s fingerprint functionality (PR #64), thanks to Yiming Wang
Handle
SELECT FROM foo
Fix collation name printer (PR #44), thanks to Ronan Dunklau
Implement
CreatePLangStmt
printer (PR #42), thanks to Bennie SwartFix privileges printer (PR #41), thanks to Bennie Swart
Handle
TRUNCATE
event inCreateTrigStmt
printer (PR #40), thanks to Bennie SwartFix function body dollar quoting (PR #39), thanks to Bennie Swart
Prettier
INSERT
representation
Prettier
CASE
representationNew option to emit a semicolon after the last statement (issue #24)
Implement
NotifyStmt
printerImplement
RuleStmt
printer, thanks to Gavin M. Roy for his PR #28Fix
RenameStmt
, properly handling object nameProduce Python 3.8 wheels, thanks to cibuildwheel 1.0.0
Support
ALTER TABLE RENAME CONSTRAINT
(PR #35), thanks to Ronan Dunklau
No visible changes, but now PyPI carries binary wheels for Python 3.7.
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.
Update libpg_query to 10-1.0.2
Support the ‘?’-style parameter placeholder variant allowed by libpg_query (details)
Prettier JOINs representation, aligning them with the starting relation
Fix cosmetic issue with ANY() and ALL()
Fix issue in the safety belt check performed by
pgpp
(issue #4)
Implement
Null
printer
Implement some other DDL statements printers
New alternative style to print comma-separated-values lists, activated by a new
--comma-at-eoln
option onpgpp
Implement
TransactionStmt
and almost allDROP xxx
printers
Implement
NamedArgExpr
printerNew alternative printers for a set of special functions, activated by a new
--special-functions
option onpgpp
(issue #2)
Handle special de-reference (
A_Indirection
) cases
Fix serialization of column labels containing double quotes
Fix corner issues surfaced implementing some more DDL statement printers
Fix endless loop due to sloppy conversion of command line option
Install the command line tool as
pgpp
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 typeInitial support for DDL statements
Fix representation of string literals containing single quotes
Update libpg_query to 10-1.0.0
Fix indentation of boolean expressions in SELECT’s targets (issue #3)
Update to latest libpg_query’s 10-latest branch, targeting PostgreSQL 10.0 final
Fix representation of subselects requiring surrounding parens
New option
--version
on the command line toolBetter enums documentation
Release the GIL while calling libpg_query functions
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
Support Python 3.4 and Python 3.5 as well as Python 3.6
Fix spacing before the $ character
Handle type modifiers
New option
--plpgsql
on the command line tool, just for fun
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)
Fix sdist including the Sphinx documentation
New option
--parse-tree
on the command line tool to show just the parse treeSphinx documentation, available online
Handle some more cases when a name must be double-quoted
Complete the serialization of the WindowDef node, handling its frame options
Expose the actual PostgreSQL version the underlying libpg_query libray is built on thru a new
get_postgresql_version()
functionNew option safety_belt for the
prettify()
function, to protect the innocentsHandle serialization of
CoalesceExpr
andMinMaxExpr
Handle serialization of
ParamRef
nodesExpose a
prettify()
helper function
Test coverage at 99%
First attempt at automatic wheel upload to PyPI, let’s see…
First release (“Hi daddy!”, as my soul would tag it)
Examples of usage¶
Here are some example of how the module can be used.
Low 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 repr
esentation 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,
'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,
'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,
'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
Medium level¶
Parse an SQL
statement and get its AST root node¶
>>> from pglast import Node
>>> root = Node(parse_sql('SELECT foo FROM bar'))
>>> print(root)
None=[1*{RawStmt}]
Get a particular node¶
>>> from_clause = root[0].stmt.fromClause
>>> print(from_clause)
fromClause=[1*{RangeVar}]
Obtain some information about a node¶
>>> range_var = from_clause[0]
>>> print(range_var.node_tag)
RangeVar
>>> print(range_var.attribute_names)
('catalogname', 'schemaname', 'relname', 'inh', 'relpersistence', 'alias', 'location')
>>> print(range_var.parent_node)
stmt={SelectStmt}
Iterate over nodes¶
>>> for a in from_clause:
... print(a)
... for b in a:
... print(b)
...
fromClause[0]={RangeVar}
inh=<True>
location=<16>
relname=<'bar'>
relpersistence=<'p'>
Recursively traverse
the parse tree¶
>>> for node in root.traverse():
... print(node)
...
None[0]={RawStmt}
stmt={SelectStmt}
all=<False>
fromClause[0]={RangeVar}
inh=<True>
location=<16>
relname=<'bar'>
relpersistence=<'p'>
limitOption=<LimitOption.LIMIT_OPTION_DEFAULT: 0>
op=<SetOperation.SETOP_NONE: 0>
targetList[0]={ResTarget}
location=<7>
val={ColumnRef}
fields[0]={String}
val=<'foo'>
location=<7>
stmt_len=<0>
stmt_location=<0>
As you can see, the repr
esentation of each value is mnemonic: {some_tag}
means a
Node
with tag some_tag
, [X*{some_tag}]
is a List
containing X nodes of that
particular kind* and <value>
is a Scalar
.
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()(root))
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('ParamRef', override=True)
... def replace_param_ref(node, output):
... output.write(repr(args[node.number.value - 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
.
—
- *
This is an approximation, because in principle a list can contain different kinds of nodes, or even sub-lists in some cases: the
List
representation arbitrarily shows the tag of the first object.
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__ = 'v3.18'¶
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 isFalse
, 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 ofslice
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’sFetchStmt.howMany
, that uses the constantFETCH_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 byparse_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 ofpglast.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 thelibpg_query
‘sJSON
-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 thelibpg_query
‘sProtobuf
-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 thelibpg_query
‘sJSON
-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 ofslice
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
(not to be confused with pglast.node.Node
which is just a
readonly generic wrapper) 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
orint
) – if notNone
, the maximum depth to reachellipsis – the marker value that will be used to replace cut-off branch
skip_none (bool) – whether
None
-valued attributes should be elidedenum_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 andEnum
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
andstmt_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.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.
- 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
- 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)
- class pglast.ast.A_Indirection(arg=None, indirection=None)¶
Wrapper for the homonymous parser node.
- 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, 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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*¶
- 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, relkind=None, missing_ok=None)¶
Wrapper for the homonymous parser node.
- relation: RangeVar*¶
Table to work on
- cmds: tuple¶
List of subcommands
- relkind: 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.CallContext(atomic=None)¶
Wrapper for the homonymous parser node.
- atomic: bool¶
- class pglast.ast.CallStmt(funccall=None, funcexpr=None)¶
Wrapper for the homonymous parser node.
- funccall: FuncCall*¶
From the parser
- funcexpr: FuncExpr*¶
Transformed
- 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, options=None)¶
Wrapper for the homonymous parser node.
- relation: RangeVar*¶
Relation being indexed, or NULL if all
- indexname: str¶
Original index defined
- options: int¶
OR of ClusterOption flags
- 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.
- 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, 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
- 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
- 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
- comment: str¶
Comment to insert, or NULL to remove
- class pglast.ast.CommonTableExpr(ctename=None, aliascolnames=None, ctematerialized=None, ctequery=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?
- 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?
- 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
- 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
- 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
- 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)¶
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
- 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
- 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, 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
- 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 inhRelation)
- 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, relkind=None, is_select_into=None, if_not_exists=None)¶
Wrapper for the homonymous parser node.
- into: IntoClause*¶
Destination table
- relkind: 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(trigname=None, relation=None, funcname=None, args=None, row=None, timing=None, events=None, columns=None, whenClause=None, isconstraint=None, transitionRels=None, deferrable=None, initdeferred=None, constrrel=None)¶
Wrapper for the homonymous parser node.
- 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
- isconstraint: bool¶
This is a constraint trigger
- 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)
- 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¶
- 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
- 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.
- 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
- class pglast.ast.FuncCall(funcname=None, args=None, agg_order=None, agg_filter=None, agg_within_group=None, agg_star=None, agg_distinct=None, func_variadic=None, over=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_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
- over: WindowDef*¶
OVER clause, if any
- 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
- 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, 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
- 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
- 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
- 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
- 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
- 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.
- 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
- 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
- skipData: bool¶
True for WITH NO DATA
- class pglast.ast.JoinExpr(jointype=None, isNatural=None, larg=None, rarg=None, usingClause=None, quals=None, alias=None, rtindex=None)¶
Wrapper for the homonymous parser node.
- isNatural: bool¶
Natural join? Will need to shape table
- usingClause: tuple¶
USING clause, if any (list of String)
- 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.
- 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.
- 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, args_unspecified=None)¶
Wrapper for the homonymous parser node.
- objname: tuple¶
Qualified name of function/operator
- objargs: tuple¶
List of Typename nodes
- args_unspecified: bool¶
Argument list was omitted, so name must be unique (note that objargs == NIL means zero args)
- 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)
- 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)
- onConflictSet: tuple¶
List of ON CONFLICT SET TargetEntrys
- 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.Param(paramkind=None, paramid=None, paramtypmod=None, location=None)¶
Wrapper for the homonymous parser node.
- 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)¶
Wrapper for the homonymous parser node.
- name: RangeVar*¶
Name of partition to attach/detach
- bound: PartitionBoundSpec*¶
FOR VALUES, if attaching
- 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
- 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¶
- 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)
- 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, cteList=None, rtable=None, jointree=None, targetList=None, override=None, onConflict=None, returningList=None, groupClause=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.
- 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?
- 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
- hasSubLinks: bool¶
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
- 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
- groupingSets: tuple¶
A list of GroupingSet’s if present
- windowClause: tuple¶
A list of WindowClause’s
- distinctClause: tuple¶
A list of SortGroupClause’s
- sortClause: tuple¶
A list of SortGroupClause’s
- limitOption: LimitOption¶
Limit type
- rowMarks: tuple¶
A list of RowMarkClause’s
- 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?
- 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?
- 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?
- 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.
- method: tuple¶
Sampling method name (possibly qualified)
- args: tuple¶
Argument(s) for sampling method
- 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, 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.
- 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?
- 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
- 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.
- 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_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, options=None, concurrent=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
- options: int¶
Reindex options flags
- concurrent: bool¶
Reindex concurrently?
- 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
- 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
- location: int¶
Token location, or -1 if unknown
- 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
- 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
- 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, 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
- groupClause: tuple¶
GROUP BY clauses
- windowClause: tuple¶
WINDOW window_name AS (…), …
- valuesLists: tuple¶
Untransformed list of expression lists
- sortClause: tuple¶
Sort clause (a list of SortBy’s)
- 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?
- 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.
- 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.SubLink(subLinkType=None, subLinkId=None, testexpr=None, operName=None, subselect=None, location=None)¶
Wrapper for the homonymous parser node.
- subLinkType: SubLinkType¶
- subLinkId: int¶
ID (1..n); 0 if not MULTIEXPR
- operName: tuple¶
Originally specified operator name
- 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¶
- 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 container (and elements too)
- 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
- 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.
- 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)
- 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
- 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
- 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
- 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.
- relname: str¶
Name of relation that specified the WCO
- polname: str¶
Name of RLS policy being checked
- 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.
- 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
- 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.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.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.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.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.
- 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_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_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_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_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_SubLink¶
- 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_AggrefExprState¶
- T_WindowFuncExprState¶
- T_SetExprState¶
- T_SubPlanState¶
- T_AlternativeSubPlanState¶
- 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_SubqueryScanPath¶
- T_ForeignPath¶
- T_CustomPath¶
- T_NestPath¶
- T_MergePath¶
- T_HashPath¶
- T_AppendPath¶
- T_MergeAppendPath¶
- T_GroupResultPath¶
- T_MaterialPath¶
- 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_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_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_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_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_OF¶
- AEXPR_IN¶
- AEXPR_LIKE¶
- AEXPR_ILIKE¶
- AEXPR_SIMILAR¶
- AEXPR_BETWEEN¶
- AEXPR_NOT_BETWEEN¶
- AEXPR_BETWEEN_SYM¶
- AEXPR_NOT_BETWEEN_SYM¶
- AEXPR_PAREN¶
- class pglast.enums.parsenodes.AlterSubscriptionType¶
Corresponds to the AlterSubscriptionType enum.
- ALTER_SUBSCRIPTION_OPTIONS¶
- ALTER_SUBSCRIPTION_CONNECTION¶
- ALTER_SUBSCRIPTION_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_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_AddIdentity¶
- AT_SetIdentity¶
- AT_DropIdentity¶
- class pglast.enums.parsenodes.CTEMaterialize¶
Corresponds to the CTEMaterialize enum.
- CTEMaterializeDefault¶
- CTEMaterializeAlways¶
- CTEMaterializeNever¶
- class pglast.enums.parsenodes.ClusterOption¶
Corresponds to the ClusterOption enum.
- CLUOPT_RECHECK¶
- CLUOPT_VERBOSE¶
- 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¶
- 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_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.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_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_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.parsenodes.REINDEXOPT_VERBOSE¶
See here for details.
- pglast.enums.parsenodes.REINDEXOPT_REPORT_PROGRESS¶
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_EXPLICIT¶
- class pglast.enums.primnodes.CoercionForm¶
Corresponds to the CoercionForm enum.
- COERCE_EXPLICIT_CALL¶
- COERCE_EXPLICIT_CAST¶
- COERCE_IMPLICIT_CAST¶
- 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_SUBLINK¶
- 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.
- EXISTS_SUBLINK¶
- ALL_SUBLINK¶
- ANY_SUBLINK¶
- ROWCOMPARE_SUBLINK¶
- EXPR_SUBLINK¶
- MULTIEXPR_SUBLINK¶
- ARRAY_SUBLINK¶
- CTE_SUBLINK¶
- 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.
From include/storage
¶
pglast.enums.lockdefs
— Constants extracted from lockdefs.h¶
- pglast.enums.lockdefs.NoLock¶
See here for details.
See here for details.
See here for details.
- pglast.enums.lockdefs.RowExclusiveLock¶
See here for details.
See here for details.
See here for details.
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¶
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.node
— The higher level interface to the parse tree¶
This module implements a set of classes that make it easier to deal with the pglast.ast
nodes.
The pglast.node.Node
wraps a single pglast.ast.Node
adding a reference to the
parent node; the class:pglast.node.List wraps a sequence of them and
pglast.node.Scalar
represents plain values such a strings, integers, booleans or
none.
Every node is identified by a tag, a string label that characterizes its content, exposed as
a set of attributes as well as with a dictionary-like interface (technically
pglast.node.Node
implements both a __getattr__
method and a __getitem__
method, while underlying pglast.ast.Node
only the former). When asked for an
attribute, the node returns an instance of the base classes, i.e. another Node
, or a
List
or a Scalar
, depending on the data type of that item. When the node does not
contain the requested attribute it returns a singleton pglast.node.Missing
marker
instance.
A List
wraps a plain Python list
and may contains a sequence of Node
instances, or
in some cases other sub-lists, that can be accessed with the usual syntax, or iterated.
Finally, a Scalar
carries a single value of some scalar type, accessible through its
value
attribute.
- class pglast.node.Base(details, parent=None, name=None)¶
Common base class.
- Parameters
details – the parse tree
parent (
None
orNode
instance) –None
to indicate that the node is the root of the parse tree, otherwise it is the immediate parent of the new nodename (str or tuple) – the name of the attribute in the parent node that points to this one; it may be a tuple (name, position) when
parent[name]
is actually a list of nodes
Its main purpose is to create the right kind of instance, depending on the type of the details argument passed to the constructor: a
ast.Node
produces aNode
instance, alist
ortuple
produces aList
instance, everything else aScalar
instance.
- class pglast.node.Comment(location, text, at_start_of_line, continue_previous)¶
A structure to carry information about a single SQL comment.
- property at_start_of_line¶
Alias for field number 2
- property continue_previous¶
Alias for field number 3
- property location¶
Alias for field number 0
- property text¶
Alias for field number 1
- class pglast.node.List(details, parent=None, name=None)¶
Represent a sequence of
Node
instances.- Parameters
items (list) – a list of items, usually
Node
instancesparent (
None
orNode
instance) –None
to indicate that the node is the root of the parse tree, otherwise it is the immediate parent of the new nodename (str or tuple) – the name of the attribute in the parent node that points to this one; it may be a tuple (name, position) when
parent[name]
is actually a list of nodes
- traverse()¶
A generator that recursively traverse all the items in the list.
- pglast.node.Missing = MISSING¶
Singleton returned when trying to get a non-existing attribute out of a
Node
.
- class pglast.node.Node(details, parent=None, name=None)¶
Represent a single entry in a parse tree.
- Parameters
details (
ast.Node
) – the parse tree of the nodeparent (
None
orNode
instance) –None
to indicate that the node is the root of the parse tree, otherwise it is the immediate parent of the new nodename (str or tuple) – the name of the attribute in the parent node that points to this one; it may be a tuple (name, position) when
parent[name]
is actually a list of nodes
- property attribute_names¶
The names of the attributes present in the parse tree of the node.
- traverse()¶
A generator that recursively traverse all attributes of the node.
- class pglast.node.Scalar(details, parent=None, name=None)¶
Represent a single scalar value.
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 towrite()
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 toFalse
.
- writes(s)¶
Shortcut for
self.write(s); self.separator()
.
- class pglast.stream.RawStream(expression_level=0, 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
expression_level (int) – start the stream with the given expression level depth, 0 by default
separate_statements (int) –
1
by default, tells how many empty lines should separate statementsspecial_functions (bool) –
False
by default, whenTrue
some functions are treated in a special way and emitted as equivalent constructscomma_at_eoln (bool) –
False
by default, whenTrue
put the comma right after each item instead of at the beginning of the next item linesemicolon_after_last_statement (bool) –
False
by default, whenTrue
add a semicolon after the last statement, otherwise it is emitted only as a separator between multiple statementscomments – optional sequence of tuples with the comments extracted from the statement
remove_pg_catalog_from_functions (bool) –
False
by default, whenTrue
remove the pg_catalog schema from functions
This augments
OutputStream
and implements the basic machinery needed to serialize the parse tree produced byparse_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 theSQL
in textual form, or anode.Node
instance, or anode.List
instance containingnode.Node
instances, or a concreteast.Node
instance or a tuple of them.
- dedent()¶
Do nothing, shall be overridden by the prettifier subclass.
- expression()¶
Create a context manager that will wrap subexpressions 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 returnNone
.
- 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)¶
Execute
print_node()
on all the nodes, separating them with sep.- Parameters
nodes – a sequence of
Node
instances or a single List nodesep (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".===
)
- 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
instancessep (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()
orprint_list()
as needed.
- print_node(node, is_name=False, is_symbol=False)¶
Lookup the specific printer for the given node and execute it.
- print_symbol(nodes, sep='.')¶
Helper method, execute
print_node()
orprint_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)¶
Execute
print_node()
on all the nodes, separating them with sep.- Parameters
nodes – a sequence of
Node
instancessep (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()
anddedent()
around a block of code.This is just an helper to simplify code that adjust 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 for any given tag define how the
associated Node
will be serialized.
- pglast.printers.NODE_PRINTERS = {'AccessPriv': <function access_priv>, 'AlterCollationStmt': <function alter_collation_stmt>, 'AlterDatabaseStmt': <function alter_database_stmt>, 'AlterDatabaseSetStmt': <function alter_database_set_stmt>, 'AlterExtensionStmt': <function alter_extension_stmt>, ('AlterExtensionStmt', 'DefElem'): <function alter_extension_stmt_def_elem>, 'AlterExtensionContentsStmt': <function alter_extension_contents_stmt>, 'AlterEnumStmt': <function alter_enum_stmt>, 'AlterDefaultPrivilegesStmt': <function alter_default_privileges_stmt>, 'AlterFunctionStmt': <function alter_function_stmt>, 'AlterObjectSchemaStmt': <function alter_object_schema_stmt>, 'AlterOperatorStmt': <function alter_operator_stmt>, ('AlterOperatorStmt', 'DefElem'): <function alter_operator_stmt_def_elem>, 'AlterOpFamilyStmt': <function alter_op_family_stmt>, 'AlterOwnerStmt': <function alter_owner_stmt>, 'AlterPolicyStmt': <function alter_policy_stmt>, 'AlterRoleStmt': <function alter_role_stmt>, 'AlterSeqStmt': <function alter_seq_stmt>, 'AlterTableStmt': <function alter_table_stmt>, ('AlterTableStmt', 'RangeVar'): <function range_var>, 'AlterTableCmd': <function alter_table_cmd>, ('IntoClause', 'DefElem'): <function alter_table_cmd_def_elem>, ('IndexStmt', 'DefElem'): <function alter_table_cmd_def_elem>, ('CreateStmt', 'DefElem'): <function alter_table_cmd_def_elem>, ('CreatePublicationStmt', 'DefElem'): <function alter_table_cmd_def_elem>, ('AlterTableCmd', 'DefElem'): <function alter_table_cmd_def_elem>, 'AlterTSConfigurationStmt': <function alter_ts_configuration_stmt>, 'AlterTSDictionaryStmt': <function alter_ts_dictionary_stmt>, 'AlterStatsStmt': <function alter_stats_stmt>, 'AlterSubscriptionStmt': <function alter_subscription_stmt>, 'AlterPublicationStmt': <function alter_publication_stmt>, 'AlterFdwStmt': <function alter_fdw_stmt>, ('AlterFdwStmt', 'DefElem'): <function alter_fdw_stmt_def_elem>, 'AlterForeignServerStmt': <function alter_foreign_server_stmt>, 'AlterUserMappingStmt': <function alter_user_mapping_stmt>, 'AlterRoleSetStmt': <function alter_role_set_stmt>, 'AlterDomainStmt': <function alter_domain_stmt>, 'AlterEventTrigStmt': <function alter_event_trig_stmt>, 'AlterTypeStmt': <function alter_type_stmt>, 'CheckPointStmt': <function check_point_stmt>, 'ClusterStmt': <function cluster_stmt>, 'ColumnDef': <function column_def>, 'CommentStmt': <function comment_stmt>, 'CompositeTypeStmt': <function composite_type_stmt>, ('CompositeTypeStmt', 'RangeVar'): <function composite_type_stmt_range_var>, 'Constraint': <function constraint>, 'CreateAmStmt': <function create_am_stmt>, 'CreatedbStmt': <function create_db_stmt>, ('CreatedbStmt', 'DefElem'): <function create_db_stmt_def_elem>, 'CreateCastStmt': <function create_cast_stmt>, 'CreateConversionStmt': <function create_conversion_stmt>, 'CreateDomainStmt': <function create_domain_stmt>, 'CreateEnumStmt': <function create_enum_stmt>, 'CreateEventTrigStmt': <function create_event_trig_stmt>, ('CreateEventTrigStmt', 'DefElem'): <function create_event_trig_stmt_def_elem>, 'CreateExtensionStmt': <function create_extension_stmt>, ('CreateExtensionStmt', 'DefElem'): <function create_extension_stmt_def_elem>, 'CreateFdwStmt': <function create_fdw_stmt>, ('CreateFdwStmt', 'DefElem'): <function create_fdw_stmt_def_elem>, ('CreateUserMappingStmt', 'DefElem'): <function create_fdw_stmt_def_elem>, ('ColumnDef', 'DefElem'): <function create_fdw_stmt_def_elem>, 'CreateForeignServerStmt': <function create_foreign_server_stmt>, 'CreateForeignTableStmt': <function create_foreign_table_stmt>, ('CreateForeignServerStmt', 'DefElem'): <function create_foreign_table_stmt_def_elem>, ('CreateForeignTableStmt', 'DefElem'): <function create_foreign_table_stmt_def_elem>, 'CreateFunctionStmt': <function create_function_stmt>, ('AlterFunctionStmt', 'DefElem'): <function create_function_option>, ('CreateFunctionStmt', 'DefElem'): <function create_function_option>, ('DoStmt', 'DefElem'): <function create_function_option>, 'CreateOpClassStmt': <function create_opclass_stmt>, 'CreateOpClassItem': <function create_opclass_item>, 'CreateOpFamilyStmt': <function create_op_family_stmt>, 'CreatePLangStmt': <function create_plang_stmt>, 'CreatePolicyStmt': <function create_policy_stmt>, 'CreatePublicationStmt': <function create_publication_stmt>, ('CreatePublicationStmt', 'RangeVar'): <function create_publication_stmt_range_var>, 'CreateRangeStmt': <function create_range_stmt>, 'CreateRoleStmt': <function create_role_stmt>, ('CreateRoleStmt', 'DefElem'): <function create_or_alter_role_option>, ('AlterRoleStmt', 'DefElem'): <function create_or_alter_role_option>, 'CreateSchemaStmt': <function create_schema_stmt>, 'CreateSeqStmt': <function create_seq_stmt>, ('AlterSeqStmt', 'DefElem'): <function create_seq_stmt_def_elem>, ('CreateSeqStmt', 'DefElem'): <function create_seq_stmt_def_elem>, ('Constraint', 'DefElem'): <function create_seq_stmt_def_elem>, 'CreateStatsStmt': <function create_stats_stmt>, 'CreateStmt': <function create_stmt>, 'CreateTableAsStmt': <function create_table_as_stmt>, 'CreateTableSpaceStmt': <function create_table_space_stmt>, 'CreateTrigStmt': <function create_trig_stmt>, ('CreateSubscriptionStmt', 'DefElem'): <function create_subscription_stmt_stmt_def_elem>, ('AlterSubscriptionStmt', 'DefElem'): <function create_subscription_stmt_stmt_def_elem>, 'CreateSubscriptionStmt': <function create_subscription_stmt>, 'CurrentOfExpr': <function current_of_expr>, 'CreateTransformStmt': <function create_transform_stmt>, 'ClosePortalStmt': <function close_portal_stmt>, 'CreateUserMappingStmt': <function create_user_mapping_stmt>, 'DeallocateStmt': <function deallocate_stmt>, 'DefineStmt': <function define_stmt>, 'DefElem': <function def_elem>, ('DefineStmt', 'DefElem'): <function define_stmt_def_elem>, 'DiscardStmt': <function discard_stmt>, 'DoStmt': <function do_stmt>, 'DropdbStmt': <function drop_db_stmt>, 'DropOwnedStmt': <function drop_owned_stmt>, 'DropRoleStmt': <function drop_role_stmt>, 'DropStmt': <function drop_stmt>, 'DropSubscriptionStmt': <function drop_subscription_stmt>, 'DropTableSpaceStmt': <function drop_table_space_stmt>, 'DropUserMappingStmt': <function drop_user_mapping_stmt>, 'FunctionParameter': <function function_parameter>, 'GrantStmt': <function grant_stmt>, 'GrantRoleStmt': <function grant_role_stmt>, 'ImportForeignSchemaStmt': <function import_foreign_schema_stmt>, 'IndexStmt': <function index_stmt>, 'LockStmt': <function lock_stmt>, 'NotifyStmt': <function notify_stmt>, 'ObjectWithArgs': <function object_with_args>, ('AlterObjectSchemaStmt', 'ObjectWithArgs'): <function alter_object_schema_stmt_object_with_args>, ('AlterOperatorStmt', 'ObjectWithArgs'): <function alter_operator_stmt_object_with_args>, ('AlterOwnerStmt', 'ObjectWithArgs'): <function alter_owner_stmt_object_with_args>, ('CommentStmt', 'ObjectWithArgs'): <function comment_stmt_object_with_args>, ('DropStmt', 'ObjectWithArgs'): <function drop_stmt_object_with_args>, 'PartitionBoundSpec': <function partition_bound_spec>, 'PartitionCmd': <function partition_cmd>, 'PartitionElem': <function partition_elem>, 'PartitionRangeDatum': <function partition_range_datum>, 'PartitionSpec': <function partition_spec>, 'ReindexStmt': <function reindex_stmt>, 'RenameStmt': <function rename_stmt>, ('RenameStmt', 'RangeVar'): <function rename_stmt_range_var>, 'ReplicaIdentityStmt': <function replica_identity_stmt>, 'RoleSpec': <function role_spec>, 'RuleStmt': <function rule_stmt_printer>, 'RefreshMatViewStmt': <function refresh_mat_view_stmt>, 'ReassignOwnedStmt': <function reassign_owned_stmt>, 'SecLabelStmt': <function sec_label_stmt>, 'TableLikeClause': <function table_like_clause>, 'TriggerTransition': <function trigger_transition>, 'VacuumStmt': <function vacuum_stmt>, ('VacuumStmt', 'DefElem'): <function vacuum_stmt_def_elem>, 'VacuumRelation': <function vacuum_relation>, 'VariableShowStmt': <function variable_show_statement>, 'ViewStmt': <function view_stmt>, ('ViewStmt', 'DefElem'): <function view_stmt_def_elem>, 'A_ArrayExpr': <function a_array_expr>, 'A_Const': <function a_const>, 'A_Expr': <function a_expr>, 'A_Indices': <function a_indices>, 'A_Indirection': <function a_indirection>, ('A_Indirection', 'A_Star'): <function a_indirection_a_star>, ('A_Indirection', 'ColumnRef'): <function a_indirection_column_ref>, ('A_Indirection', 'FuncCall'): <function a_indirection_func_call>, ('A_Indirection', 'String'): <function a_indirection_field>, 'A_Star': <function a_star>, 'Alias': <function alias>, 'BitString': <function bitstring>, 'BoolExpr': <function bool_expr>, 'BooleanTest': <function boolean_test>, 'CallStmt': <function call_stmt>, 'CaseExpr': <function case_expr>, 'CaseWhen': <function case_when>, 'CoalesceExpr': <function coalesce_expr>, 'CollateClause': <function collate_clause>, 'ColumnRef': <function column_ref>, 'CommonTableExpr': <function common_table_expr>, 'ConstraintsSetStmt': <function constraints_set_stmt>, 'CopyStmt': <function copy_stmt>, ('CopyStmt', 'DefElem'): <function copy_stmt_def_elem>, 'DeclareCursorStmt': <function declare_cursor_stmt>, 'DeleteStmt': <function delete_stmt>, 'ExecuteStmt': <function execute_stmt>, 'ExplainStmt': <function explain_stmt>, ('ExplainStmt', 'DefElem'): <function explain_stmt_def_elem>, 'FetchStmt': <function fetch_stmt>, 'Float': <function float>, 'FuncCall': <function func_call>, ('FuncCall', 'WindowDef'): <function func_call_window_def>, 'GroupingSet': <function grouping_set>, 'GroupingFunc': <function grouping_func>, 'IndexElem': <function index_elem>, 'InferClause': <function infer_clause>, 'Integer': <function integer>, 'InsertStmt': <function insert_stmt>, 'IntoClause': <function into_clause>, 'JoinExpr': <function join_expr>, 'LockingClause': <function locking_clause>, 'ListenStmt': <function listen_stmt>, 'MinMaxExpr': <function min_max_expr>, 'MultiAssignRef': <function multi_assign_ref>, 'NamedArgExpr': <function named_arg_expr>, 'Null': <function null>, 'NullTest': <function null_test>, 'ParamRef': <function param_ref>, 'PrepareStmt': <function prepare_stmt>, 'OnConflictClause': <function on_conflict_clause>, 'RangeFunction': <function range_function>, 'RangeSubselect': <function range_subselect>, 'RangeTableFunc': <function range_table_func>, ('RangeTableFunc', 'ResTarget'): <function range_table_func_res_target>, 'RangeTableFuncCol': <function range_table_func_col>, 'RangeVar': <function range_var>, 'RangeTableSample': <function range_table_sample>, 'RawStmt': <function raw_stmt>, 'ResTarget': <function res_target>, 'RowExpr': <function row_expr>, 'SelectStmt': <function select_stmt>, 'SetToDefault': <function set_to_default>, 'SortBy': <function sort_by>, 'SQLValueFunction': <function sql_value_function>, 'String': <function string>, 'SubLink': <function sub_link>, 'TransactionStmt': <function transaction_stmt>, ('TransactionStmt', 'DefElem'): <function transaction_stmt_def_elem>, 'TruncateStmt': <function truncate_stmt>, 'TypeCast': <function type_cast>, 'TypeName': <function type_name>, 'UpdateStmt': <function update_stmt>, 'UnlistenStmt': <function unlisten_stmt>, 'VariableSetStmt': <function variable_set_stmt>, 'WithClause': <function with_clause>, 'WindowDef': <function window_def>, ('OnConflictClause', 'ResTarget'): <function update_stmt_res_target>, ('UpdateStmt', 'ResTarget'): <function update_stmt_res_target>, 'XmlExpr': <function xml_expr>, 'XmlSerialize': <function xml_serialize>}¶
Registry of specialized printers, keyed by their tag.
- pglast.printers.SPECIAL_FUNCTIONS = {'pg_catalog.btrim': <function btrim>, 'pg_catalog.date_part': <function date_part>, '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_tag(parent_node_tag, node_tag)¶
Get specific printer implementation for given node_tag.
If there is a more specific printer for it, when it’s inside a particular parent_node_tag, return that instead.
- pglast.printers.node_printer(*node_tags, override=False, check_tags=True)¶
Decorator to register a specific printer implementation for given node_tag.
- Parameters
*node_tags – one or two node tags
override (bool) – when
True
the function will be registered even if already present in theNODE_PRINTERS
registrycheck_tags (bool) – by default each node_tags is checked for validity, that is must be a valid class implemented by
pglast.ast
; passFalse
to disable the check
When node_tags 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 tags, and the function will be registered under the key(parent_tag, tag)
.
- 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 theSPECIAL_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, 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 CreatePublicationStmt, 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 CreateStmt, 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 IndexStmt, 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 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, 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 CreateUserMappingStmt, 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 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, 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 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, 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 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, 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 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 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, 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 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.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.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.sec_label_stmt(node, output)¶
Pretty print a node of type SecLabelStmt 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_show_statement(node, output)¶
Pretty print a node of type VariableShowStmt 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_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.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.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.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_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.sql_value_function(node, output)¶
Pretty print a node of type SQLValueFunction to the output stream.
- pglast.printers.dml.sub_link(node, output)¶
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.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.variable_set_stmt(node, output)¶
Pretty print a node of type VariableSetStmt 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 ')
astrim(BOTH FROM ' abc ')
andpg_catalog.btrim('xxabcxx', 'x')
astrim(BOTH 'x' FROM 'xxabcxx')
.
- pglast.printers.sfuncs.date_part(node, output)¶
Emit function
pg_catalog.date_part(field, timestamp)
asEXTRACT(field FROM timestamp).
.
- pglast.printers.sfuncs.ltrim(node, output)¶
Emit function
pg_catalog.ltrim(' abc ')
astrim(LEADING FROM ' abc ')
andpg_catalog.ltrim('xxabcxx', 'x')
astrim(LEADING 'x' FROM 'xxabcxx').
- pglast.printers.sfuncs.normalize(node, output)¶
Emit function
pg_catalog.normalize(a)
asnormalize(x)
and functionpg_catalog.normalize('a','b')
asnormalize('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)
asoverlay('Txxxxas' PLACING 'hom' FROM 2 FOR 4)
.”
- pglast.printers.sfuncs.pg_collation_for(node, output)¶
Emit function
pg_catalog.pg_collation_for(x)
asCOLLATION FOR (x)
.
- pglast.printers.sfuncs.position(node, output)¶
Emit function
pg_catalog.position('abcd', 'a')
asposition('a' IN 'abcd')
.
- pglast.printers.sfuncs.rtrim(node, output)¶
Emit function
pg_catalog.rtrim(' abc ')
astrim(TRAILING FROM ' abc ')
andpg_catalog.rtrim('xxabcxx', 'x')
astrim(TRAILING 'x' FROM 'xxabcxx')
- pglast.printers.sfuncs.substring(node, output)¶
Emit function
pg_catalog.substring('Txxxxas', 2, 4)
assubstring('Txxxxas' FROM 2 FOR 4)
andpg_catalog.substring('blabla', 2)
assubstring('blabla' FROM 2)
.
- pglast.printers.sfuncs.timezone(node, output)¶
Emit function
pg_catalog.timezone(tz, timestamp)
astimestamp AT TIME ZONE tz
.
- pglast.printers.sfuncs.xmlexists(node, output)¶
Emit function
pg_catalog.xmlexists(x, y)
asxmlexists(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 anNode
instance.Iteration yields the sequence of involved members, that is the path starting from the root of the AST tree that leads to leaf node.
Accessing an instance with a positive index returns the nth node up in the hierarchy.
When applied (using the
@
operator) to anast.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 thefunctions
slot ofRangeFunction
:>>> tree = parse_sql('SELECT * FROM ROWS' ... ' FROM(generate_series(10,11), get_users())') >>> root = Ancestor() >>> from_clause_path = (root / (tree, 0) / (tree[0], 'stmt') ... / (tree[0].stmt, 'fromClause')) >>> from_clause = tree[0].stmt.fromClause >>> from_clause_path@tree is from_clause True >>> range_function_path = (from_clause_path ... / (from_clause, 0)) >>> range_function = from_clause[0] >>> functions_path = (range_function_path ... / (range_function, 'functions')) >>> functions = from_clause[0].functions >>> functions_path@tree is functions True >>> generate_series_path = (functions_path ... / (functions, 0)) >>> generate_series_path@tree is functions[0] True >>> type(generate_series_path.node) <class 'tuple'> >>> type(generate_series_path.member) <class 'int'> >>> type(generate_series_path.node[0]) <class 'tuple'> >>> generate_series_path.node[0][0] <FuncCall funcname=(<String val='generate_series'>,)...
As an aid to visitors that apply changes to the AST, there are two methods,
update()
andapply()
, 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
whereXYZ
is the name of a class name defined in thepglast.ast
module.Instances of this class are callables and accept either a
ast.Node
instance or a sequence of instances, typically the result ofparse_sql
. The argument will be traversed in a breadth first order and eachNode
instance will be passed to the correspondingvisit_XYZ
method if it is implemented, falling back to the defaultvisit
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 ofAncestor
and theNode
instance itself. The methods may return eitherNone
, 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 aast.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'}