
Research
/Security News
TensorLake npm SDK Compromised in ChainDrop Shai-Hulud Credential-Stealing Attack
Tensorlake npm SDK version 0.5.144 was compromised in a ChainDrop / Shai-Hulud attack, delivering credential-stealing malware.
libpg-query
Advanced tools
This is the official PostgreSQL parser, compiled to WebAssembly (WASM) for seamless, cross-platform compatibility. Use it in Node.js or the browser, on Linux, Windows, or anywhere JavaScript runs.
Built to power pgsql-parser, this library delivers full fidelity with the Postgres C codebase — no rewrites, no shortcuts.
🎯 Want to parse + deparse (full round trip)?
We highly recommend usingpgsql-parserwhich leverages a pure TypeScript deparser that has been battle-tested against 23,000+ SQL statements and is built on top of libpg-query.
npm install libpg-query
import { parse } from 'libpg-query';
const result = await parse('SELECT * FROM users WHERE active = true');
// {"version":180004,"stmts":[{"stmt":{"SelectStmt":{"targetList":[{"ResTarget" ... "op":"SETOP_NONE"}}}]}
Our latest is built with the 18-constructive branch of constructive-io/libpg_query
Starting with PostgreSQL 18, this package ships the full API: parse, parsePlPgSQL, scan, fingerprint, normalize and their sync variants. Versions 13–17 are parse-only.
| PG Major Version | libpg_query | npm dist-tag |
|---|---|---|
| 18 | 18.0.0 | pg18 |
| 17 | 17-6.1.0 | pg17 |
| 16 | 16-5.2.0 | pg16 |
| 15 | 15-4.2.4 | pg15 |
| 14 | 14-3.0.0 | pg14 |
| 13 | 13-2.2.0 | pg13 |
parse(query: string): Promise<ParseResult>Parses the SQL and returns a Promise for the parse tree. May reject with a parse error.
import { parse } from 'libpg-query';
const result = await parse('SELECT * FROM users WHERE active = true');
// Returns: ParseResult - parsed query object
parseSync(query: string): ParseResultSynchronous version that returns the parse tree directly. May throw a parse error.
import { parseSync } from 'libpg-query';
const result = parseSync('SELECT * FROM users WHERE active = true');
// Returns: ParseResult - parsed query object
parsePlPgSQL(funcsSql: string): Promise<ParseResult> / parsePlPgSQLSyncParses the contents of a PL/pgSQL function from a CREATE FUNCTION declaration.
import { parsePlPgSQL } from 'libpg-query';
const result = await parsePlPgSQL(`
CREATE FUNCTION get_count() RETURNS integer AS $$
BEGIN
RETURN (SELECT COUNT(*) FROM users);
END;
$$ LANGUAGE plpgsql;
`);
// { plpgsql_funcs: [...] }
scan(sql: string): Promise<ScanResult> / scanSyncTokenizes the SQL, returning token positions, text, types, and keyword kinds. See SCAN.md.
import { scan } from 'libpg-query';
const result = await scan('SELECT id FROM users');
// { version: 180004, tokens: [{ start, end, text, tokenType, tokenName, keywordKind, keywordName }, ...] }
fingerprint(sql: string): Promise<string> / fingerprintSyncGenerates a unique fingerprint for query identification/caching (equivalent queries share a fingerprint).
import { fingerprint } from 'libpg-query';
await fingerprint('SELECT * FROM users WHERE id = 1'); // e.g. 'a0ead580058af585'
normalize(sql: string): Promise<string> / normalizeSyncNormalizes the SQL, replacing constants with placeholders.
import { normalize } from 'libpg-query';
await normalize("SELECT * FROM users WHERE name = 'alice'");
// SELECT * FROM users WHERE name = $1
⚠ Note: the full API (parsePlPgSQL, scan, fingerprint, normalize) is available on pg18+ only; pg13–pg17 builds expose parse/parseSync only.
The library provides both async and sync methods. Async methods handle initialization automatically, while sync methods require explicit initialization.
Async methods handle initialization automatically and are always safe to use:
import { parse } from 'libpg-query';
// These handle initialization automatically
const result = await parse('SELECT * FROM users');
Sync methods require explicit initialization using loadModule():
import { loadModule, parseSync } from 'libpg-query';
// Initialize first
await loadModule();
// Now safe to use sync methods
const result = parseSync('SELECT * FROM users');
loadModule(): Promise<void>Explicitly initializes the WASM module. Required before using any sync methods.
import { loadModule, parseSync } from 'libpg-query';
// Initialize before using sync methods
await loadModule();
const result = parseSync('SELECT * FROM users');
Note: We recommend using async methods as they handle initialization automatically. Use sync methods only when necessary, and always call loadModule() first.
interface ParseResult {
version: number;
stmts: Statement[];
}
interface Statement {
stmt_type: string;
stmt_len: number;
stmt_location: number;
query: string;
}
Note: The return value is an array, as multiple queries may be provided in a single string (semicolon-delimited, as PostgreSQL expects).
This package uses a WASM-only build system for true cross-platform compatibility without native compilation dependencies.
Install dependencies:
pnpm install
Build WASM artifacts:
pnpm run build
Clean WASM build (if needed):
pnpm run clean
Rebuild WASM artifacts from scratch:
pnpm run clean && pnpm run build
The WASM build process:
wasm/libpg-query.js and wasm/libpg-query.wasm filespnpm run test
pnpm run clean && pnpm run build && pnpm run test
"fetch failed" errors during tests:
pnpm run clean && pnpm run build"WASM module not initialized" errors:
Build environment issues:
The build process generates these files:
wasm/libpg-query.js - Emscripten-generated JavaScript loaderwasm/libpg-query.wasm - WebAssembly binarywasm/index.js - ES module exportswasm/index.cjs - CommonJS exports with sync wrappersBuilt on the excellent work of several contributors:
🛠 Built by the Constructive team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on GitHub.
pgsql-parser.pgsql-parser for parsing and deparsing SQL queries.AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
No developer or entity involved in creating Software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the Software code or Software CLI, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
FAQs
The real PostgreSQL query parser
The npm package libpg-query receives a total of 851,516 weekly downloads. As such, libpg-query popularity was classified as popular.
We found that libpg-query demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.

Research
/Security News
Tensorlake npm SDK version 0.5.144 was compromised in a ChainDrop / Shai-Hulud attack, delivering credential-stealing malware.

Research
/Security News
Socket found 16 malicious Firefox extensions designed to steal crypto wallet recovery phrases and private keys using cloned Rabby and OKX interfaces.

Product
Socket now scans VS Code extensions, giving teams early detection of risky behaviors, hidden capabilities, and supply chain threats in developer tools.