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 diff_drop_enum_types(old, new, &mut change_set);
38
39 diff_add_enum_types(old, new, &mut change_set);
43 diff_add_functions(old, new, &mut change_set);
44 diff_add_procedures(old, new, &mut change_set);
45 diff_add_other_sql(old, new, &mut change_set);
46 diff_add_tables(old, new, &mut change_set);
47 diff_add_columns(old, new, &mut change_set);
48 diff_modify_columns(old, new, &mut change_set);
49 diff_add_keys(old, new, &mut change_set);
50 diff_add_constraints(old, new, &mut change_set);
51 diff_add_relations(old, new, &mut change_set);
52 diff_add_views(old, new, &mut change_set);
53 diff_add_triggers(old, new, &mut change_set);
54 diff_add_initial_data(old, new, &mut change_set);
56
57 change_set
58 }
59}
60
61fn diff_drop_tables(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
62 for old_table in old.tables() {
63 if new.get_optional_table(old_table.name()).is_none() {
64 cs.add_change(SchemaChange::DropTable {
65 table_name: old_table.name().to_string(),
66 });
67 }
68 }
69}
70
71fn diff_add_tables(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
81 for new_table in new.tables() {
82 if old.get_optional_table(new_table.name()).is_none() {
83 cs.add_change(SchemaChange::AddTable {
84 table: new_table.clone(),
85 });
86 }
87 }
88}
89
90fn diff_drop_columns(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
91 for old_table in old.tables() {
92 if let Some(new_table) = new.get_optional_table(old_table.name()) {
93 for old_col in old_table.columns() {
94 if !new_table.has_column(old_col.name()) {
95 let rename_candidates: Vec<String> = new_table
96 .columns()
97 .iter()
98 .filter(|nc| {
99 !old_table.has_column(nc.name())
100 && nc.column_type() == old_col.column_type()
101 })
102 .map(|nc| nc.name().to_string())
103 .collect();
104 cs.add_change(SchemaChange::DropColumn {
105 table_name: old_table.name().to_string(),
106 column_name: old_col.name().to_string(),
107 rename_candidates,
108 });
109 }
110 }
111 }
112 }
113}
114
115fn diff_add_columns(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
116 for new_table in new.tables() {
117 if let Some(old_table) = old.get_optional_table(new_table.name()) {
118 for new_col in new_table.columns() {
119 if !old_table.has_column(new_col.name()) {
120 cs.add_change(SchemaChange::AddColumn {
121 table_name: new_table.name().to_string(),
122 column: new_col.clone(),
123 });
124 }
125 }
126 }
127 }
128}
129
130fn diff_modify_columns(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
131 for new_table in new.tables() {
132 if let Some(old_table) = old.get_optional_table(new_table.name()) {
133 for new_col in new_table.columns() {
134 if old_table.has_column(new_col.name()) {
135 let old_col = old_table.column(new_col.name());
136 if columns_differ(old_col, new_col) {
137 cs.add_change(SchemaChange::ModifyColumn {
138 table_name: new_table.name().to_string(),
139 old_column: old_col.clone(),
140 new_column: new_col.clone(),
141 });
142 }
143 }
144 }
145 }
146 }
147}
148
149fn columns_differ(a: &Column, b: &Column) -> bool {
150 a.column_type() != b.column_type()
151 || a.length() != b.length()
152 || a.scale() != b.scale()
153 || a.required() != b.required()
154 || a.default_constraint() != b.default_constraint()
155 || a.check_constraint() != b.check_constraint()
156 || a.enum_type() != b.enum_type()
157 || a.element_type() != b.element_type()
158 || a.generated() != b.generated()
159 || a.min_value() != b.min_value()
160 || a.max_value() != b.max_value()
161}
162
163fn diff_drop_keys(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
164 for old_table in old.tables() {
165 if let Some(new_table) = new.get_optional_table(old_table.name()) {
166 let mut unique_ordinal = 0;
171 for old_key in old_table.keys() {
172 if old_key.key_type() == KeyType::Unique {
173 unique_ordinal += 1;
174 }
175 if !key_exists_in(old_key, new_table.keys())
176 && !key_exists_in(old_key, new_table.indexes())
177 {
178 cs.add_change(SchemaChange::DropKey {
179 table_name: old_table.name().to_string(),
180 key: old_key.clone(),
181 ordinal: unique_ordinal,
182 });
183 }
184 }
185
186 let mut index_ordinal = 0;
187 for old_key in old_table.indexes() {
188 if old_key.is_index() {
189 index_ordinal += 1;
190 }
191 if !key_exists_in(old_key, new_table.keys())
192 && !key_exists_in(old_key, new_table.indexes())
193 {
194 cs.add_change(SchemaChange::DropKey {
195 table_name: old_table.name().to_string(),
196 key: old_key.clone(),
197 ordinal: index_ordinal,
198 });
199 }
200 }
201 }
202 }
203}
204
205fn diff_add_keys(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
206 for new_table in new.tables() {
207 if let Some(old_table) = old.get_optional_table(new_table.name()) {
208 let mut unique_ordinal = 0;
211 for new_key in new_table.keys() {
212 if new_key.key_type() == KeyType::Unique {
213 unique_ordinal += 1;
214 }
215 if !key_exists_in(new_key, old_table.keys())
216 && !key_exists_in(new_key, old_table.indexes())
217 {
218 cs.add_change(SchemaChange::AddKey {
219 table_name: new_table.name().to_string(),
220 key: new_key.clone(),
221 ordinal: unique_ordinal,
222 });
223 }
224 }
225
226 let mut index_ordinal = 0;
227 for new_key in new_table.indexes() {
228 if new_key.is_index() {
229 index_ordinal += 1;
230 }
231 if !key_exists_in(new_key, old_table.keys())
232 && !key_exists_in(new_key, old_table.indexes())
233 {
234 cs.add_change(SchemaChange::AddKey {
235 table_name: new_table.name().to_string(),
236 key: new_key.clone(),
237 ordinal: index_ordinal,
238 });
239 }
240 }
241 }
242 }
243}
244
245fn key_exists_in(key: &Key, keys: &[Key]) -> bool {
246 keys.iter().any(|k| keys_equal(k, key))
247}
248
249fn keys_equal(a: &Key, b: &Key) -> bool {
250 a.key_type() == b.key_type()
251 && a.is_unique() == b.is_unique()
252 && a.is_cluster() == b.is_cluster()
253 && a.include() == b.include()
254 && a.filter() == b.filter()
255 && a.columns().len() == b.columns().len()
256 && a.columns()
257 .iter()
258 .zip(b.columns().iter())
259 .all(|(ac, bc)| ac.name().eq_ignore_ascii_case(bc.name()))
260}
261
262fn diff_drop_constraints(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
263 for old_table in old.tables() {
264 if let Some(new_table) = new.get_optional_table(old_table.name()) {
265 for old_con in old_table.constraints() {
266 if !constraint_exists_in(old_con, new_table.constraints()) {
267 cs.add_change(SchemaChange::DropConstraint {
268 table_name: old_table.name().to_string(),
269 constraint_name: old_con.name().to_string(),
270 database_type: old_con.database_type(),
271 });
272 }
273 }
274 }
275 }
276}
277
278fn diff_add_constraints(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
279 for new_table in new.tables() {
280 if let Some(old_table) = old.get_optional_table(new_table.name()) {
281 for new_con in new_table.constraints() {
282 if !constraint_exists_in(new_con, old_table.constraints()) {
283 cs.add_change(SchemaChange::AddConstraint {
284 table_name: new_table.name().to_string(),
285 constraint: new_con.clone(),
286 });
287 }
288 }
289 }
290 }
291}
292
293fn constraint_exists_in(con: &Constraint, constraints: &[Constraint]) -> bool {
294 constraints.iter().any(|c| constraints_equal(c, con))
295}
296
297fn constraints_equal(a: &Constraint, b: &Constraint) -> bool {
298 a.name().eq_ignore_ascii_case(b.name())
299 && a.database_type() == b.database_type()
300 && a.sql().trim() == b.sql().trim()
301}
302
303fn diff_drop_relations(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
304 for old_table in old.tables() {
305 if let Some(new_table) = new.get_optional_table(old_table.name()) {
306 for (index, old_rel) in old_table.relations().iter().enumerate() {
310 if !relation_exists_in(old_rel, new_table.relations()) {
311 cs.add_change(SchemaChange::DropRelation {
312 relation: old_rel.clone(),
313 ordinal: index + 1,
314 });
315 }
316 }
317 }
318 }
319}
320
321fn diff_add_relations(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
322 for new_table in new.tables() {
323 let old_relations: &[Relation] = old
327 .get_optional_table(new_table.name())
328 .map(|t| t.relations())
329 .unwrap_or(&[]);
330
331 for (index, new_rel) in new_table.relations().iter().enumerate() {
334 if !relation_exists_in(new_rel, old_relations) {
335 cs.add_change(SchemaChange::AddRelation {
336 relation: new_rel.clone(),
337 ordinal: index + 1,
338 });
339 }
340 }
341 }
342}
343
344fn relation_exists_in(rel: &Relation, relations: &[Relation]) -> bool {
345 relations.iter().any(|r| relations_equal(r, rel))
346}
347
348fn relations_equal(a: &Relation, b: &Relation) -> bool {
349 a.from_table_name()
350 .eq_ignore_ascii_case(b.from_table_name())
351 && a.to_table_name().eq_ignore_ascii_case(b.to_table_name())
352 && a.relation_type() == b.relation_type()
353 && column_pairs_equal(a.column_pairs(), b.column_pairs())
354}
355
356fn column_pairs_equal(a: &[(String, String)], b: &[(String, String)]) -> bool {
357 a.len() == b.len()
358 && a.iter()
359 .zip(b.iter())
360 .all(|((af, at), (bf, bt))| af.eq_ignore_ascii_case(bf) && at.eq_ignore_ascii_case(bt))
361}
362
363fn diff_drop_views(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
364 for old_view in old.all_views() {
365 if !view_exists_in(old_view, new.all_views()) {
366 cs.add_change(SchemaChange::DropView {
367 view_name: old_view.name().to_string(),
368 database_type: old_view.database_type(),
369 });
370 }
371 }
372}
373
374fn diff_add_views(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
375 for new_view in new.all_views() {
376 if !view_exists_in(new_view, old.all_views()) {
377 cs.add_change(SchemaChange::AddView {
378 view: new_view.clone(),
379 });
380 }
381 }
382}
383
384fn view_exists_in(view: &View, views: &[View]) -> bool {
385 views.iter().any(|v| views_equal(v, view))
386}
387
388fn views_equal(a: &View, b: &View) -> bool {
389 a.name().eq_ignore_ascii_case(b.name())
390 && a.database_type() == b.database_type()
391 && a.sql().trim() == b.sql().trim()
392}
393
394fn diff_add_enum_types(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
395 for new_enum in new.enum_types() {
396 match find_enum_type(old, new_enum.name()) {
397 None => cs.add_change(SchemaChange::AddEnumType {
398 enum_type: new_enum.clone(),
399 }),
400 Some(old_enum) if !enum_types_equal(old_enum, new_enum) => {
401 cs.add_change(SchemaChange::ModifyEnumType {
402 old_enum_type: old_enum.clone(),
403 new_enum_type: new_enum.clone(),
404 });
405 }
406 Some(_) => {}
407 }
408 }
409}
410
411fn diff_drop_enum_types(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
412 for old_enum in old.enum_types() {
413 if find_enum_type(new, old_enum.name()).is_none() {
414 cs.add_change(SchemaChange::DropEnumType {
415 enum_type_name: old_enum.name().to_string(),
416 });
417 }
418 }
419}
420
421fn find_enum_type<'a>(schema: &'a Schema, name: &str) -> Option<&'a EnumType> {
422 schema
423 .enum_types()
424 .find(|e| e.name().eq_ignore_ascii_case(name))
425}
426
427fn enum_types_equal(a: &EnumType, b: &EnumType) -> bool {
428 a.name().eq_ignore_ascii_case(b.name())
429 && a.values().len() == b.values().len()
430 && a.values()
431 .iter()
432 .zip(b.values().iter())
433 .all(|(av, bv)| av.name() == bv.name() && av.code() == bv.code())
434}
435
436fn diff_add_functions(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
437 for new_fn in new.functions() {
438 if !functions_contains(old.functions(), new_fn) {
439 cs.add_change(SchemaChange::AddFunction {
440 function: new_fn.clone(),
441 });
442 }
443 }
444}
445
446fn diff_drop_functions(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
447 for old_fn in old.functions() {
448 if !functions_contains(new.functions(), old_fn) {
449 cs.add_change(SchemaChange::DropFunction {
450 function_name: old_fn.name().to_string(),
451 database_type: old_fn.database_type(),
452 });
453 }
454 }
455}
456
457fn functions_contains(functions: &[Function], target: &Function) -> bool {
458 functions.iter().any(|f| functions_equal(f, target))
459}
460
461fn functions_equal(a: &Function, b: &Function) -> bool {
462 a.name().eq_ignore_ascii_case(b.name())
463 && a.database_type() == b.database_type()
464 && a.sql().trim() == b.sql().trim()
465}
466
467fn diff_add_procedures(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
468 for new_proc in new.procedures() {
469 if !procedures_contains(old.procedures(), new_proc) {
470 cs.add_change(SchemaChange::AddProcedure {
471 procedure: new_proc.clone(),
472 });
473 }
474 }
475}
476
477fn diff_drop_procedures(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
478 for old_proc in old.procedures() {
479 if !procedures_contains(new.procedures(), old_proc) {
480 cs.add_change(SchemaChange::DropProcedure {
481 procedure_name: old_proc.name().to_string(),
482 database_type: old_proc.database_type(),
483 });
484 }
485 }
486}
487
488fn procedures_contains(procedures: &[Procedure], target: &Procedure) -> bool {
489 procedures.iter().any(|p| procedures_equal(p, target))
490}
491
492fn procedures_equal(a: &Procedure, b: &Procedure) -> bool {
493 a.name().eq_ignore_ascii_case(b.name())
494 && a.database_type() == b.database_type()
495 && a.sql().trim() == b.sql().trim()
496}
497
498fn diff_add_other_sql(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
499 for new_sql in new.other_sql() {
500 if !other_sql_contains(old.other_sql(), new_sql) {
501 cs.add_change(SchemaChange::AddOtherSql {
502 other_sql: new_sql.clone(),
503 });
504 }
505 }
506}
507
508fn diff_drop_other_sql(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
509 for old_sql in old.other_sql() {
510 if !other_sql_contains(new.other_sql(), old_sql) {
511 cs.add_change(SchemaChange::DropOtherSql {
512 other_sql: old_sql.clone(),
513 });
514 }
515 }
516}
517
518fn other_sql_contains(entries: &[OtherSql], target: &OtherSql) -> bool {
519 entries.iter().any(|o| other_sql_equal(o, target))
520}
521
522fn other_sql_equal(a: &OtherSql, b: &OtherSql) -> bool {
523 a.database_type() == b.database_type()
524 && a.order() == b.order()
525 && a.sql().trim() == b.sql().trim()
526}
527
528fn diff_add_triggers(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
536 for new_table in new.tables() {
537 let old_triggers: &[Trigger] = old
538 .get_optional_table(new_table.name())
539 .map(|t| t.triggers())
540 .unwrap_or(&[]);
541 for new_trigger in new_table.triggers() {
542 if !triggers_contains(old_triggers, new_trigger) {
543 cs.add_change(SchemaChange::AddTrigger {
544 table_name: new_table.name().to_string(),
545 trigger: new_trigger.clone(),
546 });
547 }
548 }
549 }
550}
551
552fn diff_drop_triggers(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
553 for old_table in old.tables() {
554 if let Some(new_table) = new.get_optional_table(old_table.name()) {
555 for old_trigger in old_table.triggers() {
556 if !triggers_contains(new_table.triggers(), old_trigger) {
557 cs.add_change(SchemaChange::DropTrigger {
558 table_name: old_table.name().to_string(),
559 trigger: old_trigger.clone(),
560 });
561 }
562 }
563 }
564 }
565}
566
567fn triggers_contains(triggers: &[Trigger], target: &Trigger) -> bool {
568 triggers.iter().any(|t| triggers_equal(t, target))
569}
570
571fn triggers_equal(a: &Trigger, b: &Trigger) -> bool {
572 a.trigger_text().trim() == b.trigger_text().trim()
573 && a.trigger_type() == b.trigger_type()
574 && a.database_type() == b.database_type()
575}
576
577fn diff_add_initial_data(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
578 for new_table in new.tables() {
579 if let Some(old_table) = old.get_optional_table(new_table.name()) {
580 for new_data in new_table.initial_data() {
581 if !initial_data_contains(old_table.initial_data(), new_data) {
582 cs.add_change(SchemaChange::AddInitialData {
583 table_name: new_table.name().to_string(),
584 initial_data: new_data.clone(),
585 });
586 }
587 }
588 }
589 }
590}
591
592fn diff_drop_initial_data(old: &Schema, new: &Schema, cs: &mut ChangeSet) {
593 for old_table in old.tables() {
594 if let Some(new_table) = new.get_optional_table(old_table.name()) {
595 for old_data in old_table.initial_data() {
596 if !initial_data_contains(new_table.initial_data(), old_data) {
597 cs.add_change(SchemaChange::DropInitialData {
598 table_name: old_table.name().to_string(),
599 initial_data: old_data.clone(),
600 });
601 }
602 }
603 }
604 }
605}
606
607fn initial_data_contains(entries: &[InitialData], target: &InitialData) -> bool {
608 entries.iter().any(|d| initial_data_equal(d, target))
609}
610
611fn initial_data_equal(a: &InitialData, b: &InitialData) -> bool {
612 a.sql().trim() == b.sql().trim() && a.database_type() == b.database_type()
613}