Skip to main content

schema_diff/
diff_engine.rs

1use schema_model::model::column::Column;
2use schema_model::model::constraint::Constraint;
3use schema_model::model::enum_type::EnumType;
4use schema_model::model::function::Function;
5use schema_model::model::initial_data::InitialData;
6use schema_model::model::key::Key;
7use schema_model::model::other_sql::OtherSql;
8use schema_model::model::procedure::Procedure;
9use schema_model::model::relation::Relation;
10use schema_model::model::schema::Schema;
11use schema_model::model::trigger::Trigger;
12use schema_model::model::types::KeyType;
13use schema_model::model::view::View;
14
15use crate::change::SchemaChange;
16use crate::change_set::ChangeSet;
17
18pub struct SchemaDiffEngine;
19
20impl SchemaDiffEngine {
21    pub fn diff(old: &Schema, new: &Schema) -> ChangeSet {
22        let mut change_set = ChangeSet::new();
23
24        // Drop phase (order matters: views → relations → keys → constraints → columns → tables)
25        diff_drop_views(old, new, &mut change_set);
26        diff_drop_relations(old, new, &mut change_set);
27        diff_drop_keys(old, new, &mut change_set);
28        diff_drop_constraints(old, new, &mut change_set);
29        diff_drop_columns(old, new, &mut change_set);
30        diff_drop_tables(old, new, &mut change_set);
31        diff_drop_triggers(old, new, &mut change_set);
32        diff_drop_functions(old, new, &mut change_set);
33        diff_drop_procedures(old, new, &mut change_set);
34        diff_drop_other_sql(old, new, &mut change_set);
35        diff_drop_initial_data(old, new, &mut change_set);
36
37        // Add phase (order matters: tables → columns → modify columns → keys → constraints → relations → views)
38        // Enum types/functions/procedures/other_sql go first - columns and tables may depend on them.
39        // Also detects modified enum types (same name, different value list).
40        diff_add_enum_types(old, new, &mut change_set);
41        diff_add_functions(old, new, &mut change_set);
42        diff_add_procedures(old, new, &mut change_set);
43        diff_add_other_sql(old, new, &mut change_set);
44        diff_add_tables(old, new, &mut change_set);
45        diff_add_columns(old, new, &mut change_set);
46        diff_modify_columns(old, new, &mut change_set);
47        diff_add_keys(old, new, &mut change_set);
48        diff_add_constraints(old, new, &mut change_set);
49        diff_add_relations(old, new, &mut change_set);
50        diff_add_views(old, new, &mut change_set);
51        diff_add_triggers(old, new, &mut change_set);
52        // Last: initial data rows reference columns/keys that must already exist.
53        diff_add_initial_data(old, new, &mut change_set);
54        // Enum drops go last of all: Postgres can't DROP TYPE while a column still uses it, and
55        // columns that move off a dropped enum are only retyped by modify_columns above.
56        diff_drop_enum_types(old, new, &mut change_set);
57
58        change_set
59    }
60}
61
62fn diff_drop_tables(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
63    for old_table in old.tables() {
64        if new.get_optional_table(old_table.name()).is_none() {
65            cs.add_change(SchemaChange::DropTable {
66                table_name: old_table.name().to_string(),
67            });
68        }
69    }
70}
71
72// `AddTable` carries the table's full definition (columns, keys, column/table constraints,
73// indexes, initial data) so the migration generator can render a real `CREATE TABLE` by routing
74// it through `schema-sql-generator`'s own table generator (see schema-migration-generator).
75// That rendering covers columns/keys/constraints/indexes/initial data, but *not* relations or
76// triggers - those are always a separate generation pass even for an existing table - so
77// `diff_add_relations`/`diff_add_triggers` below are relaxed to still emit `AddRelation`/
78// `AddTrigger` for a brand-new table. `diff_add_columns`/`diff_add_keys`/`diff_add_constraints`/
79// `diff_add_initial_data` intentionally keep skipping new tables: their content is already fully
80// covered by the `AddTable` payload, and emitting them too would duplicate DDL.
81fn diff_add_tables(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
82    for new_table in new.tables() {
83        if old.get_optional_table(new_table.name()).is_none() {
84            cs.add_change(SchemaChange::AddTable {
85                table: new_table.clone(),
86            });
87        }
88    }
89}
90
91fn diff_drop_columns(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
92    for old_table in old.tables() {
93        if let Some(new_table) = new.get_optional_table(old_table.name()) {
94            for old_col in old_table.columns() {
95                if !new_table.has_column(old_col.name()) {
96                    let rename_candidates: Vec<String> = new_table
97                        .columns()
98                        .iter()
99                        .filter(|nc| {
100                            !old_table.has_column(nc.name())
101                                && nc.column_type() == old_col.column_type()
102                        })
103                        .map(|nc| nc.name().to_string())
104                        .collect();
105                    cs.add_change(SchemaChange::DropColumn {
106                        table_name: old_table.name().to_string(),
107                        column_name: old_col.name().to_string(),
108                        rename_candidates,
109                    });
110                }
111            }
112        }
113    }
114}
115
116fn diff_add_columns(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
117    for new_table in new.tables() {
118        if let Some(old_table) = old.get_optional_table(new_table.name()) {
119            for new_col in new_table.columns() {
120                if !old_table.has_column(new_col.name()) {
121                    cs.add_change(SchemaChange::AddColumn {
122                        table_name: new_table.name().to_string(),
123                        column: new_col.clone(),
124                    });
125                }
126            }
127        }
128    }
129}
130
131fn diff_modify_columns(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
132    for new_table in new.tables() {
133        if let Some(old_table) = old.get_optional_table(new_table.name()) {
134            for new_col in new_table.columns() {
135                if old_table.has_column(new_col.name()) {
136                    let old_col = old_table.column(new_col.name());
137                    if columns_differ(old_col, new_col) {
138                        cs.add_change(SchemaChange::ModifyColumn {
139                            table_name: new_table.name().to_string(),
140                            old_column: old_col.clone(),
141                            new_column: new_col.clone(),
142                        });
143                    }
144                }
145            }
146        }
147    }
148}
149
150fn columns_differ(a: &Column, b: &Column) -> bool {
151    a.column_type() != b.column_type()
152        || a.length() != b.length()
153        || a.scale() != b.scale()
154        || a.required() != b.required()
155        || a.default_constraint() != b.default_constraint()
156        || a.check_constraint() != b.check_constraint()
157        || a.enum_type() != b.enum_type()
158        || a.element_type() != b.element_type()
159        || a.generated() != b.generated()
160        || a.min_value() != b.min_value()
161        || a.max_value() != b.max_value()
162}
163
164fn diff_drop_keys(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
165    for old_table in old.tables() {
166        if let Some(new_table) = new.get_optional_table(old_table.name()) {
167            // Ordinal counts only siblings of the same category (unique keys among unique
168            // keys, indexes among indexes) in list order - matching how the create path
169            // numbers `ak_<table><n>` / `ix_<table><n>` - so the migration generator can
170            // reproduce the exact same name for the object it's dropping.
171            let mut unique_ordinal = 0;
172            for old_key in old_table.keys() {
173                if old_key.key_type() == KeyType::Unique {
174                    unique_ordinal += 1;
175                }
176                if !key_exists_in(old_key, new_table.keys())
177                    && !key_exists_in(old_key, new_table.indexes())
178                {
179                    cs.add_change(SchemaChange::DropKey {
180                        table_name: old_table.name().to_string(),
181                        key: old_key.clone(),
182                        ordinal: unique_ordinal,
183                    });
184                }
185            }
186
187            let mut index_ordinal = 0;
188            for old_key in old_table.indexes() {
189                if old_key.is_index() {
190                    index_ordinal += 1;
191                }
192                if !key_exists_in(old_key, new_table.keys())
193                    && !key_exists_in(old_key, new_table.indexes())
194                {
195                    cs.add_change(SchemaChange::DropKey {
196                        table_name: old_table.name().to_string(),
197                        key: old_key.clone(),
198                        ordinal: index_ordinal,
199                    });
200                }
201            }
202        }
203    }
204}
205
206fn diff_add_keys(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
207    for new_table in new.tables() {
208        if let Some(old_table) = old.get_optional_table(new_table.name()) {
209            // See diff_drop_keys - same per-category ordinal so an added key gets the
210            // name the create path would give it.
211            let mut unique_ordinal = 0;
212            for new_key in new_table.keys() {
213                if new_key.key_type() == KeyType::Unique {
214                    unique_ordinal += 1;
215                }
216                if !key_exists_in(new_key, old_table.keys())
217                    && !key_exists_in(new_key, old_table.indexes())
218                {
219                    cs.add_change(SchemaChange::AddKey {
220                        table_name: new_table.name().to_string(),
221                        key: new_key.clone(),
222                        ordinal: unique_ordinal,
223                    });
224                }
225            }
226
227            let mut index_ordinal = 0;
228            for new_key in new_table.indexes() {
229                if new_key.is_index() {
230                    index_ordinal += 1;
231                }
232                if !key_exists_in(new_key, old_table.keys())
233                    && !key_exists_in(new_key, old_table.indexes())
234                {
235                    cs.add_change(SchemaChange::AddKey {
236                        table_name: new_table.name().to_string(),
237                        key: new_key.clone(),
238                        ordinal: index_ordinal,
239                    });
240                }
241            }
242        }
243    }
244}
245
246fn key_exists_in(key: &Key, keys: &[Key]) -> bool {
247    keys.iter().any(|k| keys_equal(k, key))
248}
249
250fn keys_equal(a: &Key, b: &Key) -> bool {
251    a.key_type() == b.key_type()
252        && a.is_unique() == b.is_unique()
253        && a.is_cluster() == b.is_cluster()
254        && a.include() == b.include()
255        && a.filter() == b.filter()
256        && a.columns().len() == b.columns().len()
257        && a.columns()
258            .iter()
259            .zip(b.columns().iter())
260            .all(|(ac, bc)| ac.name().eq_ignore_ascii_case(bc.name()))
261}
262
263fn diff_drop_constraints(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
264    for old_table in old.tables() {
265        if let Some(new_table) = new.get_optional_table(old_table.name()) {
266            for old_con in old_table.constraints() {
267                if !constraint_exists_in(old_con, new_table.constraints()) {
268                    cs.add_change(SchemaChange::DropConstraint {
269                        table_name: old_table.name().to_string(),
270                        constraint_name: old_con.name().to_string(),
271                        database_type: old_con.database_type(),
272                    });
273                }
274            }
275        }
276    }
277}
278
279fn diff_add_constraints(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
280    for new_table in new.tables() {
281        if let Some(old_table) = old.get_optional_table(new_table.name()) {
282            for new_con in new_table.constraints() {
283                if !constraint_exists_in(new_con, old_table.constraints()) {
284                    cs.add_change(SchemaChange::AddConstraint {
285                        table_name: new_table.name().to_string(),
286                        constraint: new_con.clone(),
287                    });
288                }
289            }
290        }
291    }
292}
293
294fn constraint_exists_in(con: &Constraint, constraints: &[Constraint]) -> bool {
295    constraints.iter().any(|c| constraints_equal(c, con))
296}
297
298fn constraints_equal(a: &Constraint, b: &Constraint) -> bool {
299    a.name().eq_ignore_ascii_case(b.name())
300        && a.database_type() == b.database_type()
301        && a.sql().trim() == b.sql().trim()
302}
303
304fn diff_drop_relations(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
305    for old_table in old.tables() {
306        if let Some(new_table) = new.get_optional_table(old_table.name()) {
307            // Ordinal is the relation's 1-based position in the table's relation list,
308            // matching the create path's `fk_<table><n>` numbering, so the migration
309            // generator can reproduce the exact name of the constraint it's dropping.
310            for (index, old_rel) in old_table.relations().iter().enumerate() {
311                if !relation_exists_in(old_rel, new_table.relations()) {
312                    cs.add_change(SchemaChange::DropRelation {
313                        relation: old_rel.clone(),
314                        ordinal: index + 1,
315                    });
316                }
317            }
318        }
319    }
320}
321
322fn diff_add_relations(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
323    for new_table in new.tables() {
324        // A brand-new table (no `old_table`) still needs its relations emitted - `AddTable`'s
325        // rendered `CREATE TABLE` doesn't include them (see diff_add_tables) - so compare
326        // against an empty slice rather than skipping the table entirely.
327        let old_relations: &[Relation] = old
328            .get_optional_table(new_table.name())
329            .map(|t| t.relations())
330            .unwrap_or(&[]);
331
332        // See diff_drop_relations - same ordinal so an added relation gets the name
333        // the create path would give it.
334        for (index, new_rel) in new_table.relations().iter().enumerate() {
335            if !relation_exists_in(new_rel, old_relations) {
336                cs.add_change(SchemaChange::AddRelation {
337                    relation: new_rel.clone(),
338                    ordinal: index + 1,
339                });
340            }
341        }
342    }
343}
344
345fn relation_exists_in(rel: &Relation, relations: &[Relation]) -> bool {
346    relations.iter().any(|r| relations_equal(r, rel))
347}
348
349fn relations_equal(a: &Relation, b: &Relation) -> bool {
350    a.from_table_name()
351        .eq_ignore_ascii_case(b.from_table_name())
352        && a.to_table_name().eq_ignore_ascii_case(b.to_table_name())
353        && a.relation_type() == b.relation_type()
354        && column_pairs_equal(a.column_pairs(), b.column_pairs())
355}
356
357fn column_pairs_equal(a: &[(String, String)], b: &[(String, String)]) -> bool {
358    a.len() == b.len()
359        && a.iter()
360            .zip(b.iter())
361            .all(|((af, at), (bf, bt))| af.eq_ignore_ascii_case(bf) && at.eq_ignore_ascii_case(bt))
362}
363
364fn diff_drop_views(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
365    for old_view in old.all_views() {
366        if !view_exists_in(old_view, new.all_views()) {
367            cs.add_change(SchemaChange::DropView {
368                view_name: old_view.name().to_string(),
369                database_type: old_view.database_type(),
370            });
371        }
372    }
373}
374
375fn diff_add_views(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
376    for new_view in new.all_views() {
377        if !view_exists_in(new_view, old.all_views()) {
378            cs.add_change(SchemaChange::AddView {
379                view: new_view.clone(),
380            });
381        }
382    }
383}
384
385fn view_exists_in(view: &View, views: &[View]) -> bool {
386    views.iter().any(|v| views_equal(v, view))
387}
388
389fn views_equal(a: &View, b: &View) -> bool {
390    a.name().eq_ignore_ascii_case(b.name())
391        && a.database_type() == b.database_type()
392        && a.sql().trim() == b.sql().trim()
393}
394
395fn diff_add_enum_types(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
396    for new_enum in new.enum_types() {
397        match find_enum_type(old, new_enum.name()) {
398            None => cs.add_change(SchemaChange::AddEnumType {
399                enum_type: new_enum.clone(),
400            }),
401            Some(old_enum) if !enum_types_equal(old_enum, new_enum) => {
402                cs.add_change(SchemaChange::ModifyEnumType {
403                    old_enum_type: old_enum.clone(),
404                    new_enum_type: new_enum.clone(),
405                });
406            }
407            Some(_) => {}
408        }
409    }
410}
411
412fn diff_drop_enum_types(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
413    for old_enum in old.enum_types() {
414        if find_enum_type(new, old_enum.name()).is_none() {
415            cs.add_change(SchemaChange::DropEnumType {
416                enum_type_name: old_enum.name().to_string(),
417            });
418        }
419    }
420}
421
422fn find_enum_type<'a>(schema: &'a Schema, name: &str) -> Option<&'a EnumType> {
423    schema
424        .enum_types()
425        .find(|e| e.name().eq_ignore_ascii_case(name))
426}
427
428fn enum_types_equal(a: &EnumType, b: &EnumType) -> bool {
429    a.name().eq_ignore_ascii_case(b.name())
430        && a.values().len() == b.values().len()
431        && a.values()
432            .iter()
433            .zip(b.values().iter())
434            .all(|(av, bv)| av.name() == bv.name() && av.code() == bv.code())
435}
436
437fn diff_add_functions(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
438    for new_fn in new.functions() {
439        if !functions_contains(old.functions(), new_fn) {
440            cs.add_change(SchemaChange::AddFunction {
441                function: new_fn.clone(),
442            });
443        }
444    }
445}
446
447fn diff_drop_functions(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
448    for old_fn in old.functions() {
449        if !functions_contains(new.functions(), old_fn) {
450            cs.add_change(SchemaChange::DropFunction {
451                function_name: old_fn.name().to_string(),
452                database_type: old_fn.database_type(),
453            });
454        }
455    }
456}
457
458fn functions_contains(functions: &[Function], target: &Function) -> bool {
459    functions.iter().any(|f| functions_equal(f, target))
460}
461
462fn functions_equal(a: &Function, b: &Function) -> bool {
463    a.name().eq_ignore_ascii_case(b.name())
464        && a.database_type() == b.database_type()
465        && a.sql().trim() == b.sql().trim()
466}
467
468fn diff_add_procedures(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
469    for new_proc in new.procedures() {
470        if !procedures_contains(old.procedures(), new_proc) {
471            cs.add_change(SchemaChange::AddProcedure {
472                procedure: new_proc.clone(),
473            });
474        }
475    }
476}
477
478fn diff_drop_procedures(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
479    for old_proc in old.procedures() {
480        if !procedures_contains(new.procedures(), old_proc) {
481            cs.add_change(SchemaChange::DropProcedure {
482                procedure_name: old_proc.name().to_string(),
483                database_type: old_proc.database_type(),
484            });
485        }
486    }
487}
488
489fn procedures_contains(procedures: &[Procedure], target: &Procedure) -> bool {
490    procedures.iter().any(|p| procedures_equal(p, target))
491}
492
493fn procedures_equal(a: &Procedure, b: &Procedure) -> bool {
494    a.name().eq_ignore_ascii_case(b.name())
495        && a.database_type() == b.database_type()
496        && a.sql().trim() == b.sql().trim()
497}
498
499fn diff_add_other_sql(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
500    for new_sql in new.other_sql() {
501        if !other_sql_contains(old.other_sql(), new_sql) {
502            cs.add_change(SchemaChange::AddOtherSql {
503                other_sql: new_sql.clone(),
504            });
505        }
506    }
507}
508
509fn diff_drop_other_sql(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
510    for old_sql in old.other_sql() {
511        if !other_sql_contains(new.other_sql(), old_sql) {
512            cs.add_change(SchemaChange::DropOtherSql {
513                other_sql: old_sql.clone(),
514            });
515        }
516    }
517}
518
519fn other_sql_contains(entries: &[OtherSql], target: &OtherSql) -> bool {
520    entries.iter().any(|o| other_sql_equal(o, target))
521}
522
523fn other_sql_equal(a: &OtherSql, b: &OtherSql) -> bool {
524    a.database_type() == b.database_type()
525        && a.order() == b.order()
526        && a.sql().trim() == b.sql().trim()
527}
528
529// Initial data is table-scoped and - like `diff_add_columns` - only diffed for tables present in
530// both old and new; a brand-new table's initial data is already emitted inline by `AddTable`'s
531// rendered `CREATE TABLE` (see diff_add_tables), so that's intentional, not a gap.
532//
533// Triggers are different: they're always a separate generation pass, even for an existing table
534// (see diff_add_tables' comment), so a brand-new table's triggers must still be diffed - compare
535// against an empty slice rather than skipping the table when there's no `old_table`.
536fn diff_add_triggers(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
537    for new_table in new.tables() {
538        let old_triggers: &[Trigger] = old
539            .get_optional_table(new_table.name())
540            .map(|t| t.triggers())
541            .unwrap_or(&[]);
542        for new_trigger in new_table.triggers() {
543            if !triggers_contains(old_triggers, new_trigger) {
544                cs.add_change(SchemaChange::AddTrigger {
545                    table_name: new_table.name().to_string(),
546                    trigger: new_trigger.clone(),
547                });
548            }
549        }
550    }
551}
552
553fn diff_drop_triggers(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
554    for old_table in old.tables() {
555        if let Some(new_table) = new.get_optional_table(old_table.name()) {
556            for old_trigger in old_table.triggers() {
557                if !triggers_contains(new_table.triggers(), old_trigger) {
558                    cs.add_change(SchemaChange::DropTrigger {
559                        table_name: old_table.name().to_string(),
560                        trigger: old_trigger.clone(),
561                    });
562                }
563            }
564        }
565    }
566}
567
568fn triggers_contains(triggers: &[Trigger], target: &Trigger) -> bool {
569    triggers.iter().any(|t| triggers_equal(t, target))
570}
571
572fn triggers_equal(a: &Trigger, b: &Trigger) -> bool {
573    a.trigger_text().trim() == b.trigger_text().trim()
574        && a.trigger_type() == b.trigger_type()
575        && a.database_type() == b.database_type()
576}
577
578fn diff_add_initial_data(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
579    for new_table in new.tables() {
580        if let Some(old_table) = old.get_optional_table(new_table.name()) {
581            for new_data in new_table.initial_data() {
582                if !initial_data_contains(old_table.initial_data(), new_data) {
583                    cs.add_change(SchemaChange::AddInitialData {
584                        table_name: new_table.name().to_string(),
585                        initial_data: new_data.clone(),
586                    });
587                }
588            }
589        }
590    }
591}
592
593fn diff_drop_initial_data(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
594    for old_table in old.tables() {
595        if let Some(new_table) = new.get_optional_table(old_table.name()) {
596            for old_data in old_table.initial_data() {
597                if !initial_data_contains(new_table.initial_data(), old_data) {
598                    cs.add_change(SchemaChange::DropInitialData {
599                        table_name: old_table.name().to_string(),
600                        initial_data: old_data.clone(),
601                    });
602                }
603            }
604        }
605    }
606}
607
608fn initial_data_contains(entries: &[InitialData], target: &InitialData) -> bool {
609    entries.iter().any(|d| initial_data_equal(d, target))
610}
611
612fn initial_data_equal(a: &InitialData, b: &InitialData) -> bool {
613    a.sql().trim() == b.sql().trim() && a.database_type() == b.database_type()
614}