schema-diff 0.7.0

A set of tools to manage relational database schemas
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
use schema_model::model::column::Column;
use schema_model::model::constraint::Constraint;
use schema_model::model::enum_type::EnumType;
use schema_model::model::function::Function;
use schema_model::model::initial_data::InitialData;
use schema_model::model::key::Key;
use schema_model::model::other_sql::OtherSql;
use schema_model::model::procedure::Procedure;
use schema_model::model::relation::Relation;
use schema_model::model::schema::Schema;
use schema_model::model::trigger::Trigger;
use schema_model::model::types::KeyType;
use schema_model::model::view::View;

use crate::change::SchemaChange;
use crate::change_set::ChangeSet;

pub struct SchemaDiffEngine;

impl SchemaDiffEngine {
    pub fn diff(old: &Schema, new: &Schema) -> ChangeSet {
        let mut change_set = ChangeSet::new();

        // Drop phase (order matters: views → relations → keys → constraints → columns → tables)
        diff_drop_views(old, new, &mut change_set);
        diff_drop_relations(old, new, &mut change_set);
        diff_drop_keys(old, new, &mut change_set);
        diff_drop_constraints(old, new, &mut change_set);
        diff_drop_columns(old, new, &mut change_set);
        diff_drop_tables(old, new, &mut change_set);
        diff_drop_triggers(old, new, &mut change_set);
        diff_drop_functions(old, new, &mut change_set);
        diff_drop_procedures(old, new, &mut change_set);
        diff_drop_other_sql(old, new, &mut change_set);
        diff_drop_initial_data(old, new, &mut change_set);

        // Add phase (order matters: tables → columns → modify columns → keys → constraints → relations → views)
        // Enum types/functions/procedures/other_sql go first - columns and tables may depend on them.
        // Also detects modified enum types (same name, different value list).
        diff_add_enum_types(old, new, &mut change_set);
        diff_add_functions(old, new, &mut change_set);
        diff_add_procedures(old, new, &mut change_set);
        diff_add_other_sql(old, new, &mut change_set);
        diff_add_tables(old, new, &mut change_set);
        diff_add_columns(old, new, &mut change_set);
        diff_modify_columns(old, new, &mut change_set);
        diff_add_keys(old, new, &mut change_set);
        diff_add_constraints(old, new, &mut change_set);
        diff_add_relations(old, new, &mut change_set);
        diff_add_views(old, new, &mut change_set);
        diff_add_triggers(old, new, &mut change_set);
        // Last: initial data rows reference columns/keys that must already exist.
        diff_add_initial_data(old, new, &mut change_set);
        // Enum drops go last of all: Postgres can't DROP TYPE while a column still uses it, and
        // columns that move off a dropped enum are only retyped by modify_columns above.
        diff_drop_enum_types(old, new, &mut change_set);

        change_set
    }
}

fn diff_drop_tables(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_table in old.tables() {
        if new.get_optional_table(old_table.name()).is_none() {
            cs.add_change(SchemaChange::DropTable {
                table_name: old_table.name().to_string(),
            });
        }
    }
}

// `AddTable` carries the table's full definition (columns, keys, column/table constraints,
// indexes, initial data) so the migration generator can render a real `CREATE TABLE` by routing
// it through `schema-sql-generator`'s own table generator (see schema-migration-generator).
// That rendering covers columns/keys/constraints/indexes/initial data, but *not* relations or
// triggers - those are always a separate generation pass even for an existing table - so
// `diff_add_relations`/`diff_add_triggers` below are relaxed to still emit `AddRelation`/
// `AddTrigger` for a brand-new table. `diff_add_columns`/`diff_add_keys`/`diff_add_constraints`/
// `diff_add_initial_data` intentionally keep skipping new tables: their content is already fully
// covered by the `AddTable` payload, and emitting them too would duplicate DDL.
fn diff_add_tables(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_table in new.tables() {
        if old.get_optional_table(new_table.name()).is_none() {
            cs.add_change(SchemaChange::AddTable {
                table: new_table.clone(),
            });
        }
    }
}

