laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
//! Queries without `tx` join the transaction open on their connection, across the framework's
//! components: services, validation rules, awaited listeners, cursors, and nested transactions.

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;

/// Enough rows for two and a half PostgreSQL cursor batches.
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()
}

/// One in-memory SQLite connection, so a query that took another pooled connection would wait forever.
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,
}

/// A listener that runs at dispatch, inside the dispatching transaction.
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(())
}

/// A service that takes no connection, and wraps its own writes in a transaction.
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 }));

    // The unique rule sees the row this transaction inserted, so the request fails and rolls back...
    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());

            // Queue the cursor and another query behind the running statement, in that order...
            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]);

        // A second `join!` branch would nest inside the first branch's savepoint. It fails with an error
        // that names the fix, and the first branch and the transaction carry on. Each branch yields inside its
        // savepoint, because under load SQLite can answer every statement before the branch would wait, so the
        // first branch would finish before the second one starts...
        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?;

        // Both writes would have run inside the other branch's savepoint and rolled back with it,
        // while reporting success...
        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");

            // The insert may or may not have run, so the transaction must not carry on as if it hadn't...
            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);

                // SQLite allows one writer, so a write beside the transaction waits for it, and the
                // error says why...
                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?;
            // SQLite's driver rolls a dropped savepoint back later, on its worker thread, so repeat
            // to catch the outer transaction's next query arriving first...
            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?;
        // Stop waiting for the transaction after a growing number of polls, so some stops land in
        // its commit...
        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;
            // The last transaction runs to the end, so one commits however slowly the database answers...
            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
            })
        });
        // The caller stops waiting, such as when a client disconnects, while the commit's work runs...
        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
}

/// Insert a row for each of `ROWS` rows a cursor streams, inside a transaction, and roll it back.
/// On PostgreSQL, the callback's queries join the transaction. Elsewhere, the cursor holds the
/// connection, so they fail, and reading the rows first works instead.
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())
}

/// Statements PostgreSQL can't declare a cursor for, and cursors dropped before they finish.
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"
    );
    // A cursor opened in a nested transaction ends with it, and says so...
    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(())
}

/// A failed statement in a savepoint leaves the outer transaction usable once the savepoint rolls
/// back, including on PostgreSQL, which aborts the transaction until then.
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);

    // PostgreSQL rejects a commit after an error the closure swallowed, and says which query failed...
    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
}