API Reference
This page documents the main public functions and types in the embedded-postgres
library.
NewDatabase(config ...Config) *EmbeddedPostgres
Creates a new EmbeddedPostgres
instance.
- If called with no arguments, it uses the configuration from
DefaultConfig()
. - If called with one or more
Config
arguments, it uses the first one.
// Create with default configuration
postgres := embeddedpostgres.NewDatabase()
// Create with a custom configuration
config := embeddedpostgres.DefaultConfig().Port(5433)
postgresWithConfig := embeddedpostgres.NewDatabase(config)
DefaultConfig() Config
Returns a Config
struct with a set of sensible default values. This is the recommended starting point for creating any custom configuration.
See the Configuration Guide for a full list of defaults.
// Start with defaults, then customize
config := embeddedpostgres.DefaultConfig().
Username("myuser").
Password("secret")
(ep *EmbeddedPostgres) Start() error
Starts the PostgreSQL server. This is a blocking operation that will only return after the database is fully initialized, started, and ready to accept connections.
It performs the entire lifecycle of path setup, binary extraction, initdb
, and server startup.
Possible Errors:
ErrServerAlreadyStarted
: IfStart()
is called on an already running instance.- Returns an error if the configured port is already in use.
- Returns an error if the binaries cannot be downloaded or extracted.
- Returns an error if
initdb
orpg_ctl start
fails. - Returns a timeout error if the database does not become available within the
StartTimeout
duration.
(ep *EmbeddedPostgres) Stop() error
Gracefully stops the PostgreSQL server using pg_ctl stop
.
Possible Errors:
ErrServerNotStarted
: IfStop()
is called beforeStart()
has completed successfully.- Returns an error if the
pg_ctl stop
command fails.
type Config
A struct that holds the configuration for the PostgreSQL instance. It has a fluent, chainable API for customization. See the Configuration Guide for details on all available methods.
(c Config) GetConnectionURL() string
A helper method on the Config
struct that returns a formatted PostgreSQL connection URL string. This is useful for passing to database drivers.
Format: postgresql://<user>:<password>@localhost:<port>/<database>
config := embeddedpostgres.DefaultConfig().Database("test_db")
url := config.GetConnectionURL() // "postgresql://postgres:postgres@localhost:5432/test_db"
type PostgresVersion
A string
alias representing a semantic version used to fetch and run the PostgreSQL process. Several constants are provided for convenience (e.g., V17
, V16
).