fn diff_drop_columns(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_table in old.tables() {
        if let Some(new_table) = new.get_optional_table(old_table.name()) {
            for old_col in old_table.columns() {
                if !new_table.has_column(old_col.name()) {
                    let rename_candidates: Vec<String> = new_table
                        .columns()
                        .iter()
                        .filter(|nc| {
                            !old_table.has_column(nc.name())
                                && nc.column_type() == old_col.column_type()
                        })
                        .map(|nc| nc.name().to_string())
                        .collect();
                    cs.add_change(SchemaChange::DropColumn {
                        table_name: old_table.name().to_string(),
                        column_name: old_col.name().to_string(),
                        rename_candidates,
                    });
                }
            }
        }
    }
}

fn diff_add_columns(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_table in new.tables() {
        if let Some(old_table) = old.get_optional_table(new_table.name()) {
            for new_col in new_table.columns() {
                if !old_table.has_column(new_col.name()) {
                    cs.add_change(SchemaChange::AddColumn {
                        table_name: new_table.name().to_string(),
                        column: new_col.clone(),
                    });
                }
            }
        }
    }
}

fn diff_modify_columns(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_table in new.tables() {
        if let Some(old_table) = old.get_optional_table(new_table.name()) {
            for new_col in new_table.columns() {
                if old_table.has_column(new_col.name()) {
                    let old_col = old_table.column(new_col.name());
                    if columns_differ(old_col, new_col) {
                        cs.add_change(SchemaChange::ModifyColumn {
                            table_name: new_table.name().to_string(),
                            old_column: old_col.clone(),
                            new_column: new_col.clone(),
                        });
                    }
                }
            }
        }
    }
}

fn columns_differ(a: &Column, b: &Column) -> bool {
    a.column_type() != b.column_type()
        || a.length() != b.length()
        || a.scale() != b.scale()
        || a.required() != b.required()
        || a.default_constraint() != b.default_constraint()
        || a.check_constraint() != b.check_constraint()
        || a.database_checks() != b.database_checks()
        || a.enum_type() != b.enum_type()
        || a.element_type() != b.element_type()
        || a.generated() != b.generated()
        || a.min_value() != b.min_value()
        || a.max_value() != b.max_value()
}

fn diff_drop_keys(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_table in old.tables() {
        if let Some(new_table) = new.get_optional_table(old_table.name()) {
            // Ordinal counts only siblings of the same category (unique keys among unique
            // keys, indexes among indexes) in list order - matching how the create path
            // numbers `ak_<table><n>` / `ix_<table><n>` - so the migration generator can
            // reproduce the exact same name for the object it's dropping.
            let mut unique_ordinal = 0;
            for old_key in old_table.keys() {
                if old_key.key_type() == KeyType::Unique {
                    unique_ordinal += 1;
                }
                if !key_exists_in(old_key, new_table.keys())
                    && !key_exists_in(old_key, new_table.indexes())
                {
                    cs.add_change(SchemaChange::DropKey {
                        table_name: old_table.name().to_string(),
                        key: old_key.clone(),
                        ordinal: unique_ordinal,
                    });
                }
            }

            let mut index_ordinal = 0;
            for old_key in old_table.indexes() {
                if old_key.is_index() {
                    index_ordinal += 1;
                }
                if !key_exists_in(old_key, new_table.keys())
                    && !key_exists_in(old_key, new_table.indexes())
                {
                    cs.add_change(SchemaChange::DropKey {
                        table_name: old_table.name().to_string(),
                        key: old_key.clone(),
                        ordinal: index_ordinal,
                    });
                }
            }
        }
    }
}

fn diff_add_keys(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_table in new.tables() {
        if let Some(old_table) = old.get_optional_table(new_table.name()) {
            // See diff_drop_keys - same per-category ordinal so an added key gets the
            // name the create path would give it.
            let mut unique_ordinal = 0;
            for new_key in new_table.keys() {
                if new_key.key_type() == KeyType::Unique {
                    unique_ordinal += 1;
                }
                if !key_exists_in(new_key, old_table.keys())
                    && !key_exists_in(new_key, old_table.indexes())
                {
                    cs.add_change(SchemaChange::AddKey {
                        table_name: new_table.name().to_string(),
                        key: new_key.clone(),
                        ordinal: unique_ordinal,
                    });
                }
            }

            let mut index_ordinal = 0;
            for new_key in new_table.indexes() {
                if new_key.is_index() {
                    index_ordinal += 1;
                }
                if !key_exists_in(new_key, old_table.keys())
                    && !key_exists_in(new_key, old_table.indexes())
                {
                    cs.add_change(SchemaChange::AddKey {
                        table_name: new_table.name().to_string(),
                        key: new_key.clone(),
                        ordinal: index_ordinal,
                    });
                }
            }
        }
    }
}

