use std::sync::{Arc, Mutex};
use std::time::Duration;
use laravel::Application;
use laravel::config::Env;
use laravel::config::database::ConnectionConfig;
use laravel::db::{self, sqlx::AssertSqlSafe};
use laravel::event::Event;
use laravel::http::Json;
use laravel::testing::MakesHttpRequests;
use laravel::validation::{DatabaseRules, Rule, Rules};
use serde::Deserialize;
use serde_json::json;
use crate::support::TempDir;
const ROWS: i64 = 2500;
fn application(connection: ConnectionConfig) -> Application {
Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.database.default = "primary".into();
config.database.connections.insert("primary".into(), connection);
config
.database
.connections
.insert("reporting".into(), ConnectionConfig::new("sqlite::memory:"));
})
.with_events(|events, _| {
events.listen_at_dispatch(audit_team);
})
.with_routing(|routing, _| {
routing.api(|route| {
route.post("/teams", store_team);
});
})
.create()
}
fn sqlite() -> ConnectionConfig {
let mut connection = ConnectionConfig::new("sqlite::memory:");
connection.max_connections = 1;
connection
}
async fn create_tables() -> laravel::Result<()> {
for table in ["team_audits", "teams", "copies", "sources"] {
let sql = format!("DROP TABLE IF EXISTS {table}");
db::default_connection()?.query(AssertSqlSafe(sql)).statement().await?;
}
db::query!("CREATE TABLE teams (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL UNIQUE)")
.statement()
.await?;
db::query!("CREATE TABLE team_audits (team_id INTEGER NOT NULL)")
.statement()
.await?;
db::query!("CREATE TABLE sources (id INTEGER PRIMARY KEY)")
.statement()
.await?;
db::query!("CREATE TABLE copies (id INTEGER PRIMARY KEY)")
.statement()
.await?;
Ok(())
}
async fn count(table: &str) -> laravel::Result<i64> {
let sql = format!("SELECT COUNT(*) FROM {table}");
let rows = db::default_connection()?
.query(AssertSqlSafe(sql))
.scalar::<i64>()
.await?;
Ok(rows.unwrap_or_default())
}
#[derive(Event)]
struct TeamCreated {
id: i64,
}
async fn audit_team(event: Event<TeamCreated>) -> laravel::Result<()> {
let id = event.id;
db::query!("INSERT INTO team_audits (team_id) VALUES ({id})")
.insert()
.await?;
Ok(())
}
async fn create_team(id: i64, name: &str) -> laravel::Result<()> {
db::transaction(async |_| {
db::query!("INSERT INTO teams (id, name) VALUES ({id}, {name})")
.insert()
.await?;
TeamCreated { id }.dispatch().await
})
.await
}
#[derive(Deserialize)]
struct NewTeams {
names: Vec<String>,
}
async fn store_team(Json(input): Json<NewTeams>) -> laravel::Result<Json<serde_json::Value>> {
db::transaction(async |_| {
for (id, name) in (1..).zip(&input.names) {
let rules = Rules::new().field("name", (Rule::required(), Rule::unique_in::<String>("teams", "name")));
let input = serde_json::from_value(json!({ "name": name }))?;
rules.validate(&input).await?;
create_team(id, name).await?;
}
Ok(Json(
json!({ "teams": count("teams").await?, "audits": count("team_audits").await? }),
))
})
.await
}
#[tokio::test]
async fn services_rules_and_awaited_listeners_join_the_requests_transaction() -> laravel::Result<()> {
let app = application(sqlite());
app.scope(create_tables).await?;
app.post("/api/teams")
.json(json!({ "names": ["Laravel", "Classic"] }))
.await
.assert_ok()
.assert_json(json!({ "teams": 2, "audits": 2 }));
app.scope(async || db::query!("DELETE FROM teams").delete().await)
.await?;
app.scope(async || db::query!("DELETE FROM team_audits").delete().await)
.await?;
app.post("/api/teams")
.json(json!({ "names": ["Rust", "Rust"] }))
.await
.assert_status(422)
.assert_see("has already been taken");
assert_eq!(app.scope(async || count("teams").await).await?, 0);
assert_eq!(app.scope(async || count("team_audits").await).await?, 0);
Ok(())
}
#[tokio::test]
async fn query_info_records_which_queries_joined_and_other_connections_keep_their_pools() -> laravel::Result<()> {
let app = application(sqlite());
let queries = Arc::new(Mutex::new(Vec::new()));
app.scope({
let queries = Arc::clone(&queries);
async move || {
create_tables().await?;
db::listen(move |query| {
queries
.lock()
.unwrap()
.push((query.connection.clone(), query.sql.clone(), query.joined_transaction));
});
db::transaction(async |tx| {
db::query!(tx, "SELECT 1").scalar::<i64>().await?;
db::query!("SELECT 2").scalar::<i64>().await?;
db::connection("reporting")?.query("SELECT 3").scalar::<i64>().await?;
Ok(())
})
.await
}
})
.await?;
let queries = queries.lock().unwrap().clone();
let expected = [
("primary", "BEGIN", false),
("primary", "SELECT 1", false),
("primary", "SELECT 2", true),
("reporting", "SELECT 3", false),
("primary", "COMMIT", false),
];
let queries: Vec<_> = queries.iter().map(|(c, s, j)| (c.as_str(), s.as_str(), *j)).collect();
assert_eq!(queries, expected);
Ok(())
}
#[tokio::test]
async fn concurrent_joined_queries_take_turns_on_the_transactions_connection() -> laravel::Result<()> {
let app = application(sqlite());
app.scope(async || {
create_tables().await?;
db::transaction(async |_| {
db::query!("INSERT INTO sources (id) VALUES (1)").insert().await?;
let joined = laravel::task::try_join!(count("sources"), count("sources"), count("sources"));
let counts = tokio::time::timeout(Duration::from_secs(5), async { joined })
.await
.expect("joined queries must not wait on each other forever")?;
assert_eq!(counts, (1, 1, 1));
Ok(())
})
.await
})
.await
}
#[tokio::test]
async fn queued_queries_fail_when_a_cursor_takes_the_connection() -> laravel::Result<()> {
use futures_util::TryStreamExt;
let app = application(sqlite());
app.scope(async || {
db::transaction(async |_| {
let mut statement = Box::pin(db::query!(
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1000000) SELECT SUM(i) FROM n"
).scalar::<i64>());
assert!(futures_util::poll!(statement.as_mut()).is_pending());
let mut cursor = db::query!("SELECT 1 UNION ALL SELECT 2").cursor();
let mut first = Box::pin(cursor.try_next());
assert!(futures_util::poll!(first.as_mut()).is_pending());
let mut queued = Box::pin(db::query!("SELECT 42").scalar::<i64>());
assert!(futures_util::poll!(queued.as_mut()).is_pending());
assert_eq!(statement.await?, Some(500000500000));
assert!(first.await?.is_some());
let result = tokio::time::timeout(Duration::from_secs(1), queued).await;
drop(cursor);
let error = result
.expect("a queued query must not wait for a cursor its caller still owns")
.expect_err("the cursor holds the connection");
assert!(error.to_string().contains("cursor"), "{error}");
assert_eq!(db::query!("SELECT 43").scalar::<i64>().await?, Some(43));
Ok(())
})
.await
})
.await
}
#[tokio::test]
async fn queued_rollback_discards_a_transaction_when_a_cursor_takes_the_connection() -> laravel::Result<()> {
use futures_util::TryStreamExt;
let directory = TempDir::new("database-joining-queued-rollback");
let file = directory.join("app.sqlite");
let app = application(ConnectionConfig::new(format!("sqlite://{}?mode=rwc", file.display())));
app.scope(async || {
create_tables().await?;
let result = db::transaction(async |_| {
let child = db::begin().await?;
db::query!("INSERT INTO sources (id) VALUES (1)").insert().await?;
let mut statement = Box::pin(db::query!(
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1000000) SELECT SUM(i) FROM n"
).scalar::<i64>());
assert!(futures_util::poll!(statement.as_mut()).is_pending());
let mut cursor = db::query!("SELECT 1 UNION ALL SELECT 2").cursor();
let mut first = Box::pin(cursor.try_next());
assert!(futures_util::poll!(first.as_mut()).is_pending());
let mut rollback = Box::pin(child.rollback());
assert!(futures_util::poll!(rollback.as_mut()).is_pending());
assert_eq!(statement.await?, Some(500000500000));
assert!(first.await?.is_some());
let result = tokio::time::timeout(Duration::from_secs(1), rollback).await;
drop(cursor);
result.expect("rollback must discard the connection rather than wait for the cursor")?;
Ok(())
})
.await;
assert!(result.is_err(), "the abandoned physical transaction cannot commit");
assert_eq!(
count("sources").await?,
0,
"the discarded transaction did not persist its write"
);
db::query!("INSERT INTO sources (id) VALUES (2)").insert().await?;
assert_eq!(count("sources").await?, 1, "later queries use a healthy connection");
Ok(())
})
.await
}
#[tokio::test]
async fn nested_transactions_are_savepoints_and_concurrent_ones_fail_without_hanging() -> laravel::Result<()> {
let app = application(sqlite());
app.scope(async || {
create_tables().await?;
db::transaction(async |_| {
db::query!("INSERT INTO sources (id) VALUES (1)").insert().await?;
let failed: laravel::Result<()> = db::transaction(async |tx| {
assert_eq!(tx.level(), 2);
db::query!("INSERT INTO sources (id) VALUES (2)").insert().await?;
Err(laravel::abort_with(409, "Discard the savepoint"))
})
.await;
assert_eq!(failed.unwrap_err().status().as_u16(), 409);
db::transaction(async |_| {
db::query!("INSERT INTO sources (id) VALUES (3)")
.insert()
.await
.map(drop)
})
.await?;
Ok(())
})
.await?;
let ids: Vec<i64> = db::query!("SELECT id FROM sources ORDER BY id")
.select()
.await?
.iter()
.map(|row| row.try_get(0))
.collect::<laravel::Result<_>>()?;
assert_eq!(ids, [1, 3]);
let nested = || {
db::transaction(async |_| {
tokio::task::yield_now().await;
count("sources").await.map(drop)
})
};
let errors = Mutex::new(Vec::new());
let concurrent = db::transaction(async |_| {
let (first, second) = tokio::join!(nested(), nested());
let failures = [first, second].into_iter().filter_map(Result::err);
errors.lock().unwrap().extend(failures.map(|error| error.to_string()));
Ok(())
});
tokio::time::timeout(Duration::from_secs(5), concurrent)
.await
.expect("concurrent savepoints on one connection must not hang")?;
let errors = errors.into_inner().unwrap();
assert_eq!(errors.len(), 1, "{errors:?}");
assert!(
errors[0].contains("concurrently") && errors[0].contains("join!"),
"a branch fails with an error that names the fix: {errors:?}"
);
Ok(())
})
.await
}
#[tokio::test]
async fn queries_join_a_savepoint_begun_inside_another_connections_transaction() -> laravel::Result<()> {
let app = application(sqlite());
app.scope(async || {
create_tables().await?;
db::transaction(async |_| {
db::connection("reporting")?
.transaction(async |_| {
let savepoint = db::begin().await?;
assert_eq!(savepoint.level(), 2);
db::query!("INSERT INTO sources (id) VALUES (1)").insert().await?;
savepoint.rollback().await
})
.await?;
assert_eq!(count("sources").await?, 0, "the insert rolled back with its savepoint");
Ok(())
})
.await
})
.await
}
#[tokio::test]
async fn work_beside_a_nested_transactions_closure_fails_instead_of_rolling_back_with_it() -> laravel::Result<()> {
let app = application(sqlite());
let committed = Arc::new(Mutex::new(false));
app.scope(async || {
create_tables().await?;
let results = db::transaction(async |tx| {
let (nested, through_tx, joined, after_commit) = tokio::join!(
db::transaction(async |_| {
db::query!("INSERT INTO sources (id) VALUES (1)").insert().await?;
tokio::time::sleep(Duration::from_millis(50)).await;
Err::<(), _>(laravel::abort_with(409, "Discard the savepoint"))
}),
async {
tokio::time::sleep(Duration::from_millis(10)).await;
db::query!(tx, "INSERT INTO sources (id) VALUES (2)").insert().await
},
async {
tokio::time::sleep(Duration::from_millis(10)).await;
db::query!("INSERT INTO sources (id) VALUES (3)").insert().await
},
async {
tokio::time::sleep(Duration::from_millis(10)).await;
let committed = Arc::clone(&committed);
db::after_commit(move || async move {
*committed.lock().unwrap() = true;
Ok(())
})
.await
},
);
assert_eq!(nested.unwrap_err().status().as_u16(), 409);
after_commit?;
Ok([through_tx.map(drop), joined.map(drop)])
})
.await?;
for result in results {
let error = result.expect_err("a write beside a nested transaction's closure fails");
assert!(error.to_string().contains("join!"), "{error}");
}
assert_eq!(count("sources").await?, 0);
Ok::<_, laravel::Error>(())
})
.await?;
assert!(
*committed.lock().unwrap(),
"after-commit work registered beside the savepoint belongs to the outer transaction"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_canceled_query_discards_the_transaction_it_joined() -> laravel::Result<()> {
let directory = TempDir::new("database-joining-canceled");
let file = directory.join("app.sqlite");
let app = application(ConnectionConfig::new(format!("sqlite://{}?mode=rwc", file.display())));
app.scope(async || {
create_tables().await?;
let result: laravel::Result<()> = db::transaction(async |_| {
let slow = db::query!(
"INSERT INTO sources (id) SELECT 1 WHERE (WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL \
SELECT i + 1 FROM n WHERE i < 5000000) SELECT COUNT(*) FROM n) > 0"
)
.insert();
tokio::time::timeout(Duration::from_millis(20), slow)
.await
.expect_err("the insert outlasts the timeout");
let error = count("sources").await.expect_err("the transaction is unusable");
assert!(error.to_string().contains("was canceled"), "{error}");
assert!(
error.to_string().contains("database_joining.rs"),
"names the canceled query: {error}"
);
Err(error)
})
.await;
assert!(result.is_err());
assert_eq!(count("sources").await?, 0, "the canceled insert rolled back");
Ok(())
})
.await
}
#[tokio::test]
async fn spawned_tasks_fail_to_join_and_background_work_runs_outside() -> laravel::Result<()> {
let app = application(sqlite());
app.scope(async || {
create_tables().await?;
let rolled_back: laravel::Result<()> = db::transaction(async |_| {
let spawned = laravel::task::spawn(count("sources")).await?;
let error = spawned.expect_err("a spawned task's query can't join the transaction");
assert!(error.to_string().contains("another task"), "{error}");
assert!(error.to_string().contains("task::background"), "{error}");
laravel::task::background(async {
db::query!("INSERT INTO sources (id) VALUES (7)").insert().await?;
Ok(())
})?;
Err(laravel::abort_with(409, "Roll back"))
})
.await;
assert_eq!(rolled_back.unwrap_err().status().as_u16(), 409);
for _ in 0..200 {
if count("sources").await? == 1 {
return Ok(());
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("the background insert ran outside the rolled-back transaction");
})
.await
}
#[tokio::test]
async fn native_access_and_the_outside_transaction_opt_out() -> laravel::Result<()> {
let directory = TempDir::new("database-joining-outside");
let options = db::sqlx::sqlite::SqliteConnectOptions::new()
.filename(directory.join("app.sqlite"))
.create_if_missing(true)
.busy_timeout(Duration::from_millis(200));
let app = application(ConnectionConfig::sqlite(options));
app.scope(async || {
create_tables().await?;
db::default_connection_for::<db::sqlx::Sqlite>()?
.transaction(async |tx| {
let native = tx.native().await?;
let error = count("sources")
.await
.expect_err("a joined query can't wait for the native guard");
assert!(error.to_string().contains("Transaction::native"), "{error}");
drop(native);
db::query!("INSERT INTO sources (id) VALUES (8), (9)").insert().await?;
let mut cursor = db::query!("SELECT id FROM sources").cursor();
futures_util::TryStreamExt::try_next(&mut cursor).await?;
let native = tokio::time::timeout(Duration::from_secs(5), tx.native())
.await
.expect("native access must not wait for a streaming cursor");
let error = native.expect_err("a cursor holds the connection");
assert!(error.to_string().contains("cursor"), "{error}");
drop(cursor);
db::query!("DELETE FROM sources").delete().await?;
db::query!("INSERT INTO sources (id) VALUES (1)").insert().await?;
let outside = db::default_connection()?.outside_transaction();
let rows = outside.query("SELECT COUNT(*) FROM sources").scalar::<i64>().await?;
assert_eq!(
rows,
Some(0),
"the opt-out doesn't see the transaction's uncommitted row"
);
let typed = outside.typed::<db::sqlx::Sqlite>()?;
let rows = typed.query("SELECT COUNT(*) FROM sources").scalar::<i64>().await?;
assert_eq!(rows, Some(0), "a typed handle keeps the opt-out");
assert_eq!(count("sources").await?, 1);
let error = outside
.query("INSERT INTO sources (id) VALUES (2)")
.insert()
.await
.expect_err("the write waits for the transaction until the busy timeout");
assert!(
error.to_string().starts_with("the SQLite database is locked"),
"{error}"
);
assert!(error.to_string().contains("transaction open"), "{error}");
Ok(())
})
.await
})
.await
}
#[tokio::test]
async fn a_sqlite_write_after_another_connection_committed_says_to_retry() -> laravel::Result<()> {
let directory = TempDir::new("database-joining-snapshot");
let options = db::sqlx::sqlite::SqliteConnectOptions::new()
.filename(directory.join("app.sqlite"))
.create_if_missing(true)
.journal_mode(db::sqlx::sqlite::SqliteJournalMode::Wal);
let app = application(ConnectionConfig::sqlite(options));
app.scope(async || {
create_tables().await?;
let error = db::transaction(async |_| {
assert_eq!(count("sources").await?, 0, "the read starts the transaction's snapshot");
db::default_connection()?
.outside_transaction()
.query("INSERT INTO sources (id) VALUES (1)")
.insert()
.await?;
db::query!("INSERT INTO sources (id) VALUES (2)").insert().await?;
Ok(())
})
.await
.expect_err("the transaction's snapshot is stale");
assert!(
error
.to_string()
.starts_with("another connection wrote to the SQLite database"),
"{error}"
);
assert!(error.to_string().contains("transaction_with_attempts"), "{error}");
Ok(())
})
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_dropped_savepoint_leaves_the_outer_transaction_usable() -> laravel::Result<()> {
let directory = TempDir::new("database-joining-dropped-savepoint");
let file = directory.join("app.sqlite");
let app = application(ConnectionConfig::new(format!("sqlite://{}?mode=rwc", file.display())));
app.scope(async || {
create_tables().await?;
db::transaction(async |tx| {
db::query!(tx, "INSERT INTO sources (id) VALUES (0)").insert().await?;
for id in 1..=200 {
let failed: laravel::Result<()> = async {
let mut savepoint = tx.begin().await?;
db::query!(savepoint, "INSERT INTO sources (id) VALUES (0)")
.insert()
.await?;
Ok(())
}
.await;
assert!(failed.is_err(), "the duplicate insert fails");
db::query!("INSERT INTO sources (id) VALUES ({id})").insert().await?;
}
Ok(())
})
.await?;
assert_eq!(count("sources").await?, 201);
Ok(())
})
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn after_commit_work_runs_exactly_when_a_canceled_transaction_committed() -> laravel::Result<()> {
let directory = TempDir::new("database-joining-canceled-commit");
let file = directory.join("app.sqlite");
let app = application(ConnectionConfig::new(format!("sqlite://{}?mode=rwc", file.display())));
let ran = Arc::new(Mutex::new(Vec::new()));
app.scope(async || {
create_tables().await?;
for id in 0..300_i64 {
let ran = Arc::clone(&ran);
let transaction = std::pin::pin!(db::transaction(async move |_| {
db::query!("INSERT INTO sources (id) VALUES ({id})").insert().await?;
db::after_commit(move || async move {
ran.lock().unwrap().push(id);
Ok(())
})
.await
}));
let mut transaction = transaction;
let polls = if id == 299 { i64::MAX } else { id };
for _ in 0..polls {
if futures_util::poll!(transaction.as_mut()).is_ready() {
break;
}
tokio::task::yield_now().await;
}
}
let mut committed = Vec::new();
for _ in 0..200 {
committed = db::query!("SELECT id FROM sources ORDER BY id")
.select()
.await?
.iter()
.map(|row| row.try_get(0))
.collect::<laravel::Result<Vec<i64>>>()?;
let mut ran = ran.lock().unwrap().clone();
ran.sort_unstable();
if ran == committed {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let mut ran = ran.lock().unwrap().clone();
ran.sort_unstable();
assert_eq!(
ran, committed,
"after-commit work runs for exactly the committed transactions"
);
Ok(())
})
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_lock_waits_for_the_commit_its_dropped_callback_began() -> laravel::Result<()> {
use laravel::time::ToSpan;
let app = application(sqlite());
let held_during_commit = Arc::new(Mutex::new(None));
app.scope(async || {
create_tables().await?;
let lock = laravel::cache::lock("payment", 1.minutes())?;
let held = Arc::clone(&held_during_commit);
let pay = lock.get(|| {
db::transaction(async move |_| {
db::query!("INSERT INTO sources (id) VALUES (1)").insert().await?;
db::after_commit(move || async move {
tokio::time::sleep(Duration::from_millis(200)).await;
let locked = laravel::cache::lock("payment", 1.minutes())?.is_locked().await?;
*held.lock().unwrap() = Some(locked);
Ok(())
})
.await
})
});
tokio::time::timeout(Duration::from_millis(50), pay)
.await
.expect_err("the caller stops waiting before the commit's work finishes");
for _ in 0..200 {
if held_during_commit.lock().unwrap().is_some() && !lock.is_locked().await? {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(
*held_during_commit.lock().unwrap(),
Some(true),
"the lock is held until the commit and its after-commit work finish"
);
assert!(!lock.is_locked().await?, "the lock is released afterwards");
assert_eq!(count("sources").await?, 1);
Ok(())
})
.await
}
async fn cursor_contract() -> laravel::Result<()> {
create_tables().await?;
db::query!(
"INSERT INTO sources (id) WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 50) \
SELECT (a.i - 1) * 50 + b.i FROM n a CROSS JOIN n b"
)
.insert()
.await?;
assert_eq!(count("sources").await?, ROWS);
let postgres = matches!(db::default_connection()?.driver(), db::Driver::Postgres);
let rolled_back: laravel::Result<()> = db::transaction(async |tx| {
let copied = db::query!(tx, "SELECT id FROM sources ORDER BY id").each(async |row| {
let id: i64 = row.try_get(0)?;
db::query!("INSERT INTO copies (id) VALUES ({id})").insert().await?;
if postgres && id == 1 {
assert_eq!(
open_cursors().await?,
1,
"PostgreSQL reads through a server-side cursor"
);
}
Ok(())
});
let copied = tokio::time::timeout(Duration::from_secs(60), copied)
.await
.expect("a joined query inside a cursor's callback must not wait for the cursor");
if postgres {
copied?;
} else {
let error = copied.expect_err("the cursor holds the transaction's connection");
assert!(error.to_string().contains("select()"), "{error}");
assert_eq!(count("copies").await?, 0);
for row in db::query!(tx, "SELECT id FROM sources ORDER BY id").select().await? {
let id: i64 = row.try_get(0)?;
db::query!("INSERT INTO copies (id) VALUES ({id})").insert().await?;
}
}
assert_eq!(count("copies").await?, ROWS);
if postgres {
postgres_cursor_cases().await?;
}
Err(laravel::abort_with(409, "Roll back"))
})
.await;
assert_eq!(rolled_back.unwrap_err().status().as_u16(), 409);
assert_eq!(count("copies").await?, 0);
Ok(())
}
async fn open_cursors() -> laravel::Result<i64> {
let open = db::query!("SELECT COUNT(*) FROM pg_cursors WHERE name LIKE 'laravel_cursor_%'")
.scalar::<i64>()
.await?;
Ok(open.unwrap_or_default())
}
async fn postgres_cursor_cases() -> laravel::Result<()> {
use futures_util::TryStreamExt;
let deleted: Vec<_> =
db::query!("WITH d AS (DELETE FROM copies WHERE id <= 2 RETURNING id) SELECT id FROM d ORDER BY id")
.cursor()
.and_then(async |row| row.try_get::<i64>(0))
.try_collect()
.await?;
assert_eq!(
deleted,
[1, 2],
"a cursor over a data-modifying `WITH` works in a transaction"
);
let into: Vec<_> = db::query!("SELECT id INTO TEMP copied_ids FROM copies")
.cursor()
.try_collect()
.await?;
assert!(
into.is_empty(),
"`SELECT ... INTO` streams without a server-side cursor"
);
assert_eq!(count("copied_ids").await?, ROWS - 2);
assert_eq!(open_cursors().await?, 0, "a cursor closes when it finishes");
for _ in 0..5 {
let mut cursor = db::query!("SELECT id FROM copies ORDER BY id").cursor();
cursor.try_next().await?.expect("a row");
}
assert_eq!(
open_cursors().await?,
1,
"opening a cursor closes the ones dropped before it"
);
let mut opened = None;
let rolled_back: laravel::Result<()> = db::transaction(async |_| {
let mut cursor = db::query!("SELECT id FROM copies ORDER BY id").cursor();
cursor.try_next().await?.expect("a row");
opened = Some(cursor);
Err(laravel::abort_with(409, "Roll back the savepoint"))
})
.await;
assert_eq!(rolled_back.unwrap_err().status().as_u16(), 409);
let mut cursor = opened.expect("the cursor was opened");
let ended = loop {
match cursor.try_next().await {
Ok(Some(_)) => {}
Ok(None) => panic!("the cursor ends with its nested transaction"),
Err(error) => break error,
}
};
assert!(
ended
.to_string()
.contains("nested transaction this cursor was opened in"),
"{ended}"
);
drop(cursor);
let rows: Vec<_> = db::query!("SELECT id FROM copies").cursor().try_collect().await?;
assert_eq!(rows.len() as i64, ROWS - 2);
assert_eq!(open_cursors().await?, 0);
Ok(())
}
async fn savepoint_recovery_contract() -> laravel::Result<()> {
create_tables().await?;
db::transaction(async |_| {
db::query!("INSERT INTO sources (id) VALUES (1)").insert().await?;
let failed =
db::transaction(async |_| db::query!("SELECT * FROM missing_table").select().await.map(drop)).await;
assert!(failed.is_err(), "the table is missing");
db::query!("INSERT INTO sources (id) VALUES (2)").insert().await?;
Ok(())
})
.await?;
assert_eq!(count("sources").await?, 2);
if matches!(db::default_connection()?.driver(), db::Driver::Postgres) {
let refused = db::transaction(async |_| {
let _ = db::query!("SELECT * FROM missing_table").select().await;
Ok(())
})
.await
.expect_err("the commit is refused");
assert!(refused.to_string().contains("missing_table"), "{refused}");
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sqlite_cursor_callbacks_and_savepoints_join_the_transaction() -> laravel::Result<()> {
let app = application(sqlite());
app.scope(cursor_contract).await?;
app.scope(savepoint_recovery_contract).await
}
#[cfg(feature = "database-postgres")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn postgres_cursor_callbacks_and_savepoints_join_the_transaction() -> laravel::Result<()> {
let app = application(ConnectionConfig::new(std::env::var("LARAVEL_TEST_POSTGRES_URL")?));
app.scope(cursor_contract).await?;
app.scope(savepoint_recovery_contract).await
}
#[cfg(feature = "database-mysql")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable database"]
async fn mysql_cursor_callbacks_and_savepoints_join_the_transaction() -> laravel::Result<()> {
let app = application(ConnectionConfig::new(std::env::var("LARAVEL_TEST_MYSQL_URL")?));
app.scope(cursor_contract).await?;
app.scope(savepoint_recovery_contract).await
}