Skip to main content

begin_immediate

Function begin_immediate 

Source
pub async fn begin_immediate(
    pool: &SqlitePool,
) -> Result<Transaction<'static, Sqlite>>
Expand description

Begin a WRITE transaction with BEGIN IMMEDIATE.

sqlx’s pool.begin() issues a deferred BEGIN: a transaction that reads before it writes pins its read snapshot on the first statement, and if another connection commits in between, the later write cannot upgrade — SQLite returns a busy-snapshot error even with a busy_timeout, because the conflict is logical, not a lock wait. BEGIN IMMEDIATE takes the write lock up front, so a read-then-write transaction is safe under WAL’s single-writer rule.

Also available as SqlitePoolExt::begin_immediate (pool.begin_immediate()).

§Examples

use sqlite_hardened::{begin_immediate, HardenedSqlite};

let pool = HardenedSqlite::new("sqlite://app.db").connect().await?;
let mut tx = begin_immediate(&pool).await?;
let n: i64 = sqlx::query_scalar("SELECT n FROM counters WHERE id = 1")
    .fetch_one(&mut *tx)
    .await?;
sqlx::query("UPDATE counters SET n = ? WHERE id = 1")
    .bind(n + 1)
    .execute(&mut *tx)
    .await?;
tx.commit().await?;