Quick Start
Here is a minimal example of how to start an embedded PostgreSQL instance, connect to it using the standard database/sql
library, and then shut it down. This is ideal for a simple integration test.
package main
import (
"database/sql"
"fmt"
"log"
embeddedpostgres "github.com/fergusstrange/embedded-postgres"
_ "github.com/lib/pq"
)
func main() {
// Use DefaultConfig for a standard setup on port 5432
config := embeddedpostgres.DefaultConfig()
postgres := embeddedpostgres.NewDatabase(config)
fmt.Println("Starting PostgreSQL...")
if err := postgres.Start(); err != nil {
log.Fatalf("Failed to start database: %s", err)
}
fmt.Println("PostgreSQL started successfully!")
defer func() {
fmt.Println("Stopping PostgreSQL...")
if err := postgres.Stop(); err != nil {
log.Fatalf("Failed to stop database: %s", err)
}
fmt.Println("PostgreSQL stopped.")
}()
// Construct the connection string from the config
// Default is: "host=localhost port=5432 user=postgres password=postgres dbname=postgres sslmode=disable"
db, err := sql.Open("postgres", config.GetConnectionURL()+" sslmode=disable")
if err != nil {
log.Fatalf("Failed to open database connection: %s", err)
}
// Ping the database to verify the connection
if err = db.Ping(); err != nil {
log.Fatalf("Failed to ping database: %s", err)
}
fmt.Println("Successfully connected to the database!")
// Your application or test logic goes here...
var result int
if err := db.QueryRow("SELECT 1").Scan(&result); err != nil {
log.Fatalf("Query failed: %s", err)
}
fmt.Printf("Query result: %d\n", result)
if err := db.Close(); err != nil {
log.Fatalf("Failed to close database connection: %s", err)
}
}
Running the Example
When you run this code for the first time, you will see output indicating that the PostgreSQL binaries are being downloaded and extracted. Subsequent runs will be much faster as the binaries will be loaded from a local cache.