fn key_exists_in(key: &Key, keys: &[Key]) -> bool {
    keys.iter().any(|k| keys_equal(k, key))
}

fn keys_equal(a: &Key, b: &Key) -> bool {
    a.key_type() == b.key_type()
        && a.is_unique() == b.is_unique()
        && a.is_cluster() == b.is_cluster()
        && a.include() == b.include()
        && a.filter() == b.filter()
        && a.columns().len() == b.columns().len()
        && a.columns()
            .iter()
            .zip(b.columns().iter())
            .all(|(ac, bc)| ac.name().eq_ignore_ascii_case(bc.name()))
}

fn diff_drop_constraints(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_table in old.tables() {
        if let Some(new_table) = new.get_optional_table(old_table.name()) {
            for old_con in old_table.constraints() {
                if !constraint_exists_in(old_con, new_table.constraints()) {
                    cs.add_change(SchemaChange::DropConstraint {
                        table_name: old_table.name().to_string(),
                        constraint_name: old_con.name().to_string(),
                        database_type: old_con.database_type(),
                    });
                }
            }
        }
    }
}

fn diff_add_constraints(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_table in new.tables() {
        if let Some(old_table) = old.get_optional_table(new_table.name()) {
            for new_con in new_table.constraints() {
                if !constraint_exists_in(new_con, old_table.constraints()) {
                    cs.add_change(SchemaChange::AddConstraint {
                        table_name: new_table.name().to_string(),
                        constraint: new_con.clone(),
                    });
                }
            }
        }
    }
}

fn constraint_exists_in(con: &Constraint, constraints: &[Constraint]) -> bool {
    constraints.iter().any(|c| constraints_equal(c, con))
}

fn constraints_equal(a: &Constraint, b: &Constraint) -> bool {
    a.name().eq_ignore_ascii_case(b.name())
        && a.database_type() == b.database_type()
        && a.sql().trim() == b.sql().trim()
}

fn diff_drop_relations(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_table in old.tables() {
        if let Some(new_table) = new.get_optional_table(old_table.name()) {
            // Ordinal is the relation's 1-based position in the table's relation list,
            // matching the create path's `fk_<table><n>` numbering, so the migration
            // generator can reproduce the exact name of the constraint it's dropping.
            for (index, old_rel) in old_table.relations().iter().enumerate() {
                if !relation_exists_in(old_rel, new_table.relations()) {
                    cs.add_change(SchemaChange::DropRelation {
                        relation: old_rel.clone(),
                        ordinal: index + 1,
                    });
                }
            }
        }
    }
}

fn diff_add_relations(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_table in new.tables() {
        // A brand-new table (no `old_table`) still needs its relations emitted - `AddTable`'s
        // rendered `CREATE TABLE` doesn't include them (see diff_add_tables) - so compare
        // against an empty slice rather than skipping the table entirely.
        let old_relations: &[Relation] = old
            .get_optional_table(new_table.name())
            .map(|t| t.relations())
            .unwrap_or(&[]);

        // See diff_drop_relations - same ordinal so an added relation gets the name
        // the create path would give it.
        for (index, new_rel) in new_table.relations().iter().enumerate() {
            if !relation_exists_in(new_rel, old_relations) {
                cs.add_change(SchemaChange::AddRelation {
                    relation: new_rel.clone(),
                    ordinal: index + 1,
                });
            }
        }
    }
}

fn relation_exists_in(rel: &Relation, relations: &[Relation]) -> bool {
    relations.iter().any(|r| relations_equal(r, rel))
}

