Registry / database / pglast

pglast

JSON →
library8.4pypypi✓ verified 23d ago

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.

pip install pglast
INSTALL
IMPORT
SIG · PGLAST
P
pglast
databasepythonv8.4
Install
1.9s avg
Import
140ms
Disk
39MB
Pass rate
8/ 10
Env Coverage8 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v8.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
✓ —
✓ 1.9s
py 3.11
✓ —
✓ 1.9s
py 3.12
✓ —
✓ 1.9s
py 3.13
✓ —
✓ 1.8s
py 3.9
✕ build_error
✕ build_error
39MB installed
● package 39MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

parse_sql
from pglast import parse_sql
prettify
from pglast import prettify
ast
from pglast import ast
Provides the Python classes representing PostgreSQL AST nodes (e.g., ast.SelectStmt).

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)
pgast --version
Debug
Known issues
breakingSince v3.0, `parse_sql()` returns native Python AST objects (subclasses of `pglast.ast.Node`) directly, not a JSON string. Code expecting JSON output or requiring manual JSON parsing will break.
fix
Update code to directly interact with `pglast.ast` objects. Remove any JSON parsing logic after calling `parse_sql()`.
affects: >=3.0
breakingThe `pglast.node` wrapper classes were removed in v3.0. All AST manipulation now operates directly on the `pglast.ast` classes.
fix
Replace usages of `pglast.node` wrappers with direct interaction with `pglast.ast` classes.
affects: >=3.0
breakingThe `pglast.printer` module was removed in v3.0. Print-specific functionalities are now in the `pglast.printers` subpackage, and serialization classes are in the new `pglast.stream` module.
fix
Adjust import paths and function calls to use `pglast.printers` and `pglast.stream` as appropriate.
affects: >=3.0
breakingIn v5.0, the type of `pglast.ast.Float` values changed from `Decimal` to `str`. This was to resolve issues with floating-point representation and rendering.
fix
Ensure that code handling `Float` node values expects a string and performs explicit conversion if numerical operations are required.
affects: >=5.0
breakingVersion 7.0 introduced a requirement for Python >= 3.9 and explicitly targets PostgreSQL 17. Older Python versions or applications targeting older PostgreSQL versions might encounter compatibility issues.
fix
Upgrade Python environment to 3.9 or higher. Be aware of potential syntax changes or new features in PostgreSQL 17 that might affect parsing or prettification if interacting with older database versions.
affects: >=7.0
gotchaThe `parse_plpgsql()` function has known limitations and may not fully parse complex PL/pgSQL bodies, often treating the body as a single string literal within the AST. The maintainer has noted that its support is 'still vaporware'.
fix
For complex PL/pgSQL, be aware that the internal body might not be fully parsed into a detailed AST. You might need to extract the function body as a string and process it with external tools or custom logic.
affects: All
Errors
Common errors & fixes
pglast.parser.ParseError: syntax error at or near ";", at location 14
This error occurs when the SQL statement provided to `pglast.parse_sql()` contains a syntax error according to the PostgreSQL parser.
fix
Correct the SQL query to be valid PostgreSQL syntax. For example, `parse_sql('select 1 from; select 2')` is invalid, but `parse_sql('select 1; select 2')` would be correct if using the `split` function, or `parse_sql('select 1')` for a single statement.
ImportError: dlopen(/Users/charles/Documents/.../pglast/parser.cpython-XYZ-darwin.so, 0x0002): symbol not found in flat namespace '_pg_query__keyword_kind__descriptor'
This issue typically arises on macOS (especially with Apple Silicon) when the pre-built `pglast` wheel is improperly linked against the static `libpg_query` library, resulting in missing symbols during runtime import.
fix
Try installing `pglast` from source instead of using a pre-built wheel. This can often be done by first uninstalling any existing `pglast` installation (`pip uninstall pglast`) and then reinstalling (`pip install --no-binary :all: pglast`) to force a source build, ensuring all necessary build tools (like Xcode Command Line Tools on macOS) are installed.
ImportError: cannot import name 'ast' from 'pglast' (unknown location)
This error indicates a conflict or incorrect import path for the `ast` module within `pglast`, which has been reported specifically with Python 3.9 due to a potential clash with Python's built-in `ast` module.
fix
Upgrade `pglast` to its latest version (e.g., `pip install --upgrade pglast`) which may include a fix for this import issue. If the problem persists, consider using a different compatible Python version.
make: *** [src/pg_query_json_plpgsql.o] Error 1
This is a generic compilation error indicating that the C extension (`libpg_query`) that `pglast` depends on failed to build during installation. This can be due to missing system build tools (like `make`, a C compiler), or platform-specific incompatibilities.
fix
Ensure that essential development tools are installed on your system. On Debian/Ubuntu, run `sudo apt-get install build-essential`. On macOS, install Xcode Command Line Tools using `xcode-select --install`. For Windows, ensure a C++ build environment (like MSVC from Visual Studio Build Tools) is properly configured.
Upgrade
Version history
8.4latest on PyPI · released Jul 22, 2026
Audit
Dependencies

No dependency data recorded yet.

Agent activity
5 hits · last 30 days
node
4
Resources