1use crate::migrate::baseline::SchemaStatistics;
7use crate::schema::{
8 Column, CompositeType, Event, Grant, IndexMeta, Role, StoredFunction, StoredProcedure, Table,
9 Trigger,
10};
11use anyhow::{Context, Result};
12use chrono::{DateTime, Utc};
13use sqlx::Row;
14use std::collections::{HashMap, HashSet};
15
16#[derive(Debug, Clone, PartialEq)]
18pub enum SchemaDiff {
19 TableAdded {
20 name: String,
21 table: Table,
22 },
23 TableDropped {
24 name: String,
25 table: Table,
26 },
27 TableModified {
28 name: String,
29 old_table: Table,
30 new_table: Table,
31 },
32 ViewAdded {
33 name: String,
34 view: crate::schema::View,
35 },
36 ViewDropped {
37 name: String,
38 view: crate::schema::View,
39 },
40 ViewModified {
41 name: String,
42 old_view: crate::schema::View,
43 new_view: crate::schema::View,
44 },
45 IndexAdded {
46 name: String,
47 index: IndexMeta,
48 },
49 IndexDropped {
50 name: String,
51 index: IndexMeta,
52 },
53 IndexModified {
54 name: String,
55 old_index: IndexMeta,
56 new_index: IndexMeta,
57 },
58 EventAdded {
59 name: String,
60 event: Event,
61 },
62 EventDropped {
63 name: String,
64 event: Event,
65 },
66 EventModified {
67 name: String,
68 old_event: Event,
69 new_event: Event,
70 },
71 RoleAdded {
73 name: String,
74 role: Role,
75 },
76 RoleDropped {
77 name: String,
78 role: Role,
79 },
80 RoleModified {
81 name: String,
82 old_role: Role,
83 new_role: Role,
84 },
85 GrantAdded {
86 name: String,
87 grant: Grant,
88 },
89 GrantDropped {
90 name: String,
91 grant: Grant,
92 },
93 GrantModified {
94 name: String,
95 old_grant: Grant,
96 new_grant: Grant,
97 },
98 FunctionAdded {
100 name: String,
101 function: StoredFunction,
102 },
103 FunctionDropped {
104 name: String,
105 function: StoredFunction,
106 },
107 FunctionModified {
108 name: String,
109 old_function: StoredFunction,
110 new_function: StoredFunction,
111 },
112 ProcedureAdded {
114 name: String,
115 procedure: StoredProcedure,
116 },
117 ProcedureDropped {
118 name: String,
119 procedure: StoredProcedure,
120 },
121 ProcedureModified {
122 name: String,
123 old_procedure: StoredProcedure,
124 new_procedure: StoredProcedure,
125 },
126 TriggerAdded {
128 name: String,
129 trigger: Trigger,
130 },
131 TriggerDropped {
132 name: String,
133 trigger: Trigger,
134 },
135 TriggerModified {
136 name: String,
137 old_trigger: Trigger,
138 new_trigger: Trigger,
139 },
140 CompositeTypeAdded {
142 name: String,
143 composite_type: CompositeType,
144 },
145 CompositeTypeDropped {
146 name: String,
147 composite_type: CompositeType,
148 },
149 CompositeTypeModified {
150 name: String,
151 old_composite_type: CompositeType,
152 new_composite_type: CompositeType,
153 },
154}
155
156#[derive(Debug, Clone)]
158pub enum TableChange {
159 ColumnAdded {
160 name: String,
161 column: Column,
162 },
163 ColumnDropped {
164 name: String,
165 column: Column,
166 },
167 ColumnModified {
168 name: String,
169 old_column: Column,
170 new_column: Column,
171 },
172 PrimaryKeyChanged {
173 old_pk: Option<String>,
174 new_pk: Option<String>,
175 },
176 IndexesChanged {
177 old_indexes: Vec<IndexMeta>,
178 new_indexes: Vec<IndexMeta>,
179 },
180}
181
182#[derive(Debug, Clone)]
184pub enum ViewChange {
185 ColumnAdded {
186 name: String,
187 column: Column,
188 },
189 ColumnDropped {
190 name: String,
191 column: Column,
192 },
193 ColumnModified {
194 name: String,
195 old_column: Column,
196 new_column: Column,
197 },
198 PrimaryKeyChanged {
199 old_pk: Option<String>,
200 new_pk: Option<String>,
201 },
202 MaterializedChanged {
203 was_materialized: bool,
204 is_materialized: bool,
205 },
206 DependenciesChanged {
207 old_deps: Vec<String>,
208 new_deps: Vec<String>,
209 },
210 IndexesChanged {
211 old_indexes: Vec<crate::schema::Index>,
212 new_indexes: Vec<crate::schema::Index>,
213 },
214}
215
216#[derive(Debug, Clone)]
218pub enum IndexChange {
219 ColumnsChanged {
220 old_columns: Vec<String>,
221 new_columns: Vec<String>,
222 },
223 TypeChanged {
224 old_type: crate::schema::IndexType,
225 new_type: crate::schema::IndexType,
226 },
227 UniqueChanged {
228 was_unique: bool,
229 is_unique: bool,
230 },
231 ConcurrentChanged {
232 was_concurrent: bool,
233 is_concurrent: bool,
234 },
235 TableChanged {
236 old_table: String,
237 new_table: String,
238 },
239 SchemaChanged {
240 old_schema: Option<String>,
241 new_schema: Option<String>,
242 },
243}
244
245#[derive(Debug, Clone)]
247pub enum EventChange {
248 ScheduleChanged {
249 old_schedule: String,
250 new_schedule: String,
251 },
252 CommandChanged {
253 old_command: String,
254 new_command: String,
255 },
256 DatabaseChanged {
257 old_database: Option<String>,
258 new_database: Option<String>,
259 },
260 UsernameChanged {
261 old_username: Option<String>,
262 new_username: Option<String>,
263 },
264 DdlChanged {
265 old_ddl: String,
266 new_ddl: String,
267 },
268 EnabledChanged {
269 was_enabled: bool,
270 is_enabled: bool,
271 },
272}
273
274#[derive(Debug, Clone, PartialEq)]
276pub enum RoleChange {
277 PasswordChanged {
278 old_password: Option<String>,
279 new_password: Option<String>,
280 },
281 PrivilegesChanged {
282 old_superuser: bool,
283 new_superuser: bool,
284 },
285 LoginChanged {
286 old_login: bool,
287 new_login: bool,
288 },
289 MembershipChanged {
290 old_members: Vec<String>,
291 new_members: Vec<String>,
292 },
293 ConnectionLimitChanged {
294 old_limit: Option<i32>,
295 new_limit: Option<i32>,
296 },
297 ValidUntilChanged {
298 old_until: Option<String>,
299 new_until: Option<String>,
300 },
301}
302
303pub struct SchemaDiffEngine;
305
306impl SchemaDiffEngine {
307 pub fn compare_tables(
309 old_tables: &HashMap<String, Table>,
310 new_tables: &HashMap<String, Table>,
311 ) -> Vec<SchemaDiff> {
312 let mut diffs = Vec::new();
313
314 for (name, table) in new_tables {
316 if !old_tables.contains_key(name) {
317 diffs.push(SchemaDiff::TableAdded {
318 name: name.clone(),
319 table: table.clone(),
320 });
321 }
322 }
323
324 for (name, table) in old_tables {
326 if !new_tables.contains_key(name) {
327 diffs.push(SchemaDiff::TableDropped {
328 name: name.clone(),
329 table: table.clone(),
330 });
331 }
332 }
333
334 for (name, new_table) in new_tables {
336 if let Some(old_table) = old_tables.get(name) {
337 let changes = Self::compare_table(old_table, new_table);
338 if !changes.is_empty() {
339 diffs.push(SchemaDiff::TableModified {
340 name: name.clone(),
341 old_table: old_table.clone(),
342 new_table: new_table.clone(),
343 });
344 }
345 }
346 }
347
348 diffs
349 }
350
351 pub fn compare_events(
353 old_events: &HashMap<String, Event>,
354 new_events: &HashMap<String, Event>,
355 ) -> Vec<SchemaDiff> {
356 let mut diffs = Vec::new();
357
358 for (name, event) in new_events {
360 if !old_events.contains_key(name) {
361 diffs.push(SchemaDiff::EventAdded {
362 name: name.clone(),
363 event: event.clone(),
364 });
365 }
366 }
367
368 for (name, event) in old_events {
370 if !new_events.contains_key(name) {
371 diffs.push(SchemaDiff::EventDropped {
372 name: name.clone(),
373 event: event.clone(),
374 });
375 }
376 }
377
378 for (name, new_event) in new_events {
380 if let Some(old_event) = old_events.get(name) {
381 let changes = Self::compare_event(old_event, new_event);
382 if !changes.is_empty() {
383 diffs.push(SchemaDiff::EventModified {
384 name: name.clone(),
385 old_event: old_event.clone(),
386 new_event: new_event.clone(),
387 });
388 }
389 }
390 }
391
392 diffs
393 }
394
395 fn compare_event(old_event: &Event, new_event: &Event) -> Vec<EventChange> {
397 let mut changes = Vec::new();
398
399 if old_event.schedule != new_event.schedule {
400 changes.push(EventChange::ScheduleChanged {
401 old_schedule: old_event.schedule.clone(),
402 new_schedule: new_event.schedule.clone(),
403 });
404 }
405
406 if old_event.command != new_event.command {
407 changes.push(EventChange::CommandChanged {
408 old_command: old_event.command.clone(),
409 new_command: new_event.command.clone(),
410 });
411 }
412
413 if old_event.database != new_event.database {
414 changes.push(EventChange::DatabaseChanged {
415 old_database: old_event.database.clone(),
416 new_database: new_event.database.clone(),
417 });
418 }
419
420 if old_event.username != new_event.username {
421 changes.push(EventChange::UsernameChanged {
422 old_username: old_event.username.clone(),
423 new_username: new_event.username.clone(),
424 });
425 }
426
427 if old_event.ddl != new_event.ddl {
428 changes.push(EventChange::DdlChanged {
429 old_ddl: old_event.ddl.clone(),
430 new_ddl: new_event.ddl.clone(),
431 });
432 }
433
434 if old_event.enabled != new_event.enabled {
435 changes.push(EventChange::EnabledChanged {
436 was_enabled: old_event.enabled,
437 is_enabled: new_event.enabled,
438 });
439 }
440
441 changes
442 }
443
444 pub fn compare_indexes(
446 old_indexes: &HashMap<String, IndexMeta>,
447 new_indexes: &HashMap<String, IndexMeta>,
448 ) -> Vec<SchemaDiff> {
449 let mut diffs = Vec::new();
450
451 for (name, index) in new_indexes {
453 if !old_indexes.contains_key(name) {
454 diffs.push(SchemaDiff::IndexAdded {
455 name: name.clone(),
456 index: index.clone(),
457 });
458 }
459 }
460
461 for (name, index) in old_indexes {
463 if !new_indexes.contains_key(name) {
464 diffs.push(SchemaDiff::IndexDropped {
465 name: name.clone(),
466 index: index.clone(),
467 });
468 }
469 }
470
471 for (name, new_index) in new_indexes {
473 if let Some(old_index) = old_indexes.get(name) {
474 let changes = Self::compare_index(old_index, new_index);
475 if !changes.is_empty() {
476 diffs.push(SchemaDiff::IndexModified {
477 name: name.clone(),
478 old_index: old_index.clone(),
479 new_index: new_index.clone(),
480 });
481 }
482 }
483 }
484
485 diffs
486 }
487
488 fn compare_index(old_index: &IndexMeta, new_index: &IndexMeta) -> Vec<IndexChange> {
490 let mut changes = Vec::new();
491
492 if old_index.columns != new_index.columns {
494 let old_cols: Vec<String> = old_index.columns.iter().map(|s| s.to_string()).collect();
495 let new_cols: Vec<String> = new_index.columns.iter().map(|s| s.to_string()).collect();
496 changes.push(IndexChange::ColumnsChanged {
497 old_columns: old_cols,
498 new_columns: new_cols,
499 });
500 }
501
502 if old_index.index_type != new_index.index_type {
504 changes.push(IndexChange::TypeChanged {
505 old_type: old_index.index_type.clone(),
506 new_type: new_index.index_type.clone(),
507 });
508 }
509
510 if old_index.unique != new_index.unique {
512 changes.push(IndexChange::UniqueChanged {
513 was_unique: old_index.unique,
514 is_unique: new_index.unique,
515 });
516 }
517
518 if old_index.concurrent != new_index.concurrent {
520 changes.push(IndexChange::ConcurrentChanged {
521 was_concurrent: old_index.concurrent,
522 is_concurrent: new_index.concurrent,
523 });
524 }
525
526 if old_index.table != new_index.table {
528 changes.push(IndexChange::TableChanged {
529 old_table: old_index.table.to_string(),
530 new_table: new_index.table.to_string(),
531 });
532 }
533
534 if old_index.schema != new_index.schema {
536 let old_schema = old_index.schema.as_ref().map_or("", |v| v);
537 let new_schema = new_index.schema.as_ref().map_or("", |v| v);
538 changes.push(IndexChange::SchemaChanged {
539 old_schema: Some(old_schema.to_string()),
540 new_schema: Some(new_schema.to_string()),
541 });
542 }
543
544 changes
545 }
546
547 pub fn compare_views(
549 old_views: &HashMap<String, crate::schema::View>,
550 new_views: &HashMap<String, crate::schema::View>,
551 ) -> Vec<SchemaDiff> {
552 let mut diffs = Vec::new();
553
554 for (name, view) in new_views {
556 if !old_views.contains_key(name) {
557 diffs.push(SchemaDiff::ViewAdded {
558 name: name.clone(),
559 view: view.clone(),
560 });
561 }
562 }
563
564 for (name, view) in old_views {
566 if !new_views.contains_key(name) {
567 diffs.push(SchemaDiff::ViewDropped {
568 name: name.clone(),
569 view: view.clone(),
570 });
571 }
572 }
573
574 for (name, new_view) in new_views {
576 if let Some(old_view) = old_views.get(name) {
577 let changes = Self::compare_view(old_view, new_view);
578 if !changes.is_empty() {
579 diffs.push(SchemaDiff::ViewModified {
580 name: name.clone(),
581 old_view: old_view.clone(),
582 new_view: new_view.clone(),
583 });
584 }
585 }
586 }
587
588 diffs
589 }
590
591 fn compare_table(old_table: &Table, new_table: &Table) -> Vec<TableChange> {
593 let mut changes = Vec::new();
594
595 if old_table.primary_key != new_table.primary_key {
597 changes.push(TableChange::PrimaryKeyChanged {
598 old_pk: old_table.primary_key.clone(),
599 new_pk: new_table.primary_key.clone(),
600 });
601 }
602
603 let old_columns: HashMap<&String, &Column> =
605 old_table.columns.iter().map(|c| (&c.name, c)).collect();
606 let new_columns: HashMap<&String, &Column> =
607 new_table.columns.iter().map(|c| (&c.name, c)).collect();
608
609 for column in &new_table.columns {
611 if !old_columns.contains_key(&column.name) {
612 changes.push(TableChange::ColumnAdded {
613 name: column.name.clone(),
614 column: column.clone(),
615 });
616 }
617 }
618
619 for column in &old_table.columns {
621 if !new_columns.contains_key(&column.name) {
622 changes.push(TableChange::ColumnDropped {
623 name: column.name.clone(),
624 column: column.clone(),
625 });
626 }
627 }
628
629 for new_column in &new_table.columns {
631 if let Some(old_column) = old_columns.get(&new_column.name) {
632 if !Self::columns_equal(old_column, new_column) {
633 changes.push(TableChange::ColumnModified {
634 name: new_column.name.clone(),
635 old_column: (*old_column).clone(),
636 new_column: new_column.clone(),
637 });
638 }
639 }
640 }
641
642 changes
643 }
644
645 fn compare_view(
647 old_view: &crate::schema::View,
648 new_view: &crate::schema::View,
649 ) -> Vec<ViewChange> {
650 let mut changes = Vec::new();
651
652 let old_pk = old_view.columns.first().map(|c| &c.name);
654 let new_pk = new_view.columns.first().map(|c| &c.name);
655 if old_pk != new_pk {
656 changes.push(ViewChange::PrimaryKeyChanged {
657 old_pk: old_pk.cloned(),
658 new_pk: new_pk.cloned(),
659 });
660 }
661
662 if old_view.materialized != new_view.materialized {
664 changes.push(ViewChange::MaterializedChanged {
665 was_materialized: old_view.materialized,
666 is_materialized: new_view.materialized,
667 });
668 }
669
670 if old_view.dependencies != new_view.dependencies {
672 changes.push(ViewChange::DependenciesChanged {
673 old_deps: old_view.dependencies.clone(),
674 new_deps: new_view.dependencies.clone(),
675 });
676 }
677
678 if old_view.indexes != new_view.indexes {
680 changes.push(ViewChange::IndexesChanged {
681 old_indexes: old_view.indexes.clone(),
682 new_indexes: new_view.indexes.clone(),
683 });
684 }
685
686 let old_columns: HashMap<&String, &Column> =
688 old_view.columns.iter().map(|c| (&c.name, c)).collect();
689 let new_columns: HashMap<&String, &Column> =
690 new_view.columns.iter().map(|c| (&c.name, c)).collect();
691
692 for column in &new_view.columns {
694 if !old_columns.contains_key(&column.name) {
695 changes.push(ViewChange::ColumnAdded {
696 name: column.name.clone(),
697 column: column.clone(),
698 });
699 }
700 }
701
702 for column in &old_view.columns {
704 if !new_columns.contains_key(&column.name) {
705 changes.push(ViewChange::ColumnDropped {
706 name: column.name.clone(),
707 column: column.clone(),
708 });
709 }
710 }
711
712 for column in &new_view.columns {
714 if let Some(old_column) = old_columns.get(&column.name) {
715 if old_column != &column {
716 changes.push(ViewChange::ColumnModified {
717 name: column.name.clone(),
718 old_column: (*old_column).clone(),
719 new_column: column.clone(),
720 });
721 }
722 }
723 }
724
725 changes
726 }
727
728 pub fn columns_equal(a: &Column, b: &Column) -> bool {
730 a.name == b.name
731 && a.column_type == b.column_type
732 && a.nullable == b.nullable
733 && a.default == b.default
734 && a.unique == b.unique
735 && a.references == b.references
736 }
737
738 pub fn generate_table_change_sql(
740 table_name: &str,
741 old_table: &Table,
742 new_table: &Table,
743 ) -> Vec<String> {
744 let mut changes = Vec::new();
745
746 if old_table.primary_key != new_table.primary_key {
748 let mut sql = String::new();
749 if let Some(_old_pk) = &old_table.primary_key {
750 sql.push_str(&format!(
751 "ALTER TABLE \"{}\" DROP CONSTRAINT IF EXISTS \"{}_pkey\" CASCADE;\n",
752 table_name, table_name
753 ));
754 }
755 if let Some(new_pk) = &new_table.primary_key {
756 sql.push_str(&format!(
757 "ALTER TABLE \"{}\" ADD PRIMARY KEY (\"{}\");\n",
758 table_name, new_pk
759 ));
760 }
761 changes.push(sql);
762 }
763
764 let old_columns: HashMap<&String, &Column> =
766 old_table.columns.iter().map(|c| (&c.name, c)).collect();
767 let new_columns: HashMap<&String, &Column> =
768 new_table.columns.iter().map(|c| (&c.name, c)).collect();
769
770 for column in &new_table.columns {
772 if !old_columns.contains_key(&column.name) {
773 changes.push(format!(
774 "ALTER TABLE \"{}\" ADD COLUMN {};\n",
775 table_name,
776 column.to_sql().trim_start_matches(" ")
777 ));
778 }
779 }
780
781 for column in &old_table.columns {
783 if !new_columns.contains_key(&column.name) {
784 changes.push(format!(
785 "ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
786 table_name, column.name
787 ));
788 }
789 }
790
791 for new_column in &new_table.columns {
793 if let Some(old_column) = old_columns.get(&new_column.name) {
794 if !Self::columns_equal(old_column, new_column) {
795 let mut sql = String::new();
796 sql.push_str(&format!(
797 "ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
798 table_name, new_column.name
799 ));
800 sql.push_str(&format!(
801 "ALTER TABLE \"{}\" ADD COLUMN {};\n",
802 table_name,
803 new_column.to_sql().trim_start_matches(" ")
804 ));
805 changes.push(sql);
806 }
807 }
808 }
809
810 changes
811 }
812
813 pub fn generate_view_change_sql(
815 view_name: &str,
816 old_view: &crate::schema::View,
817 new_view: &crate::schema::View,
818 ) -> Vec<String> {
819 let mut changes = Vec::new();
820
821 let old_pk = old_view.columns.first().map(|c| &c.name);
823 let new_pk = new_view.columns.first().map(|c| &c.name);
824 if old_pk != new_pk {
825 changes.push(format!("-- Primary key changed for view {}\n", view_name));
826 }
827
828 if old_view.materialized != new_view.materialized {
830 if old_view.materialized && !new_view.materialized {
831 changes.push(format!(
833 "-- Convert materialized view {} to regular view\n",
834 view_name
835 ));
836 } else if !old_view.materialized && new_view.materialized {
837 changes.push(format!(
839 "-- Convert regular view {} to materialized view\n",
840 view_name
841 ));
842 }
843 }
844
845 if old_view.dependencies != new_view.dependencies {
847 let added: Vec<_> = new_view
848 .dependencies
849 .iter()
850 .filter(|d| !old_view.dependencies.contains(d))
851 .collect();
852 let removed: Vec<_> = old_view
853 .dependencies
854 .iter()
855 .filter(|d| !new_view.dependencies.contains(d))
856 .collect();
857
858 let mut sql = String::new();
859 if !added.is_empty() {
860 let added_names: Vec<String> = added.iter().map(|&s| s.clone()).collect();
861 sql.push_str(&format!(
862 "-- View {} now depends on: {}\n",
863 view_name,
864 added_names.join(", ")
865 ));
866 }
867 if !removed.is_empty() {
868 let removed_names: Vec<String> = removed.iter().map(|&s| s.clone()).collect();
869 sql.push_str(&format!(
870 "-- View {} no longer depends on: {}\n",
871 view_name,
872 removed_names.join(", ")
873 ));
874 }
875 changes.push(sql);
876 }
877
878 if old_view.indexes != new_view.indexes {
880 let added: Vec<_> = new_view
881 .indexes
882 .iter()
883 .filter(|i| !old_view.indexes.contains(i))
884 .collect();
885 let removed: Vec<_> = old_view
886 .indexes
887 .iter()
888 .filter(|i| !new_view.indexes.contains(i))
889 .collect();
890
891 let mut sql = String::new();
892 if !added.is_empty() {
893 let added_names: Vec<String> = added.iter().map(|i| i.name.clone()).collect();
894 sql.push_str(&format!(
895 "-- Add indexes to view {}: {}\n",
896 view_name,
897 added_names.join(", ")
898 ));
899 }
900 if !removed.is_empty() {
901 let removed_names: Vec<String> = removed.iter().map(|i| i.name.clone()).collect();
902 sql.push_str(&format!(
903 "-- Remove indexes from view {}: {}\n",
904 view_name,
905 removed_names.join(", ")
906 ));
907 }
908 changes.push(sql);
909 }
910
911 let old_columns: HashMap<&String, &Column> =
913 old_view.columns.iter().map(|c| (&c.name, c)).collect();
914 let new_columns: HashMap<&String, &Column> =
915 new_view.columns.iter().map(|c| (&c.name, c)).collect();
916
917 for column in &new_view.columns {
919 if !old_columns.contains_key(&column.name) {
920 changes.push(format!(
921 "-- Add column {} to view {}\n",
922 column.name, view_name
923 ));
924 }
925 }
926
927 for column in &old_view.columns {
929 if !new_columns.contains_key(&column.name) {
930 changes.push(format!(
931 "-- Drop column {} from view {}\n",
932 column.name, view_name
933 ));
934 }
935 }
936
937 for column in &new_view.columns {
939 if let Some(old_column) = old_columns.get(&column.name) {
940 if old_column != &column {
941 changes.push(format!(
942 "-- Modify column {} in view {}\n",
943 column.name, view_name
944 ));
945 }
946 }
947 }
948
949 changes
950 }
951
952 pub fn generate_index_change_sql(
954 index_name: &str,
955 old_index: &IndexMeta,
956 new_index: &IndexMeta,
957 ) -> Vec<String> {
958 let mut changes = Vec::new();
959
960 if old_index.columns != new_index.columns {
962 let old_cols: Vec<String> = old_index.columns.iter().map(|s| s.to_string()).collect();
963 let new_cols: Vec<String> = new_index.columns.iter().map(|s| s.to_string()).collect();
964 for old_col in old_cols {
965 changes.push(format!(
966 "ALTER INDEX \"{}\" DROP COLUMN \"{}\";\n",
967 index_name, old_col
968 ));
969 }
970 for new_col in new_cols {
971 changes.push(format!(
972 "ALTER INDEX \"{}\" ADD COLUMN \"{}\";\n",
973 index_name, new_col
974 ));
975 }
976 }
977
978 if old_index.index_type != new_index.index_type {
980 changes.push(format!(
981 "-- Index {} type changed from {} to {}\n",
982 index_name, old_index.index_type, new_index.index_type
983 ));
984 }
985
986 if old_index.unique != new_index.unique {
988 if old_index.unique && !new_index.unique {
989 changes.push(format!("-- Index {} is no longer UNIQUE\n", index_name));
990 } else if !old_index.unique && new_index.unique {
991 changes.push(format!("-- Index {} is now UNIQUE\n", index_name));
992 }
993 }
994
995 if old_index.concurrent != new_index.concurrent {
997 if old_index.concurrent && !new_index.concurrent {
998 changes.push(format!(
999 "-- Index {} is no longer CONCURRENTLY\n",
1000 index_name
1001 ));
1002 } else if !old_index.concurrent && new_index.concurrent {
1003 changes.push(format!("-- Index {} is now CONCURRENTLY\n", index_name));
1004 }
1005 }
1006
1007 if old_index.table != new_index.table {
1009 changes.push(format!(
1010 "-- Index {} table changed from {} to {}\n",
1011 index_name, old_index.table, new_index.table
1012 ));
1013 }
1014
1015 if old_index.schema != new_index.schema {
1017 let old_schema = old_index.schema.as_ref().map_or("", |v| v);
1018 let new_schema = new_index.schema.as_ref().map_or("", |v| v);
1019 changes.push(format!(
1020 "-- Index {} schema changed from {} to {}\n",
1021 index_name, old_schema, new_schema
1022 ));
1023 }
1024
1025 changes
1026 }
1027
1028 pub fn generate_event_change_sql(
1030 event_name: &str,
1031 old_event: &Event,
1032 new_event: &Event,
1033 ) -> Vec<String> {
1034 let mut changes = Vec::new();
1035
1036 if old_event.schedule != new_event.schedule {
1037 changes.push(format!(
1038 "-- Event {} schedule changed from {} to {}\n",
1039 event_name, old_event.schedule, new_event.schedule
1040 ));
1041 }
1042
1043 if old_event.command != new_event.command {
1044 changes.push(format!(
1045 "-- Event {} command changed from {} to {}\n",
1046 event_name, old_event.command, new_event.command
1047 ));
1048 }
1049
1050 if old_event.database != new_event.database {
1051 let mut sql = String::new();
1052 if let Some(old_db) = &old_event.database {
1053 sql.push_str(&format!(
1054 "ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
1055 event_name, old_db
1056 ));
1057 }
1058 if let Some(new_db) = &new_event.database {
1059 sql.push_str(&format!(
1060 "ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
1061 event_name, new_db
1062 ));
1063 }
1064 changes.push(sql);
1065 }
1066
1067 if old_event.username != new_event.username {
1068 let mut sql = String::new();
1069 if let Some(old_user) = &old_event.username {
1070 sql.push_str(&format!(
1071 "ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
1072 event_name, old_user
1073 ));
1074 }
1075 if let Some(new_user) = &new_event.username {
1076 sql.push_str(&format!(
1077 "ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
1078 event_name, new_user
1079 ));
1080 }
1081 changes.push(sql);
1082 }
1083
1084 if old_event.ddl != new_event.ddl {
1085 changes.push(format!(
1086 "-- Event {} DDL changed from {} to {}\n",
1087 event_name, old_event.ddl, new_event.ddl
1088 ));
1089 }
1090
1091 if old_event.enabled != new_event.enabled {
1092 if old_event.enabled && !new_event.enabled {
1093 changes.push(format!("-- Event {} is now DISABLED\n", event_name));
1094 } else if !old_event.enabled && new_event.enabled {
1095 changes.push(format!("-- Event {} is now ENABLED\n", event_name));
1096 }
1097 }
1098
1099 changes
1100 }
1101
1102 pub fn generate_role_change_sql(
1104 role_name: &str,
1105 old_role: &Role,
1106 new_role: &Role,
1107 ) -> Vec<String> {
1108 let mut changes = Vec::new();
1109
1110 if old_role.password != new_role.password {
1111 let mut sql = String::new();
1112 if let Some(_old_password) = &old_role.password {
1113 sql.push_str(&format!("ALTER ROLE \"{}\" PASSWORD NULL;\n", role_name));
1114 }
1115 if let Some(new_password) = &new_role.password {
1116 sql.push_str(&format!(
1117 "ALTER ROLE \"{}\" PASSWORD '{}';\n",
1118 role_name, new_password
1119 ));
1120 }
1121 changes.push(sql);
1122 }
1123
1124 if old_role.superuser != new_role.superuser {
1125 let mut sql = String::new();
1126 if !old_role.superuser && new_role.superuser {
1127 sql.push_str(&format!("ALTER ROLE \"{}\" SUPERUSER;\n", role_name));
1128 } else if old_role.superuser && !new_role.superuser {
1129 sql.push_str(&format!("ALTER ROLE \"{}\" NOSUPERUSER;\n", role_name));
1130 }
1131 changes.push(sql);
1132 }
1133
1134 if old_role.login != new_role.login {
1135 let mut sql = String::new();
1136 if !old_role.login && new_role.login {
1137 sql.push_str(&format!("ALTER ROLE \"{}\" LOGIN;\n", role_name));
1138 } else if old_role.login && !new_role.login {
1139 sql.push_str(&format!("ALTER ROLE \"{}\" NOLOGIN;\n", role_name));
1140 }
1141 changes.push(sql);
1142 }
1143
1144 if old_role.member_of != new_role.member_of || old_role.members != new_role.members {
1145 let mut sql = String::new();
1146 let mut old_members: Vec<String> =
1147 old_role.member_of.iter().map(|s| s.clone()).collect();
1148 old_members.extend(old_role.members.iter().map(|s| s.clone()));
1149 let mut new_members: Vec<String> =
1150 new_role.member_of.iter().map(|s| s.clone()).collect();
1151 new_members.extend(new_role.members.iter().map(|s| s.clone()));
1152
1153 let added: Vec<_> = new_members
1154 .iter()
1155 .filter(|d| !old_members.contains(d))
1156 .collect();
1157 let removed: Vec<_> = old_members
1158 .iter()
1159 .filter(|d| !new_members.contains(d))
1160 .collect();
1161
1162 if !added.is_empty() {
1163 let added_names: Vec<String> = added.iter().map(|&s| s.clone()).collect();
1164 sql.push_str(&format!(
1165 "ALTER ROLE \"{}\" ADD MEMBER \"{}\";\n",
1166 role_name,
1167 added_names.join(", ")
1168 ));
1169 }
1170 if !removed.is_empty() {
1171 let removed_names: Vec<String> = removed.iter().map(|&s| s.clone()).collect();
1172 sql.push_str(&format!(
1173 "ALTER ROLE \"{}\" DROP MEMBER \"{}\";\n",
1174 role_name,
1175 removed_names.join(", ")
1176 ));
1177 }
1178 changes.push(sql);
1179 }
1180
1181 if old_role.connection_limit != new_role.connection_limit {
1182 let mut sql = String::new();
1183 if let Some(_old_limit) = &old_role.connection_limit {
1184 sql.push_str(&format!(
1185 "ALTER ROLE \"{}\" CONNECTION LIMIT NULL;\n",
1186 role_name
1187 ));
1188 }
1189 if let Some(new_limit) = &new_role.connection_limit {
1190 sql.push_str(&format!(
1191 "ALTER ROLE \"{}\" CONNECTION LIMIT {};\n",
1192 role_name, new_limit
1193 ));
1194 }
1195 changes.push(sql);
1196 }
1197
1198 if old_role.valid_until != new_role.valid_until {
1199 let mut sql = String::new();
1200 if let Some(_old_until) = &old_role.valid_until {
1201 sql.push_str(&format!("ALTER ROLE \"{}\" VALID UNTIL NULL;\n", role_name));
1202 }
1203 if let Some(new_until) = &new_role.valid_until {
1204 sql.push_str(&format!(
1205 "ALTER ROLE \"{}\" VALID UNTIL '{}';\n",
1206 role_name, new_until
1207 ));
1208 }
1209 changes.push(sql);
1210 }
1211
1212 changes
1213 }
1214
1215 pub fn generate_grant_change_sql(
1217 grant_name: &str,
1218 old_grant: &Grant,
1219 new_grant: &Grant,
1220 ) -> Vec<String> {
1221 let mut changes = Vec::new();
1222
1223 if old_grant.privilege != new_grant.privilege {
1225 changes.push(format!(
1226 "-- Grant {} privilege changed from {:?} to {:?}\n",
1227 grant_name, old_grant.privilege, new_grant.privilege
1228 ));
1229 }
1230
1231 if old_grant.target != new_grant.target {
1233 changes.push(format!(
1234 "-- Grant {} target changed from {:?} to {:?}\n",
1235 grant_name, old_grant.target, new_grant.target
1236 ));
1237 }
1238
1239 if old_grant.grantee != new_grant.grantee {
1241 changes.push(format!(
1242 "-- Grant {} grantee changed from {} to {}\n",
1243 grant_name, old_grant.grantee, new_grant.grantee
1244 ));
1245 }
1246
1247 if old_grant.with_grant_option != new_grant.with_grant_option {
1249 if old_grant.with_grant_option && !new_grant.with_grant_option {
1250 changes.push(format!(
1251 "-- Grant {} no longer has GRANT OPTION\n",
1252 grant_name
1253 ));
1254 } else if !old_grant.with_grant_option && new_grant.with_grant_option {
1255 changes.push(format!("-- Grant {} now has GRANT OPTION\n", grant_name));
1256 }
1257 }
1258
1259 if old_grant.grantor != new_grant.grantor {
1261 changes.push(format!(
1262 "-- Grant {} grantor changed from {:?} to {:?}\n",
1263 grant_name, old_grant.grantor, new_grant.grantor
1264 ));
1265 }
1266
1267 changes
1268 }
1269
1270 pub fn compare_roles(
1272 old_roles: &HashMap<String, Role>,
1273 new_roles: &HashMap<String, Role>,
1274 ) -> Vec<SchemaDiff> {
1275 let mut diffs = Vec::new();
1276
1277 for (name, role) in new_roles {
1279 if !old_roles.contains_key(name) {
1280 diffs.push(SchemaDiff::RoleAdded {
1281 name: name.clone(),
1282 role: role.clone(),
1283 });
1284 }
1285 }
1286
1287 for (name, role) in old_roles {
1289 if !new_roles.contains_key(name) {
1290 diffs.push(SchemaDiff::RoleDropped {
1291 name: name.clone(),
1292 role: role.clone(),
1293 });
1294 }
1295 }
1296
1297 for (name, new_role) in new_roles {
1299 if let Some(old_role) = old_roles.get(name) {
1300 if old_role != new_role {
1301 diffs.push(SchemaDiff::RoleModified {
1302 name: name.clone(),
1303 old_role: old_role.clone(),
1304 new_role: new_role.clone(),
1305 });
1306 }
1307 }
1308 }
1309
1310 diffs
1311 }
1312
1313 pub fn compare_grants(
1315 old_grants: &HashMap<String, Grant>,
1316 new_grants: &HashMap<String, Grant>,
1317 ) -> Vec<SchemaDiff> {
1318 let mut diffs = Vec::new();
1319
1320 for (name, grant) in new_grants {
1322 if !old_grants.contains_key(name) {
1323 diffs.push(SchemaDiff::GrantAdded {
1324 name: name.clone(),
1325 grant: grant.clone(),
1326 });
1327 }
1328 }
1329
1330 for (name, grant) in old_grants {
1332 if !new_grants.contains_key(name) {
1333 diffs.push(SchemaDiff::GrantDropped {
1334 name: name.clone(),
1335 grant: grant.clone(),
1336 });
1337 }
1338 }
1339
1340 for (name, new_grant) in new_grants {
1342 if let Some(old_grant) = old_grants.get(name) {
1343 if old_grant != new_grant {
1344 diffs.push(SchemaDiff::GrantModified {
1345 name: name.clone(),
1346 old_grant: old_grant.clone(),
1347 new_grant: new_grant.clone(),
1348 });
1349 }
1350 }
1351 }
1352
1353 diffs
1354 }
1355
1356 pub fn compare_functions(
1358 old_functions: &HashMap<String, StoredFunction>,
1359 new_functions: &HashMap<String, StoredFunction>,
1360 ) -> Vec<SchemaDiff> {
1361 let mut diffs = Vec::new();
1362
1363 for (name, function) in new_functions {
1365 if !old_functions.contains_key(name) {
1366 diffs.push(SchemaDiff::FunctionAdded {
1367 name: name.clone(),
1368 function: function.clone(),
1369 });
1370 }
1371 }
1372
1373 for (name, function) in old_functions {
1375 if !new_functions.contains_key(name) {
1376 diffs.push(SchemaDiff::FunctionDropped {
1377 name: name.clone(),
1378 function: function.clone(),
1379 });
1380 }
1381 }
1382
1383 for (name, new_function) in new_functions {
1385 if let Some(old_function) = old_functions.get(name) {
1386 if old_function != new_function {
1387 diffs.push(SchemaDiff::FunctionModified {
1388 name: name.clone(),
1389 old_function: old_function.clone(),
1390 new_function: new_function.clone(),
1391 });
1392 }
1393 }
1394 }
1395
1396 diffs
1397 }
1398
1399 pub fn compare_procedures(
1401 old_procedures: &HashMap<String, StoredProcedure>,
1402 new_procedures: &HashMap<String, StoredProcedure>,
1403 ) -> Vec<SchemaDiff> {
1404 let mut diffs = Vec::new();
1405
1406 for (name, procedure) in new_procedures {
1408 if !old_procedures.contains_key(name) {
1409 diffs.push(SchemaDiff::ProcedureAdded {
1410 name: name.clone(),
1411 procedure: procedure.clone(),
1412 });
1413 }
1414 }
1415
1416 for (name, procedure) in old_procedures {
1418 if !new_procedures.contains_key(name) {
1419 diffs.push(SchemaDiff::ProcedureDropped {
1420 name: name.clone(),
1421 procedure: procedure.clone(),
1422 });
1423 }
1424 }
1425
1426 for (name, new_procedure) in new_procedures {
1428 if let Some(old_procedure) = old_procedures.get(name) {
1429 if old_procedure != new_procedure {
1430 diffs.push(SchemaDiff::ProcedureModified {
1431 name: name.clone(),
1432 old_procedure: old_procedure.clone(),
1433 new_procedure: new_procedure.clone(),
1434 });
1435 }
1436 }
1437 }
1438
1439 diffs
1440 }
1441
1442 pub fn compare_triggers(
1444 old_triggers: &HashMap<String, Trigger>,
1445 new_triggers: &HashMap<String, Trigger>,
1446 ) -> Vec<SchemaDiff> {
1447 let mut diffs = Vec::new();
1448
1449 for (name, trigger) in new_triggers {
1451 if !old_triggers.contains_key(name) {
1452 diffs.push(SchemaDiff::TriggerAdded {
1453 name: name.clone(),
1454 trigger: trigger.clone(),
1455 });
1456 }
1457 }
1458
1459 for (name, trigger) in old_triggers {
1461 if !new_triggers.contains_key(name) {
1462 diffs.push(SchemaDiff::TriggerDropped {
1463 name: name.clone(),
1464 trigger: trigger.clone(),
1465 });
1466 }
1467 }
1468
1469 for (name, new_trigger) in new_triggers {
1471 if let Some(old_trigger) = old_triggers.get(name) {
1472 if old_trigger != new_trigger {
1473 diffs.push(SchemaDiff::TriggerModified {
1474 name: name.clone(),
1475 old_trigger: old_trigger.clone(),
1476 new_trigger: new_trigger.clone(),
1477 });
1478 }
1479 }
1480 }
1481
1482 diffs
1483 }
1484
1485 pub fn compare_composite_types(
1487 old_composite_types: &HashMap<String, CompositeType>,
1488 new_composite_types: &HashMap<String, CompositeType>,
1489 ) -> Vec<SchemaDiff> {
1490 let mut diffs = Vec::new();
1491
1492 for (name, composite_type) in new_composite_types {
1494 if !old_composite_types.contains_key(name) {
1495 diffs.push(SchemaDiff::CompositeTypeAdded {
1496 name: name.clone(),
1497 composite_type: composite_type.clone(),
1498 });
1499 }
1500 }
1501
1502 for (name, composite_type) in old_composite_types {
1504 if !new_composite_types.contains_key(name) {
1505 diffs.push(SchemaDiff::CompositeTypeDropped {
1506 name: name.clone(),
1507 composite_type: composite_type.clone(),
1508 });
1509 }
1510 }
1511
1512 for (name, new_composite_type) in new_composite_types {
1514 if let Some(old_composite_type) = old_composite_types.get(name) {
1515 if old_composite_type != new_composite_type {
1516 diffs.push(SchemaDiff::CompositeTypeModified {
1517 name: name.clone(),
1518 old_composite_type: old_composite_type.clone(),
1519 new_composite_type: new_composite_type.clone(),
1520 });
1521 }
1522 }
1523 }
1524
1525 diffs
1526 }
1527}
1528
1529pub struct MigrationGenerator;
1531
1532impl MigrationGenerator {
1533 pub fn generate_migration(diffs: &[SchemaDiff]) -> String {
1535 let mut migration = String::new();
1536
1537 for diff in diffs {
1538 match diff {
1539 SchemaDiff::TableAdded { name, table } => {
1540 migration.push_str(&format!("-- Add table {}\n", name));
1541 migration.push_str(&table.generate_ddl());
1542 migration.push_str("\n\n");
1543 }
1544 SchemaDiff::TableDropped { name, .. } => {
1545 migration.push_str(&format!("-- Drop table {}\n", name));
1546 migration.push_str(&format!("DROP TABLE IF EXISTS \"{}\" CASCADE;\n\n", name));
1547 }
1548 SchemaDiff::TableModified {
1549 name,
1550 old_table,
1551 new_table,
1552 } => {
1553 migration.push_str(&format!("-- Modify table {}\n", name));
1554 for change in
1555 SchemaDiffEngine::generate_table_change_sql(name, old_table, new_table)
1556 {
1557 migration.push_str(&change);
1558 }
1559 migration.push_str("\n");
1560 }
1561 SchemaDiff::ViewAdded { name, view } => {
1562 migration.push_str(&format!("-- Add view {}\n", name));
1563 let all_ddl = view.generate_all_ddl();
1565 for ddl in all_ddl {
1566 migration.push_str(&ddl);
1567 migration.push_str("\n");
1568 }
1569 migration.push_str("\n");
1570 }
1571 SchemaDiff::ViewDropped { name, .. } => {
1572 migration.push_str(&format!("-- Drop view {}\n", name));
1573 migration.push_str(&format!("DROP VIEW IF EXISTS \"{}\" CASCADE;\n\n", name));
1574 }
1575 SchemaDiff::ViewModified {
1576 name,
1577 old_view,
1578 new_view,
1579 } => {
1580 migration.push_str(&format!("-- Modify view {}\n", name));
1581 for change in
1582 SchemaDiffEngine::generate_view_change_sql(name, old_view, new_view)
1583 {
1584 migration.push_str(&change);
1585 }
1586 migration.push_str("\n");
1587 }
1588 SchemaDiff::IndexAdded { name, index } => {
1589 migration.push_str(&format!("-- Add index {}\n", name));
1590 migration.push_str(&index.generate_ddl());
1591 migration.push_str("\n\n");
1592 }
1593 SchemaDiff::IndexDropped { name, index: _ } => {
1594 migration.push_str(&format!("-- Drop index {}\n", name));
1595 migration.push_str(&format!("DROP INDEX IF EXISTS \"{}\" CASCADE;\n\n", name));
1596 }
1597 SchemaDiff::IndexModified {
1598 name,
1599 old_index,
1600 new_index,
1601 } => {
1602 migration.push_str(&format!("-- Modify index {}\n", name));
1603 for change in
1604 SchemaDiffEngine::generate_index_change_sql(name, old_index, new_index)
1605 {
1606 migration.push_str(&change);
1607 }
1608 migration.push_str("\n");
1609 }
1610 SchemaDiff::EventAdded { name, event } => {
1611 migration.push_str(&format!("-- Add event {}\n", name));
1612 migration.push_str(&event.generate_ddl());
1613 migration.push_str("\n\n");
1614 }
1615 SchemaDiff::EventDropped { name, event: _ } => {
1616 migration.push_str(&format!("-- Drop event {}\n", name));
1617 migration.push_str(&format!("DROP EVENT IF EXISTS \"{}\" CASCADE;\n\n", name));
1618 }
1619 SchemaDiff::EventModified {
1620 name,
1621 old_event,
1622 new_event,
1623 } => {
1624 migration.push_str(&format!("-- Modify event {}\n", name));
1625 for change in
1626 SchemaDiffEngine::generate_event_change_sql(name, old_event, new_event)
1627 {
1628 migration.push_str(&change);
1629 }
1630 migration.push_str("\n");
1631 }
1632 SchemaDiff::RoleAdded { name, role } => {
1633 migration.push_str(&format!("-- Add role {}\n", name));
1634 migration.push_str(&role.generate_create_ddl());
1635 migration.push_str("\n\n");
1636 }
1637 SchemaDiff::RoleDropped { name, role } => {
1638 migration.push_str(&format!("-- Drop role {}\n", name));
1639 migration.push_str(&role.generate_drop_ddl());
1640 migration.push_str("\n\n");
1641 }
1642 SchemaDiff::RoleModified {
1643 name,
1644 old_role,
1645 new_role,
1646 } => {
1647 migration.push_str(&format!("-- Modify role {}\n", name));
1648 for change in
1649 SchemaDiffEngine::generate_role_change_sql(name, old_role, new_role)
1650 {
1651 migration.push_str(&change);
1652 }
1653 migration.push_str("\n");
1654 }
1655 SchemaDiff::GrantAdded { name, grant } => {
1656 migration.push_str(&format!("-- Add grant {}\n", name));
1657 migration.push_str(&grant.generate_grant_ddl());
1658 migration.push_str("\n\n");
1659 }
1660 SchemaDiff::GrantDropped { name, grant } => {
1661 migration.push_str(&format!("-- Drop grant {}\n", name));
1662 migration.push_str(&grant.generate_revoke_ddl());
1663 migration.push_str("\n\n");
1664 }
1665 SchemaDiff::GrantModified {
1666 name,
1667 old_grant,
1668 new_grant,
1669 } => {
1670 migration.push_str(&format!("-- Modify grant {}\n", name));
1671 for change in
1672 SchemaDiffEngine::generate_grant_change_sql(name, old_grant, new_grant)
1673 {
1674 migration.push_str(&change);
1675 }
1676 migration.push_str("\n");
1677 }
1678 SchemaDiff::FunctionAdded { name, function } => {
1680 migration.push_str(&format!("-- Add function {}\n", name));
1681 migration.push_str(&function.generate_create_ddl());
1682 migration.push_str("\n\n");
1683 }
1684 SchemaDiff::FunctionDropped { name, .. } => {
1685 migration.push_str(&format!("-- Drop function {}\n", name));
1686 migration.push_str(&format!(
1687 "DROP FUNCTION IF EXISTS \"{}\" CASCADE;\n\n",
1688 name
1689 ));
1690 }
1691 SchemaDiff::FunctionModified {
1692 name,
1693 old_function: _,
1694 new_function,
1695 } => {
1696 migration.push_str(&format!("-- Modify function {}\n", name));
1697 migration.push_str(&format!("DROP FUNCTION IF EXISTS \"{}\" CASCADE;\n", name));
1699 migration.push_str(&new_function.generate_create_ddl());
1700 migration.push_str("\n");
1701 }
1702 SchemaDiff::ProcedureAdded { name, procedure } => {
1704 migration.push_str(&format!("-- Add procedure {}\n", name));
1705 migration.push_str(&procedure.generate_create_ddl());
1706 migration.push_str("\n\n");
1707 }
1708 SchemaDiff::ProcedureDropped { name, .. } => {
1709 migration.push_str(&format!("-- Drop procedure {}\n", name));
1710 migration.push_str(&format!(
1711 "DROP PROCEDURE IF EXISTS \"{}\" CASCADE;\n\n",
1712 name
1713 ));
1714 }
1715 SchemaDiff::ProcedureModified {
1716 name,
1717 old_procedure: _,
1718 new_procedure,
1719 } => {
1720 migration.push_str(&format!("-- Modify procedure {}\n", name));
1721 migration
1723 .push_str(&format!("DROP PROCEDURE IF EXISTS \"{}\" CASCADE;\n", name));
1724 migration.push_str(&new_procedure.generate_create_ddl());
1725 migration.push_str("\n");
1726 }
1727 SchemaDiff::TriggerAdded { name, trigger } => {
1729 migration.push_str(&format!("-- Add trigger {}\n", name));
1730 migration.push_str(&trigger.generate_create_ddl());
1731 migration.push_str("\n\n");
1732 }
1733 SchemaDiff::TriggerDropped { name, .. } => {
1734 migration.push_str(&format!("-- Drop trigger {}\n", name));
1735 migration
1736 .push_str(&format!("DROP TRIGGER IF EXISTS \"{}\" CASCADE;\n\n", name));
1737 }
1738 SchemaDiff::TriggerModified {
1739 name,
1740 old_trigger: _,
1741 new_trigger,
1742 } => {
1743 migration.push_str(&format!("-- Modify trigger {}\n", name));
1744 migration.push_str(&format!("DROP TRIGGER IF EXISTS \"{}\" CASCADE;\n", name));
1746 migration.push_str(&new_trigger.generate_create_ddl());
1747 migration.push_str("\n");
1748 }
1749 SchemaDiff::CompositeTypeAdded {
1751 name,
1752 composite_type,
1753 } => {
1754 migration.push_str(&format!("-- Add composite type {}\n", name));
1755 migration.push_str(&composite_type.generate_create_ddl());
1756 migration.push_str("\n\n");
1757 }
1758 SchemaDiff::CompositeTypeDropped { name, .. } => {
1759 migration.push_str(&format!("-- Drop composite type {}\n", name));
1760 migration.push_str(&format!("DROP TYPE IF EXISTS \"{}\" CASCADE;\n\n", name));
1761 }
1762 SchemaDiff::CompositeTypeModified {
1763 name,
1764 old_composite_type: _,
1765 new_composite_type,
1766 } => {
1767 migration.push_str(&format!("-- Modify composite type {}\n", name));
1768 migration.push_str(&format!("DROP TYPE IF EXISTS \"{}\" CASCADE;\n", name));
1770 migration.push_str(&new_composite_type.generate_create_ddl());
1771 migration.push_str("\n");
1772 }
1773 }
1774 }
1775
1776 migration
1777 }
1778
1779 pub fn generate_table_migration(diffs: &[SchemaDiff]) -> String {
1781 let mut migration = String::new();
1782
1783 for diff in diffs {
1784 match diff {
1785 SchemaDiff::TableAdded { name, table } => {
1786 migration.push_str(&format!("-- Add table {}\n", name));
1787 migration.push_str(&table.generate_ddl());
1788 migration.push_str("\n\n");
1789 }
1790 SchemaDiff::TableDropped { name, .. } => {
1791 migration.push_str(&format!("-- Drop table {}\n", name));
1792 migration.push_str(&format!("DROP TABLE IF EXISTS \"{}\" CASCADE;\n\n", name));
1793 }
1794 SchemaDiff::TableModified {
1795 name,
1796 old_table,
1797 new_table,
1798 } => {
1799 migration.push_str(&format!("-- Modify table {}\n", name));
1800 for change in
1801 SchemaDiffEngine::generate_table_change_sql(name, old_table, new_table)
1802 {
1803 migration.push_str(&change);
1804 }
1805 migration.push_str("\n");
1806 }
1807 _ => {} }
1809 }
1810
1811 migration
1812 }
1813
1814 pub fn generate_view_migration(diffs: &[SchemaDiff]) -> String {
1816 let mut migration = String::new();
1817
1818 for diff in diffs {
1819 match diff {
1820 SchemaDiff::ViewAdded { name, view } => {
1821 migration.push_str(&format!("-- Add view {}\n", name));
1822 let all_ddl = view.generate_all_ddl();
1824 for ddl in all_ddl {
1825 migration.push_str(&ddl);
1826 migration.push_str("\n");
1827 }
1828 migration.push_str("\n");
1829 }
1830 SchemaDiff::ViewDropped { name, .. } => {
1831 migration.push_str(&format!("-- Drop view {}\n", name));
1832 migration.push_str(&format!("DROP VIEW IF EXISTS \"{}\" CASCADE;\n\n", name));
1833 }
1834 SchemaDiff::ViewModified {
1835 name,
1836 old_view,
1837 new_view,
1838 } => {
1839 migration.push_str(&format!("-- Modify view {}\n", name));
1840 for change in
1841 SchemaDiffEngine::generate_view_change_sql(name, old_view, new_view)
1842 {
1843 migration.push_str(&change);
1844 }
1845 migration.push_str("\n");
1846 }
1847 _ => {} }
1849 }
1850
1851 migration
1852 }
1853
1854 pub fn generate_index_change_sql(
1856 index_name: &str,
1857 old_index: &IndexMeta,
1858 new_index: &IndexMeta,
1859 ) -> Vec<String> {
1860 let mut changes = Vec::new();
1861
1862 if old_index.columns != new_index.columns {
1864 let old_cols: Vec<String> = old_index.columns.iter().map(|s| s.to_string()).collect();
1865 let new_cols: Vec<String> = new_index.columns.iter().map(|s| s.to_string()).collect();
1866 for old_col in old_cols {
1867 changes.push(format!(
1868 "ALTER INDEX \"{}\" DROP COLUMN \"{}\";\n",
1869 index_name, old_col
1870 ));
1871 }
1872 for new_col in new_cols {
1873 changes.push(format!(
1874 "ALTER INDEX \"{}\" ADD COLUMN \"{}\";\n",
1875 index_name, new_col
1876 ));
1877 }
1878 }
1879
1880 if old_index.index_type != new_index.index_type {
1882 changes.push(format!(
1883 "-- Index {} type changed from {} to {}\n",
1884 index_name, old_index.index_type, new_index.index_type
1885 ));
1886 }
1887
1888 if old_index.unique != new_index.unique {
1890 if old_index.unique && !new_index.unique {
1891 changes.push(format!("-- Index {} is no longer UNIQUE\n", index_name));
1892 } else if !old_index.unique && new_index.unique {
1893 changes.push(format!("-- Index {} is now UNIQUE\n", index_name));
1894 }
1895 }
1896
1897 if old_index.concurrent != new_index.concurrent {
1899 if old_index.concurrent && !new_index.concurrent {
1900 changes.push(format!(
1901 "-- Index {} is no longer CONCURRENTLY\n",
1902 index_name
1903 ));
1904 } else if !old_index.concurrent && new_index.concurrent {
1905 changes.push(format!("-- Index {} is now CONCURRENTLY\n", index_name));
1906 }
1907 }
1908
1909 if old_index.table != new_index.table {
1911 changes.push(format!(
1912 "-- Index {} table changed from {} to {}\n",
1913 index_name, old_index.table, new_index.table
1914 ));
1915 }
1916
1917 if old_index.schema != new_index.schema {
1919 let old_schema = old_index.schema.as_ref().map_or("", |v| v);
1920 let new_schema = new_index.schema.as_ref().map_or("", |v| v);
1921 changes.push(format!(
1922 "-- Index {} schema changed from {} to {}\n",
1923 index_name, old_schema, new_schema
1924 ));
1925 }
1926
1927 changes
1928 }
1929
1930 pub fn generate_event_change_sql(
1932 event_name: &str,
1933 old_event: &Event,
1934 new_event: &Event,
1935 ) -> Vec<String> {
1936 let mut changes = Vec::new();
1937
1938 if old_event.schedule != new_event.schedule {
1939 changes.push(format!(
1940 "-- Event {} schedule changed from {} to {}\n",
1941 event_name, old_event.schedule, new_event.schedule
1942 ));
1943 }
1944
1945 if old_event.command != new_event.command {
1946 changes.push(format!(
1947 "-- Event {} command changed from {} to {}\n",
1948 event_name, old_event.command, new_event.command
1949 ));
1950 }
1951
1952 if old_event.database != new_event.database {
1953 let mut sql = String::new();
1954 if let Some(old_db) = &old_event.database {
1955 sql.push_str(&format!(
1956 "ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
1957 event_name, old_db
1958 ));
1959 }
1960 if let Some(new_db) = &new_event.database {
1961 sql.push_str(&format!(
1962 "ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
1963 event_name, new_db
1964 ));
1965 }
1966 changes.push(sql);
1967 }
1968
1969 if old_event.username != new_event.username {
1970 let mut sql = String::new();
1971 if let Some(old_user) = &old_event.username {
1972 sql.push_str(&format!(
1973 "ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
1974 event_name, old_user
1975 ));
1976 }
1977 if let Some(new_user) = &new_event.username {
1978 sql.push_str(&format!(
1979 "ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
1980 event_name, new_user
1981 ));
1982 }
1983 changes.push(sql);
1984 }
1985
1986 if old_event.ddl != new_event.ddl {
1987 changes.push(format!(
1988 "-- Event {} DDL changed from {} to {}\n",
1989 event_name, old_event.ddl, new_event.ddl
1990 ));
1991 }
1992
1993 if old_event.enabled != new_event.enabled {
1994 if old_event.enabled && !new_event.enabled {
1995 changes.push(format!("-- Event {} is now DISABLED\n", event_name));
1996 } else if !old_event.enabled && new_event.enabled {
1997 changes.push(format!("-- Event {} is now ENABLED\n", event_name));
1998 }
1999 }
2000
2001 changes
2002 }
2003
2004 pub fn generate_role_change_sql(
2006 role_name: &str,
2007 old_role: &Role,
2008 new_role: &Role,
2009 ) -> Vec<String> {
2010 let mut changes = Vec::new();
2011
2012 if old_role.password != new_role.password {
2013 let mut sql = String::new();
2014 if let Some(_old_password) = &old_role.password {
2015 sql.push_str(&format!("ALTER ROLE \"{}\" PASSWORD NULL;\n", role_name));
2016 }
2017 if let Some(new_password) = &new_role.password {
2018 sql.push_str(&format!(
2019 "ALTER ROLE \"{}\" PASSWORD '{}';\n",
2020 role_name, new_password
2021 ));
2022 }
2023 changes.push(sql);
2024 }
2025
2026 if old_role.superuser != new_role.superuser {
2027 let mut sql = String::new();
2028 if !old_role.superuser && new_role.superuser {
2029 sql.push_str(&format!("ALTER ROLE \"{}\" SUPERUSER;\n", role_name));
2030 } else if old_role.superuser && !new_role.superuser {
2031 sql.push_str(&format!("ALTER ROLE \"{}\" NOSUPERUSER;\n", role_name));
2032 }
2033 changes.push(sql);
2034 }
2035
2036 if old_role.login != new_role.login {
2037 let mut sql = String::new();
2038 if !old_role.login && new_role.login {
2039 sql.push_str(&format!("ALTER ROLE \"{}\" LOGIN;\n", role_name));
2040 } else if old_role.login && !new_role.login {
2041 sql.push_str(&format!("ALTER ROLE \"{}\" NOLOGIN;\n", role_name));
2042 }
2043 changes.push(sql);
2044 }
2045
2046 if old_role.member_of != new_role.member_of || old_role.members != new_role.members {
2047 let mut sql = String::new();
2048 let mut old_members: Vec<String> =
2049 old_role.member_of.iter().map(|s| s.clone()).collect();
2050 old_members.extend(old_role.members.iter().map(|s| s.clone()));
2051 let mut new_members: Vec<String> =
2052 new_role.member_of.iter().map(|s| s.clone()).collect();
2053 new_members.extend(new_role.members.iter().map(|s| s.clone()));
2054
2055 let added: Vec<_> = new_members
2056 .iter()
2057 .filter(|d| !old_members.contains(d))
2058 .collect();
2059 let removed: Vec<_> = old_members
2060 .iter()
2061 .filter(|d| !new_members.contains(d))
2062 .collect();
2063
2064 if !added.is_empty() {
2065 let added_names: Vec<String> = added.iter().map(|&s| s.clone()).collect();
2066 sql.push_str(&format!(
2067 "ALTER ROLE \"{}\" ADD MEMBER \"{}\";\n",
2068 role_name,
2069 added_names.join(", ")
2070 ));
2071 }
2072 if !removed.is_empty() {
2073 let removed_names: Vec<String> = removed.iter().map(|&s| s.clone()).collect();
2074 sql.push_str(&format!(
2075 "ALTER ROLE \"{}\" DROP MEMBER \"{}\";\n",
2076 role_name,
2077 removed_names.join(", ")
2078 ));
2079 }
2080 changes.push(sql);
2081 }
2082
2083 if old_role.connection_limit != new_role.connection_limit {
2084 let mut sql = String::new();
2085 if let Some(_old_limit) = &old_role.connection_limit {
2086 sql.push_str(&format!(
2087 "ALTER ROLE \"{}\" CONNECTION LIMIT NULL;\n",
2088 role_name
2089 ));
2090 }
2091 if let Some(new_limit) = &new_role.connection_limit {
2092 sql.push_str(&format!(
2093 "ALTER ROLE \"{}\" CONNECTION LIMIT {};\n",
2094 role_name, new_limit
2095 ));
2096 }
2097 changes.push(sql);
2098 }
2099
2100 if old_role.valid_until != new_role.valid_until {
2101 let mut sql = String::new();
2102 if let Some(_old_until) = &old_role.valid_until {
2103 sql.push_str(&format!("ALTER ROLE \"{}\" VALID UNTIL NULL;\n", role_name));
2104 }
2105 if let Some(new_until) = &new_role.valid_until {
2106 sql.push_str(&format!(
2107 "ALTER ROLE \"{}\" VALID UNTIL '{}';\n",
2108 role_name, new_until
2109 ));
2110 }
2111 changes.push(sql);
2112 }
2113
2114 changes
2115 }
2116
2117 pub fn generate_grant_change_sql(
2119 grant_name: &str,
2120 old_grant: &Grant,
2121 new_grant: &Grant,
2122 ) -> Vec<String> {
2123 let mut changes = Vec::new();
2124
2125 if old_grant.privilege != new_grant.privilege {
2127 changes.push(format!(
2128 "-- Grant {} privilege changed from {:?} to {:?}\n",
2129 grant_name, old_grant.privilege, new_grant.privilege
2130 ));
2131 }
2132
2133 if old_grant.target != new_grant.target {
2135 changes.push(format!(
2136 "-- Grant {} target changed from {:?} to {:?}\n",
2137 grant_name, old_grant.target, new_grant.target
2138 ));
2139 }
2140
2141 if old_grant.grantee != new_grant.grantee {
2143 changes.push(format!(
2144 "-- Grant {} grantee changed from {} to {}\n",
2145 grant_name, old_grant.grantee, new_grant.grantee
2146 ));
2147 }
2148
2149 if old_grant.with_grant_option != new_grant.with_grant_option {
2151 if old_grant.with_grant_option && !new_grant.with_grant_option {
2152 changes.push(format!(
2153 "-- Grant {} no longer has GRANT OPTION\n",
2154 grant_name
2155 ));
2156 } else if !old_grant.with_grant_option && new_grant.with_grant_option {
2157 changes.push(format!("-- Grant {} now has GRANT OPTION\n", grant_name));
2158 }
2159 }
2160
2161 if old_grant.grantor != new_grant.grantor {
2163 changes.push(format!(
2164 "-- Grant {} grantor changed from {:?} to {:?}\n",
2165 grant_name, old_grant.grantor, new_grant.grantor
2166 ));
2167 }
2168
2169 changes
2170 }
2171}
2172
2173#[cfg(test)]
2174mod tests {
2175 use super::*;
2176 use crate::schema::{Column, ColumnType, Table};
2177
2178 #[test]
2179 fn test_table_added_diff() {
2180 let old_tables = HashMap::new();
2181 let mut new_tables = HashMap::new();
2182
2183 let users_table = Table::new("users")
2184 .add_column(Column::new("id", ColumnType::Int4))
2185 .set_primary_key("id");
2186
2187 new_tables.insert("users".to_string(), users_table);
2188
2189 let diffs = SchemaDiffEngine::compare_tables(&old_tables, &new_tables);
2190
2191 assert_eq!(diffs.len(), 1);
2192 match &diffs[0] {
2193 SchemaDiff::TableAdded { name, .. } => assert_eq!(name, "users"),
2194 diff => unreachable!("Expected TableAdded but got {:?}", diff),
2195 }
2196 }
2197
2198 #[test]
2199 fn test_column_added_diff() {
2200 let mut old_tables = HashMap::new();
2201 let mut new_tables = HashMap::new();
2202
2203 let old_users = Table::new("users")
2204 .add_column(Column::new("id", ColumnType::Int4))
2205 .set_primary_key("id");
2206
2207 let new_users = Table::new("users")
2208 .add_column(Column::new("id", ColumnType::Int4))
2209 .add_column(Column::new("email", ColumnType::Varchar(None)))
2210 .set_primary_key("id");
2211
2212 old_tables.insert("users".to_string(), old_users);
2213 new_tables.insert("users".to_string(), new_users);
2214
2215 let diffs = SchemaDiffEngine::compare_tables(&old_tables, &new_tables);
2216
2217 assert_eq!(diffs.len(), 1);
2218 match &diffs[0] {
2219 SchemaDiff::TableModified {
2220 name,
2221 old_table,
2222 new_table,
2223 } => {
2224 assert_eq!(name, "users");
2225 let changes = SchemaDiffEngine::compare_table(old_table, new_table);
2226 assert_eq!(changes.len(), 1);
2227 match &changes[0] {
2228 TableChange::ColumnAdded { name, .. } => assert_eq!(name, "email"),
2229 change => unreachable!("Expected ColumnAdded but got {:?}", change),
2230 }
2231 }
2232 diff => unreachable!("Expected TableModified but got {:?}", diff),
2233 }
2234 }
2235}
2236
2237#[derive(Debug, Clone)]
2239pub struct SchemaSnapshot {
2240 pub timestamp: DateTime<Utc>,
2241 pub checksum: String,
2242 pub tables: HashMap<String, Table>,
2243 pub views: HashMap<String, crate::schema::View>,
2244 pub indexes: HashMap<String, IndexMeta>,
2245 pub statistics: SchemaStatistics,
2246}
2247
2248pub struct IntelligentMigrationGenerator {
2250 pool: sqlx::PgPool,
2251}
2252
2253impl IntelligentMigrationGenerator {
2254 pub fn new(pool: sqlx::PgPool) -> Self {
2255 Self { pool }
2256 }
2257
2258 pub async fn generate_migration_from_current_state(
2260 &self,
2261 migrations_dir: &std::path::Path,
2262 ) -> Result<Option<String>> {
2263 let baseline_snapshot = self
2265 .get_latest_baseline_snapshot()
2266 .await
2267 .context("Failed to get baseline snapshot from migration history")?;
2268
2269 let current_snapshot = self
2271 .capture_current_schema_snapshot()
2272 .await
2273 .context("Failed to capture current database schema")?;
2274
2275 let schema_changes = self
2277 .intelligent_schema_compare(&baseline_snapshot, ¤t_snapshot)
2278 .context("Failed to compare schema states")?;
2279
2280 if schema_changes.is_empty() {
2282 return Ok(None);
2283 }
2284
2285 let migration_file = self
2287 .generate_migration_file(&schema_changes, migrations_dir)
2288 .await
2289 .context("Failed to generate migration file")?;
2290
2291 Ok(Some(migration_file))
2292 }
2293
2294 async fn get_latest_baseline_snapshot(&self) -> Result<SchemaSnapshot> {
2296 let baseline_record = sqlx::query(
2298 r#"
2299 SELECT name, checksum, applied_at
2300 FROM __ignis_migrations
2301 WHERE name LIKE '%baseline%'
2302 ORDER BY applied_at DESC
2303 LIMIT 1
2304 "#,
2305 )
2306 .fetch_one(&self.pool)
2307 .await
2308 .context("No baseline migration found. Run 'ignis-cli migrate baseline' first")?;
2309
2310 let baseline_name: String = baseline_record.get("name");
2311
2312 let baseline_json_path = format!("./migrations/{}.json", baseline_name);
2314 let baseline_json = std::fs::read_to_string(&baseline_json_path).context(format!(
2315 "Failed to read baseline JSON file: {}",
2316 baseline_json_path
2317 ))?;
2318
2319 let baseline_data: serde_json::Value =
2321 serde_json::from_str(&baseline_json).context("Failed to parse baseline JSON")?;
2322
2323 let stats = &baseline_data["statistics"];
2325 let statistics = crate::migrate::baseline::SchemaStatistics {
2326 table_count: stats["table_count"].as_u64().unwrap_or(0) as usize,
2327 view_count: stats["view_count"].as_u64().unwrap_or(0) as usize,
2328 index_count: stats["index_count"].as_u64().unwrap_or(0) as usize,
2329 function_count: stats["function_count"].as_u64().unwrap_or(0) as usize,
2330 trigger_count: stats["trigger_count"].as_u64().unwrap_or(0) as usize,
2331 composite_type_count: stats["composite_type_count"].as_u64().unwrap_or(0) as usize,
2332 total_columns: stats["total_columns"].as_u64().unwrap_or(0) as usize,
2333 total_constraints: stats["total_constraints"].as_u64().unwrap_or(0) as usize,
2334 };
2335
2336 let baseline_sql = baseline_data["baseline_sql"]
2340 .as_str()
2341 .context("Missing baseline_sql in JSON")?;
2342
2343 let baseline_tables = self
2344 .extract_tables_from_baseline_sql(baseline_sql)
2345 .await
2346 .context("Failed to extract tables from baseline SQL")?;
2347
2348 let snapshot = SchemaSnapshot {
2350 timestamp: baseline_record.get::<chrono::DateTime<chrono::Utc>, _>("applied_at"),
2351 checksum: baseline_record.get::<String, _>("checksum"),
2352 tables: baseline_tables,
2353 views: HashMap::new(), indexes: HashMap::new(), statistics,
2356 };
2357
2358 Ok(snapshot)
2359 }
2360
2361 async fn capture_current_schema_snapshot(&self) -> Result<SchemaSnapshot> {
2363 let introspector = crate::introspection::DatabaseIntrospector::new(self.pool.clone());
2365 let current_tables = introspector
2366 .introspect_tables()
2367 .await
2368 .context("Failed to introspect current database schema")?;
2369
2370 let tables: HashMap<String, Table> = current_tables
2372 .into_iter()
2373 .map(|table| (table.name.clone(), table))
2374 .collect();
2375
2376 use std::collections::hash_map::DefaultHasher;
2378 use std::hash::{Hash, Hasher};
2379
2380 let mut hasher = DefaultHasher::new();
2381 let mut sorted_tables: Vec<_> = tables.iter().collect();
2382 sorted_tables.sort_by(|a, b| a.0.cmp(b.0));
2383 for (name, table) in sorted_tables {
2384 name.hash(&mut hasher);
2385 table.columns.len().hash(&mut hasher);
2386 }
2387 let checksum = format!("{:x}", hasher.finish());
2388
2389 let table_count = tables.len();
2390 let total_columns = tables.values().map(|t| t.columns.len()).sum();
2391
2392 let snapshot = SchemaSnapshot {
2393 timestamp: Utc::now(),
2394 checksum,
2395 tables,
2396 views: HashMap::new(), indexes: HashMap::new(), statistics: crate::migrate::baseline::SchemaStatistics {
2399 table_count,
2400 view_count: 0,
2401 index_count: 0,
2402 function_count: 0,
2403 trigger_count: 0,
2404 composite_type_count: 0,
2405 total_columns,
2406 total_constraints: 0,
2407 },
2408 };
2409
2410 Ok(snapshot)
2411 }
2412
2413 async fn extract_tables_from_baseline_sql(
2417 &self,
2418 baseline_sql: &str,
2419 ) -> Result<HashMap<String, Table>> {
2420 let mut baseline_table_names = HashSet::new();
2422
2423 for line in baseline_sql.lines() {
2425 let line = line.trim();
2426 if line.starts_with("-- Table: ") {
2427 if let Some(table_name) = line.strip_prefix("-- Table: ") {
2429 baseline_table_names.insert(table_name.to_string());
2430 }
2431 }
2432 }
2433
2434 if baseline_table_names.is_empty() {
2436 for line in baseline_sql.lines() {
2437 let line = line.trim().to_uppercase();
2438 if line.starts_with("CREATE TABLE ") {
2439 if let Some(rest) = line.strip_prefix("CREATE TABLE ") {
2441 if let Some(table_name) = rest.split_whitespace().next() {
2442 let clean_name = table_name.trim_end_matches('(');
2443 baseline_table_names.insert(clean_name.to_lowercase());
2444 }
2445 }
2446 }
2447 }
2448 }
2449
2450 let introspector = crate::introspection::DatabaseIntrospector::new(self.pool.clone());
2453 let all_current_tables = introspector
2454 .introspect_tables()
2455 .await
2456 .context("Failed to introspect current database schema")?;
2457
2458 let baseline_tables: HashMap<String, Table> = all_current_tables
2460 .into_iter()
2461 .filter(|table| baseline_table_names.contains(&table.name))
2462 .map(|table| (table.name.clone(), table))
2463 .collect();
2464
2465 Ok(baseline_tables)
2466 }
2467
2468 fn intelligent_schema_compare(
2470 &self,
2471 baseline: &SchemaSnapshot,
2472 current: &SchemaSnapshot,
2473 ) -> Result<Vec<IntelligentSchemaDiff>> {
2474 let mut changes = Vec::new();
2475
2476 for (table_name, current_table) in ¤t.tables {
2478 match baseline.tables.get(table_name) {
2479 None => {
2480 changes.push(IntelligentSchemaDiff::TableAdded {
2482 name: table_name.clone(),
2483 table: current_table.clone(),
2484 safety_level: SafetyLevel::Safe,
2485 impact: ImpactLevel::Low,
2486 });
2487 }
2488 Some(baseline_table) => {
2489 if let Some(table_changes) =
2491 self.compare_table_structures(baseline_table, current_table)?
2492 {
2493 changes.push(IntelligentSchemaDiff::TableModified {
2494 name: table_name.clone(),
2495 changes: table_changes.changes,
2496 safety_level: table_changes.safety_level,
2497 impact: table_changes.impact,
2498 });
2499 }
2500 }
2501 }
2502 }
2503
2504 for (table_name, baseline_table) in &baseline.tables {
2506 if !current.tables.contains_key(table_name) {
2507 changes.push(IntelligentSchemaDiff::TableDropped {
2508 name: table_name.clone(),
2509 table: baseline_table.clone(),
2510 safety_level: SafetyLevel::Dangerous,
2511 impact: ImpactLevel::High,
2512 });
2513 }
2514 }
2515
2516 Ok(changes)
2517 }
2518
2519 fn compare_table_structures(
2521 &self,
2522 baseline_table: &Table,
2523 current_table: &Table,
2524 ) -> Result<Option<TableModification>> {
2525 let mut changes = Vec::new();
2526 let mut max_safety = SafetyLevel::Safe;
2527 let mut max_impact = ImpactLevel::Low;
2528
2529 let current_cols: HashMap<String, &Column> = current_table
2531 .columns
2532 .iter()
2533 .map(|col| (col.name.clone(), col))
2534 .collect();
2535 let baseline_cols: HashMap<String, &Column> = baseline_table
2536 .columns
2537 .iter()
2538 .map(|col| (col.name.clone(), col))
2539 .collect();
2540
2541 for (col_name, current_col) in ¤t_cols {
2543 match baseline_cols.get(col_name) {
2544 None => {
2545 let safety = if current_col.nullable {
2547 SafetyLevel::Safe
2548 } else {
2549 SafetyLevel::Risky
2550 };
2551 changes.push(DetailedTableChange::ColumnAdded {
2552 name: col_name.clone(),
2553 column: (*current_col).clone(),
2554 safety_level: safety.clone(),
2555 });
2556 if safety > max_safety {
2557 max_safety = safety;
2558 }
2559 }
2560 Some(baseline_col) => {
2561 if baseline_col != current_col {
2563 let (safety, impact) =
2564 self.analyze_column_change(baseline_col, current_col);
2565 changes.push(DetailedTableChange::ColumnModified {
2566 name: col_name.clone(),
2567 old_column: (*baseline_col).clone(),
2568 new_column: (*current_col).clone(),
2569 safety_level: safety.clone(),
2570 impact: impact.clone(),
2571 });
2572 if safety > max_safety {
2573 max_safety = safety;
2574 }
2575 if impact > max_impact {
2576 max_impact = impact;
2577 }
2578 }
2579 }
2580 }
2581 }
2582
2583 for (col_name, baseline_col) in &baseline_cols {
2585 if !current_cols.contains_key(col_name) {
2586 changes.push(DetailedTableChange::ColumnDropped {
2587 name: col_name.clone(),
2588 column: (*baseline_col).clone(),
2589 safety_level: SafetyLevel::Dangerous,
2590 });
2591 max_safety = SafetyLevel::Dangerous;
2592 max_impact = ImpactLevel::High;
2593 }
2594 }
2595
2596 if changes.is_empty() {
2597 Ok(None)
2598 } else {
2599 Ok(Some(TableModification {
2600 changes,
2601 safety_level: max_safety,
2602 impact: max_impact,
2603 }))
2604 }
2605 }
2606
2607 fn analyze_column_change(
2609 &self,
2610 old_col: &Column,
2611 new_col: &Column,
2612 ) -> (SafetyLevel, ImpactLevel) {
2613 let mut safety = SafetyLevel::Safe;
2614 let mut impact = ImpactLevel::Low;
2615
2616 if old_col.nullable && !new_col.nullable {
2618 safety = SafetyLevel::Dangerous; impact = ImpactLevel::High;
2620 }
2621
2622 if old_col.column_type != new_col.column_type {
2624 safety = SafetyLevel::Risky; impact = ImpactLevel::Medium;
2626 }
2627
2628 if old_col.default != new_col.default {
2630 safety = std::cmp::max(safety, SafetyLevel::Risky);
2631 impact = std::cmp::max(impact, ImpactLevel::Medium);
2632 }
2633
2634 (safety, impact)
2635 }
2636
2637 async fn generate_migration_file(
2639 &self,
2640 changes: &[IntelligentSchemaDiff],
2641 migrations_dir: &std::path::Path,
2642 ) -> Result<String> {
2643 let timestamp = Utc::now().format("%Y%m%d_%H%M%S").to_string();
2644 let migration_name = format!("{}_schema_changes_generated", timestamp);
2645 let migration_file = migrations_dir.join(format!("{}.sql", migration_name));
2646
2647 let mut migration_content = String::new();
2649 migration_content.push_str(&format!("-- Migration: {}\n", migration_name));
2650 migration_content.push_str(&format!(
2651 "-- Generated at: {} UTC\n",
2652 Utc::now().format("%Y-%m-%d %H:%M:%S")
2653 ));
2654 migration_content.push_str("-- AUTOMATICALLY GENERATED - Review before applying!\n\n");
2655
2656 let dangerous_changes: Vec<_> = changes
2658 .iter()
2659 .filter(|c| c.safety_level() >= SafetyLevel::Dangerous)
2660 .collect();
2661
2662 if !dangerous_changes.is_empty() {
2663 migration_content.push_str(
2664 "-- ⚠️ DANGER: This migration contains potentially destructive changes!\n",
2665 );
2666 migration_content.push_str("-- Review carefully before applying to production.\n");
2667 for change in &dangerous_changes {
2668 migration_content.push_str(&format!("-- DANGEROUS: {}\n", change.description()));
2669 }
2670 migration_content.push_str("\n");
2671 }
2672
2673 migration_content.push_str("-- UP\n");
2675 for change in changes {
2676 migration_content.push_str(&change.generate_up_sql());
2677 migration_content.push_str("\n");
2678 }
2679
2680 migration_content.push_str("\n-- DOWN\n");
2682 for change in changes.iter().rev() {
2683 migration_content.push_str(&change.generate_down_sql());
2684 migration_content.push_str("\n");
2685 }
2686
2687 std::fs::write(&migration_file, migration_content)
2689 .context("Failed to write migration file")?;
2690
2691 Ok(migration_file.to_string_lossy().to_string())
2692 }
2693}
2694
2695#[derive(Debug, Clone)]
2697pub enum IntelligentSchemaDiff {
2698 TableAdded {
2699 name: String,
2700 table: Table,
2701 safety_level: SafetyLevel,
2702 impact: ImpactLevel,
2703 },
2704 TableDropped {
2705 name: String,
2706 table: Table,
2707 safety_level: SafetyLevel,
2708 impact: ImpactLevel,
2709 },
2710 TableModified {
2711 name: String,
2712 changes: Vec<DetailedTableChange>,
2713 safety_level: SafetyLevel,
2714 impact: ImpactLevel,
2715 },
2716}
2717
2718impl IntelligentSchemaDiff {
2719 pub fn safety_level(&self) -> SafetyLevel {
2720 match self {
2721 Self::TableAdded { safety_level, .. } => safety_level.clone(),
2722 Self::TableDropped { safety_level, .. } => safety_level.clone(),
2723 Self::TableModified { safety_level, .. } => safety_level.clone(),
2724 }
2725 }
2726
2727 pub fn description(&self) -> String {
2728 match self {
2729 Self::TableAdded { name, .. } => format!("Add table '{}'", name),
2730 Self::TableDropped { name, .. } => format!("Drop table '{}'", name),
2731 Self::TableModified { name, changes, .. } => {
2732 format!("Modify table '{}' ({} changes)", name, changes.len())
2733 }
2734 }
2735 }
2736
2737 pub fn generate_up_sql(&self) -> String {
2738 match self {
2739 Self::TableAdded { name, table, .. } => {
2740 format!("-- Add table {}\n{}", name, table.generate_ddl())
2741 }
2742 Self::TableDropped { name, .. } => {
2743 format!("-- Drop table {}\nDROP TABLE IF EXISTS {};", name, name)
2744 }
2745 Self::TableModified { name, changes, .. } => {
2746 let mut sql = format!("-- Modify table {}\n", name);
2747 for change in changes {
2748 sql.push_str(&change.generate_up_sql(name));
2749 sql.push_str("\n");
2750 }
2751 sql
2752 }
2753 }
2754 }
2755
2756 pub fn generate_down_sql(&self) -> String {
2757 match self {
2758 Self::TableAdded { name, .. } => {
2759 format!(
2760 "-- Reverse: Drop table {}\nDROP TABLE IF EXISTS {};",
2761 name, name
2762 )
2763 }
2764 Self::TableDropped { name, table, .. } => {
2765 format!("-- Reverse: Add table {}\n{}", name, table.generate_ddl())
2766 }
2767 Self::TableModified { name, changes, .. } => {
2768 let mut sql = format!("-- Reverse: Modify table {}\n", name);
2769 for change in changes.iter().rev() {
2770 sql.push_str(&change.generate_down_sql(name));
2771 sql.push_str("\n");
2772 }
2773 sql
2774 }
2775 }
2776 }
2777}
2778
2779#[derive(Debug, Clone)]
2781pub struct TableModification {
2782 pub changes: Vec<DetailedTableChange>,
2783 pub safety_level: SafetyLevel,
2784 pub impact: ImpactLevel,
2785}
2786
2787#[derive(Debug, Clone)]
2789pub enum DetailedTableChange {
2790 ColumnAdded {
2791 name: String,
2792 column: Column,
2793 safety_level: SafetyLevel,
2794 },
2795 ColumnDropped {
2796 name: String,
2797 column: Column,
2798 safety_level: SafetyLevel,
2799 },
2800 ColumnModified {
2801 name: String,
2802 old_column: Column,
2803 new_column: Column,
2804 safety_level: SafetyLevel,
2805 impact: ImpactLevel,
2806 },
2807}
2808
2809impl DetailedTableChange {
2810 pub fn generate_up_sql(&self, table_name: &str) -> String {
2811 match self {
2812 Self::ColumnAdded { name, column, .. } => {
2813 format!(
2814 "ALTER TABLE {} ADD COLUMN {} {};",
2815 table_name,
2816 name,
2817 column.generate_column_definition()
2818 )
2819 }
2820 Self::ColumnDropped { name, .. } => {
2821 format!("ALTER TABLE {} DROP COLUMN IF EXISTS {};", table_name, name)
2822 }
2823 Self::ColumnModified {
2824 name, new_column, ..
2825 } => {
2826 format!(
2827 "ALTER TABLE {} ALTER COLUMN {} TYPE {};",
2828 table_name,
2829 name,
2830 new_column.column_type.to_sql()
2831 )
2832 }
2833 }
2834 }
2835
2836 pub fn generate_down_sql(&self, table_name: &str) -> String {
2837 match self {
2838 Self::ColumnAdded { name, .. } => {
2839 format!("ALTER TABLE {} DROP COLUMN IF EXISTS {};", table_name, name)
2840 }
2841 Self::ColumnDropped { name, column, .. } => {
2842 format!(
2843 "ALTER TABLE {} ADD COLUMN {} {};",
2844 table_name,
2845 name,
2846 column.generate_column_definition()
2847 )
2848 }
2849 Self::ColumnModified {
2850 name, old_column, ..
2851 } => {
2852 format!(
2853 "ALTER TABLE {} ALTER COLUMN {} TYPE {};",
2854 table_name,
2855 name,
2856 old_column.column_type.to_sql()
2857 )
2858 }
2859 }
2860 }
2861}
2862
2863#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq)]
2865pub enum SafetyLevel {
2866 Safe, Risky, Dangerous, }
2870
2871#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq)]
2873pub enum ImpactLevel {
2874 Low, Medium, High, }