1use crate::pool::{backend, pool, Backend};
2use larust_core::AppError;
3use sha2::{Digest, Sha256};
4use std::path::Path;
5
6pub 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 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 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 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 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
154pub 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}