A slightly nicer interface to Postgres over node-libpq providing both sync and async operations
npx @tessl/cli install tessl/npm-pg-native@3.5.0PG Native provides a high-performance native interface to PostgreSQL databases through libpq bindings, offering both asynchronous and synchronous operations for connecting, querying, and executing prepared statements. It serves as a lower-level alternative to the main 'pg' package, delivering direct access to native PostgreSQL client functionality with minimal overhead.
npm install pg-nativeconst Client = require('pg-native');For ES modules:
import Client from 'pg-native';const Client = require('pg-native');
// Constructor pattern (recommended)
const client = new Client();
// Factory pattern (also supported)
const client2 = Client();
client.connect(function(err) {
if(err) throw err
// Simple query
client.query('SELECT NOW() AS the_date', function(err, rows) {
if(err) throw err
console.log(rows[0].the_date);
// Parameterized query
client.query('SELECT $1::text as message', ['Hello World'], function(err, rows) {
if(err) throw err
console.log(rows[0].message); // 'Hello World'
client.end();
});
});
});PG Native is built around several key components:
Core connection management functionality for establishing and maintaining PostgreSQL database connections. Supports both asynchronous and synchronous connection patterns.
const Client = require('pg-native');
// Constructor patterns (both supported)
const client = new Client(config?: ClientConfig);
const client = Client(config?: ClientConfig); // Factory patternQuery execution functionality supporting both text queries and parameterized statements. Provides async and sync interfaces for maximum flexibility.
// Asynchronous query execution
client.query(
text: string,
values?: any[],
callback: (err: Error | null, rows: any[], results?: QueryResult | QueryResult[]) => void
): void;
// Synchronous query execution
client.querySync(text: string, values?: any[]): any[];Prepared statement functionality for optimized repeated query execution. Supports both preparation and execution phases with proper parameter binding.
// Prepare a statement
client.prepare(
statementName: string,
text: string,
nParams: number,
callback: (err: Error | null) => void
): void;
// Execute prepared statement
client.execute(
statementName: string,
parameters: any[],
callback: (err: Error | null, rows: any[], results?: any) => void
): void;PostgreSQL COPY operation support through Node.js streams. Enables high-performance bulk data import and export operations.
// Get a duplex stream for COPY operations
client.getCopyStream(): CopyStream;
interface CopyStream extends Duplex {
// Stream methods for reading/writing COPY data
write(chunk: Buffer, encoding?: string, callback?: Function): boolean;
end(): void;
}The module exports its version string for compatibility checking.
// Module version export
Client.version: string;Usage Examples:
const Client = require('pg-native');
console.log('pg-native version:', Client.version);interface ClientConfig {
/** Custom type conversion parser (defaults to pg-types) */
types?: TypeParser;
/** Return results as arrays instead of objects */
arrayMode?: boolean;
}
// Constructor/Factory function
interface ClientConstructor {
/** Create new Client instance */
new (config?: ClientConfig): Client;
/** Factory function to create Client (no 'new' required) */
(config?: ClientConfig): Client;
/** Module version string */
version: string;
}
interface Client extends EventEmitter {
/** Connect to PostgreSQL server */
connect(params?: string, callback: (err: Error | null) => void): void;
/** Synchronously connect to PostgreSQL server */
connectSync(params?: string): void;
/** Execute a query */
query(text: string, callback: (err: Error | null, rows: any[]) => void): void;
query(text: string, values: any[], callback: (err: Error | null, rows: any[]) => void): void;
/** Synchronously execute a query */
querySync(text: string, values?: any[]): any[];
/** Prepare a statement */
prepare(name: string, text: string, nParams: number, callback: (err: Error | null) => void): void;
/** Synchronously prepare a statement */
prepareSync(name: string, text: string, nParams: number): void;
/** Execute a prepared statement */
execute(name: string, params: any[], callback: (err: Error | null, rows: any[]) => void): void;
/** Synchronously execute a prepared statement */
executeSync(name: string, params: any[]): any[];
/** Cancel current query */
cancel(callback: (err: Error | null) => void): void;
/** End the connection */
end(callback?: () => void): void;
/** Escape a string literal */
escapeLiteral(value: string): string;
/** Escape an identifier */
escapeIdentifier(value: string): string;
/** Get a COPY stream */
getCopyStream(): CopyStream;
}
// Events emitted by Client
interface ClientEvents {
/** PostgreSQL notification received */
'notification': (message: NotificationMessage) => void;
/** Query result received */
'result': (result: QueryResult) => void;
/** Client ready for next query */
'readyForQuery': () => void;
/** Error occurred */
'error': (error: Error) => void;
}
interface NotificationMessage {
/** Notification channel name */
channel: string;
/** Notification payload */
payload: string;
/** Process ID of the notifying backend */
pid: number;
}
interface QueryResult {
/** SQL command that was executed */
command: string;
/** Number of rows affected by the command */
rowCount: number;
/** Column information for the result set */
fields: Array<{ name: string; dataTypeID: number }>;
/** Result rows (same as the rows parameter in callbacks) */
rows: any[];
}