or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

database-operations.mdextensions.mdfilesystem-storage.mdindex.mdlive-queries.mdsql-templates.mdvector-operations.mdworker-support.md
tile.json

database-operations.mddocs/

Database Operations

Core database functionality providing PostgreSQL query execution, transaction management, and database lifecycle operations.

Capabilities

PGlite Class

Main database class that provides the complete PostgreSQL interface.

/**
 * Main PGlite database class extending BasePGlite
 */
class PGlite extends BasePGlite implements PGliteInterface {
  constructor(dataDir?: string, options?: PGliteOptions);
  constructor(options?: PGliteOptions);
  
  /** Promise that resolves when the database is ready for use */
  readonly waitReady: Promise<void>;
  /** Whether the database is ready for operations */
  readonly ready: boolean;
  /** Whether the database has been closed */
  readonly closed: boolean;
  /** Data directory path if using persistent storage */
  readonly dataDir?: string;
  /** Debug logging level (0-5) */
  debug: DebugLevel;
  /** Emscripten WebAssembly module instance */
  readonly Module: PostgresMod;
}

Static Creation Methods

Alternative construction methods with better type inference for extensions.

/**
 * Create PGlite instance with extension types
 * @param options - Configuration options
 * @returns PGlite instance with extension namespaces
 */
static create<O extends PGliteOptions>(options?: O): Promise<PGliteWithExtensions<O>>;

/**
 * Create PGlite instance with data directory and extension types
 * @param dataDir - Data directory path
 * @param options - Configuration options
 * @returns PGlite instance with extension namespaces
 */
static create<O extends PGliteOptions>(
  dataDir?: string, 
  options?: O
): Promise<PGliteWithExtensions<O>>;

Query Execution

Core methods for executing SQL queries and statements.

/**
 * Execute a parameterized query
 * @param query - SQL query string
 * @param params - Query parameters
 * @param options - Query execution options
 * @returns Query results
 */
query<T = Record<string, any>>(
  query: string,
  params?: any[],
  options?: QueryOptions
): Promise<Results<T>>;

/**
 * Execute query using template literal syntax
 * @param strings - Template string parts
 * @param params - Template parameters
 * @returns Query results
 */
sql<T = Record<string, any>>(
  strings: TemplateStringsArray,
  ...params: any[]
): Promise<Results<T>>;

/**
 * Execute multiple statements in a single call
 * @param query - SQL statements separated by semicolons
 * @param options - Query execution options
 * @returns Array of results for each statement
 */
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;

/**
 * Get metadata about a query without executing it
 * @param query - SQL query string
 * @returns Query metadata including parameter and result types
 */
describeQuery(query: string): Promise<DescribeQueryResult>;

Transaction Management

Methods for managing database transactions.

/**
 * Execute a function within a database transaction
 * @param callback - Function to execute in transaction context
 * @returns Result of the callback function
 */
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>;

/**
 * Check if currently inside a transaction
 * @returns True if in transaction, false otherwise
 */
isInTransaction(): boolean;

Database Lifecycle

Methods for managing database state and cleanup.

/**
 * Close the database and cleanup resources
 */
close(): Promise<void>;

/**
 * Sync database state to persistent storage
 */
syncToFs(): Promise<void>;

/**
 * Export the entire data directory as a tarball
 * @param compression - Compression options
 * @returns Tarball file or blob
 */
dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>;

/**
 * Create a copy of the database instance
 * @returns New PGlite instance with same state
 */
clone(): Promise<PGliteInterface>;

/**
 * Refresh array type parsers (internal use)
 */
refreshArrayTypes(): Promise<void>;

/**
 * Auto-cleanup when using with statement (Symbol.asyncDispose)
 */
[Symbol.asyncDispose](): Promise<void>;

Notification System

PostgreSQL LISTEN/NOTIFY support for real-time messaging.

/**
 * Listen for notifications on a channel
 * @param channel - Notification channel name
 * @param callback - Function to call when notification received
 * @param tx - Optional transaction context
 * @returns Function to unlisten
 */
