1use std::collections::{HashMap, HashSet};
4use std::fmt;
5use std::sync::Arc;
6
7use crate::adapter::{Adapter, DbResult};
8use crate::schema::{ColumnDef, ColumnType, IdStorage, Schema, TableDef};
9
10#[derive(Clone, Debug, Default, PartialEq, Eq)]
12pub struct LiveSchema {
13 pub tables: HashMap<String, HashSet<String>>,
15 pub indexes: HashSet<(String, String)>,
18 pub id_storage: HashMap<(String, String), IdStorage>,
22}
23
24#[derive(Clone, Debug, PartialEq)]
25pub enum Step {
26 CreateTable(Arc<TableDef>),
27 AddColumn {
28 table: Arc<TableDef>,
29 column: ColumnDef,
30 },
31 CreateIndex {
33 table: Arc<TableDef>,
34 column: ColumnDef,
35 },
36}
37
38impl fmt::Display for Step {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 match self {
41 Step::CreateTable(t) => write!(
42 f,
43 "create table {} ({} columns, owner {})",
44 t.name,
45 t.columns.len(),
46 t.owner
47 ),
48 Step::AddColumn { table, column } => {
49 write!(
50 f,
51 "add column {}.{} ({:?}, owner {})",
52 table.name, column.name, column.ty, column.owner
53 )
54 }
55 Step::CreateIndex { table, column } => {
56 write!(
57 f,
58 "create {}index on {}.{}",
59 if column.unique { "unique " } else { "" },
60 table.name,
61 column.name
62 )
63 }
64 }
65 }
66}
67
68pub fn index_name(table: &str, column: &str) -> String {
70 format!("idx_{table}_{column}")
71}
72
73#[derive(Clone, Debug, Default, PartialEq)]
74pub struct MigrationPlan {
75 pub steps: Vec<Step>,
76 pub warnings: Vec<String>,
79}
80
81impl MigrationPlan {
82 pub fn is_empty(&self) -> bool {
83 self.steps.is_empty()
84 }
85
86 pub fn diff(schema: &Schema, live: &LiveSchema) -> Self {
87 let mut plan = MigrationPlan::default();
88 let mut mismatched_ids = Vec::new();
89 for table in schema.tables() {
90 let Some(live_columns) = live.tables.get(table.name) else {
91 plan.steps.push(Step::CreateTable(table.clone()));
92 for column in table
93 .columns
94 .iter()
95 .filter(|c| c.index && !c.unique && !c.primary_key)
96 {
97 plan.steps.push(Step::CreateIndex {
98 table: table.clone(),
99 column: *column,
100 });
101 }
102 continue;
103 };
104 for column in &table.columns {
105 let key = (table.name.to_owned(), column.name.to_owned());
106 if column.ty == ColumnType::Id
107 && live
108 .id_storage
109 .get(&key)
110 .is_some_and(|&stored| stored != schema.id_storage())
111 {
112 mismatched_ids.push(format!("{}.{}", table.name, column.name));
113 }
114 if !live_columns.contains(column.name) {
115 if !column.nullable && column.default.is_none() {
116 plan.warnings.push(format!(
117 "{}.{} is NOT NULL without a default; adding it fails if the table has rows",
118 table.name, column.name
119 ));
120 }
121 plan.steps.push(Step::AddColumn {
122 table: table.clone(),
123 column: *column,
124 });
125 }
126 if column.index
127 && !column.unique
128 && !column.primary_key
129 && !live.indexes.contains(&key)
130 {
131 plan.steps.push(Step::CreateIndex {
132 table: table.clone(),
133 column: *column,
134 });
135 }
136 }
137 for extra in live_columns.iter().filter(|c| table.column(c).is_none()) {
138 plan.warnings.push(format!(
139 "{}.{extra} exists in the database but not in the config",
140 table.name
141 ));
142 }
143 }
144 if !mismatched_ids.is_empty() {
145 let (live, configured) = match schema.id_storage() {
146 IdStorage::Uuid => ("text", "a UUID id strategy, which stores ids as uuid"),
147 IdStorage::Text => (
148 "uuid",
149 "an id strategy that stores ids as text (ULID or custom)",
150 ),
151 };
152 plan.warnings.push(format!(
153 "id columns {} are {live} in the database, but the config uses {configured}; \
154 the migrator doesn't change column types. Configure the strategy the database \
155 was created with (`.ids(IdStrategy::UuidV7)` for uuid columns, \
156 `.ids(IdStrategy::Ulid)` for text) or convert the columns yourself",
157 mismatched_ids.join(", ")
158 ));
159 }
160 plan
161 }
162}
163
164pub struct Migrator<'a, D> {
166 adapter: &'a D,
167 schema: &'a Schema,
168}
169
170impl<'a, D: Adapter> Migrator<'a, D> {
171 pub(crate) fn new(adapter: &'a D, schema: &'a Schema) -> Self {
172 Self { adapter, schema }
173 }
174
175 pub async fn plan(&self) -> DbResult<MigrationPlan> {
176 let live = self.adapter.introspect().await?;
177 Ok(MigrationPlan::diff(self.schema, &live))
178 }
179
180 pub async fn apply(&self, plan: &MigrationPlan) -> DbResult<()> {
181 for warning in &plan.warnings {
182 tracing::warn!("fastauth migrate: {warning}");
183 }
184 if plan.is_empty() {
185 return Ok(());
186 }
187 self.adapter.apply(plan).await
188 }
189
190 pub async fn run(&self) -> DbResult<MigrationPlan> {
192 let plan = self.plan().await?;
193 self.apply(&plan).await?;
194 Ok(plan)
195 }
196
197 pub async fn sql(&self) -> DbResult<String> {
199 let plan = self.plan().await?;
200 self.adapter.render_sql(&plan)
201 }
202}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207 use crate::config::IdStrategy;
208 use crate::testing::conformance_schema;
209
210 fn live_with_ids(schema: &Schema, stored: IdStorage) -> LiveSchema {
211 let mut live = LiveSchema::default();
212 for table in schema.tables() {
213 for column in &table.columns {
214 let key = (table.name.to_owned(), column.name.to_owned());
215 live.tables
216 .entry(key.0.clone())
217 .or_default()
218 .insert(key.1.clone());
219 if column.index && !column.unique && !column.primary_key {
220 live.indexes.insert(key.clone());
221 }
222 if column.ty == ColumnType::Id {
223 live.id_storage.insert(key, stored);
224 }
225 }
226 }
227 live
228 }
229
230 #[test]
231 fn matching_id_storage_plans_nothing() {
232 for ids in [IdStrategy::Ulid, IdStrategy::UuidV7] {
233 let schema = conformance_schema(&ids, false);
234 let plan = MigrationPlan::diff(&schema, &live_with_ids(&schema, ids.storage()));
235 assert_eq!(plan, MigrationPlan::default(), "{ids:?}");
236 }
237 }
238
239 #[test]
240 fn switching_id_strategy_warns_without_altering_columns() {
241 let uuid_db = conformance_schema(&IdStrategy::UuidV7, false);
242 let live = live_with_ids(&uuid_db, IdStorage::Uuid);
243 let plan = MigrationPlan::diff(&conformance_schema(&IdStrategy::Ulid, false), &live);
244 assert!(plan.steps.is_empty(), "{:?}", plan.steps);
245 let [warning] = plan.warnings.as_slice() else {
246 panic!("expected one warning: {:?}", plan.warnings);
247 };
248 for column in ["user.id", "session.user_id", "item.owner_id"] {
249 assert!(warning.contains(column), "{warning}");
250 }
251 assert!(warning.contains("are uuid in the database"), "{warning}");
252 assert!(warning.contains(".ids(IdStrategy::UuidV7)"), "{warning}");
253
254 let text_db = conformance_schema(&IdStrategy::Ulid, false);
255 let live = live_with_ids(&text_db, IdStorage::Text);
256 let plan = MigrationPlan::diff(&conformance_schema(&IdStrategy::UuidV4, false), &live);
257 assert!(plan.steps.is_empty());
258 assert_eq!(plan.warnings.len(), 1);
259 assert!(plan.warnings[0].contains("are text in the database"));
260 }
261}