Skip to main content

toasty_sql/
migration.rs

1use std::{borrow::Cow, collections::HashSet};
2
3use toasty_core::{
4    driver::{Capability, Dialect},
5    schema::{
6        db::{Column, Migration, Schema, Table, TableId, Type, TypeEnum},
7        diff,
8    },
9};
10
11use crate::Serializer;
12use crate::stmt::{AlterColumnChanges, AlterTable, AlterTableAction, DropTable, Name, Statement};
13
14/// Returns `true` if a named enum change is handled at the type level and
15/// should not produce column-level DDL.
16fn is_named_enum_type_only_change(
17    previous: &Column,
18    next: &Column,
19    renamed_types: &HashSet<(&str, &str)>,
20) -> bool {
21    if previous.name != next.name
22        || previous.nullable != next.nullable
23        || previous.primary_key != next.primary_key
24        || previous.auto_increment != next.auto_increment
25    {
26        return false;
27    }
28
29    // A scalar ↔ array change is a real column type change, so both sides
30    // must have the same shape.
31    let same_shape = matches!(
32        (&previous.storage_ty, &next.storage_ty),
33        (Type::Enum(_), Type::Enum(_)) | (Type::List(_), Type::List(_))
34    );
35
36    if !same_shape {
37        return false;
38    }
39
40    matches!(
41        (
42            previous.storage_ty.named_enum(),
43            next.storage_ty.named_enum(),
44        ),
45        (
46            Some(TypeEnum { name: Some(a), .. }),
47            Some(TypeEnum { name: Some(b), .. }),
48        ) if a == b || renamed_types.contains(&(a.as_str(), b.as_str()))
49    )
50}
51
52/// Generates the SQL [`Migration`] for a schema diff in the dialect named by
53/// `capability.sql`. PostgreSQL gets one batch; other dialects get breakpoint
54/// markers so drivers can execute one statement at a time.
55///
56/// # Panics
57///
58/// Panics if `capability.sql` is `None`.
59pub fn generate_migration(schema_diff: &diff::Schema<'_>, capability: &Capability) -> Migration {
60    let dialect = capability
61        .sql
62        .expect("cannot generate a SQL migration for a non-SQL capability");
63
64    let statements = MigrationStatement::from_diff(schema_diff, capability);
65
66    let sql_strings: Vec<String> = statements
67        .iter()
68        .map(|stmt| Serializer::new(dialect, stmt.schema()).serialize(stmt.statement()))
69        .collect();
70
71    match dialect {
72        Dialect::Postgresql => Migration::new_sql(sql_strings.join("\n")),
73        Dialect::Sqlite | Dialect::Mysql | Dialect::MariaDb => {
74            Migration::new_sql_with_breakpoints(&sql_strings)
75        }
76    }
77}
78
79/// A migration step pairing a DDL [`Statement`] with the [`Schema`] it applies against.
80///
81/// Each `MigrationStatement` carries a snapshot of the schema at the point where
82/// the statement should be serialized. This is necessary because rename and
83/// recreation operations modify the schema as they go.
84pub struct MigrationStatement<'a> {
85    statement: Statement,
86    schema: Cow<'a, Schema>,
87}
88
89impl<'a> MigrationStatement<'a> {
90    fn new(statement: Statement, schema: Cow<'a, Schema>) -> Self {
91        MigrationStatement { statement, schema }
92    }
93
94    /// Generates migration statements from a [`diff::Schema`].
95    ///
96    /// Walks the diff's type, table, column, and index changes and produces
97    /// the corresponding DDL statements. Type changes (CREATE TYPE, ALTER
98    /// TYPE) are emitted before table changes. On databases that lack
99    /// `ALTER COLUMN` support (e.g. SQLite), column type changes trigger a
100    /// full table recreation sequence.
101    pub fn from_diff(schema_diff: &'a diff::Schema<'a>, capability: &Capability) -> Vec<Self> {
102        let mut result = Vec::new();
103        let types_diff = schema_diff.types();
104        let renamed_types: HashSet<(&str, &str)> = types_diff
105            .iter()
106            .filter_map(|item| match item {
107                diff::Type::Rename { previous, next } => Some((
108                    previous.name.as_deref().expect("named enum type"),
109                    next.name.as_deref().expect("named enum type"),
110                )),
111                _ => None,
112            })
113            .collect();
114
115        // Emit enum type changes before table changes (tables may reference
116        // newly created types).
117        if capability.named_enum_types {
118            for item in types_diff.iter() {
119                match item {
120                    diff::Type::Create(ty) => {
121                        result.push(Self::new(
122                            Statement::create_enum_type(ty),
123                            Cow::Borrowed(schema_diff.next()),
124                        ));
125                    }
126                    diff::Type::Rename { previous, next } => {
127                        result.push(Self::new(
128                            Statement::rename_type(
129                                previous.name.as_deref().expect("named enum type"),
130                                next.name.as_deref().expect("named enum type"),
131                            ),
132                            Cow::Borrowed(schema_diff.previous()),
133                        ));
134                    }
135                    diff::Type::AddVariants { ty, added } => {
136                        let type_name = ty.name.as_deref().expect("named enum type");
137                        for variant in added {
138                            result.push(Self::new(
139                                Statement::alter_type_add_value(type_name, variant),
140                                Cow::Borrowed(schema_diff.next()),
141                            ));
142                        }
143                    }
144                }
145            }
146        }
147
148        for table in schema_diff.tables().iter() {
149            match table {
150                diff::Table::Create(table) => {
151                    result.push(Self::new(
152                        Statement::create_table(table, capability),
153                        Cow::Borrowed(schema_diff.next()),
154                    ));
155                    for index in &table.indices {
156                        if index.primary_key {
157                            continue; // PK indices are created as part of CREATE TABLE
158                        }
159                        result.push(Self::new(
160                            Statement::create_index(index),
161                            Cow::Borrowed(schema_diff.next()),
162                        ));
163                    }
164                }
165                diff::Table::Drop(table) => result.push(Self::new(
166                    Statement::drop_table(table),
167                    Cow::Borrowed(schema_diff.previous()),
168                )),
169                diff::Table::Alter {
170                    previous,
171                    next,
172                    columns,
173                    indices,
174                    ..
175                } => {
176                    let mut schema = Cow::Borrowed(schema_diff.previous());
177                    if previous.name != next.name {
178                        result.push(Self::new(
179                            Statement::alter_table_rename_to(previous, &next.name),
180                            schema.clone(),
181                        ));
182                        schema.to_mut().table_mut(previous.id).name = next.name.clone();
183                    }
184
185                    // Check if any column alteration requires table recreation
186                    // (e.g. SQLite can't alter column type/nullability/auto_increment)
187                    let needs_recreation = !capability.schema_mutations.alter_column_type
188                        && columns.iter().any(|item| {
189                            matches!(
190                                item,
191                                diff::Column::Alter {
192                                    previous: prev_col,
193                                    next: next_col
194                                } if AlterColumnChanges::from_diff(prev_col, next_col).has_type_change()
195                                    && !(capability.named_enum_types
196                                        && is_named_enum_type_only_change(
197                                            prev_col,
198                                            next_col,
199                                            &renamed_types,
200                                        ))
201                            )
202                        });
203
204                    // Drop existing indices before changing columns because they may
205                    // reference a column that is being removed or altered.
206                    for item in indices.iter() {
207                        match item {
208                            diff::Index::Drop(index) => {
209                                result.push(Self::new(
210                                    Statement::drop_index(index),
211                                    Cow::Borrowed(schema_diff.previous()),
212                                ));
213                            }
214                            diff::Index::Alter { previous, .. } => {
215                                result.push(Self::new(
216                                    Statement::drop_index(previous),
217                                    Cow::Borrowed(schema_diff.previous()),
218                                ));
219                            }
220                            diff::Index::Create(_) => {}
221                        }
222                    }
223
224                    if needs_recreation {
225                        Self::emit_table_recreation(
226                            &mut result,
227                            schema,
228                            previous,
229                            next,
230                            columns,
231                            capability,
232                        );
233                    } else {
234                        Self::emit_column_changes(
235                            &mut result,
236                            schema,
237                            previous.id,
238                            columns,
239                            capability,
240                            &renamed_types,
241                        );
242                    }
243
244                    // Create new indices after the column changes so they reference
245                    // the next schema's column definitions.
246                    for item in indices.iter() {
247                        match item {
248                            diff::Index::Create(index) => {
249                                result.push(Self::new(
250                                    Statement::create_index(index),
251                                    Cow::Borrowed(schema_diff.next()),
252                                ));
253                            }
254                            diff::Index::Alter { next, .. } => {
255                                result.push(Self::new(
256                                    Statement::create_index(next),
257                                    Cow::Borrowed(schema_diff.next()),
258                                ));
259                            }
260                            diff::Index::Drop(_) => {}
261                        }
262                    }
263                }
264            }
265        }
266        result
267    }
268
269    fn emit_table_recreation(
270        result: &mut Vec<Self>,
271        schema: Cow<'a, Schema>,
272        previous: &Table,
273        next: &Table,
274        columns: &[diff::Column<'_>],
275        capability: &Capability,
276    ) {
277        let current_name = schema.table(previous.id).name.clone();
278        let temp_name = format!("_toasty_new_{}", current_name);
279
280        // 1. PRAGMA foreign_keys = OFF
281        result.push(Self::new(
282            Statement::pragma_disable_foreign_keys(),
283            schema.clone(),
284        ));
285
286        // 2. CREATE TABLE temp with new schema
287        let temp_schema = {
288            let mut s = schema.as_ref().clone();
289            let t = s.table_mut(next.id);
290            t.name = temp_name.clone();
291            t.columns = next.columns.clone();
292            t.primary_key = next.primary_key.clone();
293            s
294        };
295        result.push(Self::new(
296            Statement::create_table(next, capability),
297            Cow::Owned(temp_schema),
298        ));
299
300        // 3. INSERT INTO temp SELECT ... FROM current
301        let column_mappings: Vec<(Name, Name)> = next
302            .columns
303            .iter()
304            .filter(|col| {
305                // Skip added columns (no source data)
306                !columns
307                    .iter()
308                    .any(|item| matches!(item, diff::Column::Add(c) if c.id == col.id))
309            })
310            .map(|col| {
311                let target_name = Name::from(&col.name[..]);
312                // Check if this column was renamed
313                let source_name = columns
314                    .iter()
315                    .find_map(|item| match item {
316                        diff::Column::Alter {
317                            previous: prev_col,
318                            next: next_col,
319                        } if next_col.id == col.id && prev_col.name != next_col.name => {
320                            Some(Name::from(&prev_col.name[..]))
321                        }
322                        _ => None,
323                    })
324                    .unwrap_or_else(|| Name::from(&col.name[..]));
325                (target_name, source_name)
326            })
327            .collect();
328
329        result.push(Self::new(
330            Statement::copy_table(
331                Name::from(current_name.as_str()),
332                Name::from(temp_name.as_str()),
333                column_mappings,
334            ),
335            schema.clone(),
336        ));
337
338        // 4. DROP TABLE current
339        result.push(Self::new(
340            DropTable {
341                name: Name::from(current_name.as_str()),
342                if_exists: false,
343            }
344            .into(),
345            schema.clone(),
346        ));
347
348        // 5. ALTER TABLE temp RENAME TO current
349        result.push(Self::new(
350            AlterTable {
351                name: Name::from(temp_name.as_str()),
352                action: AlterTableAction::RenameTo(Name::from(current_name.as_str())),
353            }
354            .into(),
355            schema.clone(),
356        ));
357
358        // 6. PRAGMA foreign_keys = ON
359        result.push(Self::new(
360            Statement::pragma_enable_foreign_keys(),
361            schema.clone(),
362        ));
363    }
364
365    fn emit_column_changes(
366        result: &mut Vec<Self>,
367        schema: Cow<'a, Schema>,
368        table: TableId,
369        columns: &[diff::Column<'_>],
370        capability: &Capability,
371        renamed_types: &HashSet<(&str, &str)>,
372    ) {
373        for item in columns.iter() {
374            match item {
375                diff::Column::Add(column) => {
376                    result.push(Self::new(
377                        Statement::add_column(table, column, capability),
378                        schema.clone(),
379                    ));
380                }
381                diff::Column::Drop(column) => {
382                    result.push(Self::new(Statement::drop_column(column), schema.clone()));
383                }
384                diff::Column::Alter {
385                    previous,
386                    next: col_next,
387                } => {
388                    // Skip column-level DDL for named enum changes handled by
389                    // ALTER TYPE.
390                    if capability.named_enum_types
391                        && is_named_enum_type_only_change(previous, col_next, renamed_types)
392                    {
393                        continue;
394                    }
395
396                    let changes = AlterColumnChanges::from_diff(previous, col_next);
397                    let changes = if capability.schema_mutations.alter_column_properties_atomic {
398                        vec![changes]
399                    } else {
400                        changes.split()
401                    };
402
403                    for changes in changes {
404                        result.push(Self::new(
405                            Statement::alter_column(previous, changes, capability),
406                            schema.clone(),
407                        ));
408                    }
409                }
410            }
411        }
412    }
413
414    /// Returns the DDL statement for this migration step.
415    pub fn statement(&self) -> &Statement {
416        &self.statement
417    }
418
419    /// Returns the schema snapshot this statement should be serialized against.
420    pub fn schema(&self) -> &Schema {
421        &self.schema
422    }
423}