or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

connection.mdcopy-operations.mdindex.mdprepared-statements.mdqueries.md
tile.json

tessl/npm-pg-native

A slightly nicer interface to Postgres over node-libpq providing both sync and async operations

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/pg-native@3.5.x

To install, run

npx @tessl/cli install tessl/npm-pg-native@3.5.0

index.mddocs/

PG Native

PG 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.

Package Information

  • Package Name: pg-native
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install pg-native

Core Imports

const Client = require('pg-native');

For ES modules:

import Client from 'pg-native';

Basic Usage

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();
    });
  });
});

Architecture

PG Native is built around several key components:

  • Client Class: Main interface providing both async and sync operations
  • Event System: EventEmitter-based notifications for PostgreSQL LISTEN/NOTIFY
  • Stream Support: Duplex streams for PostgreSQL COPY operations
  • Type Conversion: Integrated with pg-types for proper data type handling
  • libpq Integration: Direct bindings to the native PostgreSQL client library

Capabilities

Client Connection

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 pattern

Connection Management

Query Operations

Query 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[];

Query Operations

Prepared Statements

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;

Prepared Statements

COPY Operations

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;
}

COPY Operations

Version Export

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);

Types

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[];
}