CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-pg-protocol

The postgres client/server binary protocol, implemented in TypeScript

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

messages.mddocs/

Protocol Messages

Comprehensive TypeScript types and classes representing all PostgreSQL protocol messages, from authentication to data transfer.

Capabilities

Base Message Types

Core interfaces and types used throughout the protocol message system.

/**
 * Base interface for all backend protocol messages
 */
interface BackendMessage {
  /** Message type identifier */
  name: MessageName;
  /** Message length in bytes */
  length: number;
}

/**
 * Union type of all possible PostgreSQL protocol message names
 */
type MessageName =
  | 'parseComplete' | 'bindComplete' | 'closeComplete'
  | 'noData' | 'portalSuspended' | 'replicationStart'
  | 'emptyQuery' | 'copyDone' | 'copyData'
  | 'rowDescription' | 'parameterDescription'
  | 'parameterStatus' | 'backendKeyData' | 'notification'
  | 'readyForQuery' | 'commandComplete' | 'dataRow'
  | 'copyInResponse' | 'copyOutResponse'
  | 'authenticationOk' | 'authenticationMD5Password'
  | 'authenticationCleartextPassword' | 'authenticationSASL'
  | 'authenticationSASLContinue' | 'authenticationSASLFinal'
  | 'error' | 'notice';

/**
 * Data format mode for protocol fields
 */
type Mode = 'text' | 'binary';

Simple Message Constants

Pre-built message objects for common protocol responses.

/** Parse operation completed successfully */
const parseComplete: BackendMessage;

/** Bind operation completed successfully */
const bindComplete: BackendMessage;

/** Close operation completed successfully */
const closeComplete: BackendMessage;

/** No data available for portal */
const noData: BackendMessage;

/** Portal execution suspended */
const portalSuspended: BackendMessage;

/** Replication stream started */
const replicationStart: BackendMessage;

/** Empty query executed */
const emptyQuery: BackendMessage;

/** Copy operation completed */
const copyDone: BackendMessage;

Error and Notice Handling

Classes for handling PostgreSQL errors and notices with detailed field information.

/**
 * PostgreSQL database error with detailed diagnostic information
 */
class DatabaseError extends Error {
  /** Error severity level */
  severity?: string;
  /** PostgreSQL error code */
  code?: string;
  /** Detailed error description */
  detail?: string;
  /** Suggestion for resolving the error */
  hint?: string;
  /** Character position of error in query */
  position?: string;
  /** Internal query position (for internally generated queries) */
  internalPosition?: string;
  /** Internal query text that caused the error */
  internalQuery?: string;
  /** Location context where error occurred */
  where?: string;
  /** Schema name related to error */
  schema?: string;
  /** Table name related to error */
  table?: string;
  /** Column name related to error */
  column?: string;
  /** Data type name related to error */
  dataType?: string;
  /** Constraint name related to error */
  constraint?: string;
  /** Source file where error was generated */
  file?: string;
  /** Line number where error was generated */
  line?: string;
  /** Function name where error was generated */
  routine?: string;

  constructor(
    message: string,
    length: number,
    name: MessageName
  );
}

/**
 * PostgreSQL notice message with diagnostic information
 */
class NoticeMessage implements BackendMessage {
  readonly name = 'notice';
  severity?: string;
  code?: string;
  detail?: string;
  hint?: string;
  position?: string;
  internalPosition?: string;
  internalQuery?: string;
  where?: string;
  schema?: string;
  table?: string;
  column?: string;
  dataType?: string;
  constraint?: string;
  file?: string;
  line?: string;
  routine?: string;

  constructor(
    length: number,
    message?: string
  );
}

Query Result Messages

Classes representing query execution results and data.

/**
 * Command execution completion message
 */
class CommandCompleteMessage {
  readonly name: MessageName = 'commandComplete';
  
  constructor(
    /** Message length */
    public readonly length: number,
    /** Command tag text (e.g., "SELECT 5", "INSERT 0 1") */
    public readonly text: string
  );
}

/**
 * Single row of query result data
 */
class DataRowMessage {
  readonly name: MessageName = 'dataRow';
  /** Number of fields in the row */
  readonly fieldCount: number;
  
  constructor(
    /** Message length */
    public length: number,
    /** Array of field values (strings or null) */
    public fields: any[]
  );
}

/**
 * Description of query result structure
 */
class RowDescriptionMessage {
  readonly name: MessageName = 'rowDescription';
  /** Array of field descriptors */
  readonly fields: Field[];
  
