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
use crate::console::ConsoleInternals as _;
use std::collections::BTreeMap;
use std::fs::{self, OpenOptions};
use std::io::Write;

use comfy_table::Cell;
use regex::Regex;

use super::Migrations;
use super::migrations::Migrator;
use super::migrations::database::drop_all;
use super::migrations::schema_dump::{self, SchemaDumps, SchemaFile};
use super::seed;
use crate::Result;
use crate::console::theme::Tone;
use crate::console::{Commands, Console, clap};
use crate::container::Inject;
use crate::db::DatabaseManager;
use crate::db::seeders::Seeders;
use crate::str::Str;

pub(crate) fn register(commands: &mut Commands) {
    commands
        .add::<Make>()
        .add::<Migrate>()
        .add::<Fresh>()
        .add::<Status>()
        .add::<Dump>();
}

/// Create a migration.
#[derive(clap::Parser)]
#[command(name = "make:migration")]
struct Make {
    /// What the migration does, such as `create_posts_table`.
    name: String,
    /// The table to create.
    #[arg(long, value_name = "TABLE", conflicts_with = "table")]
    create: Option<String>,
    /// The table to change.
    #[arg(long, value_name = "TABLE")]
    table: Option<String>,
}

#[crate::console::command]
impl Make {
    async fn handle(self, console: &mut Console) -> Result<()> {
        let name = self.name.snake();
        if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
            return Err(crate::error::fail(format!(
                "migration name `{}` can only have letters, digits and underscores",
                self.name
            )));
        }

        let stub = match (self.table, self.create) {
            (None, Some(table)) => Stub::Create(table),
            (Some(table), _) => Stub::Alter(table),
            (None, None) => Stub::guess(&name),
        };
        let path = format!(
            "database/migrations/{}_{name}.rs",
            crate::now().strftime("%Y_%m_%d_%H%M%S")
        );
        let file = crate::config().app.base_path.join(&path);
        let write = || {
            fs::create_dir_all(file.parent().expect("the path has a directory"))?;
            OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&file)?
                .write_all(stub.contents().as_bytes())
        };
        use crate::ErrorContext as _;

        write().with_context(|| format!("failed to write `{path}`"))?;
        console.success(format!("Migration created at `{path}`."));
        Ok(())
    }
}

/// The migration `make:migration` writes, from the table it creates or changes.
enum Stub {
    Create(String),
    Alter(String),
    Blank,
}

impl Stub {
    /// Guess the table from a snake-case name such as `create_posts_table` or `add_slug_to_posts_table`.
    fn guess(name: &str) -> Self {
        let table = |patterns: [&str; 2], group: usize| {
            patterns.into_iter().find_map(|pattern| {
                let captures = Regex::new(pattern).expect("the pattern is valid").captures(name)?;
                Some(captures[group].to_owned())
            })
        };

        if let Some(table) = table([r"^create_(\w+)_table$", r"^create_(\w+)$"], 1) {
            Self::Create(table)
        } else if let Some(table) = table([r".+_(to|from|in)_(\w+)_table$", r".+_(to|from|in)_(\w+)$"], 2) {
            Self::Alter(table)
        } else {
            Self::Blank
        }
    }

    fn contents(&self) -> String {
        let (parameter, body) = match self {
            Self::Create(table) => (
                "tx",
                format!(
                    "    tx.schema()
        .create({table:?}, |table| {{
            table.id();
            table.timestamps();
        }})
        .await"
                ),
            ),
            Self::Alter(table) => ("tx", format!("    tx.schema().alter({table:?}, |_table| {{}}).await")),
            Self::Blank => ("_tx", "    Ok(())".to_owned()),
        };

        format!(
            "use laravel::db::AnyTransaction;

pub async fn migrate({parameter}: &mut AnyTransaction<'_>) -> laravel::Result<()> {{
{body}
}}
"
        )
    }
}

/// Run the pending migrations.
#[derive(clap::Parser)]
#[command(name = "migrate")]
struct Migrate {
    #[command(flatten)]
    options: MigrateOptions,
}

