Skip to main content

fastauth_core/
migrate.rs

1//! Diffs the configured schema against the live database. Only ever adds.
2
3use std::collections::{HashMap, HashSet};
4use std::fmt;
5use std::sync::Arc;
6
7use crate::adapter::{Adapter, DbResult};
8use crate::schema::{ColumnDef, Schema, TableDef};
9
10/// What exists in the database, as reported by `Adapter::introspect`.
11#[derive(Clone, Debug, Default, PartialEq, Eq)]
12pub struct LiveSchema {
13    /// Table name to its column names.
14    pub tables: HashMap<String, HashSet<String>>,
15    /// `(table, column)` pairs with a non-unique index named by `index_name`. Unique
16    /// columns are created with an inline constraint and aren't listed here.
17    pub indexes: HashSet<(String, String)>,
18}
19
20#[derive(Clone, Debug, PartialEq)]
21pub enum Step {
22    CreateTable(Arc<TableDef>),
23    AddColumn {
24        table: Arc<TableDef>,
25        column: ColumnDef,
26    },
27    /// A non-unique index (`ColumnDef::index`). Unique columns get an inline constraint.
28    CreateIndex {
29        table: Arc<TableDef>,
30        column: ColumnDef,
31    },
32}
33
34impl fmt::Display for Step {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        match self {
37            Step::CreateTable(t) => write!(
38                f,
39                "create table {} ({} columns, owner {})",
40                t.name,
41                t.columns.len(),
42                t.owner
43            ),
44            Step::AddColumn { table, column } => {
45                write!(
46                    f,
47                    "add column {}.{} ({:?}, owner {})",
48                    table.name, column.name, column.ty, column.owner
49                )
50            }
51            Step::CreateIndex { table, column } => {
52                write!(
53                    f,
54                    "create {}index on {}.{}",
55                    if column.unique { "unique " } else { "" },
56                    table.name,
57                    column.name
58                )
59            }
60        }
61    }
62}
63
64/// Index name every adapter uses, so introspection can recognise fastauth's indexes.
65pub fn index_name(table: &str, column: &str) -> String {
66    format!("idx_{table}_{column}")
67}
68
69#[derive(Clone, Debug, Default, PartialEq)]
70pub struct MigrationPlan {
71    pub steps: Vec<Step>,
72    /// Differences the migrator won't fix: extra columns, NOT NULL columns without a default.
73    pub warnings: Vec<String>,
74}
75
76impl MigrationPlan {
77    pub fn is_empty(&self) -> bool {
78        self.steps.is_empty()
79    }
80
81    pub fn diff(schema: &Schema, live: &LiveSchema) -> Self {
82        let mut plan = MigrationPlan::default();
83        for table in schema.tables() {
84            let Some(live_columns) = live.tables.get(table.name) else {
85                plan.steps.push(Step::CreateTable(table.clone()));
86                for column in table
87                    .columns
88                    .iter()
89                    .filter(|c| c.index && !c.unique && !c.primary_key)
90                {
91                    plan.steps.push(Step::CreateIndex {
92                        table: table.clone(),
93                        column: *column,
94                    });
95                }
96                continue;
97            };
98            for column in &table.columns {
99                if !live_columns.contains(column.name) {
100                    if !column.nullable && column.default.is_none() {
101                        plan.warnings.push(format!(
102                            "{}.{} is NOT NULL without a default; adding it fails if the table has rows",
103                            table.name, column.name
104                        ));
105                    }
106                    plan.steps.push(Step::AddColumn {
107                        table: table.clone(),
108                        column: *column,
109                    });
110                }
111                if column.index
112                    && !column.unique
113                    && !column.primary_key
114                    && !live
115                        .indexes
116                        .contains(&(table.name.to_owned(), column.name.to_owned()))
117                {
118                    plan.steps.push(Step::CreateIndex {
119                        table: table.clone(),
120                        column: *column,
121                    });
122                }
123            }
124            for extra in live_columns.iter().filter(|c| table.column(c).is_none()) {
125                plan.warnings.push(format!(
126                    "{}.{extra} exists in the database but not in the config",
127                    table.name
128                ));
129            }
130        }
131        plan
132    }
133}
134
135/// `auth.migrator()`.
136pub struct Migrator<'a, D> {
137    adapter: &'a D,
138    schema: &'a Schema,
139}
140
141impl<'a, D: Adapter> Migrator<'a, D> {
142    pub(crate) fn new(adapter: &'a D, schema: &'a Schema) -> Self {
143        Self { adapter, schema }
144    }
145
146    pub async fn plan(&self) -> DbResult<MigrationPlan> {
147        let live = self.adapter.introspect().await?;
148        Ok(MigrationPlan::diff(self.schema, &live))
149    }
150
151    pub async fn apply(&self, plan: &MigrationPlan) -> DbResult<()> {
152        for warning in &plan.warnings {
153            tracing::warn!("fastauth migrate: {warning}");
154        }
155        if plan.is_empty() {
156            return Ok(());
157        }
158        self.adapter.apply(plan).await
159    }
160
161    /// Plans and applies. Safe to call on every startup.
162    pub async fn run(&self) -> DbResult<MigrationPlan> {
163        let plan = self.plan().await?;
164        self.apply(&plan).await?;
165        Ok(plan)
166    }
167
168    /// The plan as SQL, for sqlx migration files.
169    pub async fn sql(&self) -> DbResult<String> {
170        let plan = self.plan().await?;
171        self.adapter.render_sql(&plan)
172    }
173}