listen(
  channel: string,
  callback: (payload: string) => void,
  tx?: Transaction
): Promise<() => Promise<void>>;

/**
 * Stop listening for notifications on a channel
 * @param channel - Notification channel name
 * @param callback - Optional specific callback to remove
 * @param tx - Optional transaction context
 */
unlisten(
  channel: string,
  callback?: (payload: string) => void,
  tx?: Transaction
): Promise<void>;

/**
 * Add global notification listener for all channels
 * @param callback - Function to call for any notification
 * @returns Function to remove listener
 */
onNotification(callback: (channel: string, payload: string) => void): () => void;

/**
 * Remove global notification listener
 * @param callback - Callback function to remove
 */
offNotification(callback: (channel: string, payload: string) => void): void;

Protocol Level Access

Low-level PostgreSQL wire protocol access.

/**
 * Execute PostgreSQL wire protocol message
 * @param message - Protocol message
 * @param options - Execution options
 * @returns Protocol execution result
 */
execProtocol(
  message: Uint8Array,
  options?: ExecProtocolOptions
): Promise<ExecProtocolResult>;

/**
 * Execute protocol message and return raw bytes
 * @param message - Protocol message
 * @param options - Execution options
 * @returns Raw response bytes
 */
execProtocolRaw(
  message: Uint8Array,
  options?: ExecProtocolOptions
): Promise<Uint8Array>;

/**
 * Synchronous protocol message execution
 * @param message - Protocol message
 * @param options - Execution options with dataTransferContainer
 * @returns Raw response bytes
 */
execProtocolRawSync(
  message: Uint8Array,
  options?: { dataTransferContainer?: DataTransferContainer }
): Uint8Array;

Concurrency Control

Thread safety and exclusive access methods.

/**
 * Run function with exclusive database access
 * @param fn - Function to run exclusively
 * @returns Result of the function
 */
runExclusive<T>(fn: () => Promise<T>): Promise<T>;

Types

interface Results<T = Record<string, any>> {
  /** Array of result rows */
  rows: Row<T>[];
  /** Number of rows affected by INSERT/UPDATE/DELETE */
  affectedRows?: number;
  /** Result field metadata */
  fields: { name: string; dataTypeID: number }[];
  /** Output file for COPY TO operations */
  blob?: Blob;
}

interface Transaction {
  /** Execute query in transaction */
  query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
  /** Execute template query in transaction */
  sql<T>(strings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
  /** Execute multiple statements in transaction */
  exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
  /** Roll back the transaction */
  rollback(): Promise<void>;
  /** Listen for notifications in transaction */
  listen(channel: string, callback: (payload: string) => void): Promise<() => Promise<void>>;
  /** Whether transaction is closed */
  readonly closed: boolean;
}

interface DescribeQueryResult {
  /** Parameter type OIDs */
  parameterTypes: number[];
  /** Result field metadata */
  fields: { name: string; dataTypeID: number }[];
}

type Row<T> = T extends Record<string, any> ? T : Record<string, any>;

Usage Examples:

import { PGlite } from "@electric-sql/pglite";

// Create database with persistent storage
const db = new PGlite("./my-database");
await db.waitReady;

// Basic query execution
const result = await db.query(
  "SELECT * FROM users WHERE age > $1", 
  [18]
);

// Template literal queries
const user = await db.sql`
  SELECT * FROM users WHERE id = ${userId}
`;

// Transaction example
const result = await db.transaction(async (tx) => {
  await tx.query("INSERT INTO users (name) VALUES ($1)", ["Alice"]);
  await tx.query("INSERT INTO posts (user_id, title) VALUES ($1, $2)", [1, "Hello"]);
  return tx.query("SELECT * FROM users");
});

// Notification system
const unlisten = await db.listen("user_updates", (payload) => {
  console.log("User updated:", payload);
});

// Cleanup
await unlisten();
await db.close();