|
| 1 | +//! WriteGuard for exclusive write access to the database |
| 2 | +
|
| 3 | +use sqlx::Sqlite; |
| 4 | +use sqlx::pool::PoolConnection; |
| 5 | +use sqlx::sqlite::SqliteConnection; |
| 6 | +use std::ops::{Deref, DerefMut}; |
| 7 | + |
| 8 | +/// RAII guard for exclusive write access to a database connection |
| 9 | +/// |
| 10 | +/// This guard wraps a pool connection and returns it to the pool on drop. |
| 11 | +/// Only one `WriteGuard` can exist at a time (enforced by max_connections=1), |
| 12 | +/// ensuring serialized write access. |
| 13 | +/// |
| 14 | +/// The guard derefs to `SqliteConnection` allowing direct use with sqlx queries. |
| 15 | +/// |
| 16 | +/// # Example |
| 17 | +/// |
| 18 | +/// ```no_run |
| 19 | +/// use sqlx_sqlite_conn_mgr::SqliteDatabase; |
| 20 | +/// use sqlx::query; |
| 21 | +/// |
| 22 | +/// # async fn example() -> Result<(), sqlx_sqlite_conn_mgr::Error> { |
| 23 | +/// let db = SqliteDatabase::connect("test.db").await?; |
| 24 | +/// let mut writer = db.acquire_writer().await?; |
| 25 | +/// // Use &mut *writer for INSERT/UPDATE/DELETE queries |
| 26 | +/// query("INSERT INTO users (name) VALUES (?)") |
| 27 | +/// .bind("Alice") |
| 28 | +/// .execute(&mut *writer) |
| 29 | +/// .await?; |
| 30 | +/// // Writer is automatically returned when dropped |
| 31 | +/// # Ok(()) |
| 32 | +/// # } |
| 33 | +/// ``` |
| 34 | +#[derive(Debug)] |
| 35 | +pub struct WriteGuard { |
| 36 | + conn: PoolConnection<Sqlite>, |
| 37 | +} |
| 38 | + |
| 39 | +impl WriteGuard { |
| 40 | + /// Create a new WriteGuard by taking ownership of a pool connection |
| 41 | + pub(crate) fn new(conn: PoolConnection<Sqlite>) -> Self { |
| 42 | + Self { conn } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl Deref for WriteGuard { |
| 47 | + type Target = SqliteConnection; |
| 48 | + |
| 49 | + fn deref(&self) -> &Self::Target { |
| 50 | + &self.conn |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +impl DerefMut for WriteGuard { |
| 55 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 56 | + &mut self.conn |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +// Drop is automatically implemented - PoolConnection returns itself to the pool |
| 61 | + |
| 62 | +// WriteGuard must be Send to cross .await boundaries |
| 63 | +// This is safe because SqliteConnection is Send |
| 64 | +unsafe impl Send for WriteGuard {} |
0 commit comments