fn relations_equal(a: &Relation, b: &Relation) -> bool {
    a.from_table_name()
        .eq_ignore_ascii_case(b.from_table_name())
        && a.to_table_name().eq_ignore_ascii_case(b.to_table_name())
        && a.relation_type() == b.relation_type()
        && column_pairs_equal(a.column_pairs(), b.column_pairs())
}

fn column_pairs_equal(a: &[(String, String)], b: &[(String, String)]) -> bool {
    a.len() == b.len()
        && a.iter()
            .zip(b.iter())
            .all(|((af, at), (bf, bt))| af.eq_ignore_ascii_case(bf) && at.eq_ignore_ascii_case(bt))
}

/// Views to drop: removed or modified views, plus every kept view that reads one of them
/// (directly or transitively) - Postgres and SQL Server refuse to drop a view another view still
/// reads. Ordered dependents-first so each drop happens before the views it depends on.
fn diff_drop_views(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    let affected = views_to_rebuild(old, new);
    let mut drops: Vec<&View> = old
        .all_views()
        .iter()
        .filter(|v| !view_exists_in(v, new.all_views()) || affected.iter().any(|a| same_view(a, v)))
        .collect();
    let depths: Vec<usize> = drops
        .iter()
        .map(|v| view_depth(v, old.all_views()))
        .collect();
    let mut order: Vec<usize> = (0..drops.len()).collect();
    order.sort_by(|a, b| depths[*b].cmp(&depths[*a]));
    drops = order.into_iter().map(|i| drops[i]).collect();
    for old_view in drops {
        cs.add_change(SchemaChange::DropView {
            view_name: old_view.name().to_string(),
            database_type: old_view.database_type(),
        });
    }
}

/// Views to add: new or modified views, plus the dependents dropped alongside a changed view.
/// Ordered bases-first so each view is created after the views it reads.
fn diff_add_views(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    let affected = views_to_rebuild(old, new);
    let mut adds: Vec<&View> = new
        .all_views()
        .iter()
        .filter(|v| !view_exists_in(v, old.all_views()) || affected.iter().any(|a| same_view(a, v)))
        .collect();
    let depths: Vec<usize> = adds
        .iter()
        .map(|v| view_depth(v, new.all_views()))
        .collect();
    let mut order: Vec<usize> = (0..adds.len()).collect();
    order.sort_by(|a, b| depths[*a].cmp(&depths[*b]));
    adds = order.into_iter().map(|i| adds[i]).collect();
    for new_view in adds {
        cs.add_change(SchemaChange::AddView {
            view: new_view.clone(),
        });
    }
}

/// Unchanged views (present identically in `old` and `new`) that must be dropped and recreated
/// because they read - directly or through other views - a view that is removed or modified.
fn views_to_rebuild(old: &Schema, new: &Schema) -> Vec<View> {
    let mut changed: Vec<&View> = old
        .all_views()
        .iter()
        .filter(|v| !view_exists_in(v, new.all_views()))
        .chain(
            new.all_views()
                .iter()
                .filter(|v| !view_exists_in(v, old.all_views())),
        )
        .collect();
    let mut rebuild: Vec<View> = Vec::new();
    loop {
        let before = rebuild.len();
        for view in new.all_views() {
            let unchanged = view_exists_in(view, old.all_views());
            if unchanged
                && !rebuild.iter().any(|r| same_view(r, view))
                && changed.iter().any(|c| view_reads(view, c))
            {
                rebuild.push(view.clone());
            }
        }
        if rebuild.len() == before {
            break;
        }
        changed.extend(rebuild.iter().skip(before).map(|v| {
            new.all_views()
                .iter()
                .find(|n| same_view(n, v))
                .expect("rebuilt view comes from new schema")
        }));
    }
    rebuild
}

fn same_view(a: &View, b: &View) -> bool {
    a.name().eq_ignore_ascii_case(b.name()) && a.database_type() == b.database_type()
}

/// True when `view`'s SQL mentions `target`'s name as a whole identifier. A match in a comment
/// or string literal only causes a harmless extra drop/recreate.
fn view_reads(view: &View, target: &View) -> bool {
    if view.name().eq_ignore_ascii_case(target.name()) {
        return false;
    }
    let sql = view.sql().to_lowercase();
    let name = target.name().to_lowercase();
    let is_ident = |c: char| c.is_alphanumeric() || c == '_';
    sql.match_indices(&name).any(|(i, m)| {
        let before = sql[..i].chars().next_back();
        let after = sql[i + m.len()..].chars().next();
        !before.is_some_and(is_ident) && !after.is_some_and(is_ident)
    })
}

