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