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
impl SqliteDatabase
Sourcepub async fn connect(
path: impl AsRef<Path>,
custom_config: Option<SqliteDatabaseConfig>,
) -> Result<Arc<Self>>
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. PassNoneto 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?;Sourcepub fn read_pool(&self) -> Result<&Pool<Sqlite>>
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?;Sourcepub async fn acquire_writer(&self) -> Result<WriteGuard>
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?;Sourcepub async fn run_migrations(&self, migrator: &Migrator) -> Result<()>
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 aMigratorcontaining the migrations to run. Typically created usingsqlx::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?;Sourcepub async fn close(self: Arc<Self>) -> Result<()>
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?;Sourcepub async fn remove(self: Arc<Self>) -> Result<()>
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§
Auto Trait Implementations§
impl !Freeze for SqliteDatabase
impl !RefUnwindSafe for SqliteDatabase
impl Send for SqliteDatabase
impl Sync for SqliteDatabase
impl Unpin for SqliteDatabase
impl !UnwindSafe for SqliteDatabase
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