1use luxid_core::error::{Error, Result};
9use sea_orm_migration::MigratorTrait;
10
11use crate::db::Db;
12
13pub mod prelude {
21 pub use sea_orm_migration::prelude::*;
22 pub use sea_orm_migration::schema::*;
25}
26
27#[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 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 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 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 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 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 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}