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.database_checks() != b.database_checks()
158        || a.enum_type() != b.enum_type()
159        || a.element_type() != b.element_type()
160        || a.generated() != b.generated()
161        || a.min_value() != b.min_value()
162        || a.max_value() != b.max_value()
163}
164
165fn diff_drop_keys(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
166    for old_table in old.tables() {
167        if let Some(new_table) = new.get_optional_table(old_table.name()) {
168            // Ordinal counts only siblings of the same category (unique keys among unique
169            // keys, indexes among indexes) in list order - matching how the create path
170            // numbers `ak_<table><n>` / `ix_<table><n>` - so the migration generator can
171            // reproduce the exact same name for the object it's dropping.
172            let mut unique_ordinal = 0;
173            for old_key in old_table.keys() {
174                if old_key.key_type() == KeyType::Unique {
175                    unique_ordinal += 1;
176                }
177                if !key_exists_in(old_key, new_table.keys())
178                    && !key_exists_in(old_key, new_table.indexes())
179                {
180                    cs.add_change(SchemaChange::DropKey {
181                        table_name: old_table.name().to_string(),
182                        key: old_key.clone(),
183                        ordinal: unique_ordinal,
184                    });
185                }
186            }
187
188            let mut index_ordinal = 0;
189            for old_key in old_table.indexes() {
190                if old_key.is_index() {
191                    index_ordinal += 1;
192                }
193                if !key_exists_in(old_key, new_table.keys())
194                    && !key_exists_in(old_key, new_table.indexes())
195                {
196                    cs.add_change(SchemaChange::DropKey {
197                        table_name: old_table.name().to_string(),
198                        key: old_key.clone(),
199                        ordinal: index_ordinal,
200                    });
201                }
202            }
203        }
204    }
205}
206
207fn diff_add_keys(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
208    for new_table in new.tables() {
209        if let Some(old_table) = old.get_optional_table(new_table.name()) {
210            // See diff_drop_keys - same per-category ordinal so an added key gets the
211            // name the create path would give it.
212            let mut unique_ordinal = 0;
213            for new_key in new_table.keys() {
214                if new_key.key_type() == KeyType::Unique {
215                    unique_ordinal += 1;
216                }
217                if !key_exists_in(new_key, old_table.keys())
218                    && !key_exists_in(new_key, old_table.indexes())
219                {
220                    cs.add_change(SchemaChange::AddKey {
221                        table_name: new_table.name().to_string(),
222                        key: new_key.clone(),
223                        ordinal: unique_ordinal,
224                    });
225                }
226            }
227
228            let mut index_ordinal = 0;
229            for new_key in new_table.indexes() {
230                if new_key.is_index() {
231                    index_ordinal += 1;
232                }
233                if !key_exists_in(new_key, old_table.keys())
234                    && !key_exists_in(new_key, old_table.indexes())
235                {
236                    cs.add_change(SchemaChange::AddKey {
237                        table_name: new_table.name().to_string(),
238                        key: new_key.clone(),
239                        ordinal: index_ordinal,
240                    });
241                }
242            }
243        }
244    }
245}
246
247fn key_exists_in(key: &Key, keys: &[Key]) -> bool {
248    keys.iter().any(|k| keys_equal(k, key))
249}
250
251fn keys_equal(a: &Key, b: &Key) -> bool {
252    a.key_type() == b.key_type()
253        && a.is_unique() == b.is_unique()
254        && a.is_cluster() == b.is_cluster()
255        && a.include() == b.include()
256        && a.filter() == b.filter()
257        && a.columns().len() == b.columns().len()
258        && a.columns()
259            .iter()
260            .zip(b.columns().iter())
261            .all(|(ac, bc)| ac.name().eq_ignore_ascii_case(bc.name()))
262}
263
264fn diff_drop_constraints(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
265    for old_table in old.tables() {
266        if let Some(new_table) = new.get_optional_table(old_table.name()) {
267            for old_con in old_table.constraints() {
268                if !constraint_exists_in(old_con, new_table.constraints()) {
269                    cs.add_change(SchemaChange::DropConstraint {
270                        table_name: old_table.name().to_string(),
271                        constraint_name: old_con.name().to_string(),
272                        database_type: old_con.database_type(),
273                    });
274                }
275            }
276        }
277    }
278}
279
280fn diff_add_constraints(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
281    for new_table in new.tables() {
282        if let Some(old_table) = old.get_optional_table(new_table.name()) {
283            for new_con in new_table.constraints() {
284                if !constraint_exists_in(new_con, old_table.constraints()) {
285                    cs.add_change(SchemaChange::AddConstraint {
286                        table_name: new_table.name().to_string(),
287                        constraint: new_con.clone(),
288                    });
289                }
290            }
291        }
292    }
293}
294
295fn constraint_exists_in(con: &Constraint, constraints: &[Constraint]) -> bool {
296    constraints.iter().any(|c| constraints_equal(c, con))
297}
298
299fn constraints_equal(a: &Constraint, b: &Constraint) -> bool {
300    a.name().eq_ignore_ascii_case(b.name())
301        && a.database_type() == b.database_type()
302        && a.sql().trim() == b.sql().trim()
303}
304
305fn diff_drop_relations(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
306    for old_table in old.tables() {
307        if let Some(new_table) = new.get_optional_table(old_table.name()) {
308            // Ordinal is the relation's 1-based position in the table's relation list,
309            // matching the create path's `fk_<table><n>` numbering, so the migration
310            // generator can reproduce the exact name of the constraint it's dropping.
311            for (index, old_rel) in old_table.relations().iter().enumerate() {
312                if !relation_exists_in(old_rel, new_table.relations()) {
313                    cs.add_change(SchemaChange::DropRelation {
314                        relation: old_rel.clone(),
315                        ordinal: index + 1,
316                    });
317                }
318            }
319        }
320    }
321}
322
323fn diff_add_relations(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
324    for new_table in new.tables() {
325        // A brand-new table (no `old_table`) still needs its relations emitted - `AddTable`'s
326        // rendered `CREATE TABLE` doesn't include them (see diff_add_tables) - so compare
327        // against an empty slice rather than skipping the table entirely.
328        let old_relations: &[Relation] = old
329            .get_optional_table(new_table.name())
330            .map(|t| t.relations())
331            .unwrap_or(&[]);
332
333        // See diff_drop_relations - same ordinal so an added relation gets the name
334        // the create path would give it.
335        for (index, new_rel) in new_table.relations().iter().enumerate() {
336            if !relation_exists_in(new_rel, old_relations) {
337                cs.add_change(SchemaChange::AddRelation {
338                    relation: new_rel.clone(),
339                    ordinal: index + 1,
340                });
341            }
342        }
343    }
344}
345
346fn relation_exists_in(rel: &Relation, relations: &[Relation]) -> bool {
347    relations.iter().any(|r| relations_equal(r, rel))
348}
349
350fn relations_equal(a: &Relation, b: &Relation) -> bool {
351    a.from_table_name()
352        .eq_ignore_ascii_case(b.from_table_name())
353        && a.to_table_name().eq_ignore_ascii_case(b.to_table_name())
354        && a.relation_type() == b.relation_type()
355        && column_pairs_equal(a.column_pairs(), b.column_pairs())
356}
357
358fn column_pairs_equal(a: &[(String, String)], b: &[(String, String)]) -> bool {
359    a.len() == b.len()
360        && a.iter()
361            .zip(b.iter())
362            .all(|((af, at), (bf, bt))| af.eq_ignore_ascii_case(bf) && at.eq_ignore_ascii_case(bt))
363}
364
365/// Views to drop: removed or modified views, plus every kept view that reads one of them
366/// (directly or transitively) - Postgres and SQL Server refuse to drop a view another view still
367/// reads. Ordered dependents-first so each drop happens before the views it depends on.
368fn diff_drop_views(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
369    let affected = views_to_rebuild(old, new);
370    let mut drops: Vec<&View> = old
371        .all_views()
372        .iter()
373        .filter(|v| !view_exists_in(v, new.all_views()) || affected.iter().any(|a| same_view(a, v)))
374        .collect();
375    let depths: Vec<usize> = drops
376        .iter()
377        .map(|v| view_depth(v, old.all_views()))
378        .collect();
379    let mut order: Vec<usize> = (0..drops.len()).collect();
380    order.sort_by(|a, b| depths[*b].cmp(&depths[*a]));
381    drops = order.into_iter().map(|i| drops[i]).collect();
382    for old_view in drops {
383        cs.add_change(SchemaChange::DropView {
384            view_name: old_view.name().to_string(),
385            database_type: old_view.database_type(),
386        });
387    }
388}
389
390/// Views to add: new or modified views, plus the dependents dropped alongside a changed view.
391/// Ordered bases-first so each view is created after the views it reads.
392fn diff_add_views(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
393    let affected = views_to_rebuild(old, new);
394    let mut adds: Vec<&View> = new
395        .all_views()
396        .iter()
397        .filter(|v| !view_exists_in(v, old.all_views()) || affected.iter().any(|a| same_view(a, v)))
398        .collect();
399    let depths: Vec<usize> = adds
400        .iter()
401        .map(|v| view_depth(v, new.all_views()))
402        .collect();
403    let mut order: Vec<usize> = (0..adds.len()).collect();
404    order.sort_by(|a, b| depths[*a].cmp(&depths[*b]));
405    adds = order.into_iter().map(|i| adds[i]).collect();
406    for new_view in adds {
407        cs.add_change(SchemaChange::AddView {
408            view: new_view.clone(),
409        });
410    }
411}
412
413/// Unchanged views (present identically in `old` and `new`) that must be dropped and recreated
414/// because they read - directly or through other views - a view that is removed or modified.
415fn views_to_rebuild(old: &Schema, new: &Schema) -> Vec<View> {
416    let mut changed: Vec<&View> = old
417        .all_views()
418        .iter()
419        .filter(|v| !view_exists_in(v, new.all_views()))
420        .chain(
421            new.all_views()
422                .iter()
423                .filter(|v| !view_exists_in(v, old.all_views())),
424        )
425        .collect();
426    let mut rebuild: Vec<View> = Vec::new();
427    loop {
428        let before = rebuild.len();
429        for view in new.all_views() {
430            let unchanged = view_exists_in(view, old.all_views());
431            if unchanged
432                && !rebuild.iter().any(|r| same_view(r, view))
433                && changed.iter().any(|c| view_reads(view, c))
434            {
435                rebuild.push(view.clone());
436            }
437        }
438        if rebuild.len() == before {
439            break;
440        }
441        changed.extend(rebuild.iter().skip(before).map(|v| {
442            new.all_views()
443                .iter()
444                .find(|n| same_view(n, v))
445                .expect("rebuilt view comes from new schema")
446        }));
447    }
448    rebuild
449}
450
451fn same_view(a: &View, b: &View) -> bool {
452    a.name().eq_ignore_ascii_case(b.name()) && a.database_type() == b.database_type()
453}
454
455/// True when `view`'s SQL mentions `target`'s name as a whole identifier. A match in a comment
456/// or string literal only causes a harmless extra drop/recreate.
457fn view_reads(view: &View, target: &View) -> bool {
458    if view.name().eq_ignore_ascii_case(target.name()) {
459        return false;
460    }
461    let sql = view.sql().to_lowercase();
462    let name = target.name().to_lowercase();
463    let is_ident = |c: char| c.is_alphanumeric() || c == '_';
464    sql.match_indices(&name).any(|(i, m)| {
465        let before = sql[..i].chars().next_back();
466        let after = sql[i + m.len()..].chars().next();
467        !before.is_some_and(is_ident) && !after.is_some_and(is_ident)
468    })
469}
470
471/// Length of the longest chain of views (in `views`) that `view` reads; 0 reads no other view.
472/// Cycles are cut so a malformed schema cannot loop forever.
473fn view_depth(view: &View, views: &[View]) -> usize {
474    fn depth(view: &View, views: &[View], seen: &mut Vec<String>) -> usize {
475        let key = view.name().to_lowercase();
476        if seen.contains(&key) {
477            return 0;
478        }
479        seen.push(key);
480        let result = views
481            .iter()
482            .filter(|other| view_reads(view, other))
483            .map(|other| 1 + depth(other, views, seen))
484            .max()
485            .unwrap_or(0);
486        seen.pop();
487        result
488    }
489    depth(view, views, &mut Vec::new())
490}
491
492fn view_exists_in(view: &View, views: &[View]) -> bool {
493    views.iter().any(|v| views_equal(v, view))
494}
495
496fn views_equal(a: &View, b: &View) -> bool {
497    a.name().eq_ignore_ascii_case(b.name())
498        && a.database_type() == b.database_type()
499        && a.sql().trim() == b.sql().trim()
500}
501
502fn diff_add_enum_types(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
503    for new_enum in new.enum_types() {
504        match find_enum_type(old, new_enum.name()) {
505            None => cs.add_change(SchemaChange::AddEnumType {
506                enum_type: new_enum.clone(),
507            }),
508            Some(old_enum) if !enum_types_equal(old_enum, new_enum) => {
509                cs.add_change(SchemaChange::ModifyEnumType {
510                    old_enum_type: old_enum.clone(),
511                    new_enum_type: new_enum.clone(),
512                });
513            }
514            Some(_) => {}
515        }
516    }
517}
518
519fn diff_drop_enum_types(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
520    for old_enum in old.enum_types() {
521        if find_enum_type(new, old_enum.name()).is_none() {
522            cs.add_change(SchemaChange::DropEnumType {
523                enum_type_name: old_enum.name().to_string(),
524            });
525        }
526    }
527}
528
529fn find_enum_type<'a>(schema: &'a Schema, name: &str) -> Option<&'a EnumType> {
530    schema
531        .enum_types()
532        .find(|e| e.name().eq_ignore_ascii_case(name))
533}
534
535fn enum_types_equal(a: &EnumType, b: &EnumType) -> bool {
536    a.name().eq_ignore_ascii_case(b.name())
537        && a.values().len() == b.values().len()
538        && a.values()
539            .iter()
540            .zip(b.values().iter())
541            .all(|(av, bv)| av.name() == bv.name() && av.code() == bv.code())
542}
543
544fn diff_add_functions(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
545    for new_fn in new.functions() {
546        if !functions_contains(old.functions(), new_fn) {
547            cs.add_change(SchemaChange::AddFunction {
548                function: new_fn.clone(),
549            });
550        }
551    }
552}
553
554fn diff_drop_functions(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
555    for old_fn in old.functions() {
556        if !functions_contains(new.functions(), old_fn) {
557            cs.add_change(SchemaChange::DropFunction {
558                function_name: old_fn.name().to_string(),
559                database_type: old_fn.database_type(),
560            });
561        }
562    }
563}
564
565fn functions_contains(functions: &[Function], target: &Function) -> bool {
566    functions.iter().any(|f| functions_equal(f, target))
567}
568
569fn functions_equal(a: &Function, b: &Function) -> bool {
570    a.name().eq_ignore_ascii_case(b.name())
571        && a.database_type() == b.database_type()
572        && a.sql().trim() == b.sql().trim()
573}
574
575fn diff_add_procedures(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
576    for new_proc in new.procedures() {
577        if !procedures_contains(old.procedures(), new_proc) {
578            cs.add_change(SchemaChange::AddProcedure {
579                procedure: new_proc.clone(),
580            });
581        }
582    }
583}
584
585fn diff_drop_procedures(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
586    for old_proc in old.procedures() {
587        if !procedures_contains(new.procedures(), old_proc) {
588            cs.add_change(SchemaChange::DropProcedure {
589                procedure_name: old_proc.name().to_string(),
590                database_type: old_proc.database_type(),
591            });
592        }
593    }
594}
595
596fn procedures_contains(procedures: &[Procedure], target: &Procedure) -> bool {
597    procedures.iter().any(|p| procedures_equal(p, target))
598}
599
600fn procedures_equal(a: &Procedure, b: &Procedure) -> bool {
601    a.name().eq_ignore_ascii_case(b.name())
602        && a.database_type() == b.database_type()
603        && a.sql().trim() == b.sql().trim()
604}
605
606fn diff_add_other_sql(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
607    for new_sql in new.other_sql() {
608        if !other_sql_contains(old.other_sql(), new_sql) {
609            cs.add_change(SchemaChange::AddOtherSql {
610                other_sql: new_sql.clone(),
611            });
612        }
613    }
614}
615
616fn diff_drop_other_sql(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
617    for old_sql in old.other_sql() {
618        if !other_sql_contains(new.other_sql(), old_sql) {
619            cs.add_change(SchemaChange::DropOtherSql {
620                other_sql: old_sql.clone(),
621            });
622        }
623    }
624}
625
626fn other_sql_contains(entries: &[OtherSql], target: &OtherSql) -> bool {
627    entries.iter().any(|o| other_sql_equal(o, target))
628}
629
630fn other_sql_equal(a: &OtherSql, b: &OtherSql) -> bool {
631    a.database_type() == b.database_type()
632        && a.order() == b.order()
633        && a.sql().trim() == b.sql().trim()
634}
635
636// Initial data is table-scoped and - like `diff_add_columns` - only diffed for tables present in
637// both old and new; a brand-new table's initial data is already emitted inline by `AddTable`'s
638// rendered `CREATE TABLE` (see diff_add_tables), so that's intentional, not a gap.
639//
640// Triggers are different: they're always a separate generation pass, even for an existing table
641// (see diff_add_tables' comment), so a brand-new table's triggers must still be diffed - compare
642// against an empty slice rather than skipping the table when there's no `old_table`.
643fn diff_add_triggers(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
644    for new_table in new.tables() {
645        let old_triggers: &[Trigger] = old
646            .get_optional_table(new_table.name())
647            .map(|t| t.triggers())
648            .unwrap_or(&[]);
649        for new_trigger in new_table.triggers() {
650            if !triggers_contains(old_triggers, new_trigger) {
651                cs.add_change(SchemaChange::AddTrigger {
652                    table_name: new_table.name().to_string(),
653                    trigger: new_trigger.clone(),
654                });
655            }
656        }
657    }
658}
659
660fn diff_drop_triggers(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
661    for old_table in old.tables() {
662        if let Some(new_table) = new.get_optional_table(old_table.name()) {
663            for old_trigger in old_table.triggers() {
664                if !triggers_contains(new_table.triggers(), old_trigger) {
665                    cs.add_change(SchemaChange::DropTrigger {
666                        table_name: old_table.name().to_string(),
667                        trigger: old_trigger.clone(),
668                    });
669                }
670            }
671        }
672    }
673}
674
675fn triggers_contains(triggers: &[Trigger], target: &Trigger) -> bool {
676    triggers.iter().any(|t| triggers_equal(t, target))
677}
678
679fn triggers_equal(a: &Trigger, b: &Trigger) -> bool {
680    a.trigger_text().trim() == b.trigger_text().trim()
681        && a.trigger_type() == b.trigger_type()
682        && a.database_type() == b.database_type()
683}
684
685fn diff_add_initial_data(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
686    for new_table in new.tables() {
687        if let Some(old_table) = old.get_optional_table(new_table.name()) {
688            for new_data in new_table.initial_data() {
689                if !initial_data_contains(old_table.initial_data(), new_data) {
690                    cs.add_change(SchemaChange::AddInitialData {
691                        table_name: new_table.name().to_string(),
692                        initial_data: new_data.clone(),
693                    });
694                }
695            }
696        }
697    }
698}
699
700fn diff_drop_initial_data(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
701    for old_table in old.tables() {
702        if let Some(new_table) = new.get_optional_table(old_table.name()) {
703            for old_data in old_table.initial_data() {
704                if !initial_data_contains(new_table.initial_data(), old_data) {
705                    cs.add_change(SchemaChange::DropInitialData {
706                        table_name: old_table.name().to_string(),
707                        initial_data: old_data.clone(),
708                    });
709                }
710            }
711        }
712    }
713}
714
715fn initial_data_contains(entries: &[InitialData], target: &InitialData) -> bool {
716    entries.iter().any(|d| initial_data_equal(d, target))
717}
718
719fn initial_data_equal(a: &InitialData, b: &InitialData) -> bool {
720    a.sql().trim() == b.sql().trim() && a.database_type() == b.database_type()
721}