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
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use laravel::Application;
use laravel::config::Env;
use laravel::db::{AnyConnection, DatabaseManager, Migrations};
use laravel::event::Event;
use laravel::foundation::StartupError;
use laravel::model::{Created, create, model};

use crate::migrations::{audits, users};
use crate::support::TempDir;

fn application(url: &str, migrations: Migrations) -> Application {
    configure(url).with_migrations(migrations).refresh_database().create()
}

fn configure(url: &str) -> laravel::foundation::ApplicationBuilder {
    Application::configure().replace_env(Env::from_iter([
        ("APP_ENV", "testing"),
        ("DB_CONNECTION", "primary"),
        ("DATABASE_URL", url),
    ]))
}

/// Run one test's worth of work on a runtime of its own, as `#[laravel::test]` does. The test's
/// connections close when its runtime ends, which gives its database back. Two tests that share a
/// database wait for each other, so the work has a time limit.
fn test<T>(work: impl AsyncFnOnce() -> laravel::Result<T>) -> laravel::Result<T> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(async { tokio::time::timeout(Duration::from_secs(30), work()).await })
        .expect("the test shouldn't wait for another")
}

async fn database(app: &Application) -> laravel::Result<AnyConnection> {
    app.resolve::<DatabaseManager>().await.default_connection()
}

async fn count(app: &Application, sql: &'static str) -> laravel::Result<i64> {
    Ok(database(app).await?.query(sql).scalar::<i64>().await?.unwrap_or(0))
}

fn sqlite(root: &TempDir) -> String {
    format!("sqlite://{}", root.join("database.sqlite").display())
}

fn files(root: &TempDir) -> Vec<String> {
    let mut files: Vec<_> = std::fs::read_dir(&**root)
        .expect("the directory should be readable")
        .map(|entry| {
            entry
                .expect("the entry should be readable")
                .file_name()
                .to_string_lossy()
                .into_owned()
        })
        .filter(|name| name.ends_with(".sqlite"))
        .collect();
    files.sort();
    files
}

#[test]
fn tests_that_run_one_after_another_reuse_one_migrated_database() -> laravel::Result<()> {
    let root = TempDir::new("refresh-sequential");
    let url = sqlite(&root);

    for _ in 0..2 {
        test(async || {
            let app = application(&url, users());
            assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 0);
            database(&app)
                .await?
                .query("INSERT INTO users (email) VALUES ('taylor@laravel.com')")
                .insert()
                .await?;
            assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 1);
            assert_eq!(count(&app, "SELECT COUNT(*) FROM migrations").await?, 2);
            Ok(())
        })?;
    }

    // This crate's tests compile with `cfg(test)`, so they get the copies for unit tests.
    assert_eq!(files(&root), ["database_unit_1.sqlite"]);
    Ok(())
}

#[test]
fn tests_that_run_at_the_same_time_get_databases_of_their_own() -> laravel::Result<()> {
    let root = TempDir::new("refresh-concurrent");
    let url = sqlite(&root);

    test(async || {
        let first = application(&url, users());
        let second = application(&url, users());
        let insert = "INSERT INTO users (email) VALUES ('taylor@laravel.com')";

        // The first test's transaction holds its database's write lock until the test ends...
        database(&first).await?.query(insert).insert().await?;
        tokio::time::timeout(Duration::from_secs(1), database(&second).await?.query(insert).insert())
            .await
            .expect("the second test shouldn't wait for the first")?;

        assert_eq!(count(&first, "SELECT COUNT(*) FROM users").await?, 1);
        assert_eq!(count(&second, "SELECT COUNT(*) FROM users").await?, 1);
        Ok(())
    })?;

    assert_eq!(files(&root), ["database_unit_1.sqlite", "database_unit_2.sqlite"]);
    Ok(())
}

#[test]
fn a_database_that_a_test_committed_to_is_rebuilt_for_the_next_test() -> laravel::Result<()> {
    let root = TempDir::new("refresh-committed");
    let url = sqlite(&root);

    test(async || {
        let app = application(&url, users());
        let connection = database(&app).await?;
        connection
            .query("INSERT INTO users (email) VALUES ('taylor@laravel.com')")
            .insert()
            .await?;
        // As a DDL statement on MySQL does, commit the test's transaction behind its back.
        let mut native = connection.typed::<laravel::db::sqlx::Sqlite>()?.acquire().await?;
        laravel::db::sqlx::raw_sql("COMMIT").execute(&mut *native).await?;
        Ok(())
    })?;

    test(async || {
        let app = application(&url, users());
        assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 0);
        Ok(())
    })
}

