use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;
use tokio::sync::oneshot;
use tokio::time::Instant;
use super::{count, exec, hold_snapshot, open, options, query};
use crate::db::OPTIMIZE_SQL;
use crate::gate::Priority;
use crate::maintenance::OPTIMIZE_INTERVAL;
use crate::writer::Writer;
use crate::{Db, Error, Migration, Options, WriteError, WriteOptions};
const TABLE: &str = "CREATE TABLE t (id INTEGER PRIMARY KEY, v INTEGER NOT NULL) STRICT;
CREATE INDEX t_v ON t (v);";
const HUNDRED_ROWS: &str =
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100)
INSERT INTO t (v) SELECT i % 7 FROM n;";
const TEN_ROWS: &str =
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 10)
INSERT INTO t (v) SELECT i % 7 FROM n;";
const MORE_ROWS: &str =
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 190)
INSERT INTO t (v) SELECT i % 7 FROM n;";
async fn analyzed_rows(db: &Db) -> u64 {
let stat: String = query(
db,
"SELECT stat FROM sqlite_stat1 WHERE idx = 't_v'".to_owned(),
)
.await;
stat.split_whitespace()
.next()
.and_then(|rows| rows.parse().ok())
.expect("row estimate")
}
async fn optimize(db: &Db) {
db.inner
.exclusive(Priority::Normal, |writer| writer.optimize(OPTIMIZE_SQL))
.await
.expect("optimize");
}
#[tokio::test]
async fn open_analyzes_tables_that_lack_statistics() {
let dir = TempDir::new().expect("dir");
let options = options(&dir);
let first = open(&options).await;
exec(&first, TABLE).await;
exec(&first, HUNDRED_ROWS).await;
first.close().await.expect("close");
let reopened = open(&options).await;
assert_eq!(analyzed_rows(&reopened).await, 100);
reopened.close().await.expect("close");
}
#[tokio::test]
async fn migrate_analyzes_new_indexes() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
db.migrate(vec![
Migration::new(
"0001_create.sql",
"CREATE TABLE t (id INTEGER PRIMARY KEY, v INTEGER NOT NULL) STRICT;
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100)
INSERT INTO t (v) SELECT i % 7 FROM n;",
),
Migration::new("0002_index.sql", "CREATE INDEX t_v ON t (v);"),
])
.await
.expect("migrate");
assert_eq!(analyzed_rows(&db).await, 100);
db.close().await.expect("close");
}
#[tokio::test]
async fn periodic_optimize_reanalyzes_tables_only_readers_query() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
exec(&db, TABLE).await;
exec(&db, TEN_ROWS).await;
optimize(&db).await;
let small = analyzed_rows(&db).await;
exec(&db, MORE_ROWS).await;
optimize(&db).await;
let grown = analyzed_rows(&db).await;
assert_eq!((small, grown >= 100), (10, true), "{grown}");
db.close().await.expect("close");
}
#[tokio::test]
async fn periodic_checkpoint_does_not_wait_for_readers() {
let dir = TempDir::new().expect("dir");
let db = Arc::new(open(&options(&dir)).await);
exec(
&db,
"CREATE TABLE t (v INTEGER) STRICT; INSERT INTO t VALUES (1)",
)
.await;
let mut snapshot = hold_snapshot(&db);
(&mut snapshot.taken).await.expect("snapshot");
exec(&db, "INSERT INTO t VALUES (2)").await;
let started = Instant::now();
let checkpointed = db
.inner
.exclusive(Priority::Normal, Writer::checkpoint_passive)
.await;
let waited = started.elapsed();
snapshot.finish().await;
assert!(
checkpointed.is_ok() && waited < Duration::from_secs(1),
"{waited:?}"
);
db.close().await.expect("close");
}
#[tokio::test(start_paused = true)]
async fn idle_connections_are_closed() {
let dir = TempDir::new().expect("dir");
let options = Options {
connection_max_idle: Duration::from_millis(20),
..options(&dir)
};
let db = open(&options).await;
exec(&db, "CREATE TABLE t (v INTEGER) STRICT").await;
count(&db, "t").await;
let before = (db.inner.writer.is_open(), db.inner.readers.open_count());
tokio::time::sleep(Duration::from_secs(3)).await;
let after = (db.inner.writer.is_open(), db.inner.readers.open_count());
assert_eq!((before, after), ((true, 1), (false, 0)));
db.close().await.expect("close");
}
#[tokio::test(start_paused = true)]
async fn maintenance_analyzes_tables_hourly() {
let dir = TempDir::new().expect("dir");
let db = open(&options(&dir)).await;
exec(&db, TABLE).await;
exec(&db, HUNDRED_ROWS).await;
tokio::time::sleep(OPTIMIZE_INTERVAL + Duration::from_secs(1)).await;
assert_eq!(analyzed_rows(&db).await, 100);
db.close().await.expect("close");
}
type Written = tokio::task::JoinHandle<Result<(), WriteError<rusqlite::Error>>>;
fn spawn_write(db: &Arc<Db>, value: i64, entered: Option<oneshot::Sender<()>>) -> Written {
let db = Arc::clone(db);
tokio::spawn(async move {
db.write(WriteOptions::default(), move |transaction| {
if let Some(entered) = entered {
entered.send(()).expect("entered");
std::thread::sleep(Duration::from_millis(300));
}
transaction.execute("INSERT INTO t (v) VALUES (?1)", [value])?;
Ok(())
})
.await
})
}
async fn waiting(db: &Db, waiters: usize) {
while db.inner.gate.waiting() < waiters {
tokio::task::yield_now().await;
}
}
#[tokio::test]
async fn close_skips_maintenance_queued_behind_writes() {
let dir = TempDir::new().expect("dir");
let options = Options {
checkpoint_interval: Duration::from_millis(100),
..options(&dir)
};
let db = Arc::new(open(&options).await);
exec(&db, TABLE).await;
let (entered, started) = oneshot::channel();
let holder = spawn_write(&db, 0, Some(entered));
started.await.expect("started");
let queued: Vec<_> = (1..=3).map(|value| spawn_write(&db, value, None)).collect();
waiting(&db, 4).await;
db.close().await.expect("close");
let mut refused = 0;
for write in queued {
refused += usize::from(matches!(
write.await.expect("queued write"),
Err(WriteError::NotStarted(Error::Closed))
));
}
holder.await.expect("holder").expect("held write");
let reopened = open(&options).await;
assert_eq!((refused, count(&reopened, "t").await), (3, 1));
reopened.close().await.expect("close reopened");
}
#[tokio::test]
async fn a_writer_reopened_after_idle_does_not_recreate_a_deleted_database() {
let dir = TempDir::new().expect("dir");
let options = options(&dir);
let db = open(&options).await;
exec(&db, TABLE).await;
db.inner.writer.sweep(Duration::ZERO);
for suffix in ["", "-wal", "-shm"] {
let mut file = options.path.clone().into_os_string();
file.push(suffix);
let _ = std::fs::remove_file(file);
}
let written = db
.write(WriteOptions::default(), |transaction| {
transaction.execute_batch("INSERT INTO t (v) VALUES (1)")
})
.await;
assert!(
matches!(written, Err(WriteError::NotStarted(_))) && !options.path.exists(),
"{written:?}"
);
let _ = db.close().await;
}