/// Length of the longest chain of views (in `views`) that `view` reads; 0 reads no other view.
/// Cycles are cut so a malformed schema cannot loop forever.
fn view_depth(view: &View, views: &[View]) -> usize {
    fn depth(view: &View, views: &[View], seen: &mut Vec<String>) -> usize {
        let key = view.name().to_lowercase();
        if seen.contains(&key) {
            return 0;
        }
        seen.push(key);
        let result = views
            .iter()
            .filter(|other| view_reads(view, other))
            .map(|other| 1 + depth(other, views, seen))
            .max()
            .unwrap_or(0);
        seen.pop();
        result
    }
    depth(view, views, &mut Vec::new())
}

fn view_exists_in(view: &View, views: &[View]) -> bool {
    views.iter().any(|v| views_equal(v, view))
}

fn views_equal(a: &View, b: &View) -> bool {
    a.name().eq_ignore_ascii_case(b.name())
        && a.database_type() == b.database_type()
        && a.sql().trim() == b.sql().trim()
}

fn diff_add_enum_types(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_enum in new.enum_types() {
        match find_enum_type(old, new_enum.name()) {
            None => cs.add_change(SchemaChange::AddEnumType {
                enum_type: new_enum.clone(),
            }),
            Some(old_enum) if !enum_types_equal(old_enum, new_enum) => {
                cs.add_change(SchemaChange::ModifyEnumType {
                    old_enum_type: old_enum.clone(),
                    new_enum_type: new_enum.clone(),
                });
            }
            Some(_) => {}
        }
    }
}

fn diff_drop_enum_types(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_enum in old.enum_types() {
        if find_enum_type(new, old_enum.name()).is_none() {
            cs.add_change(SchemaChange::DropEnumType {
                enum_type_name: old_enum.name().to_string(),
            });
        }
    }
}

fn find_enum_type<'a>(schema: &'a Schema, name: &str) -> Option<&'a EnumType> {
    schema
        .enum_types()
        .find(|e| e.name().eq_ignore_ascii_case(name))
}

fn enum_types_equal(a: &EnumType, b: &EnumType) -> bool {
    a.name().eq_ignore_ascii_case(b.name())
        && a.values().len() == b.values().len()
        && a.values()
            .iter()
            .zip(b.values().iter())
            .all(|(av, bv)| av.name() == bv.name() && av.code() == bv.code())
}

fn diff_add_functions(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_fn in new.functions() {
        if !functions_contains(old.functions(), new_fn) {
            cs.add_change(SchemaChange::AddFunction {
                function: new_fn.clone(),
            });
        }
    }
}

fn diff_drop_functions(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_fn in old.functions() {
        if !functions_contains(new.functions(), old_fn) {
            cs.add_change(SchemaChange::DropFunction {
                function_name: old_fn.name().to_string(),
                database_type: old_fn.database_type(),
            });
        }
    }
}

fn functions_contains(functions: &[Function], target: &Function) -> bool {
    functions.iter().any(|f| functions_equal(f, target))
}

fn functions_equal(a: &Function, b: &Function) -> bool {
    a.name().eq_ignore_ascii_case(b.name())
        && a.database_type() == b.database_type()
        && a.sql().trim() == b.sql().trim()
}

fn diff_add_procedures(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_proc in new.procedures() {
        if !procedures_contains(old.procedures(), new_proc) {
            cs.add_change(SchemaChange::AddProcedure {
                procedure: new_proc.clone(),
            });
        }
    }
}

fn diff_drop_procedures(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_proc in old.procedures() {
        if !procedures_contains(new.procedures(), old_proc) {
            cs.add_change(SchemaChange::DropProcedure {
                procedure_name: old_proc.name().to_string(),
                database_type: old_proc.database_type(),
            });
        }
    }
}

fn procedures_contains(procedures: &[Procedure], target: &Procedure) -> bool {
    procedures.iter().any(|p| procedures_equal(p, target))
}

