Crate pgdb

Source
Expand description

§pgdb

A small Rust library to create and run ephemeral Postgres databases, typically used as unit test fixtures.

§Quick start

Tests requiring a fresh database (but not cluster) instance can use db_fixture:

let db_url = pgdb::db_fixture();
// You can now use `db_url` in your ORM. The database will not be shut down before `db_url` is dropped.

Note that databases are not cleaned up until the testing process exits.

Requires that regular Postgres database utilities like postgres and initdb are available on the path at runtime.

§Detailed usage

pgdb supports configuring and starting a Postgres database instance through a builder pattern, with cleanup on Drop:

let user = "dev";
let pw = "devpw";
let db = "dev";

// Run a postgres instance.
let pg = pgdb::Postgres::build()
    .start()
    .expect("could not build postgres database");

// We can now create a regular user and a database.
pg.as_superuser()
    .create_user(user, pw)
    .expect("could not create normal user");

pg.as_superuser()
    .create_database(db, user)
    .expect("could not create normal user's db");

// Now we can run DDL commands, e.g. creating a table.
let client = pg.as_user(user, pw);
client
    .run_sql(db, "CREATE TABLE foo (id INT PRIMARY KEY);")
    .expect("could not run table creation command");

Structs§

Postgres
A wrapped postgres instance.
PostgresBuilder
Builder for a postgres instance.
PostgresClient
A virtual client for a running postgres.

Enums§

DbUrl
A database URL keeping a database alive.
Error
A Postgres server error.
ExternalUrlError
Errors that can occur when parsing an external database URL.

Functions§

create_user_and_database
Creates a user and database with the given credentials using psql.
db_fixture
A convenience function for regular applications.
run_psql_command
Executes SQL using psql with the given connection parameters.