#[crate::console::command]
impl Migrate {
    async fn handle(
        self,
        manager: Inject<DatabaseManager>,
        migrations: Inject<Migrations>,
        dumps: Inject<SchemaDumps>,
        seeders: Inject<Seeders>,
        console: &mut Console,
    ) -> Result<u8> {
        self.options
            .run(false, &manager, &migrations, &dumps, &seeders, console)
            .await
    }
}

/// Drop all tables and run every migration.
#[derive(clap::Parser)]
#[command(name = "migrate:fresh")]
struct Fresh {
    #[command(flatten)]
    options: MigrateOptions,
}

#[crate::console::command]
impl Fresh {
    async fn handle(
        self,
        manager: Inject<DatabaseManager>,
        migrations: Inject<Migrations>,
        dumps: Inject<SchemaDumps>,
        seeders: Inject<Seeders>,
        console: &mut Console,
    ) -> Result<u8> {
        self.options
            .run(true, &manager, &migrations, &dumps, &seeders, console)
            .await
    }
}

/// The options `migrate` and `migrate:fresh` share.
#[derive(clap::Args)]
struct MigrateOptions {
    /// The database connection to use.
    #[arg(long, value_name = "CONNECTION")]
    database: Option<String>,
    /// Run without asking for confirmation in production.
    #[arg(long)]
    force: bool,
    #[command(flatten)]
    schema: SchemaOptions,
    #[command(flatten)]
    seed: SeedAfter,
}

impl MigrateOptions {
    /// Migrate the connection, first dropping all its tables when `fresh`, then seed it if asked.
    async fn run(
        self,
        fresh: bool,
        manager: &DatabaseManager,
        migrations: &Migrations,
        dumps: &SchemaDumps,
        seeders: &Seeders,
        console: &mut Console,
    ) -> Result<u8> {
        let seeder = self.seed.seeder(seeders)?;
        if !confirmed(self.force, console).await? {
            return Ok(1);
        }

        let migrator = migrator(manager, self.database.as_deref(), migrations)?;
        on_database(manager, self.database, async {
            if !create_missing_database(manager, &migrator, self.force, console).await? {
                return Ok(1);
            }
            if fresh {
                console.step("Dropping all tables...");
                drop_all(&migrator.connection).await?;
            }
            migrate(&migrator, &self.schema, dumps, console).await?;
            if let Some(seeder) = seeder {
                seed::seed(seeder, console).await?;
            }
            Ok(0)
        })
        .await
    }
}

/// The schema dump options of `migrate` and `migrate:fresh`.
#[derive(clap::Args)]
struct SchemaOptions {
    /// Load this schema dump instead of the connection's.
    #[arg(long, value_name = "PATH")]
    schema_path: Option<String>,
    /// Load the schema dump without running any migrations.
    #[arg(long)]
    schema_only: bool,
}

impl SchemaOptions {
    /// The dump to load into a new database: `--schema-path` from disk, or the connection's.
    fn dump(&self, dumps: &SchemaDumps, connection: &str) -> Result<Option<SchemaFile>> {
        let base_path = &crate::config().app.base_path;
        match &self.schema_path {
            Some(path) => SchemaFile::read(&base_path.join(path)),
            None => dumps.for_connection(connection, base_path),
        }
    }
}

/// The seeding options of `migrate` and `migrate:fresh`.
#[derive(clap::Args)]
struct SeedAfter {
    /// Run the default seeder after migrating.
    #[arg(long)]
    seed: bool,
    /// Run this seeder after migrating, instead of the default.
    #[arg(long, value_name = "SEEDER")]
    seeder: Option<String>,
}

impl SeedAfter {
    /// The seeder to run, looked up before anything connects, so a misspelled name fails first.
    fn seeder(&self, seeders: &Seeders) -> Result<Option<&'static super::__Seeder>> {
        match (self.seed, self.seeder.as_deref()) {
            (false, None) => Ok(None),
            (_, name) => seeders.find(name).map(Some),
        }
    }
}

/// List migrations and their status.
#[derive(clap::Parser)]
#[command(name = "migrate:status")]
struct Status {
    /// The database connection to use.
    #[arg(long, value_name = "CONNECTION")]
    database: Option<String>,
}