#[test]
fn a_new_build_of_the_migrations_rebuilds_the_database() -> laravel::Result<()> {
    let root = TempDir::new("refresh-changed");
    let url = sqlite(&root);
    let tables = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('users', 'audits')";

    test(async || {
        let app = application(&url, users());
        assert_eq!(count(&app, tables).await?, 1);
        Ok(())
    })?;

    test(async || {
        let app = application(&url, audits());
        assert_eq!(count(&app, tables).await?, 1);
        assert_eq!(count(&app, "SELECT COUNT(*) FROM audits").await?, 0);
        Ok(())
    })
}

#[tokio::test]
async fn application_transactions_commit_into_the_tests_transaction_and_run_after_commit_callbacks()
-> laravel::Result<()> {
    let root = TempDir::new("refresh-transactions");
    let app = application(&sqlite(&root), users());
    let connection = database(&app).await?;
    let committed = Arc::new(AtomicBool::new(false));

    let flag = Arc::clone(&committed);
    connection
        .transaction(async |tx| {
            assert_eq!(tx.level(), 1);
            tx.query("INSERT INTO users (email) VALUES ('a@laravel.com')")
                .insert()
                .await?;
            tx.after_commit(move || async move {
                flag.store(true, Ordering::SeqCst);
                Ok(())
            })
            .await
        })
        .await?;
    assert!(committed.load(Ordering::SeqCst));

    let failed = connection
        .transaction(async |tx| {
            tx.query("INSERT INTO users (email) VALUES ('b@laravel.com')")
                .insert()
                .await?;
            Err::<(), _>(laravel::abort_with(500, "rolled back"))
        })
        .await;
    assert!(failed.is_err());
    assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 1);
    Ok(())
}

#[model]
pub struct User {
    pub id: i64,
    pub email: String,
}

#[tokio::test]
async fn model_listeners_run_in_the_tests_transaction_and_wait_for_the_applications_commit() -> laravel::Result<()> {
    let root = TempDir::new("refresh-events");
    let welcomed = Arc::new(Mutex::new(Vec::new()));
    let app = configure(&sqlite(&root))
        .with_migrations(users())
        .refresh_database()
        .with_events({
            let welcomed = Arc::clone(&welcomed);
            move |events, _| {
                events.listen(move |event: Event<Created<User>>| {
                    let welcomed = Arc::clone(&welcomed);
                    async move { welcomed.lock().unwrap().push(event.model.email.clone()) }
                });
            }
        })
        .create();

    app.scope(async || {
        create!(User {
            email: "taylor@laravel.com"
        })
        .await?;
        assert_eq!(*welcomed.lock().unwrap(), ["taylor@laravel.com"]);

        laravel::db::transaction(async |_| {
            create!(User {
                email: "abigail@laravel.com"
            })
            .await?;
            assert_eq!(*welcomed.lock().unwrap(), ["taylor@laravel.com"]);
            Ok(())
        })
        .await?;
        assert_eq!(*welcomed.lock().unwrap(), ["taylor@laravel.com", "abigail@laravel.com"]);
        Ok(())
    })
    .await
}

#[tokio::test]
async fn an_in_memory_database_is_migrated_for_each_test() -> laravel::Result<()> {
    for _ in 0..2 {
        let app = application("sqlite::memory:", users());
        database(&app)
            .await?
            .query("INSERT INTO users (email) VALUES ('a@laravel.com')")
            .insert()
            .await?;
        assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 1);
    }
    Ok(())
}

#[test]
fn refreshing_outside_the_testing_environment_stops_the_application() {
    let error = Application::configure()
        .replace_env(Env::from_iter([("APP_ENV", "local")]))
        .refresh_database()
        .try_create()
        .expect_err("refreshing outside testing should be a startup error");

    assert_eq!(error, StartupError::RefreshDatabase("local".into()));
}

/// A database name of this process's own on `url`'s server, and the server's URL without it.
#[cfg(any(feature = "database-postgres", feature = "database-mysql"))]
fn disposable(url: &str, purpose: &str) -> (String, String) {
    let (server, _) = url.rsplit_once('/').expect("the URL should name a database");
    (
        server.to_owned(),
        format!("laravel_refresh_{purpose}_{}", std::process::id()),
    )
}

/// Drop a PostgreSQL test database's slots, even while their connections close.
#[cfg(feature = "database-postgres")]
fn drop_postgres_slots(server: &str, name: &str) -> laravel::Result<()> {
    test(async || {
        let admin = configure(&format!("{server}/postgres")).create();
        for slot in [1, 2] {
            let sql = format!("DROP DATABASE IF EXISTS {name}_{slot} WITH (FORCE)");
            database(&admin)
                .await?
                .query(laravel::db::sqlx::AssertSqlSafe(sql))
                .statement()
                .await?;
        }
        Ok(())
    })
}

