{"id":13442,"library":"libpg-query","title":"PostgreSQL Query Parser","description":"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.","status":"active","version":"17.7.3","language":"javascript","source_language":"en","source_url":"git://github.com/constructive-io/libpg-query-node","tags":["javascript","sql","postgres","postgresql","pg","query","plpgsql","database","typescript"],"install":[{"cmd":"npm install libpg-query","lang":"bash","label":"npm"},{"cmd":"yarn add libpg-query","lang":"bash","label":"yarn"},{"cmd":"pnpm add libpg-query","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary asynchronous function to parse SQL. It automatically handles WASM module initialization.","symbol":"parse","correct":"import { parse } from 'libpg-query';"},{"note":"Synchronous parsing requires explicitly calling `loadModule()` once before its first use. Prefer `parse` (async) unless strict synchronous behavior is required.","wrong":"import { parseSync } from 'libpg-query';\nconst ast = parseSync(sql); // Fails if module not loaded","symbol":"parseSync","correct":"import { parseSync } from 'libpg-query';\n// ... later, after module is loaded ...\nconst ast = parseSync(sql);"},{"note":"Initializes the WebAssembly module. Mandatory before using `parseSync` or other synchronous API methods. The async `parse` function calls this internally if needed.","symbol":"loadModule","correct":"import { loadModule } from 'libpg-query';\nawait loadModule();"}],"quickstart":{"code":"import { parse, parseSync, loadModule } from 'libpg-query';\n\nasync function demonstrateParsing() {\n  const sqlQuery = `\n    SELECT id, name, created_at\n    FROM users\n    WHERE status = 'active' AND created_at > NOW() - INTERVAL '30 days'\n    ORDER BY created_at DESC;\n  `;\n\n  // Asynchronous parsing (recommended)\n  try {\n    const astAsync = await parse(sqlQuery);\n    console.log('--- Async Parse Result (partial) ---');\n    console.log(JSON.stringify(astAsync[0]?.stmt, null, 2));\n  } catch (error) {\n    console.error('Async parsing error:', error);\n  }\n\n  // Synchronous parsing (requires explicit module loading)\n  try {\n    await loadModule(); // Initialize the WASM module once\n    const plpgsqlQuery = `\n      CREATE FUNCTION get_user_count()\n      RETURNS integer\n      LANGUAGE plpgsql\n      AS $$\n      DECLARE\n          user_count integer;\n      BEGIN\n          SELECT COUNT(*) INTO user_count FROM users;\n          RETURN user_count;\n      END;\n      $$;\n    `;\n    const astSync = parseSync(plpgsqlQuery);\n    console.log('\\n--- Sync Parse Result (PL/pgSQL, partial) ---');\n    console.log(JSON.stringify(astSync[0]?.stmt, null, 2));\n  } catch (error) {\n    console.error('Sync parsing error:', error);\n  }\n}\n\ndemonstrateParsing();","lang":"typescript","description":"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)."},"warnings":[{"fix":"Ensure `await loadModule();` is called before any synchronous parsing function in your application's lifecycle, typically at startup or during module initialization.","message":"Synchronous 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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];`.","message":"The `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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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`.","message":"This 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`.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"While `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`.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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.","cause":"Attempting to use `parseSync` or other synchronous API methods before `loadModule()` has been called and awaited.","error":"Error: WASM module not initialized. Call `loadModule()` first."},{"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.","cause":"Stale or missing WebAssembly (WASM) artifacts needed for testing or runtime.","error":"fetch failed (during `npm test` or `pnpm test`)"},{"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.","cause":"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.","error":"node-pre-gyp ERR! build error"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}