Skip to main content

luxid_orm/
migration.rs

1//! Migrations.
2//!
3//! Luxid does not reimplement SeaORM's migrator; it wraps it, so migrations are
4//! ordinary `MigrationTrait` implementations and the cross-dialect DDL builder
5//! comes along unchanged. What Luxid adds is Luxid's error type and a status
6//! you can render, rather than one that prints to stdout.
7
8use luxid_core::error::{Error, Result};
9use sea_orm_migration::MigratorTrait;
10
11use crate::db::Db;
12
13/// Everything needed to write a migration.
14///
15/// One gotcha worth knowing: SeaORM's `DeriveMigrationName` takes the migration
16/// name from the **file stem**, not the struct name — so two migrations in one
17/// file share a name and the second is treated as already applied. One
18/// migration per file, named `m20260101_000001_create_posts.rs`. Implement
19/// `MigrationName` by hand if you need a name the filename cannot give.
20pub mod prelude {
21    pub use sea_orm_migration::prelude::*;
22    /// `pk_auto`, `string`, `integer`, `timestamp`, … — column shorthands that
23    /// SeaORM keeps out of its own prelude.
24    pub use sea_orm_migration::schema::*;
25}
26
27/// Whether a migration has run.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct MigrationState {
30    pub name: String,
31    pub applied: bool,
32}
33
34fn failed(action: &str, err: sea_orm::DbErr) -> Error {
35    Error::internal(format!("{action} failed: {err}"))
36}
37
38impl Db {
39    /// Apply every pending migration.
40    pub async fn migrate<M: MigratorTrait>(&self) -> Result<()> {
41        M::up(self.connection(), None)
42            .await
43            .map_err(|err| failed("migrate", err))
44    }
45
46    /// Apply at most `steps` pending migrations.
47    pub async fn migrate_steps<M: MigratorTrait>(&self, steps: u32) -> Result<()> {
48        M::up(self.connection(), Some(steps))
49            .await
50            .map_err(|err| failed("migrate", err))
51    }
52
53    /// Roll back the last `steps` applied migrations.
54    pub async fn rollback<M: MigratorTrait>(&self, steps: u32) -> Result<()> {
55        M::down(self.connection(), Some(steps))
56            .await
57            .map_err(|err| failed("rollback", err))
58    }
59
60    /// Drop everything and migrate from scratch. Never run this against data
61    /// you want to keep.
62    pub async fn migrate_fresh<M: MigratorTrait>(&self) -> Result<()> {
63        M::fresh(self.connection())
64            .await
65            .map_err(|err| failed("migrate:fresh", err))
66    }
67
68    /// Every migration and whether it has been applied, in declaration order.
69    pub async fn migration_status<M: MigratorTrait>(&self) -> Result<Vec<MigrationState>> {
70        let applied = M::get_applied_migrations(self.connection())
71            .await
72            .map_err(|err| failed("migrate:status", err))?;
73
74        let pending = M::get_pending_migrations(self.connection())
75            .await
76            .map_err(|err| failed("migrate:status", err))?;
77
78        let mut states: Vec<MigrationState> = applied
79            .into_iter()
80            .map(|migration| MigrationState {
81                name: migration.name().to_owned(),
82                applied: true,
83            })
84            .collect();
85
86        states.extend(pending.into_iter().map(|migration| MigrationState {
87            name: migration.name().to_owned(),
88            applied: false,
89        }));
90
91        Ok(states)
92    }
93
94    /// Whether anything is waiting to run — worth checking at boot.
95    pub async fn has_pending_migrations<M: MigratorTrait>(&self) -> Result<bool> {
96        M::get_pending_migrations(self.connection())
97            .await
98            .map(|pending| !pending.is_empty())
99            .map_err(|err| failed("migrate:status", err))
100    }
101}