sqlx_sqlite_conn_mgr/write_guard.rs
1//! WriteGuard for exclusive write access to the database
2
3use sqlx::Sqlite;
4use sqlx::pool::PoolConnection;
5use sqlx::sqlite::SqliteConnection;
6use 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", None).await?;
24/// let mut writer = db.acquire_writer().await?;
25/// // Use &mut *writer for write queries (e.g. INSERT/UPDATE/DELETE)
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#[must_use = "if unused, the write lock is immediately released"]
35#[derive(Debug)]
36pub struct WriteGuard {
37 conn: PoolConnection<Sqlite>,
38}
39
40impl WriteGuard {
41 /// Create a new WriteGuard by taking ownership of a pool connection
42 pub(crate) fn new(conn: PoolConnection<Sqlite>) -> Self {
43 Self { conn }
44 }
45}
46
47impl Deref for WriteGuard {
48 type Target = SqliteConnection;
49
50 fn deref(&self) -> &Self::Target {
51 &self.conn
52 }
53}
54
55impl DerefMut for WriteGuard {
56 fn deref_mut(&mut self) -> &mut Self::Target {
57 &mut self.conn
58 }
59}
60
61// Drop is automatically implemented - PoolConnection returns itself to the pool
62
63// WriteGuard is automatically Send because PoolConnection<Sqlite> is Send