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 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 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 diff_add_initial_data(old, new, &mut change_set);
54 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
72fn 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 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 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 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 let old_relations: &[Relation] = old
328 .get_optional_table(new_table.name())
329 .map(|t| t.relations())
330 .unwrap_or(&[]);
331
332 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) {
368 let affected = views_to_rebuild(old, new);
369 let mut drops: Vec<&View> = old
370 .all_views()
371 .iter()
372 .filter(|v| !view_exists_in(v, new.all_views()) || affected.iter().any(|a| same_view(a, v)))
373 .collect();
374 let depths: Vec<usize> = drops
375 .iter()
376 .map(|v| view_depth(v, old.all_views()))
377 .collect();
378 let mut order: Vec<usize> = (0..drops.len()).collect();
379 order.sort_by(|a, b| depths[*b].cmp(&depths[*a]));
380 drops = order.into_iter().map(|i| drops[i]).collect();
381 for old_view in drops {
382 cs.add_change(SchemaChange::DropView {
383 view_name: old_view.name().to_string(),
384 database_type: old_view.database_type(),
385 });
386 }
387}
388
389fn diff_add_views(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
392 let affected = views_to_rebuild(old, new);
393 let mut adds: Vec<&View> = new
394 .all_views()
395 .iter()
396 .filter(|v| !view_exists_in(v, old.all_views()) || affected.iter().any(|a| same_view(a, v)))
397 .collect();
398 let depths: Vec<usize> = adds
399 .iter()
400 .map(|v| view_depth(v, new.all_views()))
401 .collect();
402 let mut order: Vec<usize> = (0..adds.len()).collect();
403 order.sort_by(|a, b| depths[*a].cmp(&depths[*b]));
404 adds = order.into_iter().map(|i| adds[i]).collect();
405 for new_view in adds {
406 cs.add_change(SchemaChange::AddView {
407 view: new_view.clone(),
408 });
409 }
410}
411
412fn views_to_rebuild(old: &Schema, new: &Schema) -> Vec<View> {
415 let mut changed: Vec<&View> = old
416 .all_views()
417 .iter()
418 .filter(|v| !view_exists_in(v, new.all_views()))
419 .chain(
420 new.all_views()
421 .iter()
422 .filter(|v| !view_exists_in(v, old.all_views())),
423 )
424 .collect();
425 let mut rebuild: Vec<View> = Vec::new();
426 loop {
427 let before = rebuild.len();
428 for view in new.all_views() {
429 let unchanged = view_exists_in(view, old.all_views());
430 if unchanged
431 && !rebuild.iter().any(|r| same_view(r, view))
432 && changed.iter().any(|c| view_reads(view, c))
433 {
434 rebuild.push(view.clone());
435 }
436 }
437 if rebuild.len() == before {
438 break;
439 }
440 changed.extend(rebuild.iter().skip(before).map(|v| {
441 new.all_views()
442 .iter()
443 .find(|n| same_view(n, v))
444 .expect("rebuilt view comes from new schema")
445 }));
446 }
447 rebuild
448}
449
450fn same_view(a: &View, b: &View) -> bool {
451 a.name().eq_ignore_ascii_case(b.name()) && a.database_type() == b.database_type()
452}
453
454fn view_reads(view: &View, target: &View) -> bool {
457 if view.name().eq_ignore_ascii_case(target.name()) {
458 return false;
459 }
460 let sql = view.sql().to_lowercase();
461 let name = target.name().to_lowercase();
462 let is_ident = |c: char| c.is_alphanumeric() || c == '_';
463 sql.match_indices(&name).any(|(i, m)| {
464 let before = sql[..i].chars().next_back();
465 let after = sql[i + m.len()..].chars().next();
466 !before.is_some_and(is_ident) && !after.is_some_and(is_ident)
467 })
468}
469
470fn view_depth(view: &View, views: &[View]) -> usize {
473 fn depth(view: &View, views: &[View], seen: &mut Vec<String>) -> usize {
474 let key = view.name().to_lowercase();
475 if seen.contains(&key) {
476 return 0;
477 }
478 seen.push(key);
479 let result = views
480 .iter()
481 .filter(|other| view_reads(view, other))
482 .map(|other| 1 + depth(other, views, seen))
483 .max()
484 .unwrap_or(0);
485 seen.pop();
486 result
487 }
488 depth(view, views, &mut Vec::new())
489}
490
491fn view_exists_in(view: &View, views: &[View]) -> bool {
492 views.iter().any(|v| views_equal(v, view))
493}
494
495fn views_equal(a: &View, b: &View) -> bool {
496 a.name().eq_ignore_ascii_case(b.name())
497 && a.database_type() == b.database_type()
498 && a.sql().trim() == b.sql().trim()
499}
500
501fn diff_add_enum_types(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
502 for new_enum in new.enum_types() {
503 match find_enum_type(old, new_enum.name()) {
504 None => cs.add_change(SchemaChange::AddEnumType {
505 enum_type: new_enum.clone(),
506 }),
507 Some(old_enum) if !enum_types_equal(old_enum, new_enum) => {
508 cs.add_change(SchemaChange::ModifyEnumType {
509 old_enum_type: old_enum.clone(),
510 new_enum_type: new_enum.clone(),
511 });
512 }
513 Some(_) => {}
514 }
515 }
516}
517
518fn diff_drop_enum_types(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
519 for old_enum in old.enum_types() {
520 if find_enum_type(new, old_enum.name()).is_none() {
521 cs.add_change(SchemaChange::DropEnumType {
522 enum_type_name: old_enum.name().to_string(),
523 });
524 }
525 }
526}
527
528fn find_enum_type<'a>(schema: &'a Schema, name: &str) -> Option<&'a EnumType> {
529 schema
530 .enum_types()
531 .find(|e| e.name().eq_ignore_ascii_case(name))
532}
533
534fn enum_types_equal(a: &EnumType, b: &EnumType) -> bool {
535 a.name().eq_ignore_ascii_case(b.name())
536 && a.values().len() == b.values().len()
537 && a.values()
538 .iter()
539 .zip(b.values().iter())
540 .all(|(av, bv)| av.name() == bv.name() && av.code() == bv.code())
541}
542
543fn diff_add_functions(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
544 for new_fn in new.functions() {
545 if !functions_contains(old.functions(), new_fn) {
546 cs.add_change(SchemaChange::AddFunction {
547 function: new_fn.clone(),
548 });
549 }
550 }
551}
552
553fn diff_drop_functions(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
554 for old_fn in old.functions() {
555 if !functions_contains(new.functions(), old_fn) {
556 cs.add_change(SchemaChange::DropFunction {
557 function_name: old_fn.name().to_string(),
558 database_type: old_fn.database_type(),
559 });
560 }
561 }
562}
563
564fn functions_contains(functions: &[Function], target: &Function) -> bool {
565 functions.iter().any(|f| functions_equal(f, target))
566}
567
568fn functions_equal(a: &Function, b: &Function) -> bool {
569 a.name().eq_ignore_ascii_case(b.name())
570 && a.database_type() == b.database_type()
571 && a.sql().trim() == b.sql().trim()
572}
573
574fn diff_add_procedures(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
575 for new_proc in new.procedures() {
576 if !procedures_contains(old.procedures(), new_proc) {
577 cs.add_change(SchemaChange::AddProcedure {
578 procedure: new_proc.clone(),
579 });
580 }
581 }
582}
583
584fn diff_drop_procedures(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
585 for old_proc in old.procedures() {
586 if !procedures_contains(new.procedures(), old_proc) {
587 cs.add_change(SchemaChange::DropProcedure {
588 procedure_name: old_proc.name().to_string(),
589 database_type: old_proc.database_type(),
590 });
591 }
592 }
593}
594
595fn procedures_contains(procedures: &[Procedure], target: &Procedure) -> bool {
596 procedures.iter().any(|p| procedures_equal(p, target))
597}
598
599fn procedures_equal(a: &Procedure, b: &Procedure) -> bool {
600 a.name().eq_ignore_ascii_case(b.name())
601 && a.database_type() == b.database_type()
602 && a.sql().trim() == b.sql().trim()
603}
604
605fn diff_add_other_sql(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
606 for new_sql in new.other_sql() {
607 if !other_sql_contains(old.other_sql(), new_sql) {
608 cs.add_change(SchemaChange::AddOtherSql {
609 other_sql: new_sql.clone(),
610 });
611 }
612 }
613}
614
615fn diff_drop_other_sql(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
616 for old_sql in old.other_sql() {
617 if !other_sql_contains(new.other_sql(), old_sql) {
618 cs.add_change(SchemaChange::DropOtherSql {
619 other_sql: old_sql.clone(),
620 });
621 }
622 }
623}
624
625fn other_sql_contains(entries: &[OtherSql], target: &OtherSql) -> bool {
626 entries.iter().any(|o| other_sql_equal(o, target))
627}
628
629fn other_sql_equal(a: &OtherSql, b: &OtherSql) -> bool {
630 a.database_type() == b.database_type()
631 && a.order() == b.order()
632 && a.sql().trim() == b.sql().trim()
633}
634
635fn diff_add_triggers(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
643 for new_table in new.tables() {
644 let old_triggers: &[Trigger] = old
645 .get_optional_table(new_table.name())
646 .map(|t| t.triggers())
647 .unwrap_or(&[]);
648 for new_trigger in new_table.triggers() {
649 if !triggers_contains(old_triggers, new_trigger) {
650 cs.add_change(SchemaChange::AddTrigger {
651 table_name: new_table.name().to_string(),
652 trigger: new_trigger.clone(),
653 });
654 }
655 }
656 }
657}
658
659fn diff_drop_triggers(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
660 for old_table in old.tables() {
661 if let Some(new_table) = new.get_optional_table(old_table.name()) {
662 for old_trigger in old_table.triggers() {
663 if !triggers_contains(new_table.triggers(), old_trigger) {
664 cs.add_change(SchemaChange::DropTrigger {
665 table_name: old_table.name().to_string(),
666 trigger: old_trigger.clone(),
667 });
668 }
669 }
670 }
671 }
672}
673
674fn triggers_contains(triggers: &[Trigger], target: &Trigger) -> bool {
675 triggers.iter().any(|t| triggers_equal(t, target))
676}
677
678fn triggers_equal(a: &Trigger, b: &Trigger) -> bool {
679 a.trigger_text().trim() == b.trigger_text().trim()
680 && a.trigger_type() == b.trigger_type()
681 && a.database_type() == b.database_type()
682}
683
684fn diff_add_initial_data(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
685 for new_table in new.tables() {
686 if let Some(old_table) = old.get_optional_table(new_table.name()) {
687 for new_data in new_table.initial_data() {
688 if !initial_data_contains(old_table.initial_data(), new_data) {
689 cs.add_change(SchemaChange::AddInitialData {
690 table_name: new_table.name().to_string(),
691 initial_data: new_data.clone(),
692 });
693 }
694 }
695 }
696 }
697}
698
699fn diff_drop_initial_data(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
700 for old_table in old.tables() {
701 if let Some(new_table) = new.get_optional_table(old_table.name()) {
702 for old_data in old_table.initial_data() {
703 if !initial_data_contains(new_table.initial_data(), old_data) {
704 cs.add_change(SchemaChange::DropInitialData {
705 table_name: old_table.name().to_string(),
706 initial_data: old_data.clone(),
707 });
708 }
709 }
710 }
711 }
712}
713
714fn initial_data_contains(entries: &[InitialData], target: &InitialData) -> bool {
715 entries.iter().any(|d| initial_data_equal(d, target))
716}
717
718fn initial_data_equal(a: &InitialData, b: &InitialData) -> bool {
719 a.sql().trim() == b.sql().trim() && a.database_type() == b.database_type()
720}