### Install pglast from local clone Source: https://github.com/lelit/pglast/blob/v7/docs/installation.md After cloning the repository, use this command to install pglast from the local directory. ```bash pip install ./pglast ``` -------------------------------- ### Install pglast with pip Source: https://github.com/lelit/pglast/blob/v7/docs/installation.md Use this command to install the pglast library directly from PyPI. ```bash pip install pglast ``` -------------------------------- ### Clone pglast repository Source: https://github.com/lelit/pglast/blob/v7/docs/installation.md Clone the pglast repository from GitHub to install it locally. ```bash git clone https://github.com/lelit/pglast.git --recursive ``` -------------------------------- ### Transforming Multiple SQL Functions Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md This example demonstrates the default transformation of various SQL functions, including substring, regexp_split_to_array, btrim, trim, and position. ```shell $ 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') ``` -------------------------------- ### Parse SQL to Protobuf with pglast.parser.parse_sql_protobuf Source: https://github.com/lelit/pglast/blob/v7/docs/parser.md Use pglast.parser.parse_sql_protobuf to parse a SQL statement and get its Protobuf-serialized representation from libpg_query. ```python from pglast import parser query = "SELECT 1 FROM users" protobuf_tree = parser.parse_sql_protobuf(query) print(protobuf_tree) ``` -------------------------------- ### Get PostgreSQL Version with pglast.parser.get_postgresql_version Source: https://github.com/lelit/pglast/blob/v7/docs/parser.md Use pglast.parser.get_postgresql_version to retrieve the PostgreSQL version as a tuple of integers (major, minor, patch). ```python from pglast import parser version = parser.get_postgresql_version() print(version) ``` -------------------------------- ### Tokenize SQL Statement with pglast.parser.scan Source: https://github.com/lelit/pglast/blob/v7/docs/parser.md Use pglast.parser.scan to split a SQL query into its constituent tokens. Each token includes its start and end position, name, and kind. ```python from pglast import parser query = "SELECT 1 FROM users WHERE id = 10" for token in parser.scan(query): print(token) ``` -------------------------------- ### Parse SQL and Get AST Root Node Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md Use `parse_sql()` to convert an SQL string into a tuple of `RawStmt` AST nodes. The textual representation of a node shows its non-None attributes recursively. ```python from pglast import parse_sql stmt = parse_sql("select a, b, c from sometable") print(stmt) # Output: (, , ]> fromClause=[]>)> ``` ```python from pglast import ast stmt = parse_sql("select a, b, c from sometable") print(repr(stmt[0])) # Output: , , ]> fromClause=[]>> ``` -------------------------------- ### pglast.ast.CreateForeignServerStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Wrapper for the CreateForeignServerStmt parser node. Used for creating foreign servers. ```APIDOC ## pglast.ast.CreateForeignServerStmt ### Description Wrapper for the CreateForeignServerStmt parser node. ### Parameters #### servername - **str** - Server name #### servertype - **str** - #### version - **str** - #### fdwname - **str** - #### if_not_exists - **bool** - #### options - **tuple** - ``` -------------------------------- ### Create AST Nodes Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md New AST nodes can be created by instantiating the corresponding Python classes, passing recognized attributes as parameters. Alternatively, a single dictionary with a special '@' key can be used. ```python from pglast import ast new_node = ast.SelectStmt(targetList=[ast.ResTarget(name='col1')], fromClause=[ast.RangeVar(relationName='mytable')]) print(new_node) # Output: ] fromClause=[]> ``` ```python from pglast import ast new_node_from_dict = ast.SelectStmt({'@': 'SelectStmt', 'targetList': [ast.ResTarget(name='col2')], 'fromClause': [ast.RangeVar(relationName='anothertable')]}) print(new_node_from_dict) # Output: ] fromClause=[]> ``` -------------------------------- ### pglast.parser.scan Source: https://github.com/lelit/pglast/blob/v7/docs/parser.md Tokenizes a given SQL statement string and returns a sequence of token tuples, each containing start and end positions, name, and kind. ```APIDOC ## pglast.parser.scan(query) ### Description Split the given query into its tokens. Each token is a namedtuple with the following slots: start, end, name, kind. ### Parameters #### Parameters - **query** (str) - Required - The SQL statement ### Returns sequence of tuples ``` -------------------------------- ### pglast.ast.CreateTableAsStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE TABLE AS statement. It defines the query, destination table, object type, and whether it's a SELECT INTO. ```APIDOC ## pglast.ast.CreateTableAsStmt ### Description Wrapper for the homonymous parser node for CREATE TABLE AS statements. ### Parameters - **query** (Node) - The query to execute. - **into** (IntoClause) - Destination table. - **objtype** (ObjectType) - OBJECT_TABLE or OBJECT_MATVIEW. - **is_select_into** (bool) - True if written as SELECT INTO. - **if_not_exists** (bool) - If true, do nothing if the table already exists. ``` -------------------------------- ### pglast.ast.CreateStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE TABLE statement. It defines the table name, columns, inheritance, partitioning, and other properties. ```APIDOC ## pglast.ast.CreateStmt ### Description Wrapper for the homonymous parser node for creating tables. ### Parameters - **relation** (RangeVar) - Relation to create. - **tableElts** (tuple) - Column definitions (list of ColumnDef). - **inhRelations** (tuple) - Relations to inherit from (list of RangeVar). - **partbound** (PartitionBoundSpec) - FOR VALUES clause. - **partspec** (PartitionSpec) - PARTITION BY clause. - **ofTypename** (TypeName) - OF typename. - **constraints** (tuple) - Constraints (list of Constraint nodes). - **options** (tuple) - Options from WITH clause. - **oncommit** (OnCommitAction) - What to do at COMMIT. - **tablespacename** (str) - Table space to use, or NULL. - **accessMethod** (str) - Table access method. - **if_not_exists** (bool) - If true, do nothing if the table already exists. ``` -------------------------------- ### Parse SQL Statement to AST Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md Use the --parse-tree option to get the Abstract Syntax Tree (AST) representation of a SQL statement. The output is a JSON-like structure. ```shell $ pgpp --parse-tree --statement "select 1" [{'@': 'RawStmt', 'stmt': {'@': 'SelectStmt', 'all': False, 'limitOption': , 'op': , 'targetList': ({'@': 'ResTarget', 'location': 7, 'val': {'@': 'A_Const', 'location': 7, 'val': {'@': 'Integer', 'val': 1}}},)}, 'stmt_len': 0, 'stmt_location': 0}] ``` -------------------------------- ### Compact SQL Representation (CLI) Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md The `pgpp --compact` option generates a more compact SQL representation. The argument specifies the maximum line length before wrapping. ```shell $ 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') ``` ```shell $ 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') ``` -------------------------------- ### AlternativeSubPlan Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a subplan node in the AST. It contains a tuple of subplans that yield equivalent results. ```APIDOC ## AlternativeSubPlan ### Description Wrapper for the homonymous parser node. ### Attributes - **subplans** (tuple): SubPlan(s) with equivalent results ``` -------------------------------- ### pglast.ast.ViewStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE VIEW statement. It defines the view's name, query, and options. ```APIDOC ## pglast.ast.ViewStmt ### Description Wrapper for the homonymous parser node. ### Parameters - **view** (RangeVar) - The view to be created - **aliases** (tuple) - Target column names - **query** (Node) - The SELECT query (as a raw parse tree) - **replace** (bool) - Replace an existing view? - **options** (tuple) - Options from WITH clause - **withCheckOption** (ViewCheckOption) - WITH CHECK OPTION ``` -------------------------------- ### pglast.ast.CreateSubscriptionStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE SUBSCRIPTION statement. It includes the subscription name, connection info, publication, and options. ```APIDOC ## pglast.ast.CreateSubscriptionStmt ### Description Wrapper for the homonymous parser node for creating subscriptions. ### Parameters - **subname** (str) - Name of the subscription. - **conninfo** (str) - Connection string to the publisher. - **publication** (tuple) - One or more publications to subscribe to. - **options** (tuple) - List of DefElem nodes. ``` -------------------------------- ### pglast.ast.CreateUserMappingStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE USER MAPPING statement in PostgreSQL's AST. It specifies the user, server name, and options for the user mapping. ```APIDOC ## pglast.ast.CreateUserMappingStmt ### Description Wrapper for the homonymous parser node. ### Parameters - **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 ``` -------------------------------- ### pglast.ast.CreateSchemaStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE SCHEMA statement. It specifies the schema name, owner, elements, and whether to ignore if it already exists. ```APIDOC ## pglast.ast.CreateSchemaStmt ### Description Wrapper for the homonymous parser node for creating schemas. ### Parameters - **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) - If true, do nothing if the schema already exists. ``` -------------------------------- ### pglast.ast.CreatedbStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATEDB statement in PostgreSQL's AST. It includes the database name and any associated options. ```APIDOC ## pglast.ast.CreatedbStmt ### Description Wrapper for the homonymous parser node. ### Parameters - **dbname** (str) - Name of database to create - **options** (tuple) - List of DefElem nodes ``` -------------------------------- ### pglast.ast.PrepareStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a PREPARE statement in SQL, used to create a prepared statement. It includes the statement name, argument types, and the query itself. ```APIDOC ## pglast.ast.PrepareStmt ### Description Wrapper for the homonymous parser node. ### Parameters - **name** (str) - Required - Name of plan, arbitrary - **argtypes** (tuple) - Required - Types of parameters (List of TypeName) - **query** (Node) - Required - The query itself (as a raw parsetree) ``` -------------------------------- ### TableLikeOption Enum Source: https://github.com/lelit/pglast/blob/v7/docs/enums.md Options for creating a table like another, specifying which properties to include. ```APIDOC ## Enum: TableLikeOption ### Description Defines options for the `CREATE TABLE LIKE` statement, indicating which attributes of the source table should be copied to the new table. ### Values - **CREATE_TABLE_LIKE_COMMENTS**: Copy comments. - **CREATE_TABLE_LIKE_COMPRESSION**: Copy compression settings. - **CREATE_TABLE_LIKE_CONSTRAINTS**: Copy constraints. - **CREATE_TABLE_LIKE_DEFAULTS**: Copy default values. - **CREATE_TABLE_LIKE_GENERATED**: Copy generated column definitions. - **CREATE_TABLE_LIKE_IDENTITY**: Copy identity column properties. - **CREATE_TABLE_LIKE_INDEXES**: Copy indexes. - **CREATE_TABLE_LIKE_STATISTICS**: Copy statistics. - **CREATE_TABLE_LIKE_STORAGE**: Copy storage attributes. - **CREATE_TABLE_LIKE_ALL**: Copy all attributes. ``` -------------------------------- ### pglast.ast.PartitionCmd Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a command related to partitioning, such as attaching or detaching a partition. It includes the partition name, bound specification, and concurrency flag. ```APIDOC ## pglast.ast.PartitionCmd ### Description Wrapper for the homonymous parser node. ### Parameters - **name** (RangeVar*) - Required - Name of partition to attach/detach - **bound** (PartitionBoundSpec*) - Required - FOR VALUES, if attaching - **concurrent** (bool) - Required ``` -------------------------------- ### pglast.ast.VariableShowStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a SHOW statement, used to display the value of session parameters. ```APIDOC ## pglast.ast.VariableShowStmt ### Description Wrapper for the homonymous parser node. ### Parameters - **name** (str) ``` -------------------------------- ### pglast.ast.ExplainStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents an EXPLAIN statement, used to show the execution plan of a query. ```APIDOC ## pglast.ast.ExplainStmt ### Description Wrapper for the homonymous parser node. ### Parameters #### query - **query** (*pglast.ast.Node*) - The query to explain. #### options - **options** (*tuple*) - List of DefElem nodes for EXPLAIN options. ``` -------------------------------- ### pglast.ast.IndexStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents an index creation statement in SQL. ```APIDOC ## pglast.ast.IndexStmt ### Description Wrapper for the homonymous parser node. ### Attributes - **idxname**: str - Name of new index, or NULL for default. - **relation**: RangeVar* - Relation to build index on. - **accessMethod**: str - Name of access method (eg. btree). - **tableSpace**: str - Tablespace, or NULL for default. - **indexParams**: tuple - Columns to index: a list of IndexElem. - **indexIncludingParams**: tuple - Additional columns to index: a list of IndexElem. - **options**: tuple - WITH clause options: a list of DefElem. - **whereClause**: Node - Qualification (partial-index predicate). - **excludeOpNames**: tuple - Exclusion operator names, or NIL if none. - **idxcomment**: str - Comment to apply to index, or NULL. - **oldNumber**: RelFileNumber - Relfilenumber of existing storage, if any. - **oldCreateSubid**: SubTransactionId - Rd_createSubid of oldNumber. - **oldFirstRelfilelocatorSubid**: SubTransactionId - Rd_firstRelfilelocatorSubid of oldNumber. - **unique**: bool - Is index unique? - **nulls_not_distinct**: bool - Null treatment for UNIQUE constraints. - **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. ``` -------------------------------- ### pglast.ast.WindowClause Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Defines a window clause, including partitioning, ordering, and frame specifications. ```APIDOC ## pglast.ast.WindowClause ### Description Wrapper for the homonymous parser node. ### Parameters - **name** (str) - **refname** (str) - **partitionClause** (tuple) - PARTITION BY list - **orderClause** (tuple) - **frameOptions** (int) - Frame_clause options, see WindowDef - **startOffset** (Node) - Expression for starting bound, if any - **endOffset** (Node) - Expression for ending bound, if any - **inRangeAsc** (bool) - **inRangeNullsFirst** (bool) - **winref** (Index) - ID referenced by window functions - **copiedOrder** (bool) ``` -------------------------------- ### Normalized SQL Representation (CLI) Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md The `pgpp --normalize` option produces a highly compact and normalized SQL string, removing unnecessary whitespace and standardizing formatting. ```shell $ pgpp --normalize -S "select a,b,c from st where a='foo'" SELECT a, b, c FROM st WHERE a = 'foo' ``` -------------------------------- ### pglast.ast.CreateFdwStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Wrapper for the CreateFdwStmt parser node. Used for creating foreign-data wrappers. ```APIDOC ## pglast.ast.CreateFdwStmt ### Description Wrapper for the CreateFdwStmt parser node. ### Parameters #### fdwname - **str** - Foreign-data wrapper name #### func_options - **tuple** - HANDLER/VALIDATOR options #### options - **tuple** - Generic options to FDW ``` -------------------------------- ### pglast.ast.CreateRoleStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE ROLE or CREATE USER statement. It includes the statement type, role name, and associated options. ```APIDOC ## pglast.ast.CreateRoleStmt ### Description Wrapper for the homonymous parser node for creating roles, users, or groups. ### Parameters - **stmt_type** (RoleStmtType) - The type of statement (ROLE/USER/GROUP). - **role** (str) - The name of the role. - **options** (tuple) - A list of DefElem nodes representing options. ``` -------------------------------- ### Reconstruct Syntax Tree from Node Serialization Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md You can reconstruct a syntax tree from the result of calling a node (which serializes it to a dictionary). This demonstrates that the serialization and reconstruction process is consistent. ```python from pglast import ast stmt = ast.SelectStmt(targetList=[ast.ResTarget(name='col1')], fromClause=[ast.RangeVar(relationName='mytable')]) clone = ast.SelectStmt(stmt()) print(clone == stmt) # Output: True ``` -------------------------------- ### pglast.ast.SinglePartitionSpec Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a specification for a single partition. ```APIDOC ## pglast.ast.SinglePartitionSpec ### Description Wrapper for the homonymous parser node. ``` -------------------------------- ### pglast.ast.CreateTableSpaceStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE TABLESPACE statement. It specifies the tablespace name, owner, location, and options. ```APIDOC ## pglast.ast.CreateTableSpaceStmt ### Description Wrapper for the homonymous parser node for creating tablespaces. ### Parameters - **tablespacename** (str) - The name of the tablespace. - **owner** (RoleSpec) - The owner of the tablespace. - **location** (str) - The file system location for the tablespace. - **options** (tuple) - Options for the tablespace. ``` -------------------------------- ### A_Star Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a wildcard selection (e.g., `*`) in the SQL abstract syntax tree. ```APIDOC ## class pglast.ast.A_Star Wrapper for the [homonymous](https://github.com/pganalyze/libpg_query/blob/7be1aed/src/postgres/include/nodes/parsenodes.h#L445) parser node. ``` -------------------------------- ### pglast.ast.CreateSeqStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE SEQUENCE statement. It defines the sequence name, options, and identity properties. ```APIDOC ## pglast.ast.CreateSeqStmt ### Description Wrapper for the homonymous parser node for creating sequences. ### Parameters - **sequence** (RangeVar) - The sequence to create. - **options** (tuple) - Options for the sequence. - **for_identity** (bool) - Indicates if the sequence is for identity columns. - **if_not_exists** (bool) - If true, do nothing if the sequence already exists. ``` -------------------------------- ### Reformat SQL Statement (Under the Cover) Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md The `prettify()` function is a wrapper around the `IndentedStream` class, which extends `pglast.stream.RawStream` to provide aesthetic formatting for SQL statements. ```python from pglast.stream import IndentedStream from pglast import parse_sql sql = "select a,b,c from sometable" stmt = parse_sql(sql) stream = IndentedStream() stream.write(stmt) print(stream.getvalue()) # Output: # SELECT a # , b # , c # FROM sometable ``` -------------------------------- ### pglast.ast.CreateStatsStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE STATISTICS statement. It includes the statistics name, types, expressions, relations, and comment. ```APIDOC ## pglast.ast.CreateStatsStmt ### Description Wrapper for the homonymous parser node for creating statistics. ### Parameters - **defnames** (tuple) - Qualified name (list of String). - **stat_types** (tuple) - Statistics types (list of String). - **exprs** (tuple) - Expressions to build statistics on. - **relations** (tuple) - Relations to build stats on (list of RangeVar). - **stxcomment** (str) - Comment to apply to stats, or NULL. - **transformed** (bool) - True when transformStatsStmt is finished. - **if_not_exists** (bool) - If true, do nothing if the statistics name already exists. ``` -------------------------------- ### CreatePLangStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE PROCEDURAL LANGUAGE statement in the AST. ```APIDOC ## CreatePLangStmt ### Description Wrapper for the homonymous parser node. ### Parameters #### replace (bool) - Optional - T => replace if already exists #### plname (str) - Optional - PL name #### plhandler (tuple) - Optional - PL call handler function (qual. name) #### plinline (tuple) - Optional - Optional inline function (qual. name) #### plvalidator (tuple) - Optional - Optional validator function (qual. name) #### pltrusted (bool) - Optional - PL is trusted ``` -------------------------------- ### pglast.ast.CreateAmStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Wrapper for the CreateAmStmt parser node. Used for creating new access methods. ```APIDOC ## pglast.ast.CreateAmStmt ### Description Wrapper for the CreateAmStmt parser node. ### Parameters #### amname - **str** - Access method name #### handler_name - **tuple** - Handler function name #### amtype - **str** - Type of access method ``` -------------------------------- ### pglast.ast.CreateExtensionStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Wrapper for the CreateExtensionStmt parser node. Used for creating extensions. ```APIDOC ## pglast.ast.CreateExtensionStmt ### Description Wrapper for the CreateExtensionStmt parser node. ### Parameters #### extname - **str** - #### if_not_exists - **bool** - Just do nothing if it already exists? #### options - **tuple** - List of DefElem nodes ``` -------------------------------- ### CreateOpFamilyStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE OPERATOR FAMILY statement in the AST. ```APIDOC ## CreateOpFamilyStmt ### Description Wrapper for the homonymous parser node. ### Parameters #### opfamilyname (tuple) - Optional - Qualified name (list of String) #### amname (str) - Optional - Name of index AM opfamily is for ``` -------------------------------- ### CreatePolicyStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE POLICY statement in the AST. ```APIDOC ## CreatePolicyStmt ### Description Wrapper for the homonymous parser node. ### Parameters #### policy_name (str) - Optional - Policy’s name #### table (RangeVar*) - Optional - The table name the policy applies to #### cmd_name (str) - Optional - The command name the policy applies to #### permissive (bool) - Optional - Restrictive or permissive policy #### roles (tuple) - Optional - The roles associated with the policy #### qual (Node) - Optional - The policy’s condition #### with_check (Node) - Optional - The policy’s WITH CHECK condition. ``` -------------------------------- ### pglast.ast.CreateTransformStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE TRANSFORM statement. It defines the transformation language, type, and SQL functions. ```APIDOC ## pglast.ast.CreateTransformStmt ### Description Wrapper for the homonymous parser node for creating transformations. ### Parameters - **replace** (bool) - If true, replace existing transform. - **type_name** (str) - The type name for the transform. - **lang** (str) - The language of the transform. - **fromsql** (Node) - The function for FROM SQL. - **tosql** (Node) - The function for TO SQL. ``` -------------------------------- ### pglast.ast.FieldStore Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a FieldStore node, used for input tuple values and new field values. ```APIDOC ## pglast.ast.FieldStore ### Description Wrapper for the homonymous parser node. ### Parameters - **arg** (Expr*) - Input tuple value - **newvals** (tuple) - New value(s) for field(s) - **fieldnums** (tuple) - ``` -------------------------------- ### A_Const Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a constant value in the SQL abstract syntax tree. ```APIDOC ## class pglast.ast.A_Const(isnull=None, val=None) Wrapper for the [homonymous](https://github.com/pganalyze/libpg_query/blob/7be1aed/src/postgres/include/nodes/parsenodes.h#L357) parser node. ### Parameters * **isnull** (bool) * **val** (ValUnion) ``` -------------------------------- ### Deparse Protobuf to SQL with pglast.parser.deparse_protobuf Source: https://github.com/lelit/pglast/blob/v7/docs/parser.md Use pglast.parser.deparse_protobuf to convert a Protobuf-serialized parse tree back into a SQL statement. Various options are available for pretty-printing and formatting. ```python from pglast import parser query = "SELECT 1 FROM users" protobuf_tree = parser.parse_sql_protobuf(query) sql = parser.deparse_protobuf(protobuf_tree, pretty_print=True, indent_size=2) print(sql) ``` -------------------------------- ### pglast.ast.ReturnStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a return statement, wrapping the homonymous parser node. ```APIDOC ## pglast.ast.ReturnStmt ### Description Wrapper for the [homonymous](https://github.com/pganalyze/libpg_query/blob/7be1aed/src/postgres/include/nodes/parsenodes.h#L2210) parser node. ### Parameters #### returnval - Type: Node* ``` -------------------------------- ### pglast.ast.PartitionElem Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Defines an element within a partition specification, such as a column name or an expression used for partitioning. ```APIDOC ## pglast.ast.PartitionElem ### Description Wrapper for the homonymous parser node. ### Parameters - **name** (str) - Required - Name of column to partition on, or NULL - **expr** (Node) - Required - Expression to partition on, or NULL - **collation** (tuple) - Required - Name of collation; NIL = default - **opclass** (tuple) - Required - Name of desired opclass; NIL = default - **location** (ParseLoc) - Required - Token location, or -1 if unknown ``` -------------------------------- ### Parse SQL to AST with pglast.parser.parse_sql Source: https://github.com/lelit/pglast/blob/v7/docs/parser.md Use pglast.parser.parse_sql to parse a SQL statement into a tuple of RawStmt instances representing the Abstract Syntax Tree (AST). ```python from pglast import parser query = "SELECT 1 FROM users" parse_tree = parser.parse_sql(query) print(parse_tree) ``` -------------------------------- ### pglast.ast.RTEPermissionInfo Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Provides information about the permissions required for a range table entry. ```APIDOC ## pglast.ast.RTEPermissionInfo ### Description Wrapper for the homonymous parser node. ### Parameters - **inh** (*bool*): Indicates if inheritance children should be checked separately. - **requiredPerms** (*AclMode*): Bitmask of required access permissions. - **selectedCols** (*Bitmapset*): Set of columns requiring SELECT permission. - **insertedCols** (*Bitmapset*): Set of columns requiring INSERT permission. - **updatedCols** (*Bitmapset*): Set of columns requiring UPDATE permission. ``` -------------------------------- ### pglast.ast.Var Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a variable reference within a SQL query. ```APIDOC ## pglast.ast.Var ### Description Wrapper for the homonymous parser node. ### Parameters - **varno** (int) - **varattno** (AttrNumber) - **vartypmod** (int32) - **varnullingrels** (Bitmapset) - **varlevelsup** (Index) - **location** (ParseLoc) ``` -------------------------------- ### CreateOpClassItem Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents an item within an operator class definition in the AST. ```APIDOC ## CreateOpClassItem ### Description Wrapper for the homonymous parser node. ### Parameters #### itemtype (int) - Optional - See codes above #### name (ObjectWithArgs*) - Optional - Operator or function name and args #### number (int) - Optional - Strategy num or support proc num #### order_family (tuple) - Optional - Only used for ordering operators #### class_args (tuple) - Optional - Amproclefttype/amprocrighttype or amoplefttype/amoprighttype #### storedtype (TypeName*) - Optional - Datatype stored in index ``` -------------------------------- ### CreateOpClassStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE OPERATOR CLASS statement in the AST. ```APIDOC ## CreateOpClassStmt ### Description Wrapper for the homonymous parser node. ### Parameters #### opclassname (tuple) - Optional - Qualified name (list of String) #### opfamilyname (tuple) - Optional - Qualified name (ditto); NIL if omitted #### amname (str) - Optional - Name of index AM opclass is for #### datatype (TypeName*) - Optional - Datatype of indexed column #### items (tuple) - Optional - List of CreateOpClassItem nodes #### isDefault (bool) - Optional - Should be marked as default for type? ``` -------------------------------- ### pglast.ast.WindowDef Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Defines a window specification, used in window functions. It includes name, partitioning, ordering, and frame details. ```APIDOC ## pglast.ast.WindowDef ### Description Wrapper for the homonymous parser node. ### Parameters - **name** (str) - Window’s own name - **refname** (str) - Referenced window name, if any - **partitionClause** (tuple) - PARTITION BY expression list - **orderClause** (tuple) - ORDER BY (list of SortBy) - **frameOptions** (int) - Frame_clause options, see below - **startOffset** (Node) - Expression for starting bound, if any - **endOffset** (Node) - Expression for ending bound, if any - **location** (ParseLoc) - Parse location, or -1 if none/unknown ``` -------------------------------- ### pglast.ast.WithCheckOption Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a WithCheckOption node in the AST. It wraps the homonymous parser node. ```APIDOC ## pglast.ast.WithCheckOption ### Description Wrapper for the homonymous parser node. ### Parameters - **kind** (WCOKind) - Kind of WCO - **relname** (str) - Name of relation that specified the WCO - **polname** (str) - Name of RLS policy being checked - **qual** (Node) - Constraint qual to check - **cascaded** (bool) - True for a cascaded WCO on a view ``` -------------------------------- ### pglast.ast.FuncCall Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a function call in the AST. ```APIDOC ## pglast.ast.FuncCall ### Description Wrapper for the homonymous parser node. ### Parameters - **funcname** (tuple) - Qualified name of function - **args** (tuple) - The arguments (list of exprs) - **agg_order** (tuple) - ORDER BY (list of SortBy) - **agg_filter** (Node) - FILTER clause, if any - **over** (WindowDef*) - OVER clause, if any - **agg_within_group** (bool) - ORDER BY appeared in WITHIN GROUP - **agg_star** (bool) - Argument was really ‘*’ - **agg_distinct** (bool) - Arguments were labeled DISTINCT - **func_variadic** (bool) - Last argument was labeled VARIADIC - **funcformat** (CoercionForm) - How to display this node - **location** (ParseLoc) - Token location, or -1 if unknown ``` -------------------------------- ### Compare AST Nodes Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md AST nodes can be compared for equality. They are considered equal if all their attributes match, ignoring semantically irrelevant ones. ```python from pglast import parse_sql stmt1 = parse_sql("select a from t") stmt2 = parse_sql("select a from t") print(stmt1[0] == stmt2[0]) # Output: True ``` -------------------------------- ### pglast.ast.Query Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a parsed SQL query. It contains various fields detailing the command type, query structure, and associated metadata. ```APIDOC ## pglast.ast.Query ### Description Wrapper for the homonymous parser node. ### Parameters - **commandType** (*CmdType*): The type of SQL command (Select, Insert, Update, Delete, Merge, Utility). - **querySource** (*QuerySource*): Source of the query. - **canSetTag** (*bool*): Indicates if the query can set a tag. - **utilityStmt** (*Node*): Non-null if commandType is CMD_UTILITY. - **resultRelation** (*int*): The result relation index. - **hasAggs** (*bool*): True if the query contains aggregate functions. - **hasWindowFuncs** (*bool*): True if the query contains window functions. - **hasTargetSRFs** (*bool*): True if the query contains set-returning functions in the target list. - **hasSubLinks** (*bool*): True if the query contains subqueries. - **hasDistinctOn** (*bool*): True if the query uses DISTINCT ON. - **hasRecursive** (*bool*): True if the query is recursive (e.g., recursive CTE). - **hasModifyingCTE** (*bool*): True if the query contains a CTE that modifies data. - **hasForUpdate** (*bool*): True if the query uses FOR UPDATE or FOR SHARE. - **hasRowSecurity** (*bool*): True if row-level security policies are applied. - **isReturn** (*bool*): True if the query is a RETURN statement. - **cteList** (*tuple*): List of CommonTableExpr nodes (WITH clauses). - **rtable** (*tuple*): List of range table entries. - **rteperminfos** (*tuple*): Permission information for range table entries. - **jointree** (*FromExpr*): The FROM clause and WHERE clause structure. - **mergeActionList** (*tuple*): List of actions for MERGE statements. - **mergeTargetRelation** (*int*): Target relation for MERGE statements. - **mergeJoinCondition** (*Node*): Join condition for MERGE statements. - **targetList** (*tuple*): List of TargetEntry nodes representing the SELECT list items. - **override** (*OverridingKind*): Specifies how to handle overriding of default values. - **onConflict** (*OnConflictExpr*): ON CONFLICT clause details. - **returningList** (*tuple*): List of TargetEntry nodes for the RETURNING clause. - **groupClause** (*tuple*): List of SortGroupClause nodes for the GROUP BY clause. - **groupDistinct** (*bool*): True if the GROUP BY clause is DISTINCT. - **groupingSets** (*tuple*): List of GroupingSet nodes for GROUPING SETS. - **havingQual** (*Node*): The HAVING clause condition. - **windowClause** (*tuple*): List of WindowClause nodes for window functions. - **distinctClause** (*tuple*): List of SortGroupClause nodes for the DISTINCT clause. - **sortClause** (*tuple*): List of SortGroupClause nodes for the ORDER BY clause. - **limitOffset** (*Node*): Expression for the OFFSET clause. - **limitCount** (*Node*): Expression for the LIMIT clause. - **limitOption** (*LimitOption*): Type of limit (e.g., NORMAL, WITH TIES). - **rowMarks** (*tuple*): List of RowMarkClause nodes for row locking. - **setOperations** (*Node*): Structure for set operations (UNION, INTERSECT, EXCEPT). - **constraintDeps** (*tuple*): Constraint dependencies. - **withCheckOptions** (*tuple*): WITH CHECK OPTIONS clause details. - **stmt_location** (*ParseLoc*): Starting location of the statement in the source. - **stmt_len** (*ParseLoc*): Length of the statement in the source. ``` -------------------------------- ### pglast.ast.String Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a string literal value. ```APIDOC ## pglast.ast.String ### Description Wrapper for the homonymous parser node. ### Parameters - **sval** (str) ``` -------------------------------- ### pglast.ast.JsonReturning Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents the RETURNING clause for JSON functions, specifying format and type modifiers. It wraps the homonymous parser node. ```APIDOC ## pglast.ast.JsonReturning ### Description Wrapper for the homonymous parser node. ### Fields - **format** (*JsonFormat*): Output JSON format. - **typmod** (*int32*): Target type modifier. ``` -------------------------------- ### pglast.ast.DefElem Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a definition element in PostgreSQL's AST, used in various statements like CREATE/ALTER. ```APIDOC ## pglast.ast.DefElem ### Description Wrapper for the homonymous parser node. ### Parameters - **defnamespace** (str) - NULL if unqualified name - **defname** (str) - **arg** (Node) - Typically Integer, Float, String, or TypeName - **defaction** (DefElemAction) - Unspecified action, or SET/ADD/DROP - **location** (ParseLoc) - Token location, or -1 if unknown ``` -------------------------------- ### pglast.ast.CreateEnumStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Wrapper for the CreateEnumStmt parser node. Used for creating new enumerated types. ```APIDOC ## pglast.ast.CreateEnumStmt ### Description Wrapper for the CreateEnumStmt parser node. ### Parameters #### typeName - **tuple** - Qualified name (list of String) #### vals - **tuple** - Enum values (list of String) ``` -------------------------------- ### pglast.ast.CreateEventTrigStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Wrapper for the CreateEventTrigStmt parser node. Used for creating event triggers. ```APIDOC ## pglast.ast.CreateEventTrigStmt ### Description Wrapper for the CreateEventTrigStmt parser node. ### Parameters #### 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 ``` -------------------------------- ### Iterate Over Statements with Scanner (Error Tolerant) Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md Use the scanner variant of `split()` when dealing with potentially erroneous SQL statements. This approach is more lenient and avoids raising exceptions for syntax errors. ```python from pglast import split_scan sql = "select 1; select @@ syntax error; select 3;" statements = split_scan(sql) print(statements) # Output: []>>, ]>>, ]>>] ``` -------------------------------- ### CreateFunctionStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE FUNCTION statement in the AST. ```APIDOC ## CreateFunctionStmt ### Description Wrapper for the homonymous parser node. ### Parameters #### is_procedure (bool) - Optional - It’s really CREATE PROCEDURE #### replace (bool) - Optional - T => replace if already exists #### funcname (tuple) - Optional - Qualified name of function to create #### parameters (tuple) - Optional - A list of FunctionParameter #### returnType (TypeName*) - Optional - The return type #### options (tuple) - Optional - A list of DefElem #### sql_body (Node) - Optional - ``` -------------------------------- ### pglast.printers.ddl.access_priv Source: https://github.com/lelit/pglast/blob/v7/docs/ddl.md Pretty prints a node of type AccessPriv to the output stream. ```APIDOC ## pglast.printers.ddl.access_priv ### Description Pretty prints a node of type [AccessPriv](https://github.com/pganalyze/libpg_query/blob/7be1aed/src/postgres/include/nodes/parsenodes.h#L2540) to the output stream. ### Parameters - **node**: The AccessPriv node to print. - **output**: The output stream to write to. ``` -------------------------------- ### Reformat SQL Statement (Easy Way) Source: https://github.com/lelit/pglast/blob/v7/docs/usage.md The `prettify()` function reformats a given SQL statement string into a more readable format. This is a high-level convenience function. ```python from pglast import prettify sql = "select a,b,c from sometable" print(prettify(sql)) # Output: # SELECT a # , b # , c # FROM sometable ``` -------------------------------- ### CreateForeignTableStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a CREATE FOREIGN TABLE statement in the AST. ```APIDOC ## CreateForeignTableStmt ### Description Wrapper for the homonymous parser node. ### Parameters #### base (CreateStmt) - Optional - #### servername (str) - Optional - #### options (tuple) - Optional - Generic options to server ``` -------------------------------- ### pglast.ast.ObjectWithArgs Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents an object with arguments, typically a function or operator call, in the AST. It stores the object name and its arguments. ```APIDOC ## class pglast.ast.ObjectWithArgs(objname=None, objargs=None, objfuncargs=None, args_unspecified=None) Wrapper for the [homonymous](https://github.com/pganalyze/libpg_query/blob/7be1aed/src/postgres/include/nodes/parsenodes.h#L2524) parser node. ### Attributes - **objname** (tuple): The qualified name of the function or operator - **objargs** (tuple): A list of Typename nodes representing input arguments - **objfuncargs** (tuple): A list of FunctionParameter nodes - **args_unspecified** (bool): Indicates if the argument list was omitted ``` -------------------------------- ### pglast.ast.FuncExpr Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a function expression in the AST. ```APIDOC ## pglast.ast.FuncExpr ### Description Wrapper for the homonymous parser node. ### Parameters - **funcretset** (bool) - - **funcvariadic** (bool) - - **funcformat** (CoercionForm) - - **args** (tuple) - - **location** (ParseLoc) - ``` -------------------------------- ### IntoClause Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents an INTO clause in the AST, specifying the target relation and options for data insertion or table creation. ```APIDOC ## class pglast.ast.IntoClause(rel=None, colNames=None, accessMethod=None, options=None, onCommit=None, tableSpaceName=None, viewQuery=None, skipData=None) ### Description Wrapper for the homonymous parser node. ### Parameters #### rel - **rel** (RangeVar*) - Required - Target relation name #### colNames - **colNames** (tuple) - Optional - Column names to assign, or NIL #### accessMethod - **accessMethod** (str) - Optional - Table access method #### options - **options** (tuple) - Optional - Options from WITH clause #### onCommit - **onCommit** (OnCommitAction) - Optional - What do we do at COMMIT? #### tableSpaceName - **tableSpaceName** (str) - Optional - Table space to use, or NULL #### viewQuery - **viewQuery** (Node) - Optional #### skipData - **skipData** (bool) - Optional - True for WITH NO DATA ``` -------------------------------- ### pglast.ast.WindowFunc Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Represents a WindowFunc node in the AST. It wraps the homonymous parser node. ```APIDOC ## pglast.ast.WindowFunc ### Description Wrapper for the homonymous parser node. ### Parameters - **args** (tuple) - - **aggfilter** (Expr) - - **runCondition** (tuple) - - **winref** (Index) - - **winstar** (bool) - - **winagg** (bool) - - **location** (ParseLoc) - ``` -------------------------------- ### pglast.ast.CreateDomainStmt Source: https://github.com/lelit/pglast/blob/v7/docs/ast.md Wrapper for the CreateDomainStmt parser node. Used for creating new domain types. ```APIDOC ## pglast.ast.CreateDomainStmt ### Description Wrapper for the CreateDomainStmt parser node. ### Parameters #### domainname - **tuple** - Qualified name (list of String) #### typeName - **TypeName** - The base type #### collClause - **CollateClause** - Untransformed COLLATE spec, if any #### constraints - **tuple** - Constraints (list of Constraint nodes) ```