use slave_framework::testing::TestDatabase;
#[derive(Debug, toasty::Model)]
struct Note {
#[key]
#[auto]
id: i64,
#[unique]
title: String,
}
#[tokio::test]
async fn pooled_connections_share_data() {
let test_db = TestDatabase::start();
let mut db = test_db.connect(toasty::models!(Note)).await;
db.push_schema().await.unwrap();
toasty::create!(Note { title: "first" })
.exec(&mut db)
.await
.unwrap();
let mut other = db.clone();
let note = Note::get_by_title(&mut other, "first").await.unwrap();
assert_eq!(note.title, "first");
let duplicate = toasty::create!(Note { title: "first" }).exec(&mut db).await;
assert!(duplicate.is_err(), "unique index must reject a duplicate");
}
#[tokio::test]
async fn concurrent_writers_all_succeed() {
let test_db = TestDatabase::start();
let mut db = test_db.connect(toasty::models!(Note)).await;
db.push_schema().await.unwrap();
let tasks: Vec<_> = (0..20)
.map(|n| {
let mut db = db.clone();
tokio::spawn(async move {
toasty::create!(Note {
title: format!("note {n}")
})
.exec(&mut db)
.await
})
})
.collect();
for task in tasks {
task.await.unwrap().unwrap();
}
assert_eq!(Note::all().exec(&mut db).await.unwrap().len(), 20);
}
#[tokio::test]
async fn data_persists_in_the_database_file() {
let test_db = TestDatabase::start();
{
let mut db = test_db.connect(toasty::models!(Note)).await;
db.push_schema().await.unwrap();
toasty::create!(Note { title: "kept" })
.exec(&mut db)
.await
.unwrap();
}
let mut db = test_db.connect(toasty::models!(Note)).await;
let notes = Note::all().exec(&mut db).await.unwrap();
assert_eq!(notes.len(), 1);
assert_eq!(notes[0].title, "kept");
}