{"id":11546,"library":"pg-protocol","title":"PostgreSQL Wire Protocol Parser/Serializer","description":"pg-protocol is a foundational TypeScript library that implements the PostgreSQL client/server binary wire protocol. It provides low-level parsing and serialization capabilities for PostgreSQL messages, serving as a core internal dependency for the popular `node-postgres` client library. The version specified for this entry is 1.13.0 (though npm's 'latest' tag currently points to 1.12.0), and its release cadence is tied closely to the development of `node-postgres` itself, meaning updates are often driven by new PostgreSQL features or performance enhancements needed by the higher-level client. Its key differentiator is its precise, TypeScript-driven implementation of the PostgreSQL protocol specification, enabling robust and type-safe interaction at the binary level. While it can be used independently for specialized tasks like building custom PostgreSQL proxies or analytics tools, its primary role is to abstract away the intricate protocol details for database client developers.","status":"active","version":"1.13.0","language":"javascript","source_language":"en","source_url":"git://github.com/brianc/node-postgres","tags":["javascript","typescript"],"install":[{"cmd":"npm install pg-protocol","lang":"bash","label":"npm"},{"cmd":"yarn add pg-protocol","lang":"bash","label":"yarn"},{"cmd":"pnpm add pg-protocol","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primarily used for processing incoming PostgreSQL wire protocol buffers from the server. CommonJS `require` syntax is generally discouraged in modern TypeScript/ESM projects.","wrong":"const Parser = require('pg-protocol').Parser;","symbol":"Parser","correct":"import { Parser } from 'pg-protocol';"},{"note":"Used for constructing outgoing PostgreSQL wire protocol messages to the server. Prefer ESM named imports.","wrong":"const { Serializer } = require('pg-protocol');","symbol":"Serializer","correct":"import { Serializer } from 'pg-protocol';"},{"note":"Importing types like `Message` should use `import type` for clarity and to ensure they are stripped from the JavaScript output, avoiding accidental runtime imports.","symbol":"Message","correct":"import type { Message } from 'pg-protocol';"},{"note":"Specific message classes like `Query` might be nested within submodules or the `dist/messages` path, depending on the exact package structure. Refer to type definitions for precise paths.","symbol":"Query","correct":"import { Query } from 'pg-protocol/dist/messages';"}],"quickstart":{"code":"import { Parser, Serializer } from 'pg-protocol';\nimport { Query, ReadyForQueryMessage, BackendMessageCode } from 'pg-protocol/dist/messages';\n\n// 1. Simulate an incoming 'ReadyForQuery' message from the server\n// (Type 'Z' for ReadyForQuery, length, transaction status 'I' for idle)\nconst readyForQueryBuffer = Buffer.from([BackendMessageCode.ReadyForQuery, 0, 0, 0, 5, 'I'.charCodeAt(0)]);\n\nconst parser = new Parser();\nparser.parse(readyForQueryBuffer);\n\n// In a real scenario, you'd listen to 'message' events\n// For this example, we'll manually check the parsed queue\nlet parsedMessage: ReadyForQueryMessage | undefined;\nwhile (true) {\n    const msg = parser.shift();\n    if (msg) {\n        if (msg.name === 'ReadyForQuery') {\n            parsedMessage = msg as ReadyForQueryMessage;\n            console.log(`Parsed ReadyForQuery: Transaction Status = ${parsedMessage.transactionStatus}`);\n            break;\n        }\n    } else {\n        break;\n    }\n}\n\nif (!parsedMessage) {\n    console.error('Failed to parse ReadyForQuery message.');\n}\n\n// 2. Serialize an outgoing 'Query' message to the server\nconst query = 'SELECT 1 + 1 AS solution;';\nconst serializer = new Serializer();\n\n// The Query message expects a string and can be serialized directly\nconst queryMessage = new Query(query);\nconst serializedBuffer = serializer.query(query);\n\nconsole.log(`\nOriginal Query: ${query}`);\nconsole.log('Serialized Query Buffer (first 20 bytes):', serializedBuffer.toString('hex').substring(0, 40), '...');\nconsole.log(`Buffer length: ${serializedBuffer.length} bytes`);\n\n// Example: Basic structure of a 'Query' message buffer\n// Message type 'Q', then length including length itself, then query string + null terminator\nconst expectedHeader = Buffer.from([0x51, 0x00, 0x00, 0x00, (query.length + 5) >> 8, 0x00, 0x00, 0x00, (query.length + 5) & 0xFF]);\n// Note: Actual serialization includes the string and null terminator.\n// This is a simplified check.","lang":"typescript","description":"Demonstrates how to initialize the Parser to consume an incoming PostgreSQL `ReadyForQuery` message and how to use the Serializer to create an outgoing SQL `Query` message buffer. This highlights the low-level parsing and serialization capabilities."},"warnings":[{"fix":"Unless building a custom PostgreSQL client or proxy, prefer using the higher-level `pg` package which wraps `pg-protocol` and provides a stable, documented API.","message":"pg-protocol is primarily an internal module of the `node-postgres` ecosystem. Its API is low-level and not designed for direct public consumption. Using it directly may expose you to internal changes that are not considered breaking within `node-postgres`'s public API, but could break your direct usage.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If connecting to a PostgreSQL server with a self-signed certificate, explicitly set `{ ssl: { rejectUnauthorized: false } }` in your `pg.Client` or `pg.Pool` configuration. Alternatively, provide a valid CA certificate.","message":"With `node-postgres` v8.x (which utilizes `pg-protocol` internally), the default behavior for SSL connections changed. Previously, `rejectUnauthorized` defaulted to `false`, allowing self-signed certificates without explicit configuration. It now defaults to `true` for improved security.","severity":"breaking","affected_versions":"pg@>=8.0.0 (internal impact on pg-protocol consumers)"},{"fix":"Monitor `node-postgres` releases for explicit support of new PostgreSQL wire protocol versions. Ensure your `pg-protocol` version (via `node-postgres`) is updated to match new server capabilities if you need to leverage them.","message":"PostgreSQL 18 introduces Wire Protocol 3.2, which includes enhanced security features like 256-bit cancel request keys. While `pg-protocol` aims to support new protocol features, adopting them requires updates to both the client (e.g., `node-postgres`) and the server. Older clients or `pg-protocol` versions might not fully utilize newer protocol features.","severity":"gotcha","affected_versions":">=1.0.0 (impacted by server updates)"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `pg-protocol` is installed via `npm install pg-protocol` or `yarn add pg-protocol`. If importing specific sub-paths (e.g., for messages), verify the exact path from the package's type definitions or source.","cause":"The `pg-protocol` package is not installed, or the import path is incorrect, especially if trying to import specific nested modules.","error":"Cannot find module 'pg-protocol' or its corresponding type declarations."},{"fix":"Consult the `pg-protocol` source code or TypeScript declarations for the exact methods and their signatures available in your installed version. The internal API might change more frequently than `node-postgres`'s public API. Ensure you are importing the correct class (e.g., `Serializer`) and using its methods as defined in the current version.","cause":"Attempting to call a method that doesn't exist or using an outdated API, potentially due to `pg-protocol`'s internal nature and API instability for direct consumers.","error":"TypeError: Serializer.query is not a function"}],"ecosystem":"npm"}