#[crate::console::command]
impl Status {
    async fn handle(
        self,
        manager: Inject<DatabaseManager>,
        migrations: Inject<Migrations>,
        dumps: Inject<SchemaDumps>,
        console: &mut Console,
    ) -> Result<()> {
        let migrator = migrator(&manager, self.database.as_deref(), &migrations)?;
        let squashing = dumps
            .for_connection(migrator.connection.name(), &crate::config().app.base_path)?
            .is_some();
        let ran = migrator.ran().await?;
        let latest = ran.iter().map(|ran| ran.name.as_str()).max();

        let mut rows: BTreeMap<&str, (String, &str)> = migrations
            .by_name()
            .into_keys()
            .map(|name| {
                let status = if latest.is_some_and(|latest| latest > name) {
                    "pending, out of order"
                } else {
                    "pending"
                };
                (name, (String::new(), status))
            })
            .collect();
        // With a schema dump, a recorded migration without a file is one the dump squashed.
        let mut squashed = 0;
        for ran in &ran {
            let status = match rows.contains_key(ran.name.as_str()) {
                true => "ran",
                false if squashing => {
                    squashed += 1;
                    continue;
                }
                false => "ran, not registered",
            };
            rows.insert(&ran.name, (ran.batch.to_string(), status));
        }
        let squashed = match squashed {
            0 => None,
            1 => Some("1 migration is squashed into the schema dump.".to_owned()),
            count => Some(format!("{count} migrations are squashed into the schema dump.")),
        };

        if rows.is_empty() {
            console.info(squashed.as_deref().unwrap_or("No migrations found."));
            return Ok(());
        }
        let colors = console.stdout_colors();
        console.listing(
            vec!["Migration", "Batch", "Status"],
            rows.into_iter().map(|(name, (batch, status))| {
                let tone = if status == "ran" { Tone::Success } else { Tone::Warning };
                vec![
                    Cell::new(name),
                    Cell::new(batch),
                    Cell::new(status).fg(tone.table(colors)),
                ]
            }),
        );
        if let Some(squashed) = squashed {
            // A blank line sets the count apart from the listing, which is a deliberate exception
            // to keeping messages without blank lines around them.
            console.blank_stderr_line();
            console.info(squashed);
        }
        Ok(())
    }
}

/// Dump the database schema to a file.
#[derive(clap::Parser)]
#[command(name = "schema:dump")]
struct Dump {
    /// The database connection to use.
    #[arg(long, value_name = "CONNECTION")]
    database: Option<String>,
    /// The path where the schema dump file should be stored.
    #[arg(long, value_name = "PATH")]
    path: Option<String>,
    /// Delete all existing migration files.
    #[arg(long)]
    prune: bool,
    /// Dump the schema without the migration data.
    #[arg(long)]
    without_migration_data: bool,
}

#[crate::console::command]
impl Dump {
    async fn handle(self, manager: Inject<DatabaseManager>, console: &mut Console) -> Result<()> {
        let connection = connection(&manager, self.database.as_deref())?;
        let base_path = &crate::config().app.base_path;
        let shown = match &self.path {
            Some(path) => path.clone(),
            None => format!("database/schema/{}-schema.sql", connection.name()),
        };
        schema_dump::dump(&connection, &base_path.join(&shown), !self.without_migration_data).await?;
        console.success(format!("Database schema dumped to `{shown}`."));

        if self.prune {
            let pruned = prune(&base_path.join("database/migrations"))?;
            console.success(format!("{} pruned.", count(pruned)));
        }
        Ok(())
    }
}

/// Delete the migrations that `migrations!` compiles from the directory, its top-level `.rs`
/// files, and keep the directory in Git with a `.gitkeep` file. Returns how many it deleted.
fn prune(directory: &std::path::Path) -> Result<usize> {
    use crate::ErrorContext as _;

    let failed = || format!("failed to prune `{}`", directory.display());
    let mut pruned = 0;
    if directory.is_dir() {
        for entry in fs::read_dir(directory).with_context(failed)? {
            let path = entry.with_context(failed)?.path();
            let hidden = path
                .file_name()
                .is_some_and(|name| name.to_string_lossy().starts_with('.'));
            if path.is_file() && !hidden && path.extension().is_some_and(|extension| extension == "rs") {
                fs::remove_file(&path).with_context(failed)?;
                pruned += 1;
            }
        }
    }
    fs::create_dir_all(directory).with_context(failed)?;
    let gitkeep = directory.join(".gitkeep");
    if !gitkeep.exists() {
        fs::write(gitkeep, "").with_context(failed)?;
    }
    Ok(pruned)
}