fn procedures_equal(a: &Procedure, b: &Procedure) -> bool {
    a.name().eq_ignore_ascii_case(b.name())
        && a.database_type() == b.database_type()
        && a.sql().trim() == b.sql().trim()
}

fn diff_add_other_sql(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_sql in new.other_sql() {
        if !other_sql_contains(old.other_sql(), new_sql) {
            cs.add_change(SchemaChange::AddOtherSql {
                other_sql: new_sql.clone(),
            });
        }
    }
}

fn diff_drop_other_sql(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_sql in old.other_sql() {
        if !other_sql_contains(new.other_sql(), old_sql) {
            cs.add_change(SchemaChange::DropOtherSql {
                other_sql: old_sql.clone(),
            });
        }
    }
}

fn other_sql_contains(entries: &[OtherSql], target: &OtherSql) -> bool {
    entries.iter().any(|o| other_sql_equal(o, target))
}

fn other_sql_equal(a: &OtherSql, b: &OtherSql) -> bool {
    a.database_type() == b.database_type()
        && a.order() == b.order()
        && a.sql().trim() == b.sql().trim()
}

// Initial data is table-scoped and - like `diff_add_columns` - only diffed for tables present in
// both old and new; a brand-new table's initial data is already emitted inline by `AddTable`'s
// rendered `CREATE TABLE` (see diff_add_tables), so that's intentional, not a gap.
//
// Triggers are different: they're always a separate generation pass, even for an existing table
// (see diff_add_tables' comment), so a brand-new table's triggers must still be diffed - compare
// against an empty slice rather than skipping the table when there's no `old_table`.
fn diff_add_triggers(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_table in new.tables() {
        let old_triggers: &[Trigger] = old
            .get_optional_table(new_table.name())
            .map(|t| t.triggers())
            .unwrap_or(&[]);
        for new_trigger in new_table.triggers() {
            if !triggers_contains(old_triggers, new_trigger) {
                cs.add_change(SchemaChange::AddTrigger {
                    table_name: new_table.name().to_string(),
                    trigger: new_trigger.clone(),
                });
            }
        }
    }
}

fn diff_drop_triggers(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_table in old.tables() {
        if let Some(new_table) = new.get_optional_table(old_table.name()) {
            for old_trigger in old_table.triggers() {
                if !triggers_contains(new_table.triggers(), old_trigger) {
                    cs.add_change(SchemaChange::DropTrigger {
                        table_name: old_table.name().to_string(),
                        trigger: old_trigger.clone(),
                    });
                }
            }
        }
    }
}

fn triggers_contains(triggers: &[Trigger], target: &Trigger) -> bool {
    triggers.iter().any(|t| triggers_equal(t, target))
}

fn triggers_equal(a: &Trigger, b: &Trigger) -> bool {
    a.trigger_text().trim() == b.trigger_text().trim()
        && a.trigger_type() == b.trigger_type()
        && a.database_type() == b.database_type()
}

fn diff_add_initial_data(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for new_table in new.tables() {
        if let Some(old_table) = old.get_optional_table(new_table.name()) {
            for new_data in new_table.initial_data() {
                if !initial_data_contains(old_table.initial_data(), new_data) {
                    cs.add_change(SchemaChange::AddInitialData {
                        table_name: new_table.name().to_string(),
                        initial_data: new_data.clone(),
                    });
                }
            }
        }
    }
}

fn diff_drop_initial_data(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
    for old_table in old.tables() {
        if let Some(new_table) = new.get_optional_table(old_table.name()) {
            for old_data in old_table.initial_data() {
                if !initial_data_contains(new_table.initial_data(), old_data) {
                    cs.add_change(SchemaChange::DropInitialData {
                        table_name: old_table.name().to_string(),
                        initial_data: old_data.clone(),
                    });
                }
            }
        }
    }
}

fn initial_data_contains(entries: &[InitialData], target: &InitialData) -> bool {
    entries.iter().any(|d| initial_data_equal(d, target))
}

fn initial_data_equal(a: &InitialData, b: &InitialData) -> bool {
    a.sql().trim() == b.sql().trim() && a.database_type() == b.database_type()
}