PostgreSQL client library for Node.js with both pure JavaScript and optional native libpq bindings
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
The Client class provides core PostgreSQL connection management and query execution functionality. It extends EventEmitter to provide asynchronous event-driven operations for database interactions.
Creates a new PostgreSQL client instance with connection configuration.
/**
* Creates a new PostgreSQL client instance
* @param config - Connection configuration object
*/
class Client extends EventEmitter {
constructor(config?: ClientConfig);
}
interface ClientConfig {
/** Database user name */
user?: string;
/** Database password */
password?: string;
/** Database host (default: 'localhost') */
host?: string;
/** Database name */
database?: string;
/** Database port (default: 5432) */
port?: number;
/** PostgreSQL connection string */
connectionString?: string;
/** SSL configuration */
ssl?: boolean | SSLConfig;
/** Binary result mode */
binary?: boolean;
/** Client encoding */
client_encoding?: string;
/** Application name for logging */
application_name?: string;
/** Fallback application name for logging */
fallback_application_name?: string;
/** Connection options */
options?: string;
/** Statement timeout in milliseconds */
statement_timeout?: number | false;
/** Query timeout in milliseconds */
query_timeout?: number | false;
/** Lock timeout in milliseconds */
lock_timeout?: number | false;
/** Idle in transaction session timeout in milliseconds */
idle_in_transaction_session_timeout?: number | false;
/** Connection timeout in milliseconds */
connectionTimeoutMillis?: number;
/** Enable TCP keep-alive */
keepAlive?: boolean;
/** Initial delay for keep-alive probes */
keepAliveInitialDelayMillis?: number;
/** Enable SCRAM-SHA-256-PLUS authentication */
enableChannelBinding?: boolean;
/** Custom stream for connection */
stream?: any;
/** Custom connection object */
connection?: any;
/** Custom types configuration */
types?: TypeOverrides;
/** Promise constructor to use */
Promise?: typeof Promise;
/** Replication mode */
replication?: string;
}
interface SSLConfig {
rejectUnauthorized?: boolean;
ca?: string | Buffer;
key?: string | Buffer;
cert?: string | Buffer;
passphrase?: string;
servername?: string;
checkServerIdentity?: (servername: string, cert: any) => Error | undefined;
}Usage Examples:
const { Client } = require('pg');
// Basic connection
const client = new Client({
user: 'postgres',
host: 'localhost',
database: 'myapp',
password: 'secret',
port: 5432,
});
// Connection string
const client2 = new Client({
connectionString: 'postgresql://user:password@host:5432/database'
});
// SSL connection
const client3 = new Client({
host: 'secure-host.com',
ssl: {
rejectUnauthorized: false
}
});Establishes connection to the PostgreSQL database.
/**
* Connect to the PostgreSQL database
* @param callback - Optional callback for connection result
* @returns Promise that resolves when connected
*/
connect(callback?: (err: Error | null) => void): Promise<void>;Usage Examples:
// Promise-based
await client.connect();
// Callback-based
client.connect((err) => {
if (err) {
console.error('Connection error', err.stack);
} else {
console.log('Connected');
}
});Execute SQL queries with optional parameters and callbacks.
/**
* Execute a SQL query with text and optional parameters
* @param text - SQL query string
* @param values - Optional parameter values
* @param callback - Optional callback for query result
* @returns Promise resolving to query result
*/
query(text: string, values?: any[], callback?: QueryCallback): Promise<QueryResult>;
/**
* Execute a SQL query with configuration object
* @param config - Query configuration
* @param callback - Optional callback for query result
* @returns Promise resolving to query result
*/
query(config: QueryConfig, callback?: QueryCallback): Promise<QueryResult>;
type QueryCallback = (err: Error | null, result: QueryResult) => void;Usage Examples:
// Simple query
const res = await client.query('SELECT NOW()');
console.log(res.rows[0]);
// Parameterized query
const res2 = await client.query('SELECT * FROM users WHERE id = $1', [123]);
// Named prepared statement
const res3 = await client.query({
name: 'fetch-user',
text: 'SELECT * FROM users WHERE id = $1',
values: [123]
});
// Callback style
client.query('SELECT * FROM users', (err, result) => {
if (err) throw err;
console.log(result.rows);
});Closes the database connection.
/**
* Close the database connection
* @param callback - Optional callback for close result
* @returns Promise that resolves when connection is closed
*/
end(callback?: (err: Error | null) => void): Promise<void>;Usage Examples:
// Promise-based
await client.end();
// Callback-based
client.end((err) => {
if (err) {
console.error('Error ending client', err.stack);
}
});Manage custom type parsers for PostgreSQL data types.
/**
* Set a custom type parser for a PostgreSQL type
* @param oid - PostgreSQL type OID
* @param format - Format ('text' or 'binary')
* @param parseFn - Parser function
*/
setTypeParser(oid: number, format: string, parseFn: (value: string) => any): void;
setTypeParser(oid: number, parseFn: (value: string) => any): void;
/**
* Get the type parser for a PostgreSQL type
* @param oid - PostgreSQL type OID
* @param format - Format ('text' or 'binary')
* @returns Parser function
*/
getTypeParser(oid: number, format?: string): (value: string) => any;Usage Examples:
// Custom date parser
client.setTypeParser(1082, (val) => new Date(val));
// Custom JSON parser with reviver
client.setTypeParser(114, (val) => JSON.parse(val, customReviver));
// Get existing parser
const dateParser = client.getTypeParser(1082);Escape SQL identifiers and literals for safe query construction.
/**
* Escape a SQL identifier (table/column name)
* @param str - String to escape
* @returns Escaped identifier
*/
escapeIdentifier(str: string): string;
/**
* Escape a SQL literal value
* @param str - String to escape
* @returns Escaped literal
*/
escapeLiteral(str: string): string;Usage Examples:
const tableName = client.escapeIdentifier('user-table');
const userInput = client.escapeLiteral("O'Reilly");
const query = `SELECT * FROM ${tableName} WHERE name = ${userInput}`;Control connection reference counting for process lifecycle management.
/**
* Keep the Node.js process alive while client is active
*/
ref(): void;
/**
* Allow Node.js process to exit even with active client
*/
unref(): void;Cancel running queries on the database server.
/**
* Cancel a running query
* @param client - Client with running query to cancel
* @param query - Query to cancel
*/
cancel(client: Client, query: Query): void;interface Client {
/** Database user */
readonly user: string;
/** Database name */
readonly database: string;
/** Database host */
readonly host: string;
/** Database port */
readonly port: number;
/** Replication mode */
readonly replication: string;
/** Server process ID */
readonly processID: number | null;
/** Server secret key */
readonly secretKey: number | null;
/** Connection parameters */
readonly connectionParameters: ConnectionParameters;
/** SSL configuration */
readonly ssl: boolean | SSLConfig;
/** Binary mode setting */
readonly binary: boolean;
/** Underlying connection object */
readonly connection: Connection;
}Client emits various events during its lifecycle:
// Connection events
client.on('connect', () => {});
client.on('end', () => {});
client.on('error', (err) => {});
// Query events
client.on('drain', () => {});
// Notification events
client.on('notification', (msg) => {});
client.on('notice', (msg) => {});interface ConnectionParameters {
user: string;
database: string;
port: number;
host: string;
password: string;
ssl: boolean | SSLConfig;
client_encoding: string;
application_name: string;
fallback_application_name: string;
options: string;
statement_timeout: number | false;
lock_timeout: number | false;
idle_in_transaction_session_timeout: number | false;
replication: string;
}Install with Tessl CLI
npx tessl i tessl/npm-pg