SqliteDatabase

Struct SqliteDatabase 

Source
pub struct SqliteDatabase { /* private fields */ }
Expand description

SQLite database with connection pooling for concurrent reads and optional exclusive writes.

Once the database is opened it can be used for read-only operations by calling read_pool(). Write operations are available by calling acquire_writer() which lazily initializes WAL mode on first use.

§Example

use sqlx_sqlite_conn_mgr::SqliteDatabase;
use std::sync::Arc;

let db = SqliteDatabase::connect("test.db", None).await?;

// Use read_pool for SELECT queries (concurrent reads)
let rows = sqlx::query("SELECT * FROM users")
    .fetch_all(db.read_pool()?)
    .await?;

// Optionally acquire writer for INSERT/UPDATE/DELETE (exclusive)
let mut writer = db.acquire_writer().await?;
sqlx::query("INSERT INTO users (name) VALUES (?)")
    .bind("Alice")
    .execute(&mut *writer)
    .await?;

db.close().await?;

Implementations§

Source§

impl SqliteDatabase

Source

pub async fn connect( path: impl AsRef<Path>, custom_config: Option<SqliteDatabaseConfig>, ) -> Result<Arc<Self>>

Connect to a SQLite database

If the database is already connected, returns the existing connection. Multiple calls with the same path will return the same database instance.

The database is created if it doesn’t exist. WAL mode is enabled when acquire_writer() is first called.

§Arguments
  • path - Path to the SQLite database file (will be created if missing)
  • custom_config - Optional custom configuration for connection pools. Pass None to use defaults (6 max read connections, 30 second idle timeout). Specify a custom configuration when the defaults don’t meet your requirements.
§Examples
use sqlx_sqlite_conn_mgr::SqliteDatabase;
use std::sync::Arc;

// Connect with default configuration (recommended for most use cases)
let db = SqliteDatabase::connect("test.db", None).await?;
use sqlx_sqlite_conn_mgr::{SqliteDatabase, SqliteDatabaseConfig};
use std::sync::Arc;

// Customize configuration when defaults don't meet your requirements
let custom_config = SqliteDatabaseConfig {
   max_read_connections: 10,
   idle_timeout_secs: 60,
};
let db = SqliteDatabase::connect("test.db", Some(custom_config)).await?;
Source

pub fn read_pool(&self) -> Result<&Pool<Sqlite>>

Get a reference to the connection pool for executing read queries

Use this for concurrent read operations. Multiple readers can access the pool simultaneously.

§Example
use sqlx_sqlite_conn_mgr::SqliteDatabase;
use sqlx::query;
use std::sync::Arc;

let db = SqliteDatabase::connect("test.db", None).await?;
let result = query("SELECT * FROM users")
    .fetch_all(db.read_pool()?)
    .await?;
Source

pub async fn acquire_writer(&self) -> Result<WriteGuard>

Acquire exclusive write access to the database

This method returns a WriteGuard that provides exclusive access to the single write connection. Only one writer can exist at a time.

On the first call, this method will enable WAL mode on the database. Subsequent calls reuse the same write connection.

§Example
use sqlx_sqlite_conn_mgr::SqliteDatabase;
use sqlx::query;
use std::sync::Arc;

let db = SqliteDatabase::connect("test.db", None).await?;
let mut writer = db.acquire_writer().await?;
query("INSERT INTO users (name) VALUES (?)")
    .bind("Alice")
    .execute(&mut *writer)
    .await?;
Source

pub async fn run_migrations(&self, migrator: &Migrator) -> Result<()>

Run database migrations using the provided migrator

This method runs all pending migrations from the provided Migrator. Migrations are executed using the write connection to ensure exclusive access. WAL mode is enabled automatically before running migrations.

SQLx tracks applied migrations in a _sqlx_migrations table, so calling this method multiple times is safe - already-applied migrations are skipped.

§Arguments
  • migrator - A reference to a Migrator containing the migrations to run. Typically created using sqlx::migrate!() macro.
§Example
use sqlx_sqlite_conn_mgr::SqliteDatabase;

// sqlx::migrate! is evaluated at compile time
static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations");

let db = SqliteDatabase::connect("test.db", None).await?;
db.run_migrations(&MIGRATOR).await?;
Source

pub async fn close(self: Arc<Self>) -> Result<()>

Close the database and clean up resources

This closes all connections in the pool and removes the database from the cache. After calling close, any operations on this database will return Error::DatabaseClosed.

Note: Takes Arc<Self> to consume ownership, preventing use-after-close at compile time. The registry stores Weak references, so when this Arc is dropped, the database is freed.

§Example
use sqlx_sqlite_conn_mgr::SqliteDatabase;

let db = SqliteDatabase::connect("test.db", None).await?;
// ... use database ...
db.close().await?;
Source

pub async fn remove(self: Arc<Self>) -> Result<()>

Close the database and delete all database files

This closes all connections and then deletes the database file, WAL file, and SHM file from disk. Use with caution!

Note: Takes Arc<Self> to consume ownership, preventing use-after-close at compile time. The registry stores Weak references, so when this Arc is dropped, the database is freed.

§Example
use sqlx_sqlite_conn_mgr::SqliteDatabase;

let db = SqliteDatabase::connect("temp.db", None).await?;
// ... use database ...
db.remove().await?;

Trait Implementations§

Source§

impl Debug for SqliteDatabase

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. 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> 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<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