PostgreSQL Languages AST and statements prettifier

7.13 · active · verified Sat Apr 11

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 a set of interconnected nodes, usually called an abstract syntax tree. It provides functionalities for parsing SQL, generating ASTs, and prettifying SQL statements. The library is actively maintained with frequent releases, currently at version 7.13, and targets PostgreSQL 17.

Warnings

Install

Imports

Quickstart

Parses an SQL statement into an Abstract Syntax Tree (AST) and then demonstrates how to traverse the AST for basic inspection, followed by prettifying the original SQL statement.

from pglast import parse_sql, prettify
from pglast.ast import SelectStmt, A_Const, Integer

sql_statement = "SELECT 1 + 2 AS sum_result, 'hello' WHERE a = B;"
ast_tree = parse_sql(sql_statement)

# The root of the AST is a tuple of RawStmt objects
root_stmt = ast_tree[0].stmt

# Example of inspecting the AST
if isinstance(root_stmt, SelectStmt):
    print(f"Parsed a SelectStmt.")
    for target in root_stmt.targetList:
        print(f"  Target: {target.name or ''} value type: {type(target.val)}")
        if isinstance(target.val, A_Const) and isinstance(target.val.val, Integer):
            print(f"    Integer constant: {target.val.val.val}")

# Prettify the SQL statement
pretty_sql = prettify(sql_statement)
print("\nOriginal SQL:")
print(sql_statement)
print("\nPrettified SQL:")
print(pretty_sql)

view raw JSON →