/// Offer to create the connection's database when it doesn't exist, as on a new machine. `--force`
/// creates it without asking, and `--no-interaction` without `--force` leaves it missing. Returns
/// false when the user declines.
#[cfg(any(feature = "database-postgres", feature = "database-mysql"))]
async fn create_missing_database(
    manager: &DatabaseManager,
    migrator: &Migrator<'_>,
    force: bool,
    console: &mut Console,
) -> Result<bool> {
    let Some(missing) = migrator.missing_database().await? else {
        return Ok(true);
    };
    if !force {
        if console.no_interaction {
            return Err(crate::error::fail(format!(
                "database `{}` doesn't exist on connection `{}`; use `--force` to create it",
                missing.name,
                migrator.connection.name()
            )));
        }
        console.warn(format!(
            "Database `{}` doesn't exist on connection `{}`.",
            missing.name,
            migrator.connection.name()
        ));
        if !console.confirm("Would you like to create it?").default(true).await? {
            console.info("Command cancelled.");
            return Ok(false);
        }
    }

    let name = missing.name.clone();
    missing.create(manager).await?;
    console.success(format!("Database `{name}` created."));
    Ok(true)
}

/// Only PostgreSQL and MySQL report a missing database. SQLite creates its file with `mode=rwc`.
#[cfg(not(any(feature = "database-postgres", feature = "database-mysql")))]
#[expect(clippy::unused_async, reason = "it matches the PostgreSQL and MySQL version")]
async fn create_missing_database(_: &DatabaseManager, _: &Migrator<'_>, _: bool, _: &mut Console) -> Result<bool> {
    Ok(true)
}

/// Load the schema dump into a database no migration has run on, then run the pending migrations
/// unless `--schema-only` says not to.
async fn migrate(
    migrator: &Migrator<'_>,
    schema: &SchemaOptions,
    dumps: &SchemaDumps,
    console: &mut Console,
) -> Result<()> {
    if let Some(dump) = schema.dump(dumps, migrator.connection.name())?
        && !migrator.has_run().await?
    {
        let path = dump.display_path(&crate::config().app.base_path);
        console.step(format!("Loading schema dump `{path}`..."));
        migrator.load_schema(&dump).await?;
    }
    if schema.schema_only {
        return Ok(());
    }

    let ran = migrator
        .migrate(|name| console.step(format!("Migrating `{name}`...")))
        .await?;
    if ran == 0 {
        console.info("No pending migrations found.");
    } else {
        console.success(format!("{} ran.", count(ran)));
    }
    Ok(())
}

fn migrator<'m>(manager: &DatabaseManager, database: Option<&str>, migrations: &'m Migrations) -> Result<Migrator<'m>> {
    let connection = connection(manager, database)?;
    Ok(Migrator { connection, migrations })
}

/// The `--database` connection, or the default one.
fn connection(manager: &DatabaseManager, database: Option<&str>) -> Result<crate::db::AnyConnection> {
    match database {
        Some(name) => manager.connection(name),
        None => manager.default_connection(),
    }
}

/// Make `--database` the default connection while migrations or seeders run, so a connection-free
/// `db::query!` in them uses it too.
pub(in crate::db) async fn on_database<F: Future>(
    manager: &DatabaseManager,
    database: Option<String>,
    future: F,
) -> F::Output {
    match database {
        Some(name) => manager.using_connection(name, future).await,
        None => future.await,
    }
}

pub(in crate::db) async fn confirmed(force: bool, console: &mut Console) -> Result<bool> {
    if force || !crate::config().app.env.is_production() {
        return Ok(true);
    }

    console.warn("The application is in production.");
    let confirmed = console
        .confirm("Are you sure you want to run this command?")
        .default(false)
        .await?;
    if !confirmed {
        console.info("Command cancelled.");
    }
    Ok(confirmed)
}

fn count(migrations: usize) -> String {
    match migrations {
        1 => "1 migration".to_owned(),
        count => format!("{count} migrations"),
    }
}