#[cfg(feature = "database-postgres")]
#[test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
fn postgres_creates_a_database_for_each_concurrent_test_and_survives_failed_queries() -> laravel::Result<()> {
    let (server, name) = disposable(&std::env::var("LARAVEL_TEST_POSTGRES_URL")?, "concurrent");
    let url = format!("{server}/{name}");
    let unique = "CREATE UNIQUE INDEX users_email_unique ON users (email)";
    let insert = "INSERT INTO users (email) VALUES ('taylor@laravel.com')";

    let ran = test(async || {
        let first = application(&url, users());
        let second = application(&url, users());
        for app in [&first, &second] {
            database(app).await?.query(unique).statement().await?;
        }

        database(&first).await?.query(insert).insert().await?;
        // In a shared database, the second insert would wait for the first test's transaction.
        tokio::time::timeout(Duration::from_secs(1), database(&second).await?.query(insert).insert())
            .await
            .expect("the second test shouldn't wait for the first")?;
        assert!(database(&first).await?.query(insert).insert().await.is_err());
        assert_eq!(count(&first, "SELECT COUNT(*) FROM users").await?, 1);
        Ok(())
    })
    .and_then(|()| {
        test(async || {
            let app = application(&url, users());
            assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 0);
            Ok(())
        })
    });

    drop_postgres_slots(&server, &name)?;
    ran
}

#[cfg(feature = "database-postgres")]
#[test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
fn postgres_cache_and_its_locks_work_inside_an_application_transaction() -> laravel::Result<()> {
    let (server, name) = disposable(&std::env::var("LARAVEL_TEST_POSTGRES_URL")?, "stores");
    let mut migrations = users();
    migrations.add(laravel::db::migrations!("tests/fixtures/migrations/cache"));

    let ran = test(async || {
        let app = configure(&format!("{server}/{name}"))
            .with_env("CACHE_STORE", "database")
            .with_migrations(migrations)
            .refresh_database()
            .create();
        app.scope(async || {
            database(&app)
                .await?
                .transaction(async |tx| {
                    tx.query("INSERT INTO users (email) VALUES ('taylor@laravel.com')")
                        .insert()
                        .await?;
                    laravel::cache::put("greeting", "Hello", Duration::from_secs(60)).await?;
                    // Locks run outside the application's transaction, as they do outside tests, so
                    // they need a connection the transaction isn't holding.
                    let lock = laravel::cache::lock("reports", Duration::from_secs(60))?;
                    let acquired = tokio::time::timeout(Duration::from_secs(2), lock.acquire())
                        .await
                        .expect("the lock shouldn't wait for the transaction")?;
                    assert!(acquired);
                    Ok(())
                })
                .await?;
            assert_eq!(
                laravel::cache::get::<String>("greeting").await?.as_deref(),
                Some("Hello")
            );
            Ok(())
        })
        .await
    });

    drop_postgres_slots(&server, &name)?;
    ran
}

#[cfg(feature = "database-mysql")]
#[test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable database"]
fn mysql_rebuilds_a_database_after_ddl_commits_a_tests_transaction() -> laravel::Result<()> {
    let url = std::env::var("LARAVEL_TEST_MYSQL_URL")?;
    let (server, name) = disposable(&url, "ddl");
    let configured = format!("{server}/{name}");

    let ran = test(async || {
        let app = application(&configured, users());
        let connection = database(&app).await?;
        connection
            .query("INSERT INTO users (id, email) VALUES (1, 'taylor@laravel.com')")
            .insert()
            .await?;
        connection.query("CREATE TABLE leftovers (id INT)").statement().await?;
        Ok(())
    })
    .and_then(|()| {
        test(async || {
            let app = application(&configured, users());
            assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 0);
            let leftovers = "SELECT COUNT(*) FROM information_schema.tables \
                             WHERE table_schema = DATABASE() AND table_name = 'leftovers'";
            assert_eq!(count(&app, leftovers).await?, 0);
            Ok(())
        })
    });

    test(async || {
        let admin = configure(&url).create();
        for number in [1, 2] {
            let sql = format!("DROP DATABASE IF EXISTS `{name}_{number}`");
            database(&admin)
                .await?
                .query(laravel::db::sqlx::AssertSqlSafe(sql))
                .statement()
                .await?;
        }
        Ok(())
    })?;
    ran
}

#[test]
fn on_sqlite_writes_outside_the_transaction_join_the_tests_transaction() -> laravel::Result<()> {
    let root = TempDir::new("refresh-outside");
    let url = sqlite(&root);

    test(async || {
        let app = application(&url, users());
        let outside = database(&app).await?.outside_transaction();
        // SQLite allows one writer, and the test's transaction is already writing.
        tokio::time::timeout(
            Duration::from_secs(2),
            outside
                .query("INSERT INTO users (email) VALUES ('taylor@laravel.com')")
                .insert(),
        )
        .await
        .expect("the write shouldn't wait for the test's transaction")?;
        assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 1);
        Ok(())
    })?;

    test(async || {
        let app = application(&url, users());
        assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 0);
        Ok(())
    })
}