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: PgSettingsActive configuration for this instance.
fetch_settings: PgFetchSettingsBinary download settings used during Self::setup.
db_uri: StringBase 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: boolSet to true once a graceful stop has been initiated to prevent the
Drop impl from issuing a duplicate stop.
pg_access: PgAccessFile-system paths and I/O helpers for this instance.
Implementations§
Source§impl PgEmbed
impl PgEmbed
Sourcepub async fn new(
pg_settings: PgSettings,
fetch_settings: PgFetchSettings,
) -> Result<Self>
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.
Sourcepub async fn setup(&mut self) -> Result<()>
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.
Sourcepub async fn install_extension(&self, extension_dir: &Path) -> Result<()>
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/.dll → lib/;
.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.
Sourcepub async fn init_db(&mut self) -> Result<()>
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.
Sourcepub async fn start_db(&mut self) -> Result<()>
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.
Sourcepub async fn stop_db(&mut self) -> Result<()>
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.
Sourcepub fn stop_db_sync(&mut self) -> Result<()>
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.
Sourcepub fn handle_process_io_sync(&self, process: Child) -> Result<()>
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.
Sourcepub async fn create_database(&self, db_name: &str) -> Result<()>
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.
Sourcepub async fn drop_database(&self, db_name: &str) -> Result<()>
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.
Sourcepub async fn database_exists(&self, db_name: &str) -> Result<bool>
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.
Sourcepub fn full_db_uri(&self, db_name: &str) -> String
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.
Sourcepub async fn migrate(&self, db_name: &str) -> Result<()>
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§
Auto Trait Implementations§
impl Freeze for PgEmbed
impl !RefUnwindSafe for PgEmbed
impl Send for PgEmbed
impl Sync for PgEmbed
impl Unpin for PgEmbed
impl UnsafeUnpin for PgEmbed
impl !UnwindSafe for PgEmbed
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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