1use std::collections::{HashMap, HashSet};
4use std::fmt;
5use std::sync::Arc;
6
7use crate::adapter::{Adapter, DbError, DbResult};
8use crate::schema::{ColumnDef, ColumnType, IdStorage, Schema, TableDef};
9use crate::value::Value;
10
11#[derive(Clone, Debug, Default, PartialEq, Eq)]
13pub struct LiveSchema {
14 pub tables: HashMap<String, HashSet<String>>,
16 pub indexes: HashSet<(String, String)>,
19 pub id_storage: HashMap<(String, String), IdStorage>,
23 pub uniques: Option<HashSet<(String, Vec<String>)>>,
28}
29
30pub fn unique_key(table: &str, columns: &[impl AsRef<str>]) -> (String, Vec<String>) {
32 let mut columns: Vec<String> = columns.iter().map(|c| c.as_ref().to_owned()).collect();
33 columns.sort();
34 (table.to_owned(), columns)
35}
36
37#[derive(Clone, Debug, PartialEq)]
38pub enum Step {
39 CreateTable(Arc<TableDef>),
40 AddColumn {
41 table: Arc<TableDef>,
42 column: ColumnDef,
43 },
44 CreateIndex {
46 table: Arc<TableDef>,
47 column: ColumnDef,
48 },
49 AddUnique {
54 table: Arc<TableDef>,
55 columns: Vec<&'static str>,
56 },
57}
58
59impl fmt::Display for Step {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 match self {
62 Step::CreateTable(t) => write!(
63 f,
64 "create table {} ({} columns, owner {})",
65 t.name,
66 t.columns.len(),
67 t.owner
68 ),
69 Step::AddColumn { table, column } => {
70 write!(
71 f,
72 "add column {}.{} ({:?}, owner {})",
73 table.name, column.name, column.ty, column.owner
74 )
75 }
76 Step::CreateIndex { table, column } => {
77 write!(
78 f,
79 "create {}index on {}.{}",
80 if column.unique { "unique " } else { "" },
81 table.name,
82 column.name
83 )
84 }
85 Step::AddUnique { table, columns } => {
86 write!(f, "add unique ({}) on {}", columns.join(", "), table.name)
87 }
88 }
89 }
90}
91
92pub fn duplicates_error(table: &str, columns: &[&str], rows: &[Vec<(&str, Value)>]) -> DbError {
95 let rows: Vec<String> = rows
96 .iter()
97 .map(|row| {
98 let pairs: Vec<String> = row
99 .iter()
100 .map(|(column, value)| format!("{column}={}", show(value)))
101 .collect();
102 format!("{{{}}}", pairs.join(", "))
103 })
104 .collect();
105 DbError::Schema(format!(
106 "can't add UNIQUE ({}) to `{table}`: these rows share the same values: {}. Delete or \
107 merge the duplicates, then run the migrator again (docs/concepts/02-database.md, \
108 \"Unique constraints on an existing database\", has a query for each table)",
109 columns.join(", "),
110 rows.join("; ")
111 ))
112}
113
114fn show(value: &Value) -> String {
115 match value {
116 Value::Null => "NULL".to_owned(),
117 Value::Bool(b) => b.to_string(),
118 Value::Int(i) => i.to_string(),
119 Value::Text(text) => format!("{text:?}"),
120 Value::Bytes(bytes) => bytes.iter().map(|b| format!("{b:02x}")).collect(),
121 Value::Timestamp(at) => at.to_string(),
122 Value::Json(json) => json.to_string(),
123 }
124}
125
126pub fn index_name(table: &str, column: &str) -> String {
128 format!("idx_{table}_{column}")
129}
130
131#[derive(Clone, Debug, Default, PartialEq)]
132pub struct MigrationPlan {
133 pub steps: Vec<Step>,
134 pub warnings: Vec<String>,
137}
138
139impl MigrationPlan {
140 pub fn is_empty(&self) -> bool {
141 self.steps.is_empty()
142 }
143
144 pub fn diff(schema: &Schema, live: &LiveSchema) -> Self {
145 let mut plan = MigrationPlan::default();
146 let mut mismatched_ids = Vec::new();
147 for table in schema.tables() {
148 let Some(live_columns) = live.tables.get(table.name) else {
149 plan.steps.push(Step::CreateTable(table.clone()));
150 for column in table
151 .columns
152 .iter()
153 .filter(|c| c.index && !c.unique && !c.primary_key)
154 {
155 plan.steps.push(Step::CreateIndex {
156 table: table.clone(),
157 column: *column,
158 });
159 }
160 for unique in &table.uniques {
161 plan.steps.push(Step::AddUnique {
162 table: table.clone(),
163 columns: unique.columns.clone(),
164 });
165 }
166 continue;
167 };
168 for column in &table.columns {
169 let key = (table.name.to_owned(), column.name.to_owned());
170 if column.ty == ColumnType::Id
171 && live
172 .id_storage
173 .get(&key)
174 .is_some_and(|&stored| stored != schema.id_storage())
175 {
176 mismatched_ids.push(format!("{}.{}", table.name, column.name));
177 }
178 if !live_columns.contains(column.name) {
179 if !column.nullable && column.default.is_none() {
180 plan.warnings.push(format!(
181 "{}.{} is NOT NULL without a default; adding it fails if the table has rows",
182 table.name, column.name
183 ));
184 }
185 plan.steps.push(Step::AddColumn {
186 table: table.clone(),
187 column: *column,
188 });
189 }
190 if column.index
191 && !column.unique
192 && !column.primary_key
193 && !live.indexes.contains(&key)
194 {
195 plan.steps.push(Step::CreateIndex {
196 table: table.clone(),
197 column: *column,
198 });
199 }
200 }
201 if let Some(live_uniques) = &live.uniques {
202 for columns in table.unique_sets() {
203 let added_with_its_column =
204 columns.len() == 1 && !live_columns.contains(columns[0]);
205 if !added_with_its_column
206 && !live_uniques.contains(&unique_key(table.name, &columns))
207 {
208 plan.steps.push(Step::AddUnique {
209 table: table.clone(),
210 columns,
211 });
212 }
213 }
214 }
215 for extra in live_columns.iter().filter(|c| table.column(c).is_none()) {
216 plan.warnings.push(format!(
217 "{}.{extra} exists in the database but not in the config",
218 table.name
219 ));
220 }
221 }
222 if !mismatched_ids.is_empty() {
223 let (live, configured) = match schema.id_storage() {
224 IdStorage::Uuid => ("text", "a UUID id strategy, which stores ids as uuid"),
225 IdStorage::Text => (
226 "uuid",
227 "an id strategy that stores ids as text (ULID or custom)",
228 ),
229 };
230 plan.warnings.push(format!(
231 "id columns {} are {live} in the database, but the config uses {configured}; \
232 the migrator doesn't change column types. Configure the strategy the database \
233 was created with (`.ids(IdStrategy::UuidV7)` for uuid columns, \
234 `.ids(IdStrategy::Ulid)` for text) or convert the columns yourself",
235 mismatched_ids.join(", ")
236 ));
237 }
238 plan
239 }
240}
241
242pub struct Migrator<'a, D> {
244 adapter: &'a D,
245 schema: &'a Schema,
246}
247
248impl<'a, D: Adapter> Migrator<'a, D> {
249 pub(crate) fn new(adapter: &'a D, schema: &'a Schema) -> Self {
250 Self { adapter, schema }
251 }
252
253 pub async fn plan(&self) -> DbResult<MigrationPlan> {
254 let live = self.adapter.introspect().await?;
255 Ok(MigrationPlan::diff(self.schema, &live))
256 }
257
258 pub async fn apply(&self, plan: &MigrationPlan) -> DbResult<()> {
259 for warning in &plan.warnings {
260 tracing::warn!("fastauth migrate: {warning}");
261 }
262 if plan.is_empty() {
263 return Ok(());
264 }
265 self.adapter.apply(plan).await
266 }
267
268 pub async fn run(&self) -> DbResult<MigrationPlan> {
270 let plan = self.plan().await?;
271 self.apply(&plan).await?;
272 Ok(plan)
273 }
274
275 pub async fn sql(&self) -> DbResult<String> {
277 let plan = self.plan().await?;
278 self.adapter.render_sql(&plan)
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use crate::config::IdStrategy;
286 use crate::testing::conformance_schema;
287
288 fn live_with_ids(schema: &Schema, stored: IdStorage) -> LiveSchema {
289 let mut live = LiveSchema {
290 uniques: Some(
291 schema
292 .tables()
293 .iter()
294 .flat_map(|t| t.unique_sets().map(|cols| unique_key(t.name, &cols)))
295 .collect(),
296 ),
297 ..LiveSchema::default()
298 };
299 for table in schema.tables() {
300 for column in &table.columns {
301 let key = (table.name.to_owned(), column.name.to_owned());
302 live.tables
303 .entry(key.0.clone())
304 .or_default()
305 .insert(key.1.clone());
306 if column.index && !column.unique && !column.primary_key {
307 live.indexes.insert(key.clone());
308 }
309 if column.ty == ColumnType::Id {
310 live.id_storage.insert(key, stored);
311 }
312 }
313 }
314 live
315 }
316
317 #[test]
318 fn matching_id_storage_plans_nothing() {
319 for ids in [IdStrategy::Ulid, IdStrategy::UuidV7] {
320 let schema = conformance_schema(&ids, false);
321 let plan = MigrationPlan::diff(&schema, &live_with_ids(&schema, ids.storage()));
322 assert_eq!(plan, MigrationPlan::default(), "{ids:?}");
323 }
324 }
325
326 fn added_uniques(plan: &MigrationPlan) -> Vec<String> {
327 plan.steps
328 .iter()
329 .filter_map(|step| match step {
330 Step::AddUnique { table, columns } => {
331 Some(format!("{}({})", table.name, columns.join(",")))
332 }
333 _ => None,
334 })
335 .collect()
336 }
337
338 #[test]
339 fn new_tables_get_their_multi_column_uniques() {
340 let schema = conformance_schema(&IdStrategy::Ulid, false);
341 let plan = MigrationPlan::diff(&schema, &LiveSchema::default());
342 assert_eq!(added_uniques(&plan), ["account(provider_id,account_id)"]);
343 }
344
345 #[test]
346 fn a_unique_missing_from_an_existing_table_is_planned() {
347 let schema = conformance_schema(&IdStrategy::Ulid, true);
348 let mut live = live_with_ids(&schema, IdStorage::Text);
349 let uniques = live.uniques.as_mut().unwrap();
350 uniques.remove(&unique_key("item", &["nickname"]));
351 uniques.remove(&unique_key("account", &["account_id", "provider_id"]));
352 let plan = MigrationPlan::diff(&schema, &live);
353 assert_eq!(
354 added_uniques(&plan),
355 ["account(provider_id,account_id)", "item(nickname)"]
356 );
357 }
358
359 #[test]
360 fn a_unique_column_added_now_brings_its_constraint() {
361 let v1 = conformance_schema(&IdStrategy::Ulid, false);
362 let live = live_with_ids(&v1, IdStorage::Text);
363 let plan = MigrationPlan::diff(&conformance_schema(&IdStrategy::Ulid, true), &live);
364 assert!(added_uniques(&plan).is_empty(), "{:?}", plan.steps);
365 }
366
367 #[test]
368 fn without_reported_uniques_existing_tables_get_none() {
369 let schema = conformance_schema(&IdStrategy::Ulid, false);
370 let mut live = live_with_ids(&schema, IdStorage::Text);
371 live.uniques = None;
372 assert_eq!(
373 MigrationPlan::diff(&schema, &live),
374 MigrationPlan::default()
375 );
376 }
377
378 #[test]
379 fn switching_id_strategy_warns_without_altering_columns() {
380 let uuid_db = conformance_schema(&IdStrategy::UuidV7, false);
381 let live = live_with_ids(&uuid_db, IdStorage::Uuid);
382 let plan = MigrationPlan::diff(&conformance_schema(&IdStrategy::Ulid, false), &live);
383 assert!(plan.steps.is_empty(), "{:?}", plan.steps);
384 let [warning] = plan.warnings.as_slice() else {
385 panic!("expected one warning: {:?}", plan.warnings);
386 };
387 for column in ["user.id", "session.user_id", "item.owner_id"] {
388 assert!(warning.contains(column), "{warning}");
389 }
390 assert!(warning.contains("are uuid in the database"), "{warning}");
391 assert!(warning.contains(".ids(IdStrategy::UuidV7)"), "{warning}");
392
393 let text_db = conformance_schema(&IdStrategy::Ulid, false);
394 let live = live_with_ids(&text_db, IdStorage::Text);
395 let plan = MigrationPlan::diff(&conformance_schema(&IdStrategy::UuidV4, false), &live);
396 assert!(plan.steps.is_empty());
397 assert_eq!(plan.warnings.len(), 1);
398 assert!(plan.warnings[0].contains("are text in the database"));
399 }
400}