Skip to main content

larust_orm/
migrate.rs

1use crate::pool::{backend, pool, Backend};
2use larust_core::AppError;
3use sha2::{Digest, Sha256};
4use std::path::Path;
5
6/// Runs every `.sql` file in `migrations_dir` that hasn't already been
7/// applied, in filename order (hence the numeric prefix `xr make:migration`
8/// generates), tracking progress in a bookkeeping `_migrations` table -
9/// the same shape as Laravel's own `migrations` table.
10pub async fn run(migrations_dir: &Path) -> Result<(), AppError> {
11    let pool = pool()?;
12
13    let create_table = match backend() {
14        Backend::Sqlite => {
15            "CREATE TABLE IF NOT EXISTS _migrations (\
16                name TEXT PRIMARY KEY, \
17                checksum TEXT, \
18                applied_at TEXT NOT NULL DEFAULT (datetime('now'))\
19             )"
20        }
21        Backend::MySql => {
22            "CREATE TABLE IF NOT EXISTS _migrations (\
23                name VARCHAR(255) PRIMARY KEY, \
24                checksum TEXT, \
25                applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\
26             )"
27        }
28        // Postgres has native, unbounded `TEXT` (no MySQL-style
29        // `Any`-driver decode gap forcing a `VARCHAR(n)` cap here - see
30        // `query_builder.rs`'s doc comment) and the same standard-SQL
31        // `TIMESTAMP ... DEFAULT CURRENT_TIMESTAMP` MySQL already uses.
32        Backend::Postgres => {
33            "CREATE TABLE IF NOT EXISTS _migrations (\
34                name TEXT PRIMARY KEY, \
35                checksum TEXT, \
36                applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\
37             )"
38        }
39    };
40    sqlx::query(create_table)
41        .execute(pool)
42        .await
43        .map_err(|e| AppError::Internal(Box::new(e)))?;
44
45    // Applications created before checksums existed have the old table -
46    // upgrade it in place. SQLite-only: the `CREATE TABLE` above already
47    // includes `checksum` for a brand-new database, so a fresh MySQL app
48    // (MySQL support didn't exist before this column did) never has a
49    // pre-existing table missing it - nothing to reconcile, and no need to
50    // match MySQL's differently-worded duplicate-column error text at all.
51    if backend() == Backend::Sqlite {
52        if let Err(error) = sqlx::query("ALTER TABLE _migrations ADD COLUMN checksum TEXT")
53            .execute(pool)
54            .await
55        {
56            let duplicate_column = matches!(&error, sqlx::Error::Database(database)
57                if database.message().contains("duplicate column name"));
58            if !duplicate_column {
59                return Err(AppError::Internal(Box::new(error)));
60            }
61        }
62    }
63
64    let mut files: Vec<_> = std::fs::read_dir(migrations_dir)
65        .map_err(|e| AppError::Internal(Box::new(e)))?
66        .filter_map(|entry| entry.ok())
67        .map(|entry| entry.path())
68        .filter(|path| path.extension().is_some_and(|ext| ext == "sql"))
69        .collect();
70    files.sort();
71
72    for path in files {
73        let name = path
74            .file_name()
75            .and_then(|n| n.to_str())
76            .unwrap_or_default()
77            .to_string();
78
79        let sql = std::fs::read_to_string(&path).map_err(|e| AppError::Internal(Box::new(e)))?;
80        let checksum = format!("{:x}", Sha256::digest(sql.as_bytes()));
81
82        let select_applied_sql = match backend() {
83            Backend::Sqlite | Backend::MySql => {
84                "SELECT name, checksum FROM _migrations WHERE name = ?"
85            }
86            Backend::Postgres => "SELECT name, checksum FROM _migrations WHERE name = $1",
87        };
88        let already_applied: Option<(String, Option<String>)> = sqlx::query_as(select_applied_sql)
89            .bind(&name)
90            .fetch_optional(pool)
91            .await
92            .map_err(|e| AppError::Internal(Box::new(e)))?;
93        if let Some((_, stored_checksum)) = already_applied {
94            match stored_checksum {
95                Some(stored_checksum) if stored_checksum != checksum => {
96                    return Err(AppError::Internal(Box::new(std::io::Error::other(format!(
97                        "migration {name} was changed after it was applied; create a new migration instead"
98                    )))));
99                }
100                Some(_) => {}
101                // Treat a pre-checksum migration as trusted at upgrade time;
102                // subsequent runs detect any modification.
103                None => {
104                    let update_checksum_sql = match backend() {
105                        Backend::Sqlite | Backend::MySql => {
106                            "UPDATE _migrations SET checksum = ? WHERE name = ?"
107                        }
108                        Backend::Postgres => "UPDATE _migrations SET checksum = $1 WHERE name = $2",
109                    };
110                    sqlx::query(update_checksum_sql)
111                        .bind(&checksum)
112                        .bind(&name)
113                        .execute(pool)
114                        .await
115                        .map_err(|e| AppError::Internal(Box::new(e)))?;
116                }
117            }
118            continue;
119        }
120
121        let mut tx = pool
122            .begin()
123            .await
124            .map_err(|e| AppError::Internal(Box::new(e)))?;
125        // `raw_sql` delegates statement parsing to SQLite, so trigger
126        // bodies, comments, and string literals containing semicolons work
127        // correctly. Splitting on `;` here used to corrupt valid migrations.
128        sqlx::raw_sql(&sql)
129            .execute(&mut *tx)
130            .await
131            .map_err(|e| AppError::Internal(Box::new(e)))?;
132        let insert_migration_sql = match backend() {
133            Backend::Sqlite | Backend::MySql => {
134                "INSERT INTO _migrations (name, checksum) VALUES (?, ?)"
135            }
136            Backend::Postgres => "INSERT INTO _migrations (name, checksum) VALUES ($1, $2)",
137        };
138        sqlx::query(insert_migration_sql)
139            .bind(&name)
140            .bind(&checksum)
141            .execute(&mut *tx)
142            .await
143            .map_err(|e| AppError::Internal(Box::new(e)))?;
144        tx.commit()
145            .await
146            .map_err(|e| AppError::Internal(Box::new(e)))?;
147
148        println!("Migrated: {name}");
149    }
150
151    Ok(())
152}
153
154/// Drops every table in the connected database (including `_migrations`
155/// itself) and reapplies every migration in `migrations_dir` from scratch -
156/// Laravel's `migrate:fresh`. Forward-only, like [`run`]: there is no
157/// `down()`/rollback anywhere in this codebase, so a Laravel-style
158/// `migrate:refresh` (rollback + reapply) has nothing to build on; `fresh`
159/// needs no rollback and is what this framework can actually offer.
160///
161/// Foreign keys are disabled for the drop pass (SQLite: `PRAGMA
162/// foreign_keys`; MySQL: `FOREIGN_KEY_CHECKS`) so table order doesn't
163/// matter; Postgres instead drops each table `CASCADE`, since it has no
164/// equivalent session-wide toggle.
165///
166/// The PRAGMA/`SET` and every `DROP TABLE` run on one connection acquired
167/// from the pool (not `pool` itself as the executor) and held for the whole
168/// pass - both are session/connection-scoped settings, and `Pool::execute`
169/// is free to hand different calls different physical connections from the
170/// pool, which silently drops the toggle before the next `DROP TABLE` sees
171/// it (a real bug caught live: the very first run failed with a genuine
172/// SQLite "FOREIGN KEY constraint failed" because the `OFF` PRAGMA had
173/// landed on a connection the drop loop never actually used).
174///
175/// **`sessions` is deliberately never dropped**, unlike `_migrations` (which
176/// *is*, on purpose - see above). Unlike every other table here, `sessions`
177/// isn't tracked by `migrations_dir` at all: `larust_http::session`'s store
178/// creates it once, with `CREATE TABLE IF NOT EXISTS`, the moment
179/// `Router::with_sessions` boots - not something `run()`'s replay above can
180/// recreate. Caught live: dropping it broke the *already-running* server's
181/// own session middleware immediately (every request start failing with
182/// "no such table: sessions", including the dashboard's own login), with no
183/// way to recover short of restarting the process - since nothing re-runs
184/// that one-time `CREATE TABLE IF NOT EXISTS` again until the next boot.
185/// Treated as framework session-store plumbing, not app data to reset.
186pub async fn fresh(migrations_dir: &Path) -> Result<(), AppError> {
187    let pool = pool()?;
188    let tables: Vec<String> = crate::introspect::table_names()
189        .await?
190        .into_iter()
191        .filter(|table| table != "sessions")
192        .collect();
193    let mut conn = pool
194        .acquire()
195        .await
196        .map_err(|e| AppError::Internal(Box::new(e)))?;
197
198    if backend() == Backend::Sqlite {
199        sqlx::raw_sql("PRAGMA foreign_keys = OFF")
200            .execute(&mut *conn)
201            .await
202            .map_err(|e| AppError::Internal(Box::new(e)))?;
203    } else if backend() == Backend::MySql {
204        sqlx::raw_sql("SET FOREIGN_KEY_CHECKS = 0")
205            .execute(&mut *conn)
206            .await
207            .map_err(|e| AppError::Internal(Box::new(e)))?;
208    }
209
210    for table in &tables {
211        let sql = if backend() == Backend::Postgres {
212            format!("DROP TABLE \"{table}\" CASCADE")
213        } else {
214            format!("DROP TABLE \"{table}\"")
215        };
216        sqlx::raw_sql(&sql)
217            .execute(&mut *conn)
218            .await
219            .map_err(|e| AppError::Internal(Box::new(e)))?;
220    }
221
222    if backend() == Backend::Sqlite {
223        sqlx::raw_sql("PRAGMA foreign_keys = ON")
224            .execute(&mut *conn)
225            .await
226            .map_err(|e| AppError::Internal(Box::new(e)))?;
227    } else if backend() == Backend::MySql {
228        sqlx::raw_sql("SET FOREIGN_KEY_CHECKS = 1")
229            .execute(&mut *conn)
230            .await
231            .map_err(|e| AppError::Internal(Box::new(e)))?;
232    }
233
234    drop(conn);
235    run(migrations_dir).await
236}