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)]
16pub struct LiveSchema {
17 pub tables: HashMap<String, HashSet<String>>,
19 pub indexes: HashSet<(String, String)>,
22 pub id_storage: HashMap<(String, String), IdStorage>,
26 pub uniques: Option<HashSet<(String, Vec<String>)>>,
31}
32
33pub fn unique_key(table: &str, columns: &[impl AsRef<str>]) -> (String, Vec<String>) {
35 let mut columns: Vec<String> = columns.iter().map(|c| c.as_ref().to_owned()).collect();
36 columns.sort();
37 (table.to_owned(), columns)
38}
39
40#[derive(Clone, Debug, PartialEq)]
41pub enum Step {
42 CreateTable(Arc<TableDef>),
43 AddColumn {
44 table: Arc<TableDef>,
45 column: ColumnDef,
46 },
47 CreateIndex {
49 table: Arc<TableDef>,
50 column: ColumnDef,
51 },
52 AddUnique {
57 table: Arc<TableDef>,
58 columns: Vec<&'static str>,
59 },
60}
61
62impl fmt::Display for Step {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 match self {
65 Step::CreateTable(t) => write!(
66 f,
67 "create table {} ({} columns, owner {})",
68 t.name,
69 t.columns.len(),
70 t.owner
71 ),
72 Step::AddColumn { table, column } => {
73 write!(
74 f,
75 "add column {}.{} ({:?}, owner {})",
76 table.name, column.name, column.ty, column.owner
77 )
78 }
79 Step::CreateIndex { table, column } => {
80 write!(
81 f,
82 "create {}index on {}.{}",
83 if column.unique { "unique " } else { "" },
84 table.name,
85 column.name
86 )
87 }
88 Step::AddUnique { table, columns } => {
89 write!(f, "add unique ({}) on {}", columns.join(", "), table.name)
90 }
91 }
92 }
93}
94
95pub fn duplicates_error(table: &str, columns: &[&str], rows: &[Vec<(&str, Value)>]) -> DbError {
98 let rows: Vec<String> = rows
99 .iter()
100 .map(|row| {
101 let pairs: Vec<String> = row
102 .iter()
103 .map(|(column, value)| format!("{column}={}", show(value)))
104 .collect();
105 format!("{{{}}}", pairs.join(", "))
106 })
107 .collect();
108 DbError::Schema(format!(
109 "can't add UNIQUE ({}) to `{table}`: these rows share the same values: {}. Delete or \
110 merge the duplicates, then run the migrator again (docs/concepts/02-database.md, \
111 \"Unique constraints on an existing database\", has a query for each table)",
112 columns.join(", "),
113 rows.join("; ")
114 ))
115}
116
117fn show(value: &Value) -> String {
118 match value {
119 Value::Null => "NULL".to_owned(),
120 Value::Bool(b) => b.to_string(),
121 Value::Int(i) => i.to_string(),
122 Value::Text(text) => format!("{text:?}"),
123 Value::Bytes(bytes) => bytes.iter().map(|b| format!("{b:02x}")).collect(),
124 Value::Timestamp(at) => at.to_string(),
125 Value::Json(json) => json.to_string(),
126 }
127}
128
129pub fn index_name(table: &str, column: &str) -> String {
131 format!("idx_{table}_{column}")
132}
133
134#[derive(Clone, Debug, Default, PartialEq)]
135pub struct MigrationPlan {
136 pub steps: Vec<Step>,
137 pub warnings: Vec<String>,
140}
141
142impl MigrationPlan {
143 pub fn is_empty(&self) -> bool {
144 self.steps.is_empty()
145 }
146
147 pub fn diff(schema: &Schema, live: &LiveSchema) -> Self {
148 let mut plan = MigrationPlan::default();
149 let mut mismatched_ids = Vec::new();
150 for table in schema.tables() {
151 let Some(live_columns) = live.tables.get(table.name) else {
152 plan.steps.push(Step::CreateTable(table.clone()));
153 for column in table
154 .columns
155 .iter()
156 .filter(|c| c.index && !c.unique && !c.primary_key)
157 {
158 plan.steps.push(Step::CreateIndex {
159 table: table.clone(),
160 column: *column,
161 });
162 }
163 for unique in &table.uniques {
164 plan.steps.push(Step::AddUnique {
165 table: table.clone(),
166 columns: unique.columns.clone(),
167 });
168 }
169 continue;
170 };
171 for (position, column) in table.columns.iter().enumerate() {
172 let stored = table.stored_name(position);
173 let key = (table.name.to_owned(), stored.to_owned());
174 if column.ty == ColumnType::Id
175 && live
176 .id_storage
177 .get(&key)
178 .is_some_and(|&stored| stored != schema.id_storage())
179 {
180 mismatched_ids.push(format!("{}.{}", table.name, column.name));
181 }
182 if !live_columns.contains(stored) {
183 if !column.nullable && column.default.is_none() {
184 plan.warnings.push(format!(
185 "{}.{} is NOT NULL without a default; adding it fails if the table has rows",
186 table.name, column.name
187 ));
188 }
189 plan.steps.push(Step::AddColumn {
190 table: table.clone(),
191 column: *column,
192 });
193 }
194 if column.index
195 && !column.unique
196 && !column.primary_key
197 && !live.indexes.contains(&key)
198 {
199 plan.steps.push(Step::CreateIndex {
200 table: table.clone(),
201 column: *column,
202 });
203 }
204 }
205 if let Some(live_uniques) = &live.uniques {
206 for columns in table.unique_sets() {
207 let stored: Vec<&str> = columns
208 .iter()
209 .map(|c| table.stored_column(c).unwrap_or(c))
210 .collect();
211 let added_with_its_column =
212 columns.len() == 1 && !live_columns.contains(stored[0]);
213 if !added_with_its_column
214 && !live_uniques.contains(&unique_key(table.name, &stored))
215 {
216 plan.steps.push(Step::AddUnique {
217 table: table.clone(),
218 columns,
219 });
220 }
221 }
222 }
223 for extra in live_columns
224 .iter()
225 .filter(|c| table.column_stored_as(c).is_none())
226 {
227 plan.warnings.push(format!(
228 "{}.{extra} exists in the database but not in the config",
229 table.name
230 ));
231 }
232 }
233 if !mismatched_ids.is_empty() {
234 let (live, configured) = match schema.id_storage() {
235 IdStorage::Uuid => ("text", "a UUID id strategy, which stores ids as uuid"),
236 IdStorage::Text => (
237 "uuid",
238 "an id strategy that stores ids as text (ULID or custom)",
239 ),
240 };
241 plan.warnings.push(format!(
242 "id columns {} are {live} in the database, but the config uses {configured}; \
243 the migrator doesn't change column types. Configure the strategy the database \
244 was created with (`.ids(IdStrategy::UuidV7)` for uuid columns, \
245 `.ids(IdStrategy::Ulid)` for text) or convert the columns yourself",
246 mismatched_ids.join(", ")
247 ));
248 }
249 plan
250 }
251}
252
253#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
256pub enum Migrations {
257 #[default]
259 Apply,
260 ReviewOnly,
266}
267
268#[derive(Debug, thiserror::Error)]
270#[error(
271 "fastauth's migrations are review-only (`.migrations(Migrations::ReviewOnly)`), so the \
272 migrator doesn't change the database; write the SQL with `fastauth generate`, review it \
273 and apply it with your own migrations"
274)]
275pub struct ReviewOnly;
276
277#[derive(Clone, Debug, PartialEq, Eq)]
279pub struct MigrationSql {
280 pub name: String,
283 pub sql: String,
284}
285
286pub struct Migrator<'a, D> {
288 adapter: &'a D,
289 schema: &'a Schema,
290 mode: Migrations,
291}
292
293impl<'a, D: Adapter> Migrator<'a, D> {
294 pub(crate) fn new(adapter: &'a D, schema: &'a Schema) -> Self {
295 Self {
296 adapter,
297 schema,
298 mode: Migrations::Apply,
299 }
300 }
301
302 pub(crate) fn with_mode(mut self, mode: Migrations) -> Self {
303 self.mode = mode;
304 self
305 }
306
307 pub fn mode(&self) -> Migrations {
309 self.mode
310 }
311
312 pub async fn plan(&self) -> DbResult<MigrationPlan> {
313 let live = self.adapter.introspect().await?;
314 Ok(MigrationPlan::diff(self.schema, &live))
315 }
316
317 pub async fn apply(&self, plan: &MigrationPlan) -> DbResult<()> {
319 if self.mode == Migrations::ReviewOnly {
320 return Err(DbError::other(ReviewOnly));
321 }
322 for warning in &plan.warnings {
323 tracing::warn!("fastauth migrate: {warning}");
324 }
325 if plan.is_empty() {
326 return Ok(());
327 }
328 self.adapter.apply(plan).await
329 }
330
331 pub async fn run(&self) -> DbResult<MigrationPlan> {
333 let plan = self.plan().await?;
334 self.apply(&plan).await?;
335 Ok(plan)
336 }
337
338 pub async fn sql(&self) -> DbResult<String> {
340 let plan = self.plan().await?;
341 self.adapter.render_sql(&plan)
342 }
343
344 pub async fn sql_steps(&self) -> DbResult<Vec<MigrationSql>> {
350 let plan = self.plan().await?;
351 let mut groups: Vec<(String, Vec<Step>)> = Vec::new();
352 let mut created: Vec<&str> = Vec::new();
353 for step in &plan.steps {
354 let (name, follows_create) = match step {
355 Step::CreateTable(table) => {
356 created.push(table.name);
357 (format!("create_{}", table.name), false)
358 }
359 Step::AddColumn { table, column } => (
360 format!(
361 "add_{}_{}",
362 table.name,
363 table.stored_column(column.name).unwrap_or(column.name)
364 ),
365 false,
366 ),
367 Step::CreateIndex { table, column } => (
368 format!(
369 "index_{}_{}",
370 table.name,
371 table.stored_column(column.name).unwrap_or(column.name)
372 ),
373 created.contains(&table.name),
374 ),
375 Step::AddUnique { table, columns } => (
376 format!(
377 "unique_{}_{}",
378 table.name,
379 columns
380 .iter()
381 .map(|c| table.stored_column(c).unwrap_or(c))
382 .collect::<Vec<_>>()
383 .join("_")
384 ),
385 created.contains(&table.name),
386 ),
387 };
388 match groups.last_mut() {
389 Some((_, steps)) if follows_create => steps.push(step.clone()),
390 _ => groups.push((name, vec![step.clone()])),
391 }
392 }
393 let mut out = Vec::with_capacity(groups.len());
394 for (name, steps) in groups {
395 let mut sql = String::new();
396 if let [Step::AddUnique { table, columns }] = steps.as_slice()
397 && let Some(query) = self.adapter.duplicates_query(table, columns)
398 {
399 sql.push_str(
400 "-- Before applying: this query lists rows that share the new unique key.\n\
401 -- It must return no rows: merge or delete the duplicates it finds first.\n",
402 );
403 for line in query.lines() {
404 sql.push_str("-- ");
405 sql.push_str(line);
406 sql.push('\n');
407 }
408 }
409 sql.push_str(&self.adapter.render_sql(&MigrationPlan {
410 steps,
411 warnings: Vec::new(),
412 })?);
413 out.push(MigrationSql { name, sql });
414 }
415 Ok(out)
416 }
417}
418
419#[cfg(test)]
420mod tests {
421 use super::*;
422 use crate::config::IdStrategy;
423 use crate::testing::conformance_schema;
424
425 fn live_with_ids(schema: &Schema, stored: IdStorage) -> LiveSchema {
426 let mut live = LiveSchema {
427 uniques: Some(
428 schema
429 .tables()
430 .iter()
431 .flat_map(|t| t.unique_sets().map(|cols| unique_key(t.name, &cols)))
432 .collect(),
433 ),
434 ..LiveSchema::default()
435 };
436 for table in schema.tables() {
437 for column in &table.columns {
438 let key = (table.name.to_owned(), column.name.to_owned());
439 live.tables
440 .entry(key.0.clone())
441 .or_default()
442 .insert(key.1.clone());
443 if column.index && !column.unique && !column.primary_key {
444 live.indexes.insert(key.clone());
445 }
446 if column.ty == ColumnType::Id {
447 live.id_storage.insert(key, stored);
448 }
449 }
450 }
451 live
452 }
453
454 #[test]
455 fn matching_id_storage_plans_nothing() {
456 for ids in [IdStrategy::Ulid, IdStrategy::UuidV7] {
457 let schema = conformance_schema(&ids, false);
458 let plan = MigrationPlan::diff(&schema, &live_with_ids(&schema, ids.storage()));
459 assert_eq!(plan, MigrationPlan::default(), "{ids:?}");
460 }
461 }
462
463 fn added_uniques(plan: &MigrationPlan) -> Vec<String> {
464 plan.steps
465 .iter()
466 .filter_map(|step| match step {
467 Step::AddUnique { table, columns } => {
468 Some(format!("{}({})", table.name, columns.join(",")))
469 }
470 _ => None,
471 })
472 .collect()
473 }
474
475 #[test]
476 fn new_tables_get_their_multi_column_uniques() {
477 let schema = conformance_schema(&IdStrategy::Ulid, false);
478 let plan = MigrationPlan::diff(&schema, &LiveSchema::default());
479 assert_eq!(added_uniques(&plan), ["account(provider_id,account_id)"]);
480 }
481
482 #[test]
483 fn a_unique_missing_from_an_existing_table_is_planned() {
484 let schema = conformance_schema(&IdStrategy::Ulid, true);
485 let mut live = live_with_ids(&schema, IdStorage::Text);
486 let uniques = live.uniques.as_mut().unwrap();
487 uniques.remove(&unique_key("item", &["nickname"]));
488 uniques.remove(&unique_key("account", &["account_id", "provider_id"]));
489 let plan = MigrationPlan::diff(&schema, &live);
490 assert_eq!(
491 added_uniques(&plan),
492 ["account(provider_id,account_id)", "item(nickname)"]
493 );
494 }
495
496 #[test]
497 fn a_unique_column_added_now_brings_its_constraint() {
498 let v1 = conformance_schema(&IdStrategy::Ulid, false);
499 let live = live_with_ids(&v1, IdStorage::Text);
500 let plan = MigrationPlan::diff(&conformance_schema(&IdStrategy::Ulid, true), &live);
501 assert!(added_uniques(&plan).is_empty(), "{:?}", plan.steps);
502 }
503
504 #[test]
505 fn without_reported_uniques_existing_tables_get_none() {
506 let schema = conformance_schema(&IdStrategy::Ulid, false);
507 let mut live = live_with_ids(&schema, IdStorage::Text);
508 live.uniques = None;
509 assert_eq!(
510 MigrationPlan::diff(&schema, &live),
511 MigrationPlan::default()
512 );
513 }
514
515 #[test]
516 fn switching_id_strategy_warns_without_altering_columns() {
517 let uuid_db = conformance_schema(&IdStrategy::UuidV7, false);
518 let live = live_with_ids(&uuid_db, IdStorage::Uuid);
519 let plan = MigrationPlan::diff(&conformance_schema(&IdStrategy::Ulid, false), &live);
520 assert!(plan.steps.is_empty(), "{:?}", plan.steps);
521 let [warning] = plan.warnings.as_slice() else {
522 panic!("expected one warning: {:?}", plan.warnings);
523 };
524 for column in ["user.id", "session.user_id", "item.owner_id"] {
525 assert!(warning.contains(column), "{warning}");
526 }
527 assert!(warning.contains("are uuid in the database"), "{warning}");
528 assert!(warning.contains(".ids(IdStrategy::UuidV7)"), "{warning}");
529
530 let text_db = conformance_schema(&IdStrategy::Ulid, false);
531 let live = live_with_ids(&text_db, IdStorage::Text);
532 let plan = MigrationPlan::diff(&conformance_schema(&IdStrategy::UuidV4, false), &live);
533 assert!(plan.steps.is_empty());
534 assert_eq!(plan.warnings.len(), 1);
535 assert!(plan.warnings[0].contains("are text in the database"));
536 }
537}