  constructor(
    /** Message length */
    public readonly length: number,
    /** Number of fields in result */
    public readonly fieldCount: number
  );
}

/**
 * Individual field descriptor within a row description
 */
class Field {
  constructor(
    /** Field name */
    public readonly name: string,
    /** Table OID (0 if not from a table column) */
    public readonly tableID: number,
    /** Column attribute number (0 if not from a table column) */
    public readonly columnID: number,
    /** Data type OID */
    public readonly dataTypeID: number,
    /** Data type size (-1 for variable length) */
    public readonly dataTypeSize: number,
    /** Type modifier */
    public readonly dataTypeModifier: number,
    /** Format code (text or binary) */
    public readonly format: Mode
  );
}

Parameter and Status Messages

Classes for prepared statement parameters and server status information.

/**
 * Description of prepared statement parameters
 */
class ParameterDescriptionMessage {
  readonly name: MessageName = 'parameterDescription';
  /** Array of parameter data type OIDs */
  readonly dataTypeIDs: number[];
  
  constructor(
    /** Message length */
    public readonly length: number,
    /** Number of parameters */
    public readonly parameterCount: number
  );
}

/**
 * Server parameter status notification
 */
class ParameterStatusMessage {
  readonly name: MessageName = 'parameterStatus';
  
  constructor(
    /** Message length */
    public readonly length: number,
    /** Parameter name */
    public readonly parameterName: string,
    /** Parameter value */
    public readonly parameterValue: string
  );
}

/**
 * Server ready state indicator
 */
class ReadyForQueryMessage {
  readonly name: MessageName = 'readyForQuery';
  
  constructor(
    /** Message length */
    public readonly length: number,
    /** Transaction status: 'I' (idle), 'T' (in transaction), 'E' (error) */
    public readonly status: string
  );
}

Authentication Messages

Classes for handling various authentication methods.

/**
 * MD5 password authentication challenge
 */
class AuthenticationMD5Password implements BackendMessage {
  readonly name: MessageName = 'authenticationMD5Password';
  
  constructor(
    /** Message length */
    public readonly length: number,
    /** 4-byte salt for MD5 hashing */
    public readonly salt: Buffer
  );
}

Administrative Messages

Classes for administrative and connection management information.

/**
 * Backend process identification for query cancellation
 */
class BackendKeyDataMessage {
  readonly name: MessageName = 'backendKeyData';
  
  constructor(
    /** Message length */
    public readonly length: number,
    /** Backend process ID */
    public readonly processID: number,
    /** Secret key for cancellation requests */
    public readonly secretKey: number
  );
}

/**
 * Asynchronous notification message
 */
class NotificationResponseMessage {
  readonly name: MessageName = 'notification';
  
  constructor(
    /** Message length */
    public readonly length: number,
    /** Process ID of notifying backend */
    public readonly processId: number,
    /** Notification channel name */
    public readonly channel: string,
    /** Optional payload data */
    public readonly payload: string
  );
}

Copy Protocol Messages

Classes for handling PostgreSQL COPY operations.

/**
 * Copy operation data chunk
 */
class CopyDataMessage {
  readonly name = 'copyData';
  
  constructor(
    /** Message length */
    public readonly length: number,
    /** Data chunk */
    public readonly chunk: Buffer
  );
}

/**
 * Copy operation response (CopyIn or CopyOut)
 */
class CopyResponse {
  /** Array of column format codes */
  readonly columnTypes: number[];
  
  constructor(
    /** Message length */
    public readonly length: number,
    /** Message name ('copyInResponse' or 'copyOutResponse') */
    public readonly name: MessageName,
    /** Whether data is in binary format */
    public readonly binary: boolean,
    /** Number of columns */
    columnCount: number
  );
}

Usage Patterns

These message classes are typically created by the parser and passed to message callback functions:

import { DatabaseError } from "pg-protocol";

const callback = (message) => {
  switch (message.name) {
    case 'dataRow':
      console.log('Row data:', message.fields);
      break;
      
    case 'commandComplete':
      console.log('Command completed:', message.text);
      break;
      
    case 'error':
      const error = message;
      console.error(`Database error [${error.code}]: ${error.message}`);
      if (error.hint) console.log('Hint:', error.hint);
      break;
  }
};

Install with Tessl CLI

npx tessl i tessl/npm-pg-protocol

docs

index.md

messages.md

parsing.md

serialization.md

tile.json