### Start Embedded Postgres Process Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt The `Start` method downloads, initializes, and starts the Postgres process. It performs a health check until the server is ready or `StartTimeout` elapses. Returns `ErrServerAlreadyStarted` if already running. ```go package myapp_test import ( "database/sql" "testing" embeddedpostgres "github.com/fergusstrange/embedded-postgres" _ "github.com/lib/pq" ) func TestDatabase(t *testing.T) { postgres := embeddedpostgres.NewDatabase( embeddedpostgres.DefaultConfig(). Port(5555). Database("testdb"), ) if err := postgres.Start(); err != nil { t.Fatalf("failed to start: %v", err) } defer func() { if err := postgres.Stop(); err != nil { t.Fatalf("failed to stop: %v", err) } }() db, err := sql.Open("postgres", "host=localhost port=5555 user=postgres password=postgres dbname=testdb sslmode=disable") if err != nil { t.Fatal(err) } defer db.Close() var result int if err := db.QueryRow("SELECT 1").Scan(&result); err != nil { t.Fatal(err) } // result == 1 } ``` -------------------------------- ### Start and Stop Embedded Postgres (Zero Config) Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Demonstrates the basic usage of starting and stopping an embedded PostgreSQL database with default configurations. Ensure to handle potential errors during start and stop operations. ```go package main import ( "log" embeddedpostgres "github.com/fergusstrange/embedded-postgres" ) func main() { // Zero-config: uses all defaults db := embeddedpostgres.NewDatabase() if err := db.Start(); err != nil { log.Fatalf("start: %v", err) } defer func() { if err := db.Stop(); err != nil { log.Fatalf("stop: %v", err) } }() // Postgres is now running on localhost:5432 // Connect with: host=localhost port=5432 user=postgres password=postgres dbname=postgres sslmode=disable } ``` -------------------------------- ### (*EmbeddedPostgres).Start Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Downloads (if necessary) and extracts the binary, initializes the data cluster, starts `pg_ctl`, creates the named database (if not `postgres`), and performs a health-check loop until the server is ready or `StartTimeout` elapses. Returns `ErrServerAlreadyStarted` if called on an already-running instance. ```APIDOC ## (*EmbeddedPostgres).Start — Start the Postgres process Downloads (if necessary) and extracts the binary, initialises the data cluster, starts `pg_ctl`, creates the named database (if not `postgres`), and performs a health-check loop until the server is ready or `StartTimeout` elapses. Returns `ErrServerAlreadyStarted` if called on an already-running instance. ```go package myapp_test import ( "database/sql" "testing" embeddedpostgres "github.com/fergusstrange/embedded-postgres" _ "github.com/lib/pq" ) func TestDatabase(t *testing.T) { postgres := embeddedpostgres.NewDatabase( embeddedpostgres.DefaultConfig(). Port(5555). Database("testdb"), ) if err := postgres.Start(); err != nil { t.Fatalf("failed to start: %v", err) } defer func() { if err := postgres.Stop(); err != nil { t.Fatalf("failed to stop: %v", err) } }() db, err := sql.Open("postgres", "host=localhost port=5555 user=postgres password=postgres dbname=testdb sslmode=disable") if err != nil { t.Fatal(err) } defer db.Close() var result int if err := db.QueryRow("SELECT 1").Scan(&result); err != nil { t.Fatal(err) } // result == 1 } ``` ``` -------------------------------- ### Create Embedded Postgres with Custom Configuration Source: https://github.com/fergusstrange/embedded-postgres/blob/master/README.md Example of creating an embedded PostgreSQL instance with custom configurations like username, password, database name, version, port, and timeouts. The `RuntimePath` is erased and recreated on each `Start()`. For persistent data, set `DataPath` outside `RuntimePath`. ```go logger := &bytes.Buffer{} postgres := NewDatabase(DefaultConfig(). Username("beer"). Password("wine"). Database("gin"). Version(V12). RuntimePath("/tmp"). BinaryRepositoryURL("https://repo.local/central.proxy"). Port(9876). StartTimeout(45 * time.Second). StartParameters(map[string]string{"max_connections": "200"}). Logger(logger)) er := postgres.Start() // Do test logic er := postgres.Stop() ``` -------------------------------- ### Install embedded-postgres Go Library Source: https://github.com/fergusstrange/embedded-postgres/blob/master/README.md Add the latest release of the embedded-postgres library to your Go project using go get. This command fetches the library and its dependencies. ```bash go get -u github.com/fergusstrange/embedded-postgres ``` -------------------------------- ### Persist PostgreSQL Data Across Restarts Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Explains how to configure the database to preserve its data directory between `Start()` calls. If a matching data directory is found, initialization is skipped, and existing data is reused. ```go import embeddedpostgres "github.com/fergusstrange/embedded-postgres" cfg := embeddedpostgres.DefaultConfig(). RuntimePath("/tmp/pg-runtime"). // wiped on Start() DataPath("/var/myapp/pgdata") // preserved between starts db := embeddedpostgres.NewDatabase(cfg) // First run: initialises the cluster and creates the "postgres" database. // Subsequent runs: reuses the existing data directory as-is. _ = db.Start() deffer db.Stop() ``` -------------------------------- ### Integrate with `goose` Migrations Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Shows how to integrate `embedded-postgres` with the `goose` migration tool. The database is started, migrations are applied, tests are run, and the database is stopped. ```go package myapp_test import ( "testing" embeddedpostgres "github.com/fergusstrange/embedded-postgres" "github.com/jmoiron/sqlx" _ "github.com/lib/pq" "github.com/pressly/goose/v3" ) func TestWithMigrations(t *testing.T) { database := embeddedpostgres.NewDatabase() if err := database.Start(); err != nil { t.Fatal(err) } defer func() { if err := database.Stop(); err != nil { t.Fatal(err) } }() db, err := sqlx.Connect("postgres", "host=localhost port=5432 user=postgres password=postgres dbname=postgres sslmode=disable") if err != nil { t.Fatal(err) } defer db.Close() // Apply all Up migrations from ./migrations/*.sql if err := goose.Up(db.DB, "./migrations"); err != nil { t.Fatal(err) } // Run application tests against a fully migrated schema. var count int if err := db.QueryRow("SELECT COUNT(*) FROM beer_catalogue").Scan(&count); err != nil { t.Fatal(err) } t.Logf("rows in beer_catalogue: %d", count) } ``` -------------------------------- ### Start and Stop Embedded Postgres Source: https://github.com/fergusstrange/embedded-postgres/blob/master/README.md Basic usage for creating, starting, and stopping a default embedded PostgreSQL instance. Ensure `postgres.Stop()` is called to release the child process. ```go postgres := embeddedpostgres.NewDatabase() er := postgres.Start() // Do test logic er = postgres.Stop() ``` -------------------------------- ### Config.Logger Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Accepts any `io.Writer`. Postgres stdout/stderr is written to this writer during and after `Start()` and `Stop()`. This is useful for capturing logs in tests or routing to structured loggers. ```APIDOC ## Config.Logger — Redirect Postgres log output Accepts any `io.Writer`. Postgres stdout/stderr is written to this writer during and after `Start()` and `Stop()`. Useful for capturing logs in tests or routing to structured loggers. ```go package myapp_test import ( "testing" embeddedpostgres "github.com/fergusstrange/embedded-postgres" "go.uber.org/zap" "go.uber.org/zap/zapio" ) func TestWithZapLogger(t *testing.T) { logger, _ := zap.NewProduction() w := &zapio.Writer{Log: logger} db := embeddedpostgres.NewDatabase( embeddedpostgres.DefaultConfig().Logger(w), ) if err := db.Start(); err != nil { t.Fatal(err) } defer func() { if err := db.Stop(); err != nil { t.Fatal(err) } }() // All Postgres log lines now flow through Zap. } ``` ``` -------------------------------- ### Select PostgreSQL Version Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Illustrates how to specify the PostgreSQL version to be downloaded and run. You can use predefined constants for major releases or provide a custom semver string. ```go import embeddedpostgres "github.com/fergusstrange/embedded-postgres" // Predefined constants // embeddedpostgres.V18 → "18.3.0" // embeddedpostgres.V17 → "17.5.0" // embeddedpostgres.V16 → "16.9.0" // embeddedpostgres.V15 → "15.13.0" // embeddedpostgres.V14 → "14.18.0" // embeddedpostgres.V13 → "13.21.0" // embeddedpostgres.V12 → "12.22.0" // embeddedpostgres.V11 → "11.22.0" // embeddedpostgres.V10 → "10.23.0" // embeddedpostgres.V9 → "9.6.24" db := embeddedpostgres.NewDatabase( embeddedpostgres.DefaultConfig().Version(embeddedpostgres.V15), ) ``` -------------------------------- ### Config.StartParameters Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Passes arbitrary PostgreSQL GUC (Grand Unified Configuration) parameters to the server at startup via `pg_ctl -o "-c key=value"`. This is equivalent to setting entries in `postgresql.conf`. ```APIDOC ## Config.StartParameters — Pass runtime GUC parameters Passes arbitrary PostgreSQL GUC (Grand Unified Configuration) parameters to the server at startup via `pg_ctl -o "-c key=value"`. Equivalent to setting entries in `postgresql.conf`. ```go import embeddedpostgres "github.com/fergusstrange/embedded-postgres" cfg := embeddedpostgres.DefaultConfig(). StartParameters(map[string]string{ "max_connections": "300", "shared_buffers": "256MB", "log_min_duration_statement": "0", // log all queries }) db := embeddedpostgres.NewDatabase(cfg) _ = db.Start() def db.Stop() ``` ``` -------------------------------- ### Supply Pre-Downloaded Binaries Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Use `BinariesPath` to point to a directory containing pre-extracted Postgres binaries. This bypasses the download step. Combine with `RuntimePath` for parallel versions. ```go import embeddedpostgres "github.com/fergusstrange/embedded-postgres" cfg := embeddedpostgres.DefaultConfig(). RuntimePath("/tmp/pg-runtime"). BinariesPath("/opt/postgres-binaries/16") // must contain bin/pg_ctl db := embeddedpostgres.NewDatabase(cfg) _ = db.Start() deferr db.Stop() ``` -------------------------------- ### Pass Runtime GUC Parameters Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Configure PostgreSQL GUC parameters at startup using `StartParameters`. This is equivalent to setting entries in `postgresql.conf` and is passed via `pg_ctl -o "-c key=value"`. ```go import embeddedpostgres "github.com/fergusstrange/embedded-postgres" cfg := embeddedpostgres.DefaultConfig(). StartParameters(map[string]string{ "max_connections": "300", "shared_buffers": "256MB", "log_min_duration_statement": "0", // log all queries }) db := embeddedpostgres.NewDatabase(cfg) _ = db.Start() deferr db.Stop() ``` -------------------------------- ### Config.Version Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Sets the PostgreSQL binary version to download and run. Supports predefined constants for major releases or a custom semver string. ```APIDOC ## Config.Version ### Description Selects the PostgreSQL binary version to download and run. Predefined constants cover supported major releases (v9 through v18), or a custom semver string can be used. ### Method `Version(version PostgresVersion) *Config` ### Parameters - `version` (PostgresVersion) - Required - The desired PostgreSQL version. Can be a predefined constant (e.g., `embeddedpostgres.V18`) or a custom semver string. ``` -------------------------------- ### Configure Embedded Postgres with Custom Settings Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Shows how to create a custom PostgreSQL configuration using a fluent builder API. This allows overriding defaults for version, port, credentials, paths, timeouts, startup parameters, and logging. ```go package main import ( "bytes" "log" "time" embeddedpostgres "github.com/fergusstrange/embedded-postgres" ) func main() { var logBuf bytes.Buffer cfg := embeddedpostgres.DefaultConfig(). Version(embeddedpostgres.V16). // Postgres 16.x Port(9876). // non-default port Username("appuser"). Password("s3cret"). Database("myapp"). RuntimePath("/tmp/pg-runtime"). // erased on each Start() CachePath("/tmp/pg-cache"). // binary archive cache StartTimeout(30 * time.Second). StartParameters(map[string]string{ "max_connections": "200", "shared_buffers": "128MB", }). Logger(&logBuf) // capture Postgres log output db := embeddedpostgres.NewDatabase(cfg) if err := db.Start(); err != nil { log.Fatalf("start: %v", err) } defer db.Stop() log.Printf("Postgres log so far:\n%s", logBuf.String()) } ``` -------------------------------- ### Config.BinariesPath Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Points the library at a directory that already contains an extracted Postgres binary tree. When set, no download is attempted. This can be combined with a subdirectory of `RuntimePath` when running multiple versions in parallel. ```APIDOC ## Config.BinariesPath — Supply pre-downloaded binaries Points the library at a directory that already contains an extracted Postgres binary tree (i.e., a `bin/pg_ctl` exists). When set, no download is attempted. Combine with a subdirectory of `RuntimePath` when running multiple versions in parallel. ```go import embeddedpostgres "github.com/fergusstrange/embedded-postgres" cfg := embeddedpostgres.DefaultConfig(). RuntimePath("/tmp/pg-runtime"). BinariesPath("/opt/postgres-binaries/16") // must contain bin/pg_ctl db := embeddedpostgres.NewDatabase(cfg) _ = db.Start() def db.Stop() ``` ``` -------------------------------- ### Run Multiple Postgres Versions in Parallel Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Demonstrates running multiple `EmbeddedPostgres` instances concurrently with unique ports and runtime paths. Binary downloads are mutex-protected. ```go package platform_test import ( "database/sql" "fmt" "os" "path/filepath" "testing" embeddedpostgres "github.com/fergusstrange/embedded-postgres" _ "github.com/lib/pq" ) func TestMultipleVersions(t *testing.T) { versions := []embeddedpostgres.PostgresVersion{ embeddedpostgres.V16, embeddedpostgres.V15, embeddedpostgres.V14, } tmp, _ := os.MkdirTemp("", "pg_multi_") for i, version := range versions { version := version port := uint32(5600 + i) runtimePath := filepath.Join(tmp, string(version)) t.Run(fmt.Sprintf("pg_%s", version), func(t *testing.T) { t.Parallel() db := embeddedpostgres.NewDatabase( embeddedpostgres.DefaultConfig(). Version(version). Port(port). RuntimePath(runtimePath), ) if err := db.Start(); err != nil { t.Fatal(err) } defer db.Stop() conn, err := sql.Open("postgres", fmt.Sprintf("host=localhost port=%d user=postgres password=postgres dbname=postgres sslmode=disable", port)) if err != nil { t.Fatal(err) } defer conn.Close() var v string _ = conn.QueryRow("SHOW server_version").Scan(&v) t.Logf("Postgres %s reports version: %s", version, v) }) } } ``` -------------------------------- ### Override Default Binary Download URL Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Use `BinaryRepositoryURL` to specify a custom Maven mirror for downloading Postgres binaries. This is useful for air-gapped environments or corporate proxies. ```go import embeddedpostgres "github.com/fergusstrange/embedded-postgres" cfg := embeddedpostgres.DefaultConfig(). BinaryRepositoryURL("https://nexus.corp.internal/repository/maven-central") db := embeddedpostgres.NewDatabase(cfg) _ = db.Start() deferr db.Stop() ``` -------------------------------- ### Config.GetConnectionURL Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Returns a `postgresql://` URL built from the current `Config` fields. This is convenient for passing to `sql.Open`, `sqlx.Connect`, or ORM configuration. ```APIDOC ## Config.GetConnectionURL — Retrieve the DSN Returns a `postgresql://` URL built from the current `Config` fields. Convenient for passing to `sql.Open`, `sqlx.Connect`, or ORM configuration. ```go import ( "database/sql" embeddedpostgres "github.com/fergusstrange/embedded-postgres" _ "github.com/lib/pq" ) cfg := embeddedpostgres.DefaultConfig(). Username("alice"). Password("hunter2"). Database("warehouse"). Port(5433) db := embeddedpostgres.NewDatabase(cfg) _ = db.Start() def db.Stop() connURL := cfg.GetConnectionURL() // → "postgresql://alice:hunter2@localhost:5433/warehouse" sqlDB, err := sql.Open("postgres", connURL) ``` ``` -------------------------------- ### Config.BinaryRepositoryURL Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Overrides the default Maven Central URL used to download Postgres binary JARs. This is useful in air-gapped environments or when routing through a corporate Maven proxy. ```APIDOC ## Config.BinaryRepositoryURL — Use a custom Maven mirror Overrides the default Maven Central URL used to download Postgres binary JARs. Useful in air-gapped environments or when routing through a corporate Maven proxy. ```go import embeddedpostgres "github.com/fergusstrange/embedded-postgres" cfg := embeddedpostgres.DefaultConfig(). BinaryRepositoryURL("https://nexus.corp.internal/repository/maven-central") db := embeddedpostgres.NewDatabase(cfg) _ = db.Start() def db.Stop() ``` ``` -------------------------------- ### DefaultConfig Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Provides a default `Config` struct that can be customized using fluent builder methods for various PostgreSQL settings. ```APIDOC ## DefaultConfig ### Description Returns a `Config` struct pre-filled with defaults. Every field is overridable via fluent builder methods. The modified `Config` is passed to `NewDatabase`. ### Method `DefaultConfig() *Config` ### Returns - `*Config` - A configuration object with default settings. ``` -------------------------------- ### Config.DataPath Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Configures a persistent data directory for the PostgreSQL cluster, allowing data to survive restarts. If the directory exists and matches the version, initialization is skipped. ```APIDOC ## Config.DataPath ### Description Persists data across restarts by specifying a data directory outside the runtime path. If an existing data directory is found and its major version matches the configured version, `initdb` is skipped and existing data is reused. ### Method `DataPath(path string) *Config` ### Parameters - `path` (string) - Required - The file system path for the persistent data directory. ``` -------------------------------- ### NewDatabase Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Creates a new *EmbeddedPostgres instance. It can be called with zero arguments to use default configuration or with a custom Config struct. ```APIDOC ## NewDatabase ### Description Creates a new `*EmbeddedPostgres` ready to be started. Accepts zero or one `Config` argument. When called with no arguments, `DefaultConfig()` is used. ### Method `NewDatabase(cfg ...*Config)` ### Parameters - `cfg` (*Config) - Optional - A custom configuration for the embedded PostgreSQL database. If not provided, default configuration is used. ``` -------------------------------- ### Retrieve Connection DSN Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt The `GetConnectionURL` method returns a `postgresql://` URL constructed from the current `Config` fields. This is convenient for passing to database connection functions. ```go import ( "database/sql" embeddedpostgres "github.com/fergusstrange/embedded-postgres" _ "github.com/lib/pq" ) cfg := embeddedpostgres.DefaultConfig(). Username("alice"). Password("hunter2"). Database("warehouse"). Port(5433) db := embeddedpostgres.NewDatabase(cfg) _ = db.Start() deferr db.Stop() connURL := cfg.GetConnectionURL() // → "postgresql://alice:hunter2@localhost:5433/warehouse" sqlDB, err := sql.Open("postgres", connURL) ``` -------------------------------- ### Redirect Postgres Log Output Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Use the `Logger` option to redirect Postgres stdout/stderr to an `io.Writer`. This is useful for capturing logs in tests or routing them to structured loggers like Zap. ```go package myapp_test import ( "testing" embeddedpostgres "github.com/fergusstrange/embedded-postgres" "go.uber.org/zap" "go.uber.org/zap/zapio" ) func TestWithZapLogger(t *testing.T) { logger, _ := zap.NewProduction() w := &zapio.Writer{Log: logger} db := embeddedpostgres.NewDatabase( embeddedpostgres.DefaultConfig().Logger(w), ) if err := db.Start(); err != nil { t.Fatal(err) } defer func() { if err := db.Stop(); err != nil { t.Fatal(err) } }() // All Postgres log lines now flow through Zap. } ``` -------------------------------- ### Stop Embedded Postgres Process Source: https://context7.com/fergusstrange/embedded-postgres/llms.txt Gracefully stops the Postgres process. Returns `ErrServerNotStarted` if the instance is not running. ```go import ( "errors" embeddedpostgres "github.com/fergusstrange/embedded-postgres" ) db := embeddedpostgres.NewDatabase() _ = db.Start() // Calling Stop on an already-stopped instance returns a sentinel error. _ = db.Stop() err := db.Stop() if errors.Is(err, embeddedpostgres.ErrServerNotStarted) { // handle: server was not running } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.