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