pg-embedded
Version:
Embedded PostgreSQL database for Node.js - Easy setup, high performance, TypeScript support
1,592 lines (1,563 loc) • 70.1 kB
TypeScript
/* auto-generated by NAPI-RS */
/* eslint-disable */
/** Connection information structure */
export declare class ConnectionInfo {
/** Host address */
host: string
/** Port number */
port: number
/** Username */
username: string
/** Password */
password: string
/** Database name */
databaseName: string
/** Connection string */
connectionString: string
/** Generate a safe connection string without password (for logging) */
safeConnectionString(): string
/** Generate JDBC format connection string */
jdbcUrl(): string
}
/**
* A tool for taking base backups of a running PostgreSQL cluster.
* This class provides an interface to the `pg_basebackup` command-line utility.
*
* @example
* ```typescript
* import { PgBasebackupTool, PgBasebackupFormat, PgBasebackupWalMethod } from 'pg-embedded';
*
* const backup = new PgBasebackupTool({
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* password: 'password',
* },
* programDir: '/path/to/postgres/bin',
* config: {
* pgdata: './backup_dir',
* format: PgBasebackupFormat.Plain,
* walMethod: PgBasebackupWalMethod.Fetch,
* }
* });
*
* const result = await backup.execute();
* if (result.exitCode === 0) {
* console.log('Base backup completed successfully.');
* } else {
* console.error(`Backup failed with error: ${result.stderr}`);
* }
* ```
*/
export declare class PgBasebackupTool {
/**
* Creates a new `PgBasebackupTool` instance with complete options.
* @param options - The configuration options for `pg_basebackup`.
*/
constructor(options: PgBasebackupOptions)
/**
* Creates a PgBasebackupTool from connection info and basebackup-specific config.
*
* This is the preferred method when using with PostgresInstance,
* as it separates connection concerns from tool-specific configuration.
*
* @param connection - Database connection configuration
* @param program_dir - Directory containing the pg_basebackup executable
* @param config - Pg_basebackup-specific configuration options (including pgdata)
* @returns A new PgBasebackupTool instance
*
* @example
* ```typescript
* import { PgBasebackupTool, PgBasebackupFormat, PgBasebackupWalMethod } from 'pg-embedded';
*
* const backupTool = PgBasebackupTool.fromConnection(
* instance.connectionInfo,
* instance.programDir + '/bin',
* {
* pgdata: './backup_directory',
* format: PgBasebackupFormat.Plain,
* walMethod: PgBasebackupWalMethod.Fetch,
* verbose: true
* }
* );
* ```
*/
static fromConnection(connection: ConnectionConfig, programDir: string, config: PgBasebackupConfig): PgBasebackupTool
/**
* Executes the `pg_basebackup` command.
*
* The backup will be written to the directory specified in the `pgdata` option.
*
* @returns A promise that resolves with the result of the command execution.
*/
execute(): Promise<ToolResult>
}
/**
* A tool for creating a dump of all databases in a PostgreSQL cluster.
*
* This class provides an interface to the `pg_dumpall` command-line utility.
*
* @example
* ```typescript
* import { PgDumpallTool } from 'pg-embedded';
*
* const dumpall = new PgDumpallTool({
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* password: 'password',
* },
* programDir: '/path/to/postgres/bin',
* config: {
* file: 'fulldump.sql',
* }
* });
*
* const result = await dumpall.execute();
* if (result.exitCode === 0) {
* console.log('Dump completed successfully.');
* } else {
* console.error(`Dump failed with error: ${result.stderr}`);
* }
* ```
*/
export declare class PgDumpallTool {
/**
* Creates a new `PgDumpallTool` instance with complete options.
* @param options - The configuration options for `pg_dumpall`.
*/
constructor(options: PgDumpallOptions)
/**
* Creates a PgDumpallTool from connection info and dumpall-specific config.
*
* This is the preferred method when using with PostgresInstance,
* as it separates connection concerns from tool-specific configuration.
*
* @param connection - Database connection configuration
* @param program_dir - Directory containing the pg_dumpall executable
* @param config - Pg_dumpall-specific configuration options
* @returns A new PgDumpallTool instance
*
* @example
* ```typescript
* const dumpallTool = PgDumpallTool.fromConnection(
* instance.connectionInfo,
* instance.programDir + '/bin',
* {
* globalsOnly: true,
* clean: true,
* file: './globals.sql'
* }
* );
* ```
*/
static fromConnection(connection: ConnectionConfig, programDir: string, config: PgDumpallConfig): PgDumpallTool
/**
* Executes the `pg_dumpall` command and returns the output as a string.
*
* This method is useful for capturing the dump output directly, for example,
* to process it in memory or send it over a network stream.
*
* @returns A promise that resolves with the result of the command execution.
* The dump content will be available in the `stdout` property of the result.
*/
executeToString(): Promise<ToolResult>
/**
* Executes the `pg_dumpall` command.
*
* If the `file` option is specified in the constructor, the dump will be written to that file.
* Otherwise, the dump output will be available in the `stdout` property of the returned result.
*
* @returns A promise that resolves with the result of the command execution.
*/
execute(): Promise<ToolResult>
}
/**
* PostgreSQL database backup tool using pg_dump.
*
* This class provides a TypeScript interface for creating database backups using PostgreSQL's
* pg_dump utility. It supports all major pg_dump options and can output to files or return
* the dump as a string.
*
* @example Basic usage (SQL format)
* ```typescript
* import { PgDumpTool, PgDumpFormat } from 'pg-embedded';
*
* const dumpTool = new PgDumpTool({
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* password: 'password',
* database: 'mydb'
* },
* programDir: '/home/postgresql/17.5.0/bin',
* config: {
* format: PgDumpFormat.Plain
* }
* });
*
* const result = await dumpTool.execute();
* if (result.exitCode === 0) {
* console.log('Database dump:', result.stdout);
* }
* ```
*/
export declare class PgDumpTool {
/**
* Creates a new PgDumpTool instance with complete options.
*
* @param options - Configuration options for the pg_dump operation
* @returns A new PgDumpTool instance ready to execute dumps
*
* @example
* ```typescript
* import { PgDumpTool, PgDumpFormat } from 'pg-embedded';
*
* const dumpTool = new PgDumpTool({
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* password: 'password',
* database: 'mydb'
* },
* programDir: '/home/postgresql/17.5.0/bin',
* config: {
* format: PgDumpFormat.Custom,
* file: './backup.dump'
* }
* });
* ```
*/
constructor(options: PgDumpOptions)
/**
* Creates a PgDumpTool from connection info and dump-specific config.
*
* This is the preferred method when using with PostgresInstance,
* as it separates connection concerns from tool-specific configuration.
*
* @param connection - Database connection configuration
* @param program_dir - Directory containing the pg_dump executable
* @param config - Pg_dump-specific configuration options
* @returns A new PgDumpTool instance
*
* @example
* ```typescript
* import { PgDumpTool, PgDumpFormat } from 'pg-embedded';
*
* const dumpTool = PgDumpTool.fromConnection(
* instance.connectionInfo,
* instance.programDir + '/bin',
* {
* format: PgDumpFormat.Custom,
* file: './backup.dump',
* clean: true
* }
* );
* ```
*/
static fromConnection(connection: ConnectionConfig, programDir: string, config: PgDumpConfig): PgDumpTool
/**
* Executes the pg_dump command and returns the backup content as a string.
*
* This method forces the output to stdout, ignoring the `file` option if it was set.
* It is a convenient way to get the dump content directly into a variable.
*
* @returns Promise<ToolResult> containing exit code, stdout (the dump content), and stderr.
* @throws Error if the command fails to execute or if there are configuration issues.
*
* @example
* ```typescript
* import { PgDumpTool, PgDumpFormat } from 'pg-embedded';
*
* const dumpTool = new PgDumpTool({
* connection: { host: 'localhost', port: 5432, username: 'postgres' },
* programDir: '/home/postgresql/17.5.0/bin',
* config: {
* format: PgDumpFormat.Plain
* }
* });
* const result = await dumpTool.executeToString();
* if (result.exitCode === 0) {
* console.log('Dump successful. SQL content:', result.stdout);
* } else {
* console.error('Dump failed:', result.stderr);
* }
* ```
*/
executeToString(): Promise<ToolResult>
/**
* Executes the pg_dump command with the configured options.
*
* This method runs the pg_dump utility and returns the result. The behavior depends on
* whether a file output path was specified:
* - If `file` option is set: writes dump to the specified file, stdout will be empty
* - If `file` option is not set: returns dump content in the stdout field
*
* @returns Promise<ToolResult> containing exit code, stdout, and stderr
* @throws Error if the command fails to execute or if there are configuration issues
*
* @example Dump to string
* ```typescript
* const result = await dumpTool.execute();
* if (result.exitCode === 0) {
* console.log('Dump successful');
* console.log('SQL content:', result.stdout);
* } else {
* console.error('Dump failed:', result.stderr);
* }
* ```
*/
execute(): Promise<ToolResult>
}
/**
* A tool for checking the connection status of a PostgreSQL server.
*
* This class provides a TypeScript interface for checking PostgreSQL server availability
* using the pg_isready utility. Both `connection` and `programDir` parameters are required.
*
* @example Basic connection check
* ```typescript
* import { PgIsReadyTool } from 'pg-embedded';
*
* const readyTool = new PgIsReadyTool({
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* password: 'password',
* database: 'mydb'
* },
* programDir: '/home/postgresql/17.5.0/bin',
* config: {}
* });
*
* const isReady = await readyTool.check();
* console.log('Server is ready:', isReady);
* ```
*
* @example Detailed status check
* ```typescript
* const result = await readyTool.execute();
* if (result.exitCode === 0) {
* console.log('Server is accepting connections');
* } else {
* console.log('Server is not ready:', result.stderr);
* }
* ```
*/
export declare class PgIsReadyTool {
/**
* Creates a new `PgIsReadyTool` instance with complete options.
*
* @param options - Configuration options for the pg_isready operation (connection and programDir are required)
* @returns A new PgIsReadyTool instance ready to check server status
*
* @example
* ```typescript
* const readyTool = new PgIsReadyTool({
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* password: 'password',
* database: 'mydb'
* },
* programDir: '/home/postgresql/17.5.0/bin',
* config: {
* timeout: 10,
* silent: false
* }
* });
* ```
*/
constructor(options: PgIsReadyOptions)
/**
* Creates a PgIsReadyTool from connection info and isready-specific config.
*
* This is the preferred method when using with PostgresInstance,
* as it separates connection concerns from tool-specific configuration.
*
* @param connection - Database connection configuration
* @param program_dir - Directory containing the pg_isready executable
* @param config - Pg_isready-specific configuration options
* @returns A new PgIsReadyTool instance
*
* @example
* ```typescript
* const readyTool = PgIsReadyTool.fromConnection(
* instance.connectionInfo,
* instance.programDir + '/bin',
* {
* timeout: 30,
* silent: true
* }
* );
* ```
*/
static fromConnection(connection: ConnectionConfig, programDir: string, config: PgIsReadyConfig): PgIsReadyTool
/** Performs a quick check to see if the server is running. */
check(): Promise<boolean>
/** Executes `pg_isready` and returns the detailed result. */
execute(): Promise<ToolResult>
}
/** A tool for restoring a PostgreSQL database from an archive created by `pg_dump`. */
export declare class PgRestoreTool {
/**
* Creates a new `PgRestoreTool` instance with complete options.
* @param {PgRestoreOptions} options - The options for the `pg_restore` tool.
* @returns {PgRestoreTool} A new `PgRestoreTool` instance.
*/
constructor(options: PgRestoreOptions)
/**
* Creates a PgRestoreTool from connection info and restore-specific config.
*
* This is the preferred method when using with PostgresInstance,
* as it separates connection concerns from tool-specific configuration.
*
* @param connection - Database connection configuration
* @param program_dir - Directory containing the pg_restore executable
* @param config - Pg_restore-specific configuration options (including file)
* @returns A new PgRestoreTool instance
*
* @example
* ```typescript
* import { PgRestoreTool, PgRestoreFormat } from 'pg-embedded';
*
* const restoreTool = PgRestoreTool.fromConnection(
* instance.connectionInfo,
* instance.programDir + '/bin',
* {
* file: './backup.dump',
* format: PgRestoreFormat.Custom,
* clean: true,
* noOwner: true
* }
* );
* ```
*/
static fromConnection(connection: ConnectionConfig, programDir: string, config: PgRestoreConfig): PgRestoreTool
/**
* Executes the pg_restore command with the configured options.
*
* This method runs the pg_restore utility and restores a database from an archive.
*
* @returns {Promise<ToolResult>} A promise that resolves with the result of the command,
* including exit code, stdout, and stderr.
* @throws {Error} If the command fails to execute or if there are configuration issues.
*
* @example
* ```typescript
* import { PgRestoreTool, PgRestoreFormat } from 'pg-embedded';
*
* const restoreTool = new PgRestoreTool({
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* database: 'restored_db'
* },
* programDir: '/home/postgresql/17.5.0/bin',
* config: {
* file: './backup.dump',
* format: PgRestoreFormat.Custom,
* clean: true,
* create: true
* }
* });
*
* const result = await restoreTool.execute();
* if (result.exitCode === 0) {
* console.log('Database restored successfully.');
* } else {
* console.error('Restore failed:', result.stderr);
* }
* ```
*/
execute(): Promise<ToolResult>
}
/**
* PostgreSQL data directory synchronization tool using pg_rewind.
*
* This class provides a TypeScript interface for synchronizing PostgreSQL data directories
* using PostgreSQL's pg_rewind utility. It's commonly used in failover scenarios to rewind
* a former primary server so it can become a standby server again.
*
* pg_rewind works by finding the point where the target and source servers' timelines
* diverged, then replaying changes from the source to bring the target back in sync.
* This requires that the target server has WAL logging enabled and either data checksums
* or wal_log_hints enabled.
*
* @example Basic rewind operation
* ```typescript
* import { PgRewindTool } from 'pg-embedded';
*
* const rewindTool = new PgRewindTool({
* programDir: '/home/postgresql/17.5.0/bin',
* targetPgdata: './former_primary_data',
* sourceServer: 'host=localhost port=5432 user=postgres password=secret',
* progress: true,
* dryRun: false
* });
*
* const result = await rewindTool.execute();
* if (result.exitCode === 0) {
* console.log('Rewind completed successfully');
* } else {
* console.error('Rewind failed:', result.stderr);
* }
* ```
*
* @example Simplified usage with auto-configuration
* ```typescript
* const rewindTool = new PgRewindTool({
* connection: targetConnectionInfo,
* programDir: '/home/postgresql/17.5.0/bin',
* targetPgdata: './target_data_dir',
* sourceInstance: sourceConnectionInfo,
* autoConfigureWal: true,
* progress: true
* });
*
* const result = await rewindTool.execute();
* ```
*
* @example Dry run for validation
* ```typescript
* const rewindTool = new PgRewindTool({
* programDir: '/home/postgresql/17.5.0/bin',
* targetPgdata: './target_data_dir',
* sourceServer: 'host=source-server port=5432 user=postgres',
* dryRun: true,
* debug: true
* });
*
* const result = await rewindTool.execute();
* console.log('Dry run output:', result.stdout);
* ```
*/
export declare class PgRewindTool {
/**
* Creates a new PgRewindTool instance with complete options.
*
* @param options - Configuration options for the pg_rewind operation (programDir and targetPgdata are required)
* @returns A new PgRewindTool instance ready to execute rewind operations
*
* @example
* ```typescript
* const rewindTool = new PgRewindTool({
* connection: targetConnectionInfo,
* programDir: '/home/postgresql/17.5.0/bin',
* targetPgdata: './target_data_dir',
* config: {
* sourceServer: 'host=localhost port=5432 user=postgres',
* progress: true
* }
* });
* ```
*/
constructor(options: PgRewindOptions)
/**
* Creates a PgRewindTool from connection info and rewind-specific config.
*
* This is the preferred method when using with PostgresInstance,
* as it separates connection concerns from tool-specific configuration.
*
* @param connection - Database connection configuration for target server
* @param program_dir - Directory containing the pg_rewind executable
* @param config - Pg_rewind-specific configuration options (including targetPgdata)
* @returns A new PgRewindTool instance
*
* @example
* ```typescript
* const rewindTool = PgRewindTool.fromConnection(
* targetInstance.connectionInfo,
* targetInstance.programDir + '/bin',
* {
* targetPgdata: './target_data_dir',
* sourceInstance: sourceInstance.connectionInfo,
* progress: true,
* autoConfigureWal: true
* }
* );
* ```
*/
static fromConnection(connection: ConnectionConfig, programDir: string, config: PgRewindConfig): PgRewindTool
/**
* Executes the pg_rewind command with the configured options.
*
* This method runs the pg_rewind utility to synchronize the target data directory
* with the source. If autoConfigureWal is enabled, it will first configure all
* necessary WAL settings automatically.
*
* The target PostgreSQL server must be stopped before running this command.
* The source server should be running and accessible.
*
* @returns Promise<ToolResult> containing exit code, stdout, and stderr
* @throws Error if the command fails to execute or if there are configuration issues
*
* @example Basic execution
* ```typescript
* const result = await rewindTool.execute();
* if (result.exitCode === 0) {
* console.log('Rewind completed successfully');
* console.log('Output:', result.stdout);
* } else {
* console.error('Rewind failed:', result.stderr);
* }
* ```
*
* @example With error handling
* ```typescript
* try {
* const result = await rewindTool.execute();
* if (result.exitCode === 0) {
* console.log('Target server successfully rewound');
* } else {
* console.error('pg_rewind failed with exit code:', result.exitCode);
* console.error('Error details:', result.stderr);
* }
* } catch (error) {
* console.error('Failed to execute pg_rewind:', error.message);
* }
* ```
*/
execute(): Promise<ToolResult>
}
/**
* PostgreSQL embedded instance manager
*
* This class provides a high-level interface for managing embedded PostgreSQL instances.
* It supports both synchronous and asynchronous operations, automatic resource management,
* and connection caching for optimal performance.
*
* @example
* ```typescript
* import { PostgresInstance } from 'pg-embedded';
*
* const instance = new PostgresInstance({
* port: 5432,
* username: 'postgres',
* password: 'password'
* });
*
* await instance.start();
* await instance.createDatabase('mydb');
* await instance.stop();
* ```
*/
export declare class PostgresInstance {
/**
* Creates a new PostgreSQL instance with the specified settings
*
* @param settings - Configuration settings for the PostgreSQL instance
* @returns A new PostgresInstance
*
* @example
* ```typescript
* const instance = new PostgresInstance({
* port: 5432,
* username: 'postgres',
* password: 'password',
* persistent: false
* });
* ```
*/
constructor(settings?: PostgresSettings | undefined | null)
/**
* Gets the unique instance ID
*
* @returns The unique identifier for this PostgreSQL instance
*/
get instanceId(): string
/**
* Gets the configuration hash for this instance
*
* This hash is used internally for caching and can be useful for debugging.
*
* @returns A string hash of the instance configuration
*/
getConfigHash(): string
/** Gets the directory where the PostgreSQL binaries are located. */
get programDir(): string
/** Gets the directory where the PostgreSQL data is stored. */
get dataDir(): string
/**
* # Safety
* Promotes a standby server to a primary server.
*
* @returns Promise that resolves when the server is promoted.
* @throws Error if promotion fails.
*/
promote(): Promise<void>
/**
* Gets the current state of the PostgreSQL instance
*
* @returns The current instance state (Stopped, Starting, Running, or Stopping)
*/
get state(): InstanceState
/**
* Gets the connection information for the PostgreSQL instance
*
* This method returns cached connection information when available for better performance.
* The cache is automatically invalidated after 5 minutes.
*
* @returns Connection information including host, port, username, and connection string
* @throws Error if the instance is not running
*/
get connectionInfo(): ConnectionInfo
/**
* Checks if the PostgreSQL instance is healthy and running
*
* @returns true if the instance is running and healthy, false otherwise
*/
isHealthy(): boolean
/**
* # Safety
* Sets up the PostgreSQL instance asynchronously
*
* This method initializes the PostgreSQL instance but does not start it.
* It's automatically called by start() if needed.
*
* @returns Promise that resolves when setup is complete
* @throws Error if setup fails
*/
setup(): Promise<void>
/**
* # Safety
* Starts the PostgreSQL instance asynchronously
*
* This method starts the PostgreSQL server and makes it ready to accept connections.
* It includes automatic setup if the instance hasn't been set up yet.
*
* @returns Promise that resolves when the instance is started and ready
* @throws Error if the instance is already running or if startup fails
*
* @example
* ```typescript
* await instance.start();
* console.log('PostgreSQL is ready!');
* ```
*/
start(initialize?: boolean | undefined | null): Promise<void>
/**
* # Safety
* Stops the PostgreSQL instance asynchronously
*
* This method gracefully shuts down the PostgreSQL server.
*
* @returns Promise that resolves when the instance is stopped
* @throws Error if the instance is already stopped or if stopping fails
*
* @example
* ```typescript
* await instance.stop();
* console.log('PostgreSQL stopped');
* ```
*/
stop(): Promise<void>
/**
* # Safety
* Creates a new database asynchronously
*
* @param name - The name of the database to create
* @returns Promise that resolves when the database is created
* @throws Error if the instance is not running or if database creation fails
*
* @example
* ```typescript
* await instance.createDatabase('myapp');
* ```
*/
createDatabase(name: string): Promise<void>
/**
* # Safety
* Creates a database dump using pg_dump
*
* This method executes pg_dump to create a backup of a PostgreSQL database.
* The instance must be running before calling this method.
*
* @param options - Configuration options for pg_dump
* @param database_name - Optional name of the database to dump (defaults to 'postgres')
* @returns Promise that resolves with the execution result when the dump is complete
* @throws Error if the instance is not running or if the dump fails
*
* @example
* ```typescript
* const result = await instance.createDump({
* file: '/path/to/backup.sql',
* format: PgDumpFormat.Plain,
* create: true
* }, 'mydb');
* console.log(result.stdout);
* ```
*/
createDump(options: PgDumpConfig, databaseName?: string | undefined | null): Promise<ToolResult>
/**
* # Safety
* Creates a base backup using pg_basebackup
*
* This method executes pg_basebackup to create a binary backup of a PostgreSQL
* database cluster. The backup can be used for point-in-time recovery or to
* set up streaming replication. The instance must be running before calling this method.
*
* @param options - Configuration options for pg_basebackup
* @param database_name - Optional name of the database to connect to (defaults to 'postgres')
* @returns Promise that resolves with the execution result when the backup is complete
* @throws Error if the instance is not running or if the backup fails
*
* @example
* ```typescript
* const result = await instance.createBaseBackup({
* pgdata: '/path/to/backup',
* format: PgBasebackupFormat.Tar,
* walMethod: PgBasebackupWalMethod.Stream
* });
* console.log(result.stdout);
* ```
*/
createBaseBackup(options: PgBasebackupConfig, databaseName?: string | undefined | null): Promise<ToolResult>
/**
* # Safety
* Restores a database from a backup using pg_restore
*
* This method executes pg_restore to restore a PostgreSQL database from a backup
* file created by pg_dump. The instance must be running before calling this method.
*
* @param options - Configuration options for pg_restore
* @param database_name - Optional name of the database to restore to (defaults to 'postgres')
* @returns Promise that resolves with the execution result when the restore is complete
* @throws Error if the instance is not running or if the restore fails
*
* @example
* ```typescript
* const result = await instance.createRestore({
* file: '/path/to/backup.dump',
* format: PgRestoreFormat.Custom,
* clean: true
* }, 'mydb');
* console.log(result.stdout);
* ```
*/
createRestore(options: PgRestoreConfig, databaseName?: string | undefined | null): Promise<ToolResult>
/**
* # Safety
* Rewinds a PostgreSQL cluster using pg_rewind
*
* This method executes pg_rewind to synchronize a PostgreSQL cluster with another
* copy of the same cluster, after the clusters' timelines have diverged.
* The instance must be running before calling this method.
*
* @param options - Configuration options for pg_rewind
* @param database_name - Optional name of the database to connect to (defaults to 'postgres')
* @returns Promise that resolves with the execution result when the rewind is complete
* @throws Error if the instance is not running or if the rewind fails
*
* @example
* ```typescript
* const result = await instance.createRewind({
* targetPgdata: '/path/to/target/data',
* sourceServer: 'host=source_host port=5432'
* });
* console.log(result.stdout);
* ```
*/
createRewind(options: PgRewindConfig, databaseName?: string | undefined | null): Promise<ToolResult>
/**
* # Safety
* Creates a dump of all databases using pg_dumpall
*
* This method executes pg_dumpall to create a backup of all databases in the
* PostgreSQL cluster, including global objects like roles and tablespaces.
* The instance must be running before calling this method.
*
* @param options - Configuration options for pg_dumpall
* @returns Promise that resolves with the execution result when the dump is complete
* @throws Error if the instance is not running or if the dump fails
*
* @example
* ```typescript
* const result = await instance.createDumpall({
* file: '/path/to/cluster_backup.sql',
* rolesOnly: false,
* clean: true
* });
* console.log(result.stdout);
* ```
*/
createDumpall(options: PgDumpallConfig): Promise<ToolResult>
/**
* # Safety
* Executes SQL commands using psql
*
* This method executes SQL commands directly using the psql command-line tool.
* The instance must be running before calling this method.
*
* @param sql - The SQL command(s) to execute
* @param options - Configuration options for psql
* @param database_name - Optional database name to connect to (defaults to 'postgres')
* @returns Promise that resolves with the execution result
* @throws Error if the instance is not running or if the execution fails
*
* @example
* ```typescript
* const result = await instance.executeSql('SELECT version();', {});
* console.log(result.stdout);
* ```
*/
executeSql(sql: string, options: PsqlConfig, databaseName?: string | undefined | null): Promise<ToolResult>
/**
* # Safety
* Executes SQL commands from a file using psql
*
* This method executes SQL commands from a file using the psql command-line tool.
* The instance must be running before calling this method.
*
* @param file_path - Path to the SQL file to execute
* @param options - Configuration options for psql
* @param database_name - Optional database name to connect to (defaults to 'postgres')
* @returns Promise that resolves with the execution result
* @throws Error if the instance is not running, if the file doesn't exist, or if the execution fails
*
* @example
* ```typescript
* const result = await instance.executeFile('/path/to/script.sql', {}, 'mydb');
* console.log(result.stdout);
* ```
*/
executeFile(filePath: string, options: PsqlConfig, databaseName?: string | undefined | null): Promise<ToolResult>
/**
* # Safety
* Drops (deletes) a database asynchronously
*
* @param name - The name of the database to drop
* @returns Promise that resolves when the database is dropped
* @throws Error if the instance is not running or if database deletion fails
*
* @example
* ```typescript
* await instance.dropDatabase('myapp');
* ```
*/
dropDatabase(name: string): Promise<void>
/**
* Checks if a database exists asynchronously
*
* @param name - The name of the database to check
* @returns Promise that resolves to true if the database exists, false otherwise
* @throws Error if the instance is not running or if the check fails
*
* @example
* ```typescript
* const exists = await instance.databaseExists('myapp');
* if (exists) {
* console.log('Database exists');
* }
* ```
*/
databaseExists(name: string): Promise<boolean>
/**
* # Safety
* Starts the PostgreSQL instance asynchronously with a timeout
*
* @param timeout_seconds - Maximum time to wait for startup in seconds
* @returns Promise that resolves when the instance is started and ready
* @throws Error if the instance is already running, if startup fails, or if timeout is exceeded
*
* @example
* ```typescript
* await instance.startWithTimeout(30); // 30 second timeout
* ```
*/
startWithTimeout(timeoutSeconds: number): Promise<void>
/**
* # Safety
* Stops the PostgreSQL instance asynchronously with a timeout
*
* @param timeout_seconds - Maximum time to wait for shutdown in seconds
* @returns Promise that resolves when the instance is stopped
* @throws Error if the instance is already stopped, if stopping fails, or if timeout is exceeded
*
* @example
* ```typescript
* await instance.stopWithTimeout(10); // 10 second timeout
* ```
*/
stopWithTimeout(timeoutSeconds: number): Promise<void>
/**
* Gets the startup time of the PostgreSQL instance in seconds
*
* This method returns the time it took for the last successful start operation.
*
* @returns The startup time in seconds, or null if the instance hasn't been started yet
*
* @example
* ```typescript
* await instance.start();
* const startupTime = instance.getStartupTime();
* console.log(`Started in ${startupTime} seconds`);
* ```
*/
getStartupTime(): number | null
/**
* Clears the connection information cache
*
* This forces the next call to connectionInfo to regenerate the connection information.
*
* @returns void
*/
clearConnectionCache(): void
/**
* Checks if the connection information cache is valid
*
* The cache is considered valid if it exists and is less than 5 minutes old.
*
* @returns true if the cache is valid, false otherwise
*/
isConnectionCacheValid(): boolean
/**
* Gets the PostgreSQL version used by this instance
*
* @returns PostgreSQL version string (e.g., "15.4")
*
* @example
* ```typescript
* const version = instance.getPostgreSQLVersion();
* console.log(`Using PostgreSQL ${version}`);
* ```
*/
getPostgreSqlVersion(): string
/**
* # Safety
* Manually cleans up all resources associated with this instance
*
* This method stops the PostgreSQL instance (if running) and cleans up all resources.
* It's automatically called when the instance is dropped, but can be called manually
* for immediate cleanup.
*
* @returns void
*
* @example
* ```typescript
* await instance.cleanup();
* console.log('Resources cleaned up');
* ```
*/
cleanup(): Promise<void>
}
/**
* A tool for executing SQL commands and scripts using the `psql` interactive terminal.
*
* This class provides a TypeScript interface for running SQL commands and scripts using
* PostgreSQL's psql utility. Both `connection` and `programDir` parameters are required.
*
* @example Basic SQL command execution
* ```typescript
* import { PsqlTool } from 'pg-embedded';
*
* const psqlTool = new PsqlTool({
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* password: 'password',
* database: 'mydb'
* },
* programDir: '/home/postgresql/17.5.0/bin',
* config: {}
* });
*
* const result = await psqlTool.executeCommand('SELECT * FROM users;');
* if (result.exitCode === 0) {
* console.log('Query result:', result.stdout);
* }
* ```
*
* @example Execute SQL file
* ```typescript
* const result = await psqlTool.executeFile('./schema.sql');
* if (result.exitCode === 0) {
* console.log('Script executed successfully');
* }
* ```
*/
export declare class PsqlTool {
/**
* Creates a new instance of the `PsqlTool` with complete options.
*
* @param options - Configuration options for the psql operation (connection and programDir are required)
* @returns A new PsqlTool instance ready to execute SQL commands
*
* @example
* ```typescript
* const psqlTool = new PsqlTool({
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* password: 'password',
* database: 'mydb'
* },
* programDir: '/home/postgresql/17.5.0/bin',
* config: {
* flags: ['--csv', '--tuples-only']
* }
* });
* ```
*/
constructor(options: PsqlOptions)
/**
* Creates a PsqlTool from connection info and psql-specific config.
*
* This is the preferred method when using with PostgresInstance,
* as it separates connection concerns from tool-specific configuration.
*
* @param connection - Database connection configuration
* @param program_dir - Directory containing the psql executable
* @param config - Psql-specific configuration options
* @returns A new PsqlTool instance
*
* @example
* ```typescript
* const psqlTool = PsqlTool.fromConnection(
* instance.connectionInfo,
* instance.programDir + '/bin',
* {
* csv: true,
* tuplesOnly: true,
* variable: ['MY_VAR', 'value']
* }
* );
* ```
*/
static fromConnection(connection: ConnectionConfig, programDir: string, config: PsqlConfig): PsqlTool
/**
* Executes a given SQL command string.
*
* This method allows reusing a `PsqlTool` instance with the same connection settings
* to run multiple different commands.
*
* @param command_str - The SQL command string to execute.
* @returns A promise that resolves to a `ToolResult` object.
* @throws An error if the `psql` command fails to execute.
*
* @example
* ```typescript
* const result = await psql.executeCommand('SELECT version();');
* console.log(result.stdout);
* ```
*/
executeCommand(commandStr: string): Promise<ToolResult>
/**
* Executes SQL commands from a given file.
*
* This method allows reusing a `PsqlTool` instance to run multiple different SQL script files.
*
* @param file_path - The path to the file containing SQL commands.
* @returns A promise that resolves to a `ToolResult` object.
* @throws An error if the `psql` command fails to execute.
*
* @example
* ```typescript
* const result = await psql.executeFile('/path/to/my/script.sql');
* console.log(result.stdout);
* ```
*/
executeFile(filePath: string): Promise<ToolResult>
}
/** Build information */
export interface BuildInfo {
/** Target platform (e.g., "x86_64-apple-darwin") */
target: string
/** Build profile (debug or release) */
profile: string
/** Rust compiler version used for build */
rustcVersion: string
/** Build timestamp */
buildTimestamp: string
}
/** Configuration for connecting to a PostgreSQL server. */
export interface ConnectionConfig {
/** The host of the PostgreSQL server. */
host?: string
/** The port of the PostgreSQL server. */
port?: number
/** The username to connect with. */
username?: string
/** The password to connect with. */
password?: string
/** The database to connect to. */
database?: string
}
/**
* Gets the package version of pg-embedded
*
* @returns Package version string (e.g., "1.0.0")
*
* @example
* ```typescript
* import { getPackageVersion } from 'pg-embedded';
*
* const version = getPackageVersion();
* console.log(`pg-embedded version: ${version}`);
* ```
*/
export declare function getPackageVersion(): string
/**
* Gets the version of the embedded PostgreSQL binary
*
* @returns PostgreSQL version string (e.g., "15.4")
*
* @example
* ```typescript
* import { getPostgreSQLVersion } from 'pg-embedded';
*
* const pgVersion = getPostgreSQLVersion();
* console.log(`Using PostgreSQL ${pgVersion}`);
* ```
*/
export declare function getPostgreSqlVersion(): string
/**
* Gets comprehensive version information about pg-embedded and PostgreSQL
*
* This function returns detailed version information including:
* - pg-embedded package version
* - Embedded PostgreSQL version
* - Build information
*
* @returns Version information object
*
* @example
* ```typescript
* import { getVersionInfo } from 'pg-embedded';
*
* const versionInfo = getVersionInfo();
* console.log(`Package version: ${versionInfo.packageVersion}`);
* console.log(`PostgreSQL version: ${versionInfo.postgresqlVersion}`);
* console.log(`Built for: ${versionInfo.buildInfo.target}`);
* ```
*/
export declare function getVersionInfo(): VersionInfo
/** Initialize logger */
export declare function initLogger(level?: LogLevel | undefined | null): void
/** PostgreSQL instance state enumeration */
export declare const enum InstanceState {
/** Stopped */
Stopped = 0,
/** Starting */
Starting = 1,
/** Running */
Running = 2,
/** Stopping */
Stopping = 3
}
/** Log debug message */
export declare function logDebug(message: string): void
/** Log error message */
export declare function logError(message: string): void
/** Log info message */
export declare function logInfo(message: string): void
/** Log level enumeration */
export declare const enum LogLevel {
/** Error level */
Error = 0,
/** Warning level */
Warn = 1,
/** Information level */
Info = 2,
/** Debug level */
Debug = 3,
/** Trace level */
Trace = 4
}
/** Log trace message */
export declare function logTrace(message: string): void
/** Log warning message */
export declare function logWarn(message: string): void
/**
* Checkpoint mode options for pg_basebackup.
*
* Specifies how the checkpoint should be performed.
*/
export declare const enum PgBasebackupCheckpoint {
/** Fast checkpoint (may cause I/O spike) */
Fast = 0,
/** Spread checkpoint over time (default) */
Spread = 1
}
/**
* Configuration for pg_basebackup-specific options, separate from connection settings.
*
* This contains only the pg_basebackup tool-specific configuration options,
* allowing for clean separation when used with PostgresInstance.
*/
export interface PgBasebackupConfig {
/** Generic tool options like silent mode and timeout. */
tool?: ToolOptions
/** Specifies the output directory for the backup. */
pgdata: string
/** The output format for the backup. */
format?: PgBasebackupFormat
/**
* Enable verbose mode.
* Corresponds to the `--verbose` command-line argument.
*/
verbose?: boolean
/**
* Set checkpoint mode.
* Corresponds to the `--checkpoint` command-line argument.
*/
checkpoint?: PgBasebackupCheckpoint
/**
* Create a temporary replication slot.
* Corresponds to the `--create-slot` command-line argument.
*/
createSlot?: boolean
/**
* Maximum transfer rate of the data directory.
* Corresponds to the `--max-rate` command-line argument.
*/
maxRate?: string
/**
* Method for including WAL files.
* Corresponds to the `--wal-method` command-line argument.
*/
walMethod?: PgBasebackupWalMethod
}
/**
* PostgreSQL base backup format options.
*
* Specifies the output format for the base backup.
*/
export declare const enum PgBasebackupFormat {
/** Plain format - creates a directory with database files */
Plain = 0,
/** Tar format - creates tar archive files */
Tar = 1
}
/**
* Complete options for configuring the `pg_basebackup` command.
*
* This interface corresponds to the command-line arguments of the `pg_basebackup` utility.
* For use with PostgresInstance, consider using PgBasebackupConfig instead.
*
* @example
* ```typescript
* import { PgBasebackupTool, PgBasebackupFormat, PgBasebackupWalMethod } from 'pg-embedded';
*
* const basebackupOptions: PgBasebackupOptions = {
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* password: 'password',
* },
* programDir: '/path/to/postgres/bin',
* config: {
* pgdata: './backup_dir',
* format: PgBasebackupFormat.Plain,
* walMethod: PgBasebackupWalMethod.Fetch,
* }
* };
* ```
*/
export interface PgBasebackupOptions {
/** Database connection parameters. */
connection: ConnectionConfig
/** The directory containing the `pg_basebackup` executable. */
programDir: string
/** Pg_basebackup-specific configuration options. */
config: PgBasebackupConfig
}
/**
* WAL method options for pg_basebackup.
*
* Specifies how WAL files should be handled during backup.
*/
export declare const enum PgBasebackupWalMethod {
/** Don't include WAL files */
None = 0,
/** Fetch WAL files at the end of backup */
Fetch = 1,
/** Stream WAL files during backup */
Stream = 2
}
/**
* Configuration for pg_dumpall-specific options, separate from connection settings.
*
* This contains only the pg_dumpall tool-specific configuration options,
* allowing for clean separation when used with PostgresInstance.
*/
export interface PgDumpallConfig {
/** Generic tool options like silent mode and timeout. */
tool?: ToolOptions
/**
* Specifies the output file for the dump. If not provided, the output is sent to standard output.
* Corresponds to the `--file` command-line argument.
*/
file?: string
/**
* Dump only global objects (roles and tablespaces), not databases.
* Corresponds to the `--globals-only` command-line argument.
*/
globalsOnly?: boolean
/**
* Dump only roles.
* Corresponds to the `--roles-only` command-line argument.
*/
rolesOnly?: boolean
/**
* Dump only tablespaces.
* Corresponds to the `--tablespaces-only` command-line argument.
*/
tablespacesOnly?: boolean
/**
* Enable verbose mode.
* Corresponds to the `--verbose` command-line argument.
*/
verbose?: boolean
/**
* Output commands to `DROP` objects before recreating them.
* Corresponds to the `--clean` command-line argument.
*/
clean?: boolean
/**
* Do not output commands to set object ownership.
* Corresponds to the `--no-owner` command-line argument.
*/
noOwner?: boolean
/**
* Do not dump privileges (GRANT/REVOKE commands).
* Corresponds to the `--no-privileges` command-line argument.
*/
noPrivileges?: boolean
}
/**
* Complete options for configuring the `pg_dumpall` command.
*
* This interface corresponds to the command-line arguments of the `pg_dumpall` utility.
* For use with PostgresInstance, consider using PgDumpallConfig instead.
*
* @example
* ```typescript
* const dumpallOptions: PgDumpallOptions = {
* connection: {
* host: 'localhost',
* port: 5432,
* username: 'postgres',
* password: 'password',
* },
* programDir: '/path/to/postgres/bin',
* config: {
* file: 'dump.sql',
* globalsOnly: true,
* }
* };
* ```
*/
export interface PgDumpallOptions {
/** Database connection parameters. */
connection: ConnectionConfig
/** The directory containing the `pg_dumpall` executable. */
programDir: string
/** Pg_dumpall-specific configuration options. */
config: PgDumpallConfig
}
/**
* Configuration for pg_dump-specific options, separate from connection settings.
*
* This contains only the pg_dump tool-specific configuration options,
* allowing for clean separation when used with PostgresInstance.
*/
export interface PgDumpConfig {
/** Generic tool options like silent mode and timeout. */
tool?: ToolOptions
/**
* Output file path. If not specified, output goes to stdout.
* Equivalent to pg_dump --file flag.
*/
file?: string
/**
* Output format for the dump.
* Default is Plain (SQL text format). Equivalent to pg_dump --format flag.
*/
format?: PgDumpFormat
/**
* Export only table data, excluding schema definitions.
* Equivalent to pg_dump --data-only flag.
*/
dataOnly?: boolean
/**
* Include DROP statements before CREATE statements in the output.
* Useful for recreating objects cleanly. Equivalent to pg_dump --clean flag.
*/
clean?: boolean
/**
* Include CREATE DATABASE statement in the dump output.
* Equivalent to pg_dump --create flag.
*/
create?: boolean
/**
* Export only schema definitions, excluding table data.
* Equivalent to pg_dump --schema-only flag.
*/
schemaOnly?: boolean
/**
* Do not output commands to set ownership of objects.
* Equivalent to pg_dump --no-owner flag.
*/
noOwner?: boolean
/**
* Do not dump access privileges (GRANT/REVOKE commands).
* Equivalent to pg_dump --no-privileges flag.
*/
noPrivileges?: boolean
/**
* Enable verbose output showing detailed progress information.
* Equivalent to pg_dump --verbose flag.
*/
verbose?: boolean
/**
* Export only the specified table and its dependencies.
* Equivalent to pg_dump --table flag.
*/
table?: string
/**
* Exclude the specified table from the dump.
* Equivalent to pg_dump --exclude-table flag.
*/
excludeTable?: string
/**
* Export only objects in the specified schema.
* Equivalent to pg_dump --schema flag.
*/
schema?: string
/**
* Exclude the specified schema from the dump.
* Equivalent to pg_dump --exclude-schema flag.
*/
excludeSchema?: string
/**
* Character encoding for the dump output (e.g., 'UTF8', 'LATIN1').
* Equivalent to pg_dump --encoding flag.
*/
encoding?: string
/**
* Number of parallel worker processes for dumping (custom format only).
* Equivalent to pg_dump --jobs flag.
*/
jobs?: number
/**
* Compression level (0-9) for compressed output formats.
* Higher values mean better compression but slower processing.
* Equivalent to pg_dump --compress flag.
*/
compression?: number
/**
* When used with `clean`, suppresses errors for non-existent objects.
* Equivalent to the pg_dump --if-exists flag.
*/
ifExists?: boolea