To inspect or transform the AST, subclass pglast.visitors.Visitor and implement the visit method or specific visit_<NodeName> methods.
- Inspection: Use
visit to perform actions on every node (e.g., counting node types). - Transformation/Deletion: Returning the
pglast.visitors.Delete object from a visit method will remove that node (and its subtree) from the AST during the visitor pass.
Example of deleting a specific constraint type:
from pglast import parse_sql, enums
from pglast.visitors import Visitor, 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)')
modified_raw = DropNullConstraint()(raw)