Registry / database / libpg-query

libpg-query

JSON →
library17.7.3jsnpmunverified

libpg-query provides Node.js and browser bindings for `libpg_query`, the real PostgreSQL C parser, compiled to WebAssembly (WASM). This library offers 100% spec-accurate parsing of SQL queries into PostgreSQL's internal Abstract Syntax Tree (AST) format, supporting PostgreSQL versions 13 through 17. Its key differentiators include being entirely cross-platform with zero native dependencies, eliminating common `node-gyp` compilation headaches. The package currently ships as version 17.7.3 and generally releases updates in alignment with new PostgreSQL major versions. It is distinct from other parsers by using the actual PostgreSQL source code, ensuring fidelity, and provides full TypeScript support for robust development.

npm install libpg-query
INSTALL
IMPORT
SIG · LIBPG-QUERY
L
libpg-query
databasejavascriptv17.7.3
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
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
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

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

parse
import { parse } from 'libpg-query';
The primary asynchronous function to parse SQL. It automatically handles WASM module initialization.
parseSync
import { parseSync } from 'libpg-query'; // ... later, after module is loaded ... const ast = parseSync(sql);
import { parseSync } from 'libpg-query'; const ast = parseSync(sql); // Fails if module not loaded
Synchronous parsing requires explicitly calling `loadModule()` once before its first use. Prefer `parse` (async) unless strict synchronous behavior is required.
loadModule
import { loadModule } from 'libpg-query'; await loadModule();
Initializes the WebAssembly module. Mandatory before using `parseSync` or other synchronous API methods. The async `parse` function calls this internally if needed.

This quickstart demonstrates both asynchronous and synchronous SQL parsing using `libpg-query`, including a PL/pgSQL function. It highlights the requirement to load the WASM module explicitly for synchronous operations and logs a partial view of the generated Abstract Syntax Tree (AST).

import { parse, parseSync, loadModule } from 'libpg-query'; async function demonstrateParsing() { const sqlQuery = ` SELECT id, name, created_at FROM users WHERE status = 'active' AND created_at > NOW() - INTERVAL '30 days' ORDER BY created_at DESC; `; // Asynchronous parsing (recommended) try { const astAsync = await parse(sqlQuery); console.log('--- Async Parse Result (partial) ---'); console.log(JSON.stringify(astAsync[0]?.stmt, null, 2)); } catch (error) { console.error('Async parsing error:', error); } // Synchronous parsing (requires explicit module loading) try { await loadModule(); // Initialize the WASM module once const plpgsqlQuery = ` CREATE FUNCTION get_user_count() RETURNS integer LANGUAGE plpgsql AS $$ DECLARE user_count integer; BEGIN SELECT COUNT(*) INTO user_count FROM users; RETURN user_count; END; $$; `; const astSync = parseSync(plpgsqlQuery); console.log('\n--- Sync Parse Result (PL/pgSQL, partial) ---'); console.log(JSON.stringify(astSync[0]?.stmt, null, 2)); } catch (error) { console.error('Sync parsing error:', error); } } demonstrateParsing();
Debug
Known issues
gotchaSynchronous parsing methods like `parseSync` and `parsePlPgSQLSync` require the WebAssembly module to be explicitly initialized by calling `await loadModule()` once beforehand. Failure to do so will result in runtime errors. Asynchronous methods handle this initialization automatically.
fix
Ensure `await loadModule();` is called before any synchronous parsing function in your application's lifecycle, typically at startup or during module initialization.
affects: >=1.0.0
gotchaThe `parse` and `parseSync` functions return an array of statement objects, even if only a single SQL query is provided. This is because PostgreSQL allows multiple semicolon-delimited queries in a single string. Always iterate or access `result[0]` for single queries.
fix
When expecting a single query result, access the first element of the returned array, e.g., `const ast = await parse(sql); const firstStatement = ast[0];`.
affects: >=1.0.0
gotchaThis library (`libpg-query`) focuses solely on parsing SQL into an AST. For round-trip functionality (parsing SQL and then deparsing the AST back into SQL) or for dynamic multi-version PostgreSQL support within a single package, consider using related packages like `pgsql-parser` or `@pgsql/parser`.
fix
Evaluate your specific needs. If deparsing or multi-version runtime selection is required, refer to `pgsql-parser` or `@pgsql/parser` which build upon `libpg-query`.
affects: >=1.0.0
gotchaWhile `libpg-query` aims for zero native dependencies via WebAssembly, certain environments or interactions with other native modules can still lead to unexpected compilation issues, particularly on Windows or with complex build setups involving `node-gyp`.
fix
Ensure your build environment (Node.js version, `pnpm` or `npm` version) is up-to-date. If encountering `node-gyp` errors, try rebuilding WASM artifacts with `pnpm run clean && pnpm run build`. For persistent issues, isolate `libpg-query` from other native dependency-heavy packages if possible.
affects: >=1.0.0
Errors
Common errors & fixes
Error: WASM module not initialized. Call `loadModule()` first.
Attempting to use `parseSync` or other synchronous API methods before `loadModule()` has been called and awaited.
fix
Add `await loadModule();` to your application's startup code or before the first synchronous call. This only needs to be done once per application instance.
fetch failed (during `npm test` or `pnpm test`)
Stale or missing WebAssembly (WASM) artifacts needed for testing or runtime.
fix
Rebuild the WASM artifacts by running `pnpm run clean && pnpm run build` (or `npm run clean && npm run build` if using npm), then retry the tests.
node-pre-gyp ERR! build error
A dependency of `libpg-query` (or `libpg-query` itself in older/misconfigured setups) attempted a native compilation with `node-gyp` but failed due to missing build tools (e.g., `make`, Python, C++ compiler) or platform incompatibilities.
fix
Ensure all necessary build tools for `node-gyp` are installed on your system. For `libpg-query` specifically, ensure you are using the WebAssembly distribution correctly, as it is designed to avoid native compilation. If the error persists, check related issues on the project's GitHub for specific OS/Node.js version solutions.
Upgrade
Version history
17.7.3latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
5 hits · last 30 days
node
4
Amazon
1
Resources
libpg-query — npm install libpg-query · libregistry