Skip to main content

PgEmbed

Struct PgEmbed 

Source
pub struct PgEmbed {
    pub pg_settings: PgSettings,
    pub fetch_settings: PgFetchSettings,
    pub db_uri: String,
    pub server_status: Arc<Mutex<PgServerStatus>>,
    pub shutting_down: bool,
    pub pg_access: PgAccess,
}
Expand description

An embedded PostgreSQL server with full lifecycle management.

Dropping a PgEmbed instance that has not been explicitly stopped will automatically call pg_ctl stop synchronously and, if PgSettings::persistent is false, remove the cluster directory and password file.

Fields§

§pg_settings: PgSettings

Active configuration for this instance.

§fetch_settings: PgFetchSettings

Binary download settings used during Self::setup.

§db_uri: String

Base connection URI: postgres://{user}:{password}@localhost:{port}.

§server_status: Arc<Mutex<PgServerStatus>>

Current server lifecycle state, protected by an async mutex so it can be observed from concurrent tasks.

§shutting_down: bool

Set to true once a graceful stop has been initiated to prevent the Drop impl from issuing a duplicate stop.

§pg_access: PgAccess

File-system paths and I/O helpers for this instance.

Implementations§

Source§

impl PgEmbed

Source

pub async fn new( pg_settings: PgSettings, fetch_settings: PgFetchSettings, ) -> Result<Self>

Creates a new PgEmbed instance and prepares the directory structure.

Does not download binaries or start the server. Call Self::setup followed by Self::start_db to bring the server up.

§Arguments
  • pg_settings — Server configuration (port, auth, directories, …).
  • fetch_settings — Which PostgreSQL version/platform to download.
§Errors

Returns Error::DirCreationError if the cache or database directories cannot be created. Returns Error::InvalidPgUrl if the OS cache directory is unavailable.

Source

pub async fn setup(&mut self) -> Result<()>

Downloads the binaries (if needed), writes the password file, and runs initdb (if the cluster does not already exist).

This method is idempotent: if the binaries are already cached and the cluster is already initialised it returns immediately after verifying both.

§Errors

Returns any error from PgAccess::maybe_acquire_postgres, PgAccess::create_password_file, or Self::init_db.

Source

pub async fn install_extension(&self, extension_dir: &Path) -> Result<()>

Installs a third-party PostgreSQL extension into the binary cache.

Must be called after Self::setup (so the cache directory exists) and before Self::start_db (so the server loads the shared library on startup). Once the server is running, activate the extension in a specific database with:

CREATE EXTENSION IF NOT EXISTS <extension_name>;

Delegates to PgAccess::install_extension. See that method for the file-routing rules (.so/.dylib/.dlllib/; .control/.sql → the PostgreSQL share extension directory).

§Arguments
  • extension_dir — Directory containing the pre-compiled extension files (shared library + control + SQL scripts).
§Errors

Returns Error::DirCreationError if the target directories cannot be created. Returns Error::ReadFileError if extension_dir cannot be read. Returns Error::WriteFileError if a file cannot be copied.

Source

pub async fn init_db(&mut self) -> Result<()>

Runs initdb to create a new database cluster.

Updates Self::server_status to PgServerStatus::Initializing before the call and to PgServerStatus::Initialized on success.

§Errors

Returns Error::InvalidPgUrl if any path cannot be converted to UTF-8. Returns Error::PgInitFailure if initdb cannot be spawned. Returns Error::PgTimedOutError if the process exceeds PgSettings::timeout.

Source

pub async fn start_db(&mut self) -> Result<()>

Starts the PostgreSQL server with pg_ctl start -w.

Updates Self::server_status to PgServerStatus::Starting before the call and to PgServerStatus::Started on success.

§Errors

Returns Error::InvalidPgUrl if the cluster path cannot be converted to UTF-8. Returns Error::PgStartFailure if the process exits with a non-zero status or cannot be spawned. Returns Error::PgTimedOutError if the process exceeds PgSettings::timeout.

Source

pub async fn stop_db(&mut self) -> Result<()>

Stops the PostgreSQL server with pg_ctl stop -w.

Updates Self::server_status to PgServerStatus::Stopping before the call and to PgServerStatus::Stopped on success. Sets Self::shutting_down to true so the Drop impl does not issue a duplicate stop.

§Errors

Returns Error::InvalidPgUrl if the cluster path cannot be converted to UTF-8. Returns Error::PgStopFailure if pg_ctl stop fails. Returns Error::PgTimedOutError if the process exceeds PgSettings::timeout.

Source

pub fn stop_db_sync(&mut self) -> Result<()>

Stops the PostgreSQL server synchronously.

Used by the Drop impl where async is unavailable. Stdout and stderr of the pg_ctl stop process are forwarded to the log crate.

§Errors

Returns Error::PgError if the process cannot be spawned.

Source

pub fn handle_process_io_sync(&self, process: Child) -> Result<()>

Drains stdout and stderr of process, logging each line.

Lines from stdout are logged at info level; lines from stderr at error level. Read errors are silently ignored (the line is skipped).

§Arguments
  • process — A child process with piped stdout/stderr.
Source

pub async fn create_database(&self, db_name: &str) -> Result<()>

Creates a new PostgreSQL database.

Requires the rt_tokio_migrate feature.

§Arguments
  • db_name — Name of the database to create.
§Errors

Returns Error::PgTaskJoinError if the sqlx operation fails.

Source

pub async fn drop_database(&self, db_name: &str) -> Result<()>

Drops a PostgreSQL database if it exists.

Uses DROP DATABASE IF EXISTS semantics: if the database does not exist the call succeeds silently. Requires the rt_tokio_migrate feature.

§Arguments
  • db_name — Name of the database to drop.
§Errors

Returns Error::PgTaskJoinError if the sqlx operation fails.

Source

pub async fn database_exists(&self, db_name: &str) -> Result<bool>

Returns true if a database named db_name exists.

Requires the rt_tokio_migrate feature.

§Arguments
  • db_name — Name of the database to check.
§Errors

Returns Error::PgTaskJoinError if the sqlx operation fails.

Source

pub fn full_db_uri(&self, db_name: &str) -> String

Returns the full connection URI for a specific database.

Format: postgres://{user}:{password}@localhost:{port}/{db_name}.

§Arguments
  • db_name — Database name to append to the base URI.
Source

pub async fn migrate(&self, db_name: &str) -> Result<()>

Runs sqlx migrations from PgSettings::migration_dir against db_name.

Does nothing if PgSettings::migration_dir is None. Requires the rt_tokio_migrate feature.

§Arguments
  • db_name — Name of the target database.
§Errors

Returns Error::MigrationError if the migrator cannot be created or if a migration fails. Returns Error::SqlQueryError if the database connection fails.

Trait Implementations§

Source§

impl Drop for PgEmbed

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more