use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use rusqlite::{Connection, Transaction};
use tempfile::TempDir;
use tokio::time::Instant;
use super::{count, exec, open, options, query};
use crate::Db;
use crate::{Error, Migration, Priority, WriteError, WriteOptions};
const ENDLESS_INSERT: &str =
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) INSERT INTO t SELECT i FROM n";
const LONG_COUNT: &str = "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100000) SELECT count(*) FROM n";
fn panicking(_: &Transaction<'_>) -> Result<(), &'static str> {
panic!("stop")
}
fn insert(db: &Arc<Db>, priority: Priority, value: i64) -> tokio::task::JoinHandle<()> {
let db = Arc::clone(db);
tokio::spawn(async move {
let options = WriteOptions {
priority,
deadline: None,
};
db.write(options, move |transaction| {
transaction.execute("INSERT INTO t VALUES (?1)", [value])
})
.await
.expect("insert");
})
}
async fn queued(db: &Db, waiters: usize) {
while db.inner.gate.waiting() < waiters {
tokio::task::yield_now().await;
}
}
fn within(duration: Duration) -> WriteOptions {
WriteOptions {
priority: Priority::Normal,
deadline: Some(Instant::now() + duration),
}
}
#[tokio::test]
async fn write_rolls_back_on_error() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
exec(&db, "CREATE TABLE t (v INTEGER) STRICT").await;
let written = db
.write(WriteOptions::default(), |transaction| {
transaction
.execute("INSERT INTO t VALUES (1)", [])
.map_err(|_| "insert")?;
Err::<(), _>("stop")
})
.await;
assert!(matches!(written, Err(WriteError::Aborted("stop"))));
assert_eq!(count(&db, "t").await, 0);
db.close().await.expect("close");
}
#[tokio::test]
async fn write_releases_the_writer_after_a_panic() {
let dir = TempDir::new().expect("dir");
let db = Arc::new(open(&options(&dir)).await);
let panicked = tokio::spawn({
let db = Arc::clone(&db);
async move { db.write(WriteOptions::default(), panicking).await }
})
.await;
let after = db
.write(within(Duration::from_secs(1)), |_| Ok::<_, &str>(()))
.await;
assert!(panicked.is_err_and(|error| error.is_panic()) && after.is_ok());
db.close().await.expect("close");
}
#[tokio::test]
async fn write_reports_the_deadline_while_the_database_is_locked() {
let dir = TempDir::new().expect("dir");
let options = options(&dir);
let db = open(&options).await;
let holder = Connection::open(&options.path).expect("holder");
holder
.execute_batch("BEGIN IMMEDIATE")
.expect("hold the write lock");
let started = Instant::now();
let written = db
.write(within(Duration::from_millis(50)), |_| Ok::<_, &str>(()))
.await;
let waited = started.elapsed();
holder
.execute_batch("ROLLBACK")
.expect("release the write lock");
drop(holder);
assert!(matches!(
written,
Err(WriteError::NotStarted(Error::Deadline))
));
assert!(waited < options.busy_timeout, "{waited:?}");
db.close().await.expect("close");
}
#[tokio::test]
async fn write_reports_the_deadline_while_waiting_for_the_writer() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
let permit = db.inner.gate.acquire(Priority::High).await;
let written = db
.write(within(Duration::from_millis(50)), |_| Ok::<_, &str>(()))
.await;
drop(permit);
let after = db
.write(WriteOptions::default(), |_| Ok::<_, &str>(()))
.await;
assert!(matches!(written, Err(WriteError::NotStarted(Error::Deadline))) && after.is_ok());
db.close().await.expect("close");
}
#[tokio::test]
async fn a_write_past_its_deadline_does_not_start() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
let ran = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&ran);
let past = Instant::now()
.checked_sub(Duration::from_millis(1))
.expect("past instant");
let options = WriteOptions {
priority: Priority::Normal,
deadline: Some(past),
};
let written = db
.write(options, move |_| {
flag.store(true, Ordering::SeqCst);
Ok::<_, &str>(())
})
.await;
let not_started = matches!(written, Err(WriteError::NotStarted(Error::Deadline)));
assert_eq!((not_started, ran.load(Ordering::SeqCst)), (true, false));
db.close().await.expect("close");
}
#[tokio::test]
async fn high_priority_writes_go_first() {
let dir = TempDir::new().expect("dir");
let db = Arc::new(open(&options(&dir)).await);
exec(&db, "CREATE TABLE t (v INTEGER) STRICT").await;
let permit = db.inner.gate.acquire(Priority::Normal).await;
let normal = insert(&db, Priority::Normal, 1);
queued(&db, 1).await;
let high = insert(&db, Priority::High, 2);
queued(&db, 2).await;
drop(permit);
let finished = (normal.await.is_ok(), high.await.is_ok());
let order: String = query(
&db,
"SELECT group_concat(v) FROM (SELECT v FROM t ORDER BY rowid)".to_owned(),
)
.await;
assert_eq!((finished, order.as_str()), ((true, true), "2,1"));
db.close().await.expect("close");
}
#[tokio::test]
async fn a_statement_interrupted_by_the_deadline_expires_the_write() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
exec(&db, "CREATE TABLE t (v INTEGER) STRICT").await;
let written = db
.write(within(Duration::from_millis(100)), |transaction| {
transaction.execute(ENDLESS_INSERT, [])
})
.await;
assert!(matches!(written, Err(WriteError::Expired)), "{written:?}");
assert_eq!(count(&db, "t").await, 0);
db.close().await.expect("close");
}
#[tokio::test]
async fn a_write_that_panicked_leaves_later_commits_allowed() {
let dir = TempDir::new().expect("dir");
let db = Arc::new(open(&options(&dir)).await);
let panicked = tokio::spawn({
let db = Arc::clone(&db);
async move { db.write(within(Duration::from_secs(5)), panicking).await }
})
.await;
let migrated = db
.migrate(vec![Migration::new(
"0001_create.sql",
"CREATE TABLE t (v INTEGER) STRICT;",
)])
.await;
assert!(
panicked.is_err_and(|error| error.is_panic()),
"{migrated:?}"
);
migrated.expect("migrate after the panic");
assert_eq!(count(&db, "t").await, 0);
db.close().await.expect("close");
}
#[tokio::test]
async fn statements_after_an_interrupt_do_not_commit() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
exec(&db, "CREATE TABLE t (v INTEGER) STRICT").await;
let written = db
.write(within(Duration::from_millis(100)), |transaction| {
let interrupted = transaction.execute(ENDLESS_INSERT, []).is_err();
let late = transaction.execute("INSERT INTO t VALUES (-1)", []).is_ok();
Ok::<_, &str>((interrupted, late))
})
.await;
assert!(matches!(written, Err(WriteError::Expired)), "{written:?}");
assert_eq!(count(&db, "t").await, 0);
db.close().await.expect("close");
}
#[tokio::test]
async fn a_deadline_ends_with_its_write() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
db.write(within(Duration::from_millis(200)), |_| Ok::<_, &str>(()))
.await
.expect("short write");
tokio::time::sleep(Duration::from_millis(250)).await;
let counted = db
.write(WriteOptions::default(), |transaction| {
let busy =
transaction.query_row("PRAGMA busy_timeout", [], |row| row.get::<_, i64>(0))?;
let rows = transaction.query_row(LONG_COUNT, [], |row| row.get::<_, i64>(0))?;
Ok::<_, rusqlite::Error>((busy, rows))
})
.await;
assert_eq!(counted.ok(), Some((2000, 100_000)));
db.close().await.expect("close");
}
#[tokio::test]
async fn a_write_past_its_deadline_is_rolled_back() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
exec(&db, "CREATE TABLE t (v INTEGER) STRICT").await;
let written = db
.write(within(Duration::from_millis(30)), |transaction| {
transaction.execute("INSERT INTO t VALUES (1)", [])?;
std::thread::sleep(Duration::from_millis(80));
Ok::<_, rusqlite::Error>(())
})
.await;
assert!(matches!(written, Err(WriteError::Expired)));
assert_eq!(count(&db, "t").await, 0);
db.close().await.expect("close");
}
#[tokio::test]
async fn a_failed_commit_reports_an_unknown_outcome_and_the_next_write_still_runs() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
exec(
&db,
"CREATE TABLE parent (id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE child (parent INTEGER REFERENCES parent(id) DEFERRABLE INITIALLY DEFERRED) STRICT",
)
.await;
let written = db
.write(WriteOptions::default(), |transaction| {
transaction.execute("INSERT INTO child VALUES (1)", [])
})
.await;
assert!(matches!(written, Err(WriteError::CommitUnknown(_))));
assert_eq!(count(&db, "child").await, 0);
let after = db
.write(within(Duration::from_secs(1)), |transaction| {
transaction.execute("INSERT INTO parent VALUES (1)", [])
})
.await;
assert!(after.is_ok());
assert_eq!(count(&db, "parent").await, 1);
db.close().await.expect("close");
}
#[tokio::test]
async fn a_write_whose_caller_is_aborted_after_it_started_still_commits() {
let dir = TempDir::new().expect("dir");
let db = Arc::new(open(&options(&dir)).await);
exec(&db, "CREATE TABLE t (v INTEGER) STRICT").await;
let (started, entered) = std::sync::mpsc::channel::<()>();
let (release, released) = std::sync::mpsc::channel::<()>();
let apply = move |transaction: &Transaction<'_>| {
started.send(()).expect("started");
released.recv().expect("released");
transaction.execute("INSERT INTO t VALUES (1)", [])
};
let writer = Arc::clone(&db);
let caller = tokio::spawn(async move { writer.write(WriteOptions::default(), apply).await });
tokio::task::spawn_blocking(move || entered.recv())
.await
.expect("join")
.expect("entered");
caller.abort();
assert!(caller.await.is_err_and(|error| error.is_cancelled()));
release.send(()).expect("release");
let after = db
.write(within(Duration::from_secs(2)), |transaction| {
transaction.execute("INSERT INTO t VALUES (2)", [])
})
.await;
assert!(after.is_ok());
assert_eq!(count(&db, "t").await, 2);
db.close().await.expect("close");
}