### Project Build and Dependency Installation Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md Commands to install project dependencies using pnpm and build the native module, which are prerequisites for running the examples. ```bash # Install dependencies pnpm install # Build the native module pnpm run build ``` -------------------------------- ### Simple JavaScript Example Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md A quick start example demonstrating basic pg-embedded instance creation, configuration, starting/stopping PostgreSQL, managing databases, accessing connection info, and cleanup. ```javascript import { PostgresInstance } from 'pg-embedded' const postgres = new PostgresInstance({ port: 5432, username: 'postgres', password: 'password', }) try { await postgres.start() // Use the database... await postgres.stop() } finally { await postgres.cleanup() } ``` -------------------------------- ### Basic Usage Pattern Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md Illustrates the fundamental pattern for initializing, starting, using, stopping, and cleaning up a pg-embedded PostgreSQL instance. ```javascript import { PostgresInstance } from 'pg-embedded' const postgres = new PostgresInstance({ port: 5432, username: 'postgres', password: 'password', }) try { await postgres.start() // Use the database... await postgres.stop() } finally { await postgres.cleanup() } ``` -------------------------------- ### Running Individual Examples Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md Bash commands to execute specific example scripts from the examples directory using Node.js. ```bash # Run simple example node examples/simple-example.js # Run async example node examples/async-example.js # Run testing example node examples/testing-example.js ``` -------------------------------- ### Running All Examples Sequentially Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md A bash script to iterate through all JavaScript files in the examples directory and run them sequentially using Node.js. ```bash # Run all examples sequentially for example in examples/*.js; do echo "Running $example..." node "$example" echo "---" done ``` -------------------------------- ### Quick Start with PostgresInstance Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Demonstrates the basic usage of the PostgresInstance class, including starting the server, creating/dropping databases, checking existence, accessing connection info, and cleaning up resources. ```typescript import { PostgresInstance } from 'pg-embedded' async function example() { // Create a new PostgreSQL instance const postgres = new PostgresInstance({ port: 5432, username: 'postgres', password: 'password', persistent: false, }) try { // Start the PostgreSQL server await postgres.start() console.log('PostgreSQL started successfully!') // Create a database await postgres.createDatabase('myapp') // Check if database exists const exists = await postgres.databaseExists('myapp') console.log(`Database exists: ${exists}`) // Get connection information const connectionInfo = postgres.connectionInfo console.log(`Connect to: ${connectionInfo.connectionString}`) // Drop the database await postgres.dropDatabase('myapp') // Stop the server await postgres.stop() } finally { // Clean up resources await postgres.cleanup() } } example().catch(console.error) ``` -------------------------------- ### TypeScript Test Example Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md An example of a unit test written in TypeScript using Ava, demonstrating how to interact with the `PostgresInstance` class, including starting, creating databases, and cleanup. ```typescript import test from 'ava' import { PostgresInstance } from '../index.js' test('should create database successfully', async (t) => { // Arrange const instance = new PostgresInstance({ port: 5432 }) await instance.start() try { // Act await instance.createDatabase('test_db') // Assert const exists = await instance.databaseExists('test_db') t.is(exists, true) } finally { // Cleanup await instance.stop() instance.cleanup() } }) ``` -------------------------------- ### Async/Await JavaScript Example Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md A comprehensive example showcasing async/await usage for PostgreSQL instance lifecycle management, database operations, connection caching, performance monitoring, error handling, and timeouts. ```javascript // Comprehensive async/await usage example // Creating and configuring PostgreSQL instances // Async lifecycle management (start/stop) // Database operations (create, check, drop) // Connection information and caching // Performance monitoring // Error handling and cleanup // Timeout functionality // Example snippet demonstrating async lifecycle: // const postgres = new PostgresInstance({ port: 5432 }) // await postgres.start() // await postgres.stop() // await postgres.cleanup() ``` -------------------------------- ### PostgresInstance API Reference Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Detailed API documentation for the PostgresInstance class, covering its constructor, properties, and methods for managing embedded PostgreSQL instances. Includes setup, start, stop, and database creation functionalities. ```APIDOC PostgresInstance: __constructor(settings?: PostgresSettings) Creates a new PostgreSQL instance with the specified settings. Parameters: - settings (optional): Configuration settings for the PostgreSQL instance. Example: const instance = new PostgresInstance({ port: 5432, username: 'postgres', password: 'password' }) state: InstanceState (readonly) Gets the current state of the PostgreSQL instance. Possible values: - "Stopped" - Instance is not running - "Starting" - Instance is in the process of starting - "Running" - Instance is running and ready to accept connections - "Stopping" - Instance is in the process of stopping Example: console.log(`Current state: ${instance.state}`) connectionInfo: ConnectionInfo (readonly) Gets the connection information for the PostgreSQL instance. Only available when the instance is running. Throws: Error if the instance is not running Example: if (instance.state === 'Running') { const info = instance.connectionInfo console.log(`Connect to: ${info.connectionString}`) } instanceId: string (readonly) Gets the unique identifier for this PostgreSQL instance. Example: console.log(`Instance ID: ${instance.instanceId}`) setup(): Promise 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. Throws: - Error if setup fails Example: try { await instance.setup() console.log('PostgreSQL setup completed') } catch (error) { console.error('Failed to setup:', error.message) } start(): Promise Starts the PostgreSQL instance asynchronously. This method includes automatic setup if the instance hasn't been set up yet. Throws: - Error if the instance is already running or starting - Error if startup fails Example: try { await instance.start() console.log('PostgreSQL started successfully') } catch (error) { console.error('Failed to start:', error.message) } stop(): Promise Stops the PostgreSQL instance asynchronously. Throws: - Error if the instance is already stopped or stopping - Error if stopping fails Example: try { await instance.stop() console.log('PostgreSQL stopped successfully') } catch (error) { console.error('Failed to stop:', error.message) } startWithTimeout(timeoutSeconds: number): Promise Starts the PostgreSQL instance with a specified timeout. Parameters: - timeoutSeconds: Maximum time to wait for startup in seconds Throws: - Error if the instance is already running or starting - Error if startup fails or timeout is exceeded Example: try { await instance.startWithTimeout(30) // 30 second timeout console.log('Started within timeout') } catch (error) { console.error('Start failed or timed out:', error.message) } stopWithTimeout(timeoutSeconds: number): Promise Stops the PostgreSQL instance with a specified timeout. Parameters: - timeoutSeconds: Maximum time to wait for shutdown in seconds Throws: - Error if the instance is already stopped or stopping - Error if stopping fails or timeout is exceeded Example: try { await instance.stopWithTimeout(10) // 10 second timeout console.log('Stopped within timeout') } catch (error) { console.error('Stop failed or timed out:', error.message) } createDatabase(name: string): Promise Creates a new database asynchronously. Parameters: - name: The name of the database to create Throws: - Error if the instance is not running - Error if database creation fails - Error if database name is empty Example: try { await instance.createDatabase('myapp') console.log('Database created successfully') } catch (error) { console.error('Failed to create database:', error.message) } ``` -------------------------------- ### Testing Pattern with Setup/Teardown Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md Demonstrates the common pattern for setting up and tearing down pg-embedded instances within a testing context, including database isolation per test. ```javascript // Setup let postgres beforeAll(async () => { postgres = new PostgresInstance({ port: 5433 }) await postgres.start() }) // Cleanup afterAll(async () => { await postgres.stop() await postgres.cleanup() }) // Test isolation beforeEach(async () => { await postgres.createDatabase('test_db') }) afterEach(async () => { await postgres.dropDatabase('test_db') }) ``` -------------------------------- ### Development Environment Use Case Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md Demonstrates setting up a local PostgreSQL instance for development purposes, with options for persistent data storage. ```javascript const postgres = new PostgresInstance({ port: 5432, persistent: true, // Keep data between runs dataDir: './dev-data', }) ``` -------------------------------- ### Performance Tip: Monitor Startup Times Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Provides a code example for monitoring PostgreSQL startup times, allowing developers to identify and address slow startup performance. It checks the returned startup time and logs a warning if it exceeds a threshold. ```typescript await postgres.start() const startupTime = postgres.getStartupTime() if (startupTime > 5) { console.warn(`Slow startup detected: ${startupTime}s`) } ``` -------------------------------- ### CI/CD Pipeline Use Case Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md Configuration example for using pg-embedded in CI/CD pipelines, focusing on fast startup and temporary data for reliable, isolated testing. ```javascript // Fast startup for CI const postgres = new PostgresInstance({ persistent: false, // Temporary data timeout: 60, // Allow more time in CI }) ``` -------------------------------- ### Testing JavaScript Example Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md An example demonstrating integration with testing frameworks, including test suite setup/teardown, database isolation for tests, concurrent operation testing, performance benchmarking, and error scenario testing. ```javascript // Setup let postgres beforeAll(async () => { postgres = new PostgresInstance({ port: 5433 }) await postgres.start() }) // Cleanup afterAll(async () => { await postgres.stop() await postgres.cleanup() }) // Test isolation beforeEach(async () => { await postgres.createDatabase('test_db') }) afterEach(async () => { await postgres.dropDatabase('test_db') }) ``` -------------------------------- ### Microservice Testing Use Case Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md Example of setting up dedicated, isolated PostgreSQL instances for testing individual microservices. ```javascript // Each service gets its own database const userServiceDb = new PostgresInstance({ port: 5432 }) const orderServiceDb = new PostgresInstance({ port: 5433 }) ``` -------------------------------- ### Install pg-embedded Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Installs the pg-embedded library using npm. This is the first step to integrate embedded PostgreSQL into your Node.js project. ```bash npm install pg-embedded ``` -------------------------------- ### Rust Code Style and API Documentation Example Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Demonstrates recommended Rust code style, including the use of documentation comments for public APIs, parameter descriptions, return values, and error handling. This snippet illustrates how to generate API documentation from Rust code. ```rust /// Creates a new database with the specified name /// /// # Arguments /// * `name` - The name of the database to create /// /// # Returns /// * `Ok(())` if the database was created successfully /// * `Err(napi::Error)` if creation failed /// /// # Example /// ```rust /// instance.create_database("my_database".to_string())?; /// ``` #[napi] pub async unsafe fn create_database(&mut self, name: String) -> napi::Result<()> { // Implementation } ``` -------------------------------- ### Get Instance Startup Time (TypeScript) Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Retrieves the startup time of the PostgreSQL instance in seconds. Returns a number representing the time or null if the instance has not yet started. ```typescript getStartupTime(): number | null Gets the startup time of the PostgreSQL instance in seconds. Returns: The startup time in seconds, or `null` if the instance hasn't been started yet ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Installs all necessary project dependencies using the pnpm package manager. This command ensures your development environment is set up correctly. ```bash pnpm install ``` -------------------------------- ### Clone pg-embedded Repository Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Clones the pg-embedded repository from GitHub and navigates into the project directory. This is the first step to start contributing locally. ```bash git clone https://github.com/your-username/pg-embedded.git cd pg-embedded ``` -------------------------------- ### Integration Testing Use Case Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md Example of using pg-embedded to create isolated database instances specifically for integration tests, ensuring each test has a fresh database. ```javascript // Each test gets a fresh database const testDb = await postgres.createTestDatabase('my_test') // Run your test... await postgres.dropDatabase(testDb) ``` -------------------------------- ### Error Handling in pg-embedded Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Provides an example of how to implement robust error handling when using pg-embedded. It shows how to catch potential errors during instance startup, such as invalid configurations, and inspect error details like message and code. ```typescript import { PostgresInstance } from 'pg-embedded' const postgres = new PostgresInstance({ port: 80, // Invalid port for PostgreSQL }) try { await postgres.start() } catch (error) { console.error('Failed to start PostgreSQL:', error.message) // Handle specific error types if (error.code === 'ConfigurationError') { console.log('Configuration issue detected') } }) ``` -------------------------------- ### PostgresSettings Configuration Options Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Defines various configuration settings for an embedded PostgreSQL instance, including custom installation directories, operation timeouts, setup timeouts, and persistence options. Each setting has a default value and can be specified during instance creation. ```typescript interface PostgresSettings { installationDir?: string, timeout?: number, setupTimeout?: number, persistent?: boolean } // Example usage: const settings: PostgresSettings = { installationDir: '/path/to/postgres', timeout: 60, setupTimeout: 120, persistent: true, } ``` -------------------------------- ### Changelog Format Example Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Illustrates the standard markdown format for the project's changelog, detailing how to structure release notes according to Semantic Versioning (SemVer). It includes sections for Added, Changed, Fixed, and Deprecated items. ```markdown ## [1.2.0] - 2024-01-15 ### Added - New connection pooling feature - Support for PostgreSQL 16 ### Changed - Improved startup performance by 20% - Updated default timeout to 30 seconds ### Fixed - Fixed memory leak in connection caching - Resolved issue with database name validation ### Deprecated - Old configuration format (will be removed in v2.0) ``` -------------------------------- ### Mocha Integration with pg-embedded Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Shows how to use pg-embedded with the Mocha testing framework. This example includes setting up the PostgreSQL instance with a longer timeout for startup and performing basic database operations within tests. ```typescript import { PostgresInstance } from 'pg-embedded' describe('Database Tests', function () { let postgres: PostgresInstance before(async function () { this.timeout(30000) // Allow time for PostgreSQL to start postgres = new PostgresInstance() await postgres.start() }) after(async function () { await postgres.stop() await postgres.cleanup() }) it('should handle database operations', async function () { await postgres.createDatabase('mocha_test') const exists = await postgres.databaseExists('mocha_test') expect(exists).to.be.true await postgres.dropDatabase('mocha_test') }) }) ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md Code snippet to enable detailed debug logging for pg-embedded operations by initializing the logger with the Debug level. ```javascript import { initLogger, LogLevel } from 'pg-embedded' initLogger(LogLevel.Debug) ``` -------------------------------- ### Publish to npm Source: https://github.com/pgtslabs/pg-embedded/blob/main/RELEASE_CHECKLIST.md Publishes the package to the npm registry, making it available for installation by users. The `--access public` flag ensures the package is publicly accessible. ```bash npm publish --access public ``` -------------------------------- ### Performance Tip: Reuse Instances Across Tests Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Suggests reusing a single pg-embedded instance across multiple test suites or tests to avoid the overhead of starting and stopping the PostgreSQL server repeatedly. ```typescript // Create once, use multiple times const postgres = new PostgresInstance() await postgres.start() // Run multiple test suites... await postgres.stop() ``` -------------------------------- ### CI/CD: Extract PostgreSQL Version (YAML) Source: https://github.com/pgtslabs/pg-embedded/blob/main/scripts/README.md Example of how the PostgreSQL version is extracted and set as an environment variable within a CI workflow. This ensures consistency across build and deployment stages. ```yaml - name: Extract PostgreSQL version id: pg-version run: | PG_VERSION=$(node scripts/extract-pg-version.js) echo "POSTGRESQL_VERSION=$PG_VERSION" >> $GITHUB_ENV echo "postgresql_version=$PG_VERSION" >> $GITHUB_OUTPUT echo "PostgreSQL version: $PG_VERSION" ``` -------------------------------- ### Error Handling Pattern Source: https://github.com/pgtslabs/pg-embedded/blob/main/examples/README.md Shows a robust error handling pattern for pg-embedded operations, including try-catch blocks for operations and specific error code handling. ```javascript try { await postgres.start() await postgres.createDatabase('mydb') } catch (error) { console.error('Operation failed:', error.message) // Handle specific error types if (error.code === 'DatabaseError') { // Handle database-specific errors } } finally { // Always cleanup postgres.cleanup() } ``` -------------------------------- ### Automated Release Commands Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Automates patch, minor, and major releases for the pg-embedded project using pnpm. These commands preserve the PostgreSQL version in the release tag. Requires pnpm to be installed and configured. ```bash # Patch release: 0.1.0+pg17.5 -> 0.1.1+pg17.5 pnpm release:patch # Minor release: 0.1.0+pg17.5 -> 0.2.0+pg17.5 pnpm release:minor # Major release: 0.1.0+pg17.5 -> 1.0.0+pg17.5 pnpm release:major ``` -------------------------------- ### Feature Request Structure Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Provides a template for submitting feature requests, guiding users to describe the problem they aim to solve, propose a solution, mention alternatives considered, and explain the potential impact of the feature. ```markdown For feature requests, please provide: 1. **Use Case**: Describe the problem you're trying to solve 2. **Proposed Solution**: Your idea for how it should work 3. **Alternatives**: Other solutions you've considered 4. **Impact**: Who would benefit from this feature ``` -------------------------------- ### Get Instance Configuration Hash (TypeScript) Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Retrieves a string hash representing the current configuration of the PostgreSQL instance. This can be useful for detecting configuration changes. ```typescript getConfigHash(): string Gets the configuration hash for this instance. Returns: A string hash of the instance configuration ``` -------------------------------- ### Release Steps Overview Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Outlines the sequential steps required to perform a project release, from updating version numbers in configuration files to publishing the release on platforms like npm and GitHub. ```markdown 1. Update version in `package.json` and `Cargo.toml` 2. Update `CHANGELOG.md` with release notes 3. Create release commit and tag 4. Push to main branch 5. Create GitHub release 6. Publish to npm registry ``` -------------------------------- ### Performance Monitoring with pg-embedded Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md This snippet illustrates how to monitor the startup performance of a pg-embedded PostgreSQL instance. It shows how to measure external startup time and retrieve internal startup time measurements, as well as checking the instance's health. ```typescript import { PostgresInstance } from 'pg-embedded' const postgres = new PostgresInstance() // Monitor startup performance const startTime = Date.now() await postgres.start() const externalStartupTime = Date.now() - startTime // Get internal startup time measurement const internalStartupTime = postgres.getStartupTime() console.log(`External measurement: ${externalStartupTime}ms`) console.log(`Internal measurement: ${internalStartupTime * 1000}ms`) // Check instance health if (postgres.isHealthy()) { console.log('PostgreSQL instance is healthy') }) ``` -------------------------------- ### Documentation Building Commands Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Provides essential bash commands for managing and building project documentation, including generating API documentation from source code, building all documentation assets, and serving documentation locally for preview. ```bash # Generate API documentation pnpm run docs:api # Build all documentation pnpm run docs:build # Serve documentation locally pnpm run docs:serve ``` -------------------------------- ### Build the Project Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Builds the pg-embedded project, compiling the Rust source code and preparing it for execution or testing. ```bash pnpm run build ``` -------------------------------- ### Authenticate with npm Source: https://github.com/pgtslabs/pg-embedded/blob/main/RELEASE_CHECKLIST.md Run `npm login` to authenticate your npm account. This is often required before publishing packages or interacting with private npm registries. ```bash npm login ``` -------------------------------- ### PostgresSettings Configuration Options Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Defines the configuration options for initializing a PostgresInstance. This includes version, port, credentials, data directory, timeouts, and persistence settings. ```APIDOC PostgresSettings: version?: string PostgreSQL version (e.g., "15.0", ">=14.0") port?: number Port number (0-65535, default: 5432, 0 for random) username?: string Username for database connection (default: "postgres") password?: string Password for database connection (default: "postgres") databaseName?: string Default database name (default: "postgres") dataDir?: string Custom data directory path installationDir?: string Custom installation directory path timeout?: number Timeout in seconds for database operations (default: 30) setupTimeout?: number Setup timeout in seconds for PostgreSQL initialization (default: 300 on Windows, 30 on other platforms) persistent?: boolean Whether to persist data between runs (default: false) ``` -------------------------------- ### Semantic Versioning (SemVer) Guidelines Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Defines the version management strategy for the project based on Semantic Versioning (SemVer). It explains the meaning of MAJOR, MINOR, and PATCH versions and their implications for backward compatibility. ```markdown We follow [Semantic Versioning](https://semver.org/): - **MAJOR**: Breaking changes - **MINOR**: New features (backward compatible) - **PATCH**: Bug fixes (backward compatible) ``` -------------------------------- ### Prepare Patch Release with pnpm Source: https://github.com/pgtslabs/pg-embedded/blob/main/RELEASE_CHECKLIST.md Initiates the preparation for a patch release, typically for bug fixes. This command handles necessary version bumps and initial commit generation. ```bash pnpm release:prepare ``` -------------------------------- ### Performance Tip: Use Persistent Instances Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Recommends using persistent instances for development environments to speed up repeated test runs. This involves configuring the `persistent` option and specifying a `data_dir`. ```typescript const postgres = new PostgresInstance({ persistent: true, data_dir: './postgres-data', }) ``` -------------------------------- ### PostgresInstance API Reference Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Details the constructor, properties, and methods available for managing an embedded PostgreSQL instance. This includes lifecycle management, database operations, and utility functions. ```APIDOC PostgresInstance: Constructor: new PostgresInstance(settings?: PostgresSettings) Creates a new PostgreSQL instance with the specified settings. Properties: state: InstanceState - Current state of the instance (Stopped, Starting, Running, Stopping) connectionInfo: ConnectionInfo - Connection information (only available when running) instanceId: string - Unique identifier for this instance Methods: setup(): Promise Set up the PostgreSQL instance (called automatically by start). start(): Promise Start the PostgreSQL instance. stop(): Promise Stop the PostgreSQL instance. startWithTimeout(seconds: number): Promise Start the PostgreSQL instance with a specified timeout. stopWithTimeout(seconds: number): Promise Stop the PostgreSQL instance with a specified timeout. createDatabase(name: string): Promise Create a new database with the given name. dropDatabase(name: string): Promise Drop a database with the given name. databaseExists(name: string): Promise Check if a database with the given name exists. Utility Methods: isHealthy(): boolean Check if the instance is healthy. getStartupTime(): number | null Get startup time in seconds. getConfigHash(): string Get configuration hash. getPostgreSqlVersion(): string Get PostgreSQL version. clearConnectionCache(): void Clear connection info cache. isConnectionCacheValid(): boolean Check if connection cache is valid. cleanup(): Promise Manually clean up resources. ``` -------------------------------- ### Jest Integration with pg-embedded Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Demonstrates how to integrate pg-embedded with the Jest testing framework. It covers setting up a PostgreSQL instance before tests run and cleaning it up afterwards, including database creation and dropping for each test suite. ```typescript import { PostgresInstance } from 'pg-embedded' describe('Database Tests', () => { let postgres: PostgresInstance beforeAll(async () => { postgres = new PostgresInstance({ port: 5434, persistent: false, }) await postgres.start() }) afterAll(async () => { await postgres.stop() await postgres.cleanup() }) beforeEach(async () => { await postgres.createDatabase('test_db') }) afterEach(async () => { await postgres.dropDatabase('test_db') }) test('should create and connect to database', async () => { const exists = await postgres.databaseExists('test_db') expect(exists).toBe(true) }) }) ``` -------------------------------- ### Version Information Methods Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Provides methods to retrieve version details for the package and the embedded PostgreSQL instance. This helps in debugging and compatibility checks. ```APIDOC Version Information: getVersionInfo(): VersionInfo Get comprehensive version information. getPostgreSQLVersion(): string Get PostgreSQL version. getPackageVersion(): string Get package version. ``` -------------------------------- ### Platform-Specific Script Execution Source: https://github.com/pgtslabs/pg-embedded/blob/main/scripts/README.md Demonstrates how to execute the project's utility scripts on different operating systems and shell environments. It covers Node.js scripts, PowerShell, and Windows Command Prompt. ```bash # Linux/macOS (Bash): # Direct script execution node scripts/extract-pg-version.js # Using npm scripts (recommended) pnpm pg:version pnpm pg:update 17.6 ``` ```powershell # Windows (PowerShell): # Using PowerShell script powershell -ExecutionPolicy Bypass -File scripts/extract-pg-version.ps1 # Using npm scripts (recommended) pnpm pg:version:win pnpm pg:update 17.6 # Or use the Node.js version (works on all platforms) pnpm pg:version ``` ```cmd # Windows (Command Prompt): # Using batch script scripts\extract-pg-version.cmd # Using npm scripts (recommended) pnpm pg:version pnpm pg:update 17.6 ``` -------------------------------- ### Publish Release (pnpm) Source: https://github.com/pgtslabs/pg-embedded/blob/main/scripts/README.md Publishes the prepared release to the package registry. This command should be run after the release has been prepared and validated. ```bash pnpm release:publish ``` -------------------------------- ### Run Validation and Build Checks Source: https://github.com/pgtslabs/pg-embedded/blob/main/RELEASE_CHECKLIST.md Executes pre-flight checks to ensure the project is ready for release. This includes validating the build artifacts and overall release readiness. ```bash pnpm validate ``` ```bash pnpm build:check ``` -------------------------------- ### Enabling Debug Logging in pg-embedded Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Illustrates how to enable detailed debug logging for pg-embedded to aid in troubleshooting. It shows the usage of `initLogger` with `LogLevel.Debug` to capture verbose output during instance operations. ```typescript import { initLogger, LogLevel } from 'pg-embedded' // Enable debug logging initLogger(LogLevel.Debug) const postgres = new PostgresInstance() await postgres.start() // Will output detailed logs ``` -------------------------------- ### Version Management Commands Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Details the command-line interface (CLI) commands used for managing the PostgreSQL version within the pg-embedded project. This includes checking the current version and updating to a specific version. ```bash # Check current PostgreSQL version pnpm pg:version # Update PostgreSQL version pnpm pg:update 17.6 # The CI automatically uses the PostgreSQL version from package.json ``` -------------------------------- ### Publish Release with pnpm Source: https://github.com/pgtslabs/pg-embedded/blob/main/RELEASE_CHECKLIST.md Publishes the prepared release to the package registry. This command should be run after a successful dry run and all pre-release checks are complete. ```bash pnpm release:publish ``` -------------------------------- ### Prepare Release (pnpm) Source: https://github.com/pgtslabs/pg-embedded/blob/main/scripts/README.md Prepares the package for release by automatically preserving the PostgreSQL version suffix when incrementing the base version number. Supports patch, minor, and major releases. ```bash # Patch release (e.g., 0.1.0+pg17.5 -> 0.1.1+pg17.5) pnpm release:prepare # Minor release (e.g., 0.1.0+pg17.5 -> 0.2.0+pg17.5) pnpm release:prepare:minor # Major release (e.g., 0.1.0+pg17.5 -> 1.0.0+pg17.5) pnpm release:prepare:major ``` -------------------------------- ### Prepare Minor Release with pnpm Source: https://github.com/pgtslabs/pg-embedded/blob/main/RELEASE_CHECKLIST.md Initiates the preparation for a minor release, suitable for new features that are backward compatible. This command updates the version and prepares the release commit. ```bash pnpm release:prepare:minor ``` -------------------------------- ### Run Project Tests Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Executes the project's test suite to ensure functionality and verify changes. This command runs all unit, integration, and other defined tests. ```bash pnpm test ``` -------------------------------- ### ConnectionInfo Interface Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Defines the structure for connection details, including host, port, credentials, database name, and the complete connection string. ```APIDOC ConnectionInfo: host: string port: number username: string password: string databaseName: string connectionString: string ``` -------------------------------- ### Publish Release with pnpm (Dry Run) Source: https://github.com/pgtslabs/pg-embedded/blob/main/RELEASE_CHECKLIST.md Performs a dry run of the release publishing process. This allows verification of the publish steps without actually deploying the package to the registry. ```bash pnpm release:publish:dry ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Runs the project's test suite and generates a code coverage report, indicating which parts of the codebase are exercised by tests. ```bash pnpm run test:coverage ``` -------------------------------- ### Safe Resource Cleanup in Finally Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Illustrates a robust approach to resource cleanup using a finally block. It includes a check to ensure the resource (e.g., an instance) exists before attempting to clean it up, preventing potential errors if the resource was never successfully initialized. ```typescript let instance try { instance = new PostgresInstance() await instance.start() // ... operations } catch (error) { console.error('Error:', error.message) } finally { if (instance) { await instance.cleanup() } } ``` -------------------------------- ### Create Release Commit and Tag with Git Source: https://github.com/pgtslabs/pg-embedded/blob/main/RELEASE_CHECKLIST.md Stages all changes, creates a commit for the release, and applies an annotated Git tag. This is a crucial step in marking the release point in the project's history. ```bash git add . git commit -m "chore: release v1.0.0" git tag -a v1.0.0 -m "Release v1.0.0" ``` -------------------------------- ### Conventional Commits Format Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Illustrates the conventional commits format for writing clear and structured commit messages, aiding in automated changelog generation and understanding. ```markdown type(scope): description feat(postgres): add connection pooling support fix(settings): validate port range correctly docs(readme): update installation instructions test(integration): add database creation tests ``` -------------------------------- ### Connection Caching in pg-embedded Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Explains how pg-embedded utilizes connection caching for improved performance. It demonstrates accessing cached connection information, checking cache validity, and manually clearing the cache. ```typescript import { PostgresInstance } from 'pg-embedded' const postgres = new PostgresInstance() await postgres.start() // Connection info is cached for performance const info1 = postgres.connectionInfo const info2 = postgres.connectionInfo // Uses cached version // Check cache validity console.log(`Cache valid: ${postgres.isConnectionCacheValid()}`) // Manually clear cache if needed postgres.clearConnectionCache() console.log(`Cache valid after clear: ${postgres.isConnectionCacheValid()}`) ``` -------------------------------- ### Run Performance Benchmarks Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Executes performance benchmarks to measure the efficiency of critical operations within the pg-embedded project. ```bash pnpm run test:performance ``` -------------------------------- ### Prepare Major Release with pnpm Source: https://github.com/pgtslabs/pg-embedded/blob/main/RELEASE_CHECKLIST.md Initiates the preparation for a major release, used for breaking changes. This command updates the version and prepares the release commit, signaling significant API changes. ```bash pnpm release:prepare:major ``` -------------------------------- ### Async Try-Catch with Cleanup Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Demonstrates using try-catch-finally blocks for asynchronous operations. This pattern ensures that cleanup actions are always executed, regardless of whether an error occurred during the main operation. It's crucial for managing resources like database connections. ```typescript try { await instance.start() // ... database operations } catch (error) { console.error('Operation failed:', error.message) } finally { instance.cleanup() } ``` -------------------------------- ### Bug Reporting Structure Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Details the essential information required when reporting a bug, including environment details, clear steps to reproduce the issue, expected versus actual behavior, and any relevant error messages or logs. ```markdown When reporting bugs, please include: 1. **Environment Information**: - Operating system and version - Node.js version - pg-embedded version - PostgreSQL version (if relevant) 2. **Steps to Reproduce**: - Minimal code example - Expected behavior - Actual behavior - Error messages or logs 3. **Additional Context**: - Screenshots if applicable - Related issues or pull requests - Possible solutions you've tried ``` -------------------------------- ### InstanceState Enum Source: https://github.com/pgtslabs/pg-embedded/blob/main/README.md Defines the possible states for a PostgreSQL instance, indicating its current operational status. ```APIDOC InstanceState: Stopped = 'Stopped' Starting = 'Starting' Running = 'Running' Stopping = 'Stopping' ``` -------------------------------- ### Push to Repository with Git Source: https://github.com/pgtslabs/pg-embedded/blob/main/RELEASE_CHECKLIST.md Pushes the local commits and tags to the remote repository. This ensures the release tag and commit are available on the central version control system. ```bash git push origin main --tags ``` -------------------------------- ### Push Changes to Fork Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Pushes the local branch containing your changes to your forked repository on GitHub. This makes your contributions available for a pull request. ```bash git push origin your-branch-name ``` -------------------------------- ### Error Handling with Common Error Codes Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Details common error types encountered when using the pg-embedded library, such as configuration issues, startup failures, database operation errors, and timeouts. Each error typically includes a message and a specific error code for programmatic handling. ```typescript // Example for ConfigurationError try { const instance = new PostgresInstance({ port: 0, // Invalid port }); } catch (error) { if (error.code === 'ConfigurationError') { console.log('Configuration issue:', error.message); } } // Example for StartupError try { await instance.start(); } catch (error) { if (error.code === 'StartupError') { console.log('Startup failed:', error.message); } } // Example for DatabaseError try { await instance.createDatabase('invalid name!'); } catch (error) { if (error.code === 'DatabaseError') { console.log('Database operation failed:', error.message); } } // Example for TimeoutError try { await instance.startWithTimeout(1); // Very short timeout } catch (error) { if (error.code === 'TimeoutError') { console.log('Operation timed out:', error.message); } } ``` -------------------------------- ### Run Specific Test Files Source: https://github.com/pgtslabs/pg-embedded/blob/main/CONTRIBUTING.md Executes only specific test files within the project. This is useful for focusing on a particular area during development. ```bash pnpm test -- test/basic.test.ts ``` -------------------------------- ### Validate Release (pnpm) Source: https://github.com/pgtslabs/pg-embedded/blob/main/scripts/README.md Validates that the package is ready for release. This script performs checks to ensure the project meets release criteria. ```bash pnpm validate ``` -------------------------------- ### InstanceState Enumeration Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Defines the possible states of an embedded PostgreSQL instance. This enumeration helps in tracking and managing the lifecycle of the PostgreSQL server, from being stopped to running or undergoing startup/shutdown processes. ```typescript enum InstanceState { Stopped = 'Stopped', Starting = 'Starting', Running = 'Running', Stopping = 'Stopping', } // Example usage: // const currentState: InstanceState = instance.state; // if (currentState === InstanceState.Running) { // console.log('Instance is ready.'); // } ``` -------------------------------- ### Drop Database (TypeScript) Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Asynchronously drops (deletes) a specified database. It requires the instance to be running and handles errors related to instance state, deletion failure, or empty database names. ```typescript dropDatabase(name: string): Promise Drops (deletes) a database asynchronously. Parameters: - name: The name of the database to drop Throws: - Error if the instance is not running - Error if database deletion fails - Error if database name is empty ``` -------------------------------- ### ConnectionInfo Interface Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Represents the connection details required to access a running PostgreSQL instance. It includes host, port, username, password, database name, and a complete connection string. This information is crucial for connecting external clients or applications to the embedded database. ```typescript interface ConnectionInfo { host: string port: number username: string password: string databaseName: string connectionString: string } // Example usage: // Assuming 'instance' is an initialized PostgresInstance const info = instance.connectionInfo console.log(`Host: ${info.host}`) console.log(`Port: ${info.port}`) console.log(`Database: ${info.databaseName}`) console.log(`Connection String: ${info.connectionString}`) // Use with a PostgreSQL client (e.g., 'pg' library) import { Client } from 'pg' const client = new Client(info.connectionString) // await client.connect() // ... perform database operations ``` -------------------------------- ### Conditional Error Handling by Code Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Shows how to implement specific error handling logic based on error codes returned by operations. This allows for more granular control over how different types of failures are managed, such as database-specific or configuration errors. ```typescript try { await instance.createDatabase(dbName) } catch (error) { if (error.code === 'DatabaseError') { // Handle database-specific errors } else if (error.code === 'ConfigurationError') { // Handle configuration errors } else { // Handle other errors } } ``` -------------------------------- ### PostgresSettings Interface Definition (TypeScript) Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Defines the configuration settings for an embedded PostgreSQL instance. This interface allows customization of version, port, credentials, data directory, and timeouts. ```typescript interface PostgresSettings { version?: string port?: number username?: string password?: string databaseName?: string dataDir?: string installationDir?: string timeout?: number setupTimeout?: number persistent?: boolean } // Properties: // version?: string - PostgreSQL version specification (e.g., "15.0", ">=14.0"). Uses semantic versioning syntax. Default: Latest available version // port?: number - Port number for the PostgreSQL server (1-65535). Default: 5432 // username?: string - Username for database connection. Default: "postgres" // password?: string - Password for database connection. Default: "postgres" // databaseName?: string - Default database name. Default: "postgres" // dataDir?: string - Custom data directory path. If not specified, a temporary directory will be used. Default: System temporary directory // installationDir?: string - Path to the PostgreSQL installation directory. // timeout?: number - Timeout for instance operations in milliseconds. // setupTimeout?: number - Timeout for instance setup in milliseconds. // persistent?: boolean - Whether the instance data should be persistent across runs. ``` -------------------------------- ### Cleanup Instance Resources (TypeScript) Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Manually cleans up all resources associated with the PostgreSQL instance, including stopping the instance if it is running. This method can be called explicitly, though it's also invoked during garbage collection. ```typescript cleanup(): Promise 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 garbage collected, but can be called manually for immediate cleanup. ``` -------------------------------- ### Check Database Existence (TypeScript) Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Asynchronously checks if a database exists. It returns a promise resolving to a boolean indicating existence. Errors can occur if the instance is not running, the check fails, or the database name is empty. ```typescript databaseExists(name: string): Promise Checks if a database exists asynchronously. Parameters: - 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 - Error if the check fails - Error if database name is empty ``` -------------------------------- ### initLogger Function and LogLevel Enum Source: https://github.com/pgtslabs/pg-embedded/blob/main/API.md Provides functionality to initialize the library's logging system and defines the available log levels. Developers can set the verbosity of logs by choosing an appropriate level, aiding in debugging and monitoring the embedded PostgreSQL instance. ```typescript enum LogLevel { Error = 'Error', Warn = 'Warn', Info = 'Info', Debug = 'Debug', } function initLogger(level: LogLevel): void; // Example usage: import { initLogger, LogLevel } from 'pg-embedded' initLogger(LogLevel.Info) initLogger(LogLevel.Debug) ```