use crate::migrate::baseline::SchemaStatistics;
use crate::schema::{
Column, CompositeType, Event, Grant, IndexMeta, Role, StoredFunction, StoredProcedure, Table,
Trigger,
};
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use sqlx::Row;
use std::collections::{HashMap, HashSet};
#[derive(Debug, Clone, PartialEq)]
pub enum SchemaDiff {
TableAdded {
name: String,
table: Table,
},
TableDropped {
name: String,
table: Table,
},
TableModified {
name: String,
old_table: Table,
new_table: Table,
},
ViewAdded {
name: String,
view: crate::schema::View,
},
ViewDropped {
name: String,
view: crate::schema::View,
},
ViewModified {
name: String,
old_view: crate::schema::View,
new_view: crate::schema::View,
},
IndexAdded {
name: String,
index: IndexMeta,
},
IndexDropped {
name: String,
index: IndexMeta,
},
IndexModified {
name: String,
old_index: IndexMeta,
new_index: IndexMeta,
},
EventAdded {
name: String,
event: Event,
},
EventDropped {
name: String,
event: Event,
},
EventModified {
name: String,
old_event: Event,
new_event: Event,
},
RoleAdded {
name: String,
role: Role,
},
RoleDropped {
name: String,
role: Role,
},
RoleModified {
name: String,
old_role: Role,
new_role: Role,
},
GrantAdded {
name: String,
grant: Grant,
},
GrantDropped {
name: String,
grant: Grant,
},
GrantModified {
name: String,
old_grant: Grant,
new_grant: Grant,
},
FunctionAdded {
name: String,
function: StoredFunction,
},
FunctionDropped {
name: String,
function: StoredFunction,
},
FunctionModified {
name: String,
old_function: StoredFunction,
new_function: StoredFunction,
},
ProcedureAdded {
name: String,
procedure: StoredProcedure,
},
ProcedureDropped {
name: String,
procedure: StoredProcedure,
},
ProcedureModified {
name: String,
old_procedure: StoredProcedure,
new_procedure: StoredProcedure,
},
TriggerAdded {
name: String,
trigger: Trigger,
},
TriggerDropped {
name: String,
trigger: Trigger,
},
TriggerModified {
name: String,
old_trigger: Trigger,
new_trigger: Trigger,
},
CompositeTypeAdded {
name: String,
composite_type: CompositeType,
},
CompositeTypeDropped {
name: String,
composite_type: CompositeType,
},
CompositeTypeModified {
name: String,
old_composite_type: CompositeType,
new_composite_type: CompositeType,
},
}
#[derive(Debug, Clone)]
pub enum TableChange {
ColumnAdded {
name: String,
column: Column,
},
ColumnDropped {
name: String,
column: Column,
},
ColumnModified {
name: String,
old_column: Column,
new_column: Column,
},
PrimaryKeyChanged {
old_pk: Option<String>,
new_pk: Option<String>,
},
IndexesChanged {
old_indexes: Vec<IndexMeta>,
new_indexes: Vec<IndexMeta>,
},
}
#[derive(Debug, Clone)]
pub enum ViewChange {
ColumnAdded {
name: String,
column: Column,
},
ColumnDropped {
name: String,
column: Column,
},
ColumnModified {
name: String,
old_column: Column,
new_column: Column,
},
PrimaryKeyChanged {
old_pk: Option<String>,
new_pk: Option<String>,
},
MaterializedChanged {
was_materialized: bool,
is_materialized: bool,
},
DependenciesChanged {
old_deps: Vec<String>,
new_deps: Vec<String>,
},
IndexesChanged {
old_indexes: Vec<crate::schema::Index>,
new_indexes: Vec<crate::schema::Index>,
},
}
#[derive(Debug, Clone)]
pub enum IndexChange {
ColumnsChanged {
old_columns: Vec<String>,
new_columns: Vec<String>,
},
TypeChanged {
old_type: crate::schema::IndexType,
new_type: crate::schema::IndexType,
},
UniqueChanged {
was_unique: bool,
is_unique: bool,
},
ConcurrentChanged {
was_concurrent: bool,
is_concurrent: bool,
},
TableChanged {
old_table: String,
new_table: String,
},
SchemaChanged {
old_schema: Option<String>,
new_schema: Option<String>,
},
}
#[derive(Debug, Clone)]
pub enum EventChange {
ScheduleChanged {
old_schedule: String,
new_schedule: String,
},
CommandChanged {
old_command: String,
new_command: String,
},
DatabaseChanged {
old_database: Option<String>,
new_database: Option<String>,
},
UsernameChanged {
old_username: Option<String>,
new_username: Option<String>,
},
DdlChanged {
old_ddl: String,
new_ddl: String,
},
EnabledChanged {
was_enabled: bool,
is_enabled: bool,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum RoleChange {
PasswordChanged {
old_password: Option<String>,
new_password: Option<String>,
},
PrivilegesChanged {
old_superuser: bool,
new_superuser: bool,
},
LoginChanged {
old_login: bool,
new_login: bool,
},
MembershipChanged {
old_members: Vec<String>,
new_members: Vec<String>,
},
ConnectionLimitChanged {
old_limit: Option<i32>,
new_limit: Option<i32>,
},
ValidUntilChanged {
old_until: Option<String>,
new_until: Option<String>,
},
}
pub struct SchemaDiffEngine;
impl SchemaDiffEngine {
pub fn compare_tables(
old_tables: &HashMap<String, Table>,
new_tables: &HashMap<String, Table>,
) -> Vec<SchemaDiff> {
let mut diffs = Vec::new();
for (name, table) in new_tables {
if !old_tables.contains_key(name) {
diffs.push(SchemaDiff::TableAdded {
name: name.clone(),
table: table.clone(),
});
}
}
for (name, table) in old_tables {
if !new_tables.contains_key(name) {
diffs.push(SchemaDiff::TableDropped {
name: name.clone(),
table: table.clone(),
});
}
}
for (name, new_table) in new_tables {
if let Some(old_table) = old_tables.get(name) {
let changes = Self::compare_table(old_table, new_table);
if !changes.is_empty() {
diffs.push(SchemaDiff::TableModified {
name: name.clone(),
old_table: old_table.clone(),
new_table: new_table.clone(),
});
}
}
}
diffs
}
pub fn compare_events(
old_events: &HashMap<String, Event>,
new_events: &HashMap<String, Event>,
) -> Vec<SchemaDiff> {
let mut diffs = Vec::new();
for (name, event) in new_events {
if !old_events.contains_key(name) {
diffs.push(SchemaDiff::EventAdded {
name: name.clone(),
event: event.clone(),
});
}
}
for (name, event) in old_events {
if !new_events.contains_key(name) {
diffs.push(SchemaDiff::EventDropped {
name: name.clone(),
event: event.clone(),
});
}
}
for (name, new_event) in new_events {
if let Some(old_event) = old_events.get(name) {
let changes = Self::compare_event(old_event, new_event);
if !changes.is_empty() {
diffs.push(SchemaDiff::EventModified {
name: name.clone(),
old_event: old_event.clone(),
new_event: new_event.clone(),
});
}
}
}
diffs
}
fn compare_event(old_event: &Event, new_event: &Event) -> Vec<EventChange> {
let mut changes = Vec::new();
if old_event.schedule != new_event.schedule {
changes.push(EventChange::ScheduleChanged {
old_schedule: old_event.schedule.clone(),
new_schedule: new_event.schedule.clone(),
});
}
if old_event.command != new_event.command {
changes.push(EventChange::CommandChanged {
old_command: old_event.command.clone(),
new_command: new_event.command.clone(),
});
}
if old_event.database != new_event.database {
changes.push(EventChange::DatabaseChanged {
old_database: old_event.database.clone(),
new_database: new_event.database.clone(),
});
}
if old_event.username != new_event.username {
changes.push(EventChange::UsernameChanged {
old_username: old_event.username.clone(),
new_username: new_event.username.clone(),
});
}
if old_event.ddl != new_event.ddl {
changes.push(EventChange::DdlChanged {
old_ddl: old_event.ddl.clone(),
new_ddl: new_event.ddl.clone(),
});
}
if old_event.enabled != new_event.enabled {
changes.push(EventChange::EnabledChanged {
was_enabled: old_event.enabled,
is_enabled: new_event.enabled,
});
}
changes
}
pub fn compare_indexes(
old_indexes: &HashMap<String, IndexMeta>,
new_indexes: &HashMap<String, IndexMeta>,
) -> Vec<SchemaDiff> {
let mut diffs = Vec::new();
for (name, index) in new_indexes {
if !old_indexes.contains_key(name) {
diffs.push(SchemaDiff::IndexAdded {
name: name.clone(),
index: index.clone(),
});
}
}
for (name, index) in old_indexes {
if !new_indexes.contains_key(name) {
diffs.push(SchemaDiff::IndexDropped {
name: name.clone(),
index: index.clone(),
});
}
}
for (name, new_index) in new_indexes {
if let Some(old_index) = old_indexes.get(name) {
let changes = Self::compare_index(old_index, new_index);
if !changes.is_empty() {
diffs.push(SchemaDiff::IndexModified {
name: name.clone(),
old_index: old_index.clone(),
new_index: new_index.clone(),
});
}
}
}
diffs
}
fn compare_index(old_index: &IndexMeta, new_index: &IndexMeta) -> Vec<IndexChange> {
let mut changes = Vec::new();
if old_index.columns != new_index.columns {
let old_cols: Vec<String> = old_index.columns.iter().map(|s| s.to_string()).collect();
let new_cols: Vec<String> = new_index.columns.iter().map(|s| s.to_string()).collect();
changes.push(IndexChange::ColumnsChanged {
old_columns: old_cols,
new_columns: new_cols,
});
}
if old_index.index_type != new_index.index_type {
changes.push(IndexChange::TypeChanged {
old_type: old_index.index_type.clone(),
new_type: new_index.index_type.clone(),
});
}
if old_index.unique != new_index.unique {
changes.push(IndexChange::UniqueChanged {
was_unique: old_index.unique,
is_unique: new_index.unique,
});
}
if old_index.concurrent != new_index.concurrent {
changes.push(IndexChange::ConcurrentChanged {
was_concurrent: old_index.concurrent,
is_concurrent: new_index.concurrent,
});
}
if old_index.table != new_index.table {
changes.push(IndexChange::TableChanged {
old_table: old_index.table.to_string(),
new_table: new_index.table.to_string(),
});
}
if old_index.schema != new_index.schema {
let old_schema = old_index.schema.as_ref().map_or("", |v| v);
let new_schema = new_index.schema.as_ref().map_or("", |v| v);
changes.push(IndexChange::SchemaChanged {
old_schema: Some(old_schema.to_string()),
new_schema: Some(new_schema.to_string()),
});
}
changes
}
pub fn compare_views(
old_views: &HashMap<String, crate::schema::View>,
new_views: &HashMap<String, crate::schema::View>,
) -> Vec<SchemaDiff> {
let mut diffs = Vec::new();
for (name, view) in new_views {
if !old_views.contains_key(name) {
diffs.push(SchemaDiff::ViewAdded {
name: name.clone(),
view: view.clone(),
});
}
}
for (name, view) in old_views {
if !new_views.contains_key(name) {
diffs.push(SchemaDiff::ViewDropped {
name: name.clone(),
view: view.clone(),
});
}
}
for (name, new_view) in new_views {
if let Some(old_view) = old_views.get(name) {
let changes = Self::compare_view(old_view, new_view);
if !changes.is_empty() {
diffs.push(SchemaDiff::ViewModified {
name: name.clone(),
old_view: old_view.clone(),
new_view: new_view.clone(),
});
}
}
}
diffs
}
fn compare_table(old_table: &Table, new_table: &Table) -> Vec<TableChange> {
let mut changes = Vec::new();
if old_table.primary_key != new_table.primary_key {
changes.push(TableChange::PrimaryKeyChanged {
old_pk: old_table.primary_key.clone(),
new_pk: new_table.primary_key.clone(),
});
}
let old_columns: HashMap<&String, &Column> =
old_table.columns.iter().map(|c| (&c.name, c)).collect();
let new_columns: HashMap<&String, &Column> =
new_table.columns.iter().map(|c| (&c.name, c)).collect();
for column in &new_table.columns {
if !old_columns.contains_key(&column.name) {
changes.push(TableChange::ColumnAdded {
name: column.name.clone(),
column: column.clone(),
});
}
}
for column in &old_table.columns {
if !new_columns.contains_key(&column.name) {
changes.push(TableChange::ColumnDropped {
name: column.name.clone(),
column: column.clone(),
});
}
}
for new_column in &new_table.columns {
if let Some(old_column) = old_columns.get(&new_column.name) {
if !Self::columns_equal(old_column, new_column) {
changes.push(TableChange::ColumnModified {
name: new_column.name.clone(),
old_column: (*old_column).clone(),
new_column: new_column.clone(),
});
}
}
}
changes
}
fn compare_view(
old_view: &crate::schema::View,
new_view: &crate::schema::View,
) -> Vec<ViewChange> {
let mut changes = Vec::new();
let old_pk = old_view.columns.first().map(|c| &c.name);
let new_pk = new_view.columns.first().map(|c| &c.name);
if old_pk != new_pk {
changes.push(ViewChange::PrimaryKeyChanged {
old_pk: old_pk.cloned(),
new_pk: new_pk.cloned(),
});
}
if old_view.materialized != new_view.materialized {
changes.push(ViewChange::MaterializedChanged {
was_materialized: old_view.materialized,
is_materialized: new_view.materialized,
});
}
if old_view.dependencies != new_view.dependencies {
changes.push(ViewChange::DependenciesChanged {
old_deps: old_view.dependencies.clone(),
new_deps: new_view.dependencies.clone(),
});
}
if old_view.indexes != new_view.indexes {
changes.push(ViewChange::IndexesChanged {
old_indexes: old_view.indexes.clone(),
new_indexes: new_view.indexes.clone(),
});
}
let old_columns: HashMap<&String, &Column> =
old_view.columns.iter().map(|c| (&c.name, c)).collect();
let new_columns: HashMap<&String, &Column> =
new_view.columns.iter().map(|c| (&c.name, c)).collect();
for column in &new_view.columns {
if !old_columns.contains_key(&column.name) {
changes.push(ViewChange::ColumnAdded {
name: column.name.clone(),
column: column.clone(),
});
}
}
for column in &old_view.columns {
if !new_columns.contains_key(&column.name) {
changes.push(ViewChange::ColumnDropped {
name: column.name.clone(),
column: column.clone(),
});
}
}
for column in &new_view.columns {
if let Some(old_column) = old_columns.get(&column.name) {
if old_column != &column {
changes.push(ViewChange::ColumnModified {
name: column.name.clone(),
old_column: (*old_column).clone(),
new_column: column.clone(),
});
}
}
}
changes
}
pub fn columns_equal(a: &Column, b: &Column) -> bool {
a.name == b.name
&& a.column_type == b.column_type
&& a.nullable == b.nullable
&& a.default == b.default
&& a.unique == b.unique
&& a.references == b.references
}
pub fn generate_table_change_sql(
table_name: &str,
old_table: &Table,
new_table: &Table,
) -> Vec<String> {
let mut changes = Vec::new();
if old_table.primary_key != new_table.primary_key {
let mut sql = String::new();
if let Some(_old_pk) = &old_table.primary_key {
sql.push_str(&format!(
"ALTER TABLE \"{}\" DROP CONSTRAINT IF EXISTS \"{}_pkey\" CASCADE;\n",
table_name, table_name
));
}
if let Some(new_pk) = &new_table.primary_key {
sql.push_str(&format!(
"ALTER TABLE \"{}\" ADD PRIMARY KEY (\"{}\");\n",
table_name, new_pk
));
}
changes.push(sql);
}
let old_columns: HashMap<&String, &Column> =
old_table.columns.iter().map(|c| (&c.name, c)).collect();
let new_columns: HashMap<&String, &Column> =
new_table.columns.iter().map(|c| (&c.name, c)).collect();
for column in &new_table.columns {
if !old_columns.contains_key(&column.name) {
changes.push(format!(
"ALTER TABLE \"{}\" ADD COLUMN {};\n",
table_name,
column.to_sql().trim_start_matches(" ")
));
}
}
for column in &old_table.columns {
if !new_columns.contains_key(&column.name) {
changes.push(format!(
"ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
table_name, column.name
));
}
}
for new_column in &new_table.columns {
if let Some(old_column) = old_columns.get(&new_column.name) {
if !Self::columns_equal(old_column, new_column) {
let mut sql = String::new();
sql.push_str(&format!(
"ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
table_name, new_column.name
));
sql.push_str(&format!(
"ALTER TABLE \"{}\" ADD COLUMN {};\n",
table_name,
new_column.to_sql().trim_start_matches(" ")
));
changes.push(sql);
}
}
}
changes
}
pub fn generate_view_change_sql(
view_name: &str,
old_view: &crate::schema::View,
new_view: &crate::schema::View,
) -> Vec<String> {
let mut changes = Vec::new();
let old_pk = old_view.columns.first().map(|c| &c.name);
let new_pk = new_view.columns.first().map(|c| &c.name);
if old_pk != new_pk {
changes.push(format!("-- Primary key changed for view {}\n", view_name));
}
if old_view.materialized != new_view.materialized {
if old_view.materialized && !new_view.materialized {
changes.push(format!(
"-- Convert materialized view {} to regular view\n",
view_name
));
} else if !old_view.materialized && new_view.materialized {
changes.push(format!(
"-- Convert regular view {} to materialized view\n",
view_name
));
}
}
if old_view.dependencies != new_view.dependencies {
let added: Vec<_> = new_view
.dependencies
.iter()
.filter(|d| !old_view.dependencies.contains(d))
.collect();
let removed: Vec<_> = old_view
.dependencies
.iter()
.filter(|d| !new_view.dependencies.contains(d))
.collect();
let mut sql = String::new();
if !added.is_empty() {
let added_names: Vec<String> = added.iter().map(|&s| s.clone()).collect();
sql.push_str(&format!(
"-- View {} now depends on: {}\n",
view_name,
added_names.join(", ")
));
}
if !removed.is_empty() {
let removed_names: Vec<String> = removed.iter().map(|&s| s.clone()).collect();
sql.push_str(&format!(
"-- View {} no longer depends on: {}\n",
view_name,
removed_names.join(", ")
));
}
changes.push(sql);
}
if old_view.indexes != new_view.indexes {
let added: Vec<_> = new_view
.indexes
.iter()
.filter(|i| !old_view.indexes.contains(i))
.collect();
let removed: Vec<_> = old_view
.indexes
.iter()
.filter(|i| !new_view.indexes.contains(i))
.collect();
let mut sql = String::new();
if !added.is_empty() {
let added_names: Vec<String> = added.iter().map(|i| i.name.clone()).collect();
sql.push_str(&format!(
"-- Add indexes to view {}: {}\n",
view_name,
added_names.join(", ")
));
}
if !removed.is_empty() {
let removed_names: Vec<String> = removed.iter().map(|i| i.name.clone()).collect();
sql.push_str(&format!(
"-- Remove indexes from view {}: {}\n",
view_name,
removed_names.join(", ")
));
}
changes.push(sql);
}
let old_columns: HashMap<&String, &Column> =
old_view.columns.iter().map(|c| (&c.name, c)).collect();
let new_columns: HashMap<&String, &Column> =
new_view.columns.iter().map(|c| (&c.name, c)).collect();
for column in &new_view.columns {
if !old_columns.contains_key(&column.name) {
changes.push(format!(
"-- Add column {} to view {}\n",
column.name, view_name
));
}
}
for column in &old_view.columns {
if !new_columns.contains_key(&column.name) {
changes.push(format!(
"-- Drop column {} from view {}\n",
column.name, view_name
));
}
}
for column in &new_view.columns {
if let Some(old_column) = old_columns.get(&column.name) {
if old_column != &column {
changes.push(format!(
"-- Modify column {} in view {}\n",
column.name, view_name
));
}
}
}
changes
}
pub fn generate_index_change_sql(
index_name: &str,
old_index: &IndexMeta,
new_index: &IndexMeta,
) -> Vec<String> {
let mut changes = Vec::new();
if old_index.columns != new_index.columns {
let old_cols: Vec<String> = old_index.columns.iter().map(|s| s.to_string()).collect();
let new_cols: Vec<String> = new_index.columns.iter().map(|s| s.to_string()).collect();
for old_col in old_cols {
changes.push(format!(
"ALTER INDEX \"{}\" DROP COLUMN \"{}\";\n",
index_name, old_col
));
}
for new_col in new_cols {
changes.push(format!(
"ALTER INDEX \"{}\" ADD COLUMN \"{}\";\n",
index_name, new_col
));
}
}
if old_index.index_type != new_index.index_type {
changes.push(format!(
"-- Index {} type changed from {} to {}\n",
index_name, old_index.index_type, new_index.index_type
));
}
if old_index.unique != new_index.unique {
if old_index.unique && !new_index.unique {
changes.push(format!("-- Index {} is no longer UNIQUE\n", index_name));
} else if !old_index.unique && new_index.unique {
changes.push(format!("-- Index {} is now UNIQUE\n", index_name));
}
}
if old_index.concurrent != new_index.concurrent {
if old_index.concurrent && !new_index.concurrent {
changes.push(format!(
"-- Index {} is no longer CONCURRENTLY\n",
index_name
));
} else if !old_index.concurrent && new_index.concurrent {
changes.push(format!("-- Index {} is now CONCURRENTLY\n", index_name));
}
}
if old_index.table != new_index.table {
changes.push(format!(
"-- Index {} table changed from {} to {}\n",
index_name, old_index.table, new_index.table
));
}
if old_index.schema != new_index.schema {
let old_schema = old_index.schema.as_ref().map_or("", |v| v);
let new_schema = new_index.schema.as_ref().map_or("", |v| v);
changes.push(format!(
"-- Index {} schema changed from {} to {}\n",
index_name, old_schema, new_schema
));
}
changes
}
pub fn generate_event_change_sql(
event_name: &str,
old_event: &Event,
new_event: &Event,
) -> Vec<String> {
let mut changes = Vec::new();
if old_event.schedule != new_event.schedule {
changes.push(format!(
"-- Event {} schedule changed from {} to {}\n",
event_name, old_event.schedule, new_event.schedule
));
}
if old_event.command != new_event.command {
changes.push(format!(
"-- Event {} command changed from {} to {}\n",
event_name, old_event.command, new_event.command
));
}
if old_event.database != new_event.database {
let mut sql = String::new();
if let Some(old_db) = &old_event.database {
sql.push_str(&format!(
"ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
event_name, old_db
));
}
if let Some(new_db) = &new_event.database {
sql.push_str(&format!(
"ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
event_name, new_db
));
}
changes.push(sql);
}
if old_event.username != new_event.username {
let mut sql = String::new();
if let Some(old_user) = &old_event.username {
sql.push_str(&format!(
"ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
event_name, old_user
));
}
if let Some(new_user) = &new_event.username {
sql.push_str(&format!(
"ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
event_name, new_user
));
}
changes.push(sql);
}
if old_event.ddl != new_event.ddl {
changes.push(format!(
"-- Event {} DDL changed from {} to {}\n",
event_name, old_event.ddl, new_event.ddl
));
}
if old_event.enabled != new_event.enabled {
if old_event.enabled && !new_event.enabled {
changes.push(format!("-- Event {} is now DISABLED\n", event_name));
} else if !old_event.enabled && new_event.enabled {
changes.push(format!("-- Event {} is now ENABLED\n", event_name));
}
}
changes
}
pub fn generate_role_change_sql(
role_name: &str,
old_role: &Role,
new_role: &Role,
) -> Vec<String> {
let mut changes = Vec::new();
if old_role.password != new_role.password {
let mut sql = String::new();
if let Some(_old_password) = &old_role.password {
sql.push_str(&format!("ALTER ROLE \"{}\" PASSWORD NULL;\n", role_name));
}
if let Some(new_password) = &new_role.password {
sql.push_str(&format!(
"ALTER ROLE \"{}\" PASSWORD '{}';\n",
role_name, new_password
));
}
changes.push(sql);
}
if old_role.superuser != new_role.superuser {
let mut sql = String::new();
if !old_role.superuser && new_role.superuser {
sql.push_str(&format!("ALTER ROLE \"{}\" SUPERUSER;\n", role_name));
} else if old_role.superuser && !new_role.superuser {
sql.push_str(&format!("ALTER ROLE \"{}\" NOSUPERUSER;\n", role_name));
}
changes.push(sql);
}
if old_role.login != new_role.login {
let mut sql = String::new();
if !old_role.login && new_role.login {
sql.push_str(&format!("ALTER ROLE \"{}\" LOGIN;\n", role_name));
} else if old_role.login && !new_role.login {
sql.push_str(&format!("ALTER ROLE \"{}\" NOLOGIN;\n", role_name));
}
changes.push(sql);
}
if old_role.member_of != new_role.member_of || old_role.members != new_role.members {
let mut sql = String::new();
let mut old_members: Vec<String> =
old_role.member_of.iter().map(|s| s.clone()).collect();
old_members.extend(old_role.members.iter().map(|s| s.clone()));
let mut new_members: Vec<String> =
new_role.member_of.iter().map(|s| s.clone()).collect();
new_members.extend(new_role.members.iter().map(|s| s.clone()));
let added: Vec<_> = new_members
.iter()
.filter(|d| !old_members.contains(d))
.collect();
let removed: Vec<_> = old_members
.iter()
.filter(|d| !new_members.contains(d))
.collect();
if !added.is_empty() {
let added_names: Vec<String> = added.iter().map(|&s| s.clone()).collect();
sql.push_str(&format!(
"ALTER ROLE \"{}\" ADD MEMBER \"{}\";\n",
role_name,
added_names.join(", ")
));
}
if !removed.is_empty() {
let removed_names: Vec<String> = removed.iter().map(|&s| s.clone()).collect();
sql.push_str(&format!(
"ALTER ROLE \"{}\" DROP MEMBER \"{}\";\n",
role_name,
removed_names.join(", ")
));
}
changes.push(sql);
}
if old_role.connection_limit != new_role.connection_limit {
let mut sql = String::new();
if let Some(_old_limit) = &old_role.connection_limit {
sql.push_str(&format!(
"ALTER ROLE \"{}\" CONNECTION LIMIT NULL;\n",
role_name
));
}
if let Some(new_limit) = &new_role.connection_limit {
sql.push_str(&format!(
"ALTER ROLE \"{}\" CONNECTION LIMIT {};\n",
role_name, new_limit
));
}
changes.push(sql);
}
if old_role.valid_until != new_role.valid_until {
let mut sql = String::new();
if let Some(_old_until) = &old_role.valid_until {
sql.push_str(&format!("ALTER ROLE \"{}\" VALID UNTIL NULL;\n", role_name));
}
if let Some(new_until) = &new_role.valid_until {
sql.push_str(&format!(
"ALTER ROLE \"{}\" VALID UNTIL '{}';\n",
role_name, new_until
));
}
changes.push(sql);
}
changes
}
pub fn generate_grant_change_sql(
grant_name: &str,
old_grant: &Grant,
new_grant: &Grant,
) -> Vec<String> {
let mut changes = Vec::new();
if old_grant.privilege != new_grant.privilege {
changes.push(format!(
"-- Grant {} privilege changed from {:?} to {:?}\n",
grant_name, old_grant.privilege, new_grant.privilege
));
}
if old_grant.target != new_grant.target {
changes.push(format!(
"-- Grant {} target changed from {:?} to {:?}\n",
grant_name, old_grant.target, new_grant.target
));
}
if old_grant.grantee != new_grant.grantee {
changes.push(format!(
"-- Grant {} grantee changed from {} to {}\n",
grant_name, old_grant.grantee, new_grant.grantee
));
}
if old_grant.with_grant_option != new_grant.with_grant_option {
if old_grant.with_grant_option && !new_grant.with_grant_option {
changes.push(format!(
"-- Grant {} no longer has GRANT OPTION\n",
grant_name
));
} else if !old_grant.with_grant_option && new_grant.with_grant_option {
changes.push(format!("-- Grant {} now has GRANT OPTION\n", grant_name));
}
}
if old_grant.grantor != new_grant.grantor {
changes.push(format!(
"-- Grant {} grantor changed from {:?} to {:?}\n",
grant_name, old_grant.grantor, new_grant.grantor
));
}
changes
}
pub fn compare_roles(
old_roles: &HashMap<String, Role>,
new_roles: &HashMap<String, Role>,
) -> Vec<SchemaDiff> {
let mut diffs = Vec::new();
for (name, role) in new_roles {
if !old_roles.contains_key(name) {
diffs.push(SchemaDiff::RoleAdded {
name: name.clone(),
role: role.clone(),
});
}
}
for (name, role) in old_roles {
if !new_roles.contains_key(name) {
diffs.push(SchemaDiff::RoleDropped {
name: name.clone(),
role: role.clone(),
});
}
}
for (name, new_role) in new_roles {
if let Some(old_role) = old_roles.get(name) {
if old_role != new_role {
diffs.push(SchemaDiff::RoleModified {
name: name.clone(),
old_role: old_role.clone(),
new_role: new_role.clone(),
});
}
}
}
diffs
}
pub fn compare_grants(
old_grants: &HashMap<String, Grant>,
new_grants: &HashMap<String, Grant>,
) -> Vec<SchemaDiff> {
let mut diffs = Vec::new();
for (name, grant) in new_grants {
if !old_grants.contains_key(name) {
diffs.push(SchemaDiff::GrantAdded {
name: name.clone(),
grant: grant.clone(),
});
}
}
for (name, grant) in old_grants {
if !new_grants.contains_key(name) {
diffs.push(SchemaDiff::GrantDropped {
name: name.clone(),
grant: grant.clone(),
});
}
}
for (name, new_grant) in new_grants {
if let Some(old_grant) = old_grants.get(name) {
if old_grant != new_grant {
diffs.push(SchemaDiff::GrantModified {
name: name.clone(),
old_grant: old_grant.clone(),
new_grant: new_grant.clone(),
});
}
}
}
diffs
}
pub fn compare_functions(
old_functions: &HashMap<String, StoredFunction>,
new_functions: &HashMap<String, StoredFunction>,
) -> Vec<SchemaDiff> {
let mut diffs = Vec::new();
for (name, function) in new_functions {
if !old_functions.contains_key(name) {
diffs.push(SchemaDiff::FunctionAdded {
name: name.clone(),
function: function.clone(),
});
}
}
for (name, function) in old_functions {
if !new_functions.contains_key(name) {
diffs.push(SchemaDiff::FunctionDropped {
name: name.clone(),
function: function.clone(),
});
}
}
for (name, new_function) in new_functions {
if let Some(old_function) = old_functions.get(name) {
if old_function != new_function {
diffs.push(SchemaDiff::FunctionModified {
name: name.clone(),
old_function: old_function.clone(),
new_function: new_function.clone(),
});
}
}
}
diffs
}
pub fn compare_procedures(
old_procedures: &HashMap<String, StoredProcedure>,
new_procedures: &HashMap<String, StoredProcedure>,
) -> Vec<SchemaDiff> {
let mut diffs = Vec::new();
for (name, procedure) in new_procedures {
if !old_procedures.contains_key(name) {
diffs.push(SchemaDiff::ProcedureAdded {
name: name.clone(),
procedure: procedure.clone(),
});
}
}
for (name, procedure) in old_procedures {
if !new_procedures.contains_key(name) {
diffs.push(SchemaDiff::ProcedureDropped {
name: name.clone(),
procedure: procedure.clone(),
});
}
}
for (name, new_procedure) in new_procedures {
if let Some(old_procedure) = old_procedures.get(name) {
if old_procedure != new_procedure {
diffs.push(SchemaDiff::ProcedureModified {
name: name.clone(),
old_procedure: old_procedure.clone(),
new_procedure: new_procedure.clone(),
});
}
}
}
diffs
}
pub fn compare_triggers(
old_triggers: &HashMap<String, Trigger>,
new_triggers: &HashMap<String, Trigger>,
) -> Vec<SchemaDiff> {
let mut diffs = Vec::new();
for (name, trigger) in new_triggers {
if !old_triggers.contains_key(name) {
diffs.push(SchemaDiff::TriggerAdded {
name: name.clone(),
trigger: trigger.clone(),
});
}
}
for (name, trigger) in old_triggers {
if !new_triggers.contains_key(name) {
diffs.push(SchemaDiff::TriggerDropped {
name: name.clone(),
trigger: trigger.clone(),
});
}
}
for (name, new_trigger) in new_triggers {
if let Some(old_trigger) = old_triggers.get(name) {
if old_trigger != new_trigger {
diffs.push(SchemaDiff::TriggerModified {
name: name.clone(),
old_trigger: old_trigger.clone(),
new_trigger: new_trigger.clone(),
});
}
}
}
diffs
}
pub fn compare_composite_types(
old_composite_types: &HashMap<String, CompositeType>,
new_composite_types: &HashMap<String, CompositeType>,
) -> Vec<SchemaDiff> {
let mut diffs = Vec::new();
for (name, composite_type) in new_composite_types {
if !old_composite_types.contains_key(name) {
diffs.push(SchemaDiff::CompositeTypeAdded {
name: name.clone(),
composite_type: composite_type.clone(),
});
}
}
for (name, composite_type) in old_composite_types {
if !new_composite_types.contains_key(name) {
diffs.push(SchemaDiff::CompositeTypeDropped {
name: name.clone(),
composite_type: composite_type.clone(),
});
}
}
for (name, new_composite_type) in new_composite_types {
if let Some(old_composite_type) = old_composite_types.get(name) {
if old_composite_type != new_composite_type {
diffs.push(SchemaDiff::CompositeTypeModified {
name: name.clone(),
old_composite_type: old_composite_type.clone(),
new_composite_type: new_composite_type.clone(),
});
}
}
}
diffs
}
}
pub struct MigrationGenerator;
impl MigrationGenerator {
pub fn generate_migration(diffs: &[SchemaDiff]) -> String {
let mut migration = String::new();
for diff in diffs {
match diff {
SchemaDiff::TableAdded { name, table } => {
migration.push_str(&format!("-- Add table {}\n", name));
migration.push_str(&table.generate_ddl());
migration.push_str("\n\n");
}
SchemaDiff::TableDropped { name, .. } => {
migration.push_str(&format!("-- Drop table {}\n", name));
migration.push_str(&format!("DROP TABLE IF EXISTS \"{}\" CASCADE;\n\n", name));
}
SchemaDiff::TableModified {
name,
old_table,
new_table,
} => {
migration.push_str(&format!("-- Modify table {}\n", name));
for change in
SchemaDiffEngine::generate_table_change_sql(name, old_table, new_table)
{
migration.push_str(&change);
}
migration.push_str("\n");
}
SchemaDiff::ViewAdded { name, view } => {
migration.push_str(&format!("-- Add view {}\n", name));
let all_ddl = view.generate_all_ddl();
for ddl in all_ddl {
migration.push_str(&ddl);
migration.push_str("\n");
}
migration.push_str("\n");
}
SchemaDiff::ViewDropped { name, .. } => {
migration.push_str(&format!("-- Drop view {}\n", name));
migration.push_str(&format!("DROP VIEW IF EXISTS \"{}\" CASCADE;\n\n", name));
}
SchemaDiff::ViewModified {
name,
old_view,
new_view,
} => {
migration.push_str(&format!("-- Modify view {}\n", name));
for change in
SchemaDiffEngine::generate_view_change_sql(name, old_view, new_view)
{
migration.push_str(&change);
}
migration.push_str("\n");
}
SchemaDiff::IndexAdded { name, index } => {
migration.push_str(&format!("-- Add index {}\n", name));
migration.push_str(&index.generate_ddl());
migration.push_str("\n\n");
}
SchemaDiff::IndexDropped { name, index: _ } => {
migration.push_str(&format!("-- Drop index {}\n", name));
migration.push_str(&format!("DROP INDEX IF EXISTS \"{}\" CASCADE;\n\n", name));
}
SchemaDiff::IndexModified {
name,
old_index,
new_index,
} => {
migration.push_str(&format!("-- Modify index {}\n", name));
for change in
SchemaDiffEngine::generate_index_change_sql(name, old_index, new_index)
{
migration.push_str(&change);
}
migration.push_str("\n");
}
SchemaDiff::EventAdded { name, event } => {
migration.push_str(&format!("-- Add event {}\n", name));
migration.push_str(&event.generate_ddl());
migration.push_str("\n\n");
}
SchemaDiff::EventDropped { name, event: _ } => {
migration.push_str(&format!("-- Drop event {}\n", name));
migration.push_str(&format!("DROP EVENT IF EXISTS \"{}\" CASCADE;\n\n", name));
}
SchemaDiff::EventModified {
name,
old_event,
new_event,
} => {
migration.push_str(&format!("-- Modify event {}\n", name));
for change in
SchemaDiffEngine::generate_event_change_sql(name, old_event, new_event)
{
migration.push_str(&change);
}
migration.push_str("\n");
}
SchemaDiff::RoleAdded { name, role } => {
migration.push_str(&format!("-- Add role {}\n", name));
migration.push_str(&role.generate_create_ddl());
migration.push_str("\n\n");
}
SchemaDiff::RoleDropped { name, role } => {
migration.push_str(&format!("-- Drop role {}\n", name));
migration.push_str(&role.generate_drop_ddl());
migration.push_str("\n\n");
}
SchemaDiff::RoleModified {
name,
old_role,
new_role,
} => {
migration.push_str(&format!("-- Modify role {}\n", name));
for change in
SchemaDiffEngine::generate_role_change_sql(name, old_role, new_role)
{
migration.push_str(&change);
}
migration.push_str("\n");
}
SchemaDiff::GrantAdded { name, grant } => {
migration.push_str(&format!("-- Add grant {}\n", name));
migration.push_str(&grant.generate_grant_ddl());
migration.push_str("\n\n");
}
SchemaDiff::GrantDropped { name, grant } => {
migration.push_str(&format!("-- Drop grant {}\n", name));
migration.push_str(&grant.generate_revoke_ddl());
migration.push_str("\n\n");
}
SchemaDiff::GrantModified {
name,
old_grant,
new_grant,
} => {
migration.push_str(&format!("-- Modify grant {}\n", name));
for change in
SchemaDiffEngine::generate_grant_change_sql(name, old_grant, new_grant)
{
migration.push_str(&change);
}
migration.push_str("\n");
}
SchemaDiff::FunctionAdded { name, function } => {
migration.push_str(&format!("-- Add function {}\n", name));
migration.push_str(&function.generate_create_ddl());
migration.push_str("\n\n");
}
SchemaDiff::FunctionDropped { name, .. } => {
migration.push_str(&format!("-- Drop function {}\n", name));
migration.push_str(&format!(
"DROP FUNCTION IF EXISTS \"{}\" CASCADE;\n\n",
name
));
}
SchemaDiff::FunctionModified {
name,
old_function: _,
new_function,
} => {
migration.push_str(&format!("-- Modify function {}\n", name));
migration.push_str(&format!("DROP FUNCTION IF EXISTS \"{}\" CASCADE;\n", name));
migration.push_str(&new_function.generate_create_ddl());
migration.push_str("\n");
}
SchemaDiff::ProcedureAdded { name, procedure } => {
migration.push_str(&format!("-- Add procedure {}\n", name));
migration.push_str(&procedure.generate_create_ddl());
migration.push_str("\n\n");
}
SchemaDiff::ProcedureDropped { name, .. } => {
migration.push_str(&format!("-- Drop procedure {}\n", name));
migration.push_str(&format!(
"DROP PROCEDURE IF EXISTS \"{}\" CASCADE;\n\n",
name
));
}
SchemaDiff::ProcedureModified {
name,
old_procedure: _,
new_procedure,
} => {
migration.push_str(&format!("-- Modify procedure {}\n", name));
migration
.push_str(&format!("DROP PROCEDURE IF EXISTS \"{}\" CASCADE;\n", name));
migration.push_str(&new_procedure.generate_create_ddl());
migration.push_str("\n");
}
SchemaDiff::TriggerAdded { name, trigger } => {
migration.push_str(&format!("-- Add trigger {}\n", name));
migration.push_str(&trigger.generate_create_ddl());
migration.push_str("\n\n");
}
SchemaDiff::TriggerDropped { name, .. } => {
migration.push_str(&format!("-- Drop trigger {}\n", name));
migration
.push_str(&format!("DROP TRIGGER IF EXISTS \"{}\" CASCADE;\n\n", name));
}
SchemaDiff::TriggerModified {
name,
old_trigger: _,
new_trigger,
} => {
migration.push_str(&format!("-- Modify trigger {}\n", name));
migration.push_str(&format!("DROP TRIGGER IF EXISTS \"{}\" CASCADE;\n", name));
migration.push_str(&new_trigger.generate_create_ddl());
migration.push_str("\n");
}
SchemaDiff::CompositeTypeAdded {
name,
composite_type,
} => {
migration.push_str(&format!("-- Add composite type {}\n", name));
migration.push_str(&composite_type.generate_create_ddl());
migration.push_str("\n\n");
}
SchemaDiff::CompositeTypeDropped { name, .. } => {
migration.push_str(&format!("-- Drop composite type {}\n", name));
migration.push_str(&format!("DROP TYPE IF EXISTS \"{}\" CASCADE;\n\n", name));
}
SchemaDiff::CompositeTypeModified {
name,
old_composite_type: _,
new_composite_type,
} => {
migration.push_str(&format!("-- Modify composite type {}\n", name));
migration.push_str(&format!("DROP TYPE IF EXISTS \"{}\" CASCADE;\n", name));
migration.push_str(&new_composite_type.generate_create_ddl());
migration.push_str("\n");
}
}
}
migration
}
pub fn generate_table_migration(diffs: &[SchemaDiff]) -> String {
let mut migration = String::new();
for diff in diffs {
match diff {
SchemaDiff::TableAdded { name, table } => {
migration.push_str(&format!("-- Add table {}\n", name));
migration.push_str(&table.generate_ddl());
migration.push_str("\n\n");
}
SchemaDiff::TableDropped { name, .. } => {
migration.push_str(&format!("-- Drop table {}\n", name));
migration.push_str(&format!("DROP TABLE IF EXISTS \"{}\" CASCADE;\n\n", name));
}
SchemaDiff::TableModified {
name,
old_table,
new_table,
} => {
migration.push_str(&format!("-- Modify table {}\n", name));
for change in
SchemaDiffEngine::generate_table_change_sql(name, old_table, new_table)
{
migration.push_str(&change);
}
migration.push_str("\n");
}
_ => {} }
}
migration
}
pub fn generate_view_migration(diffs: &[SchemaDiff]) -> String {
let mut migration = String::new();
for diff in diffs {
match diff {
SchemaDiff::ViewAdded { name, view } => {
migration.push_str(&format!("-- Add view {}\n", name));
let all_ddl = view.generate_all_ddl();
for ddl in all_ddl {
migration.push_str(&ddl);
migration.push_str("\n");
}
migration.push_str("\n");
}
SchemaDiff::ViewDropped { name, .. } => {
migration.push_str(&format!("-- Drop view {}\n", name));
migration.push_str(&format!("DROP VIEW IF EXISTS \"{}\" CASCADE;\n\n", name));
}
SchemaDiff::ViewModified {
name,
old_view,
new_view,
} => {
migration.push_str(&format!("-- Modify view {}\n", name));
for change in
SchemaDiffEngine::generate_view_change_sql(name, old_view, new_view)
{
migration.push_str(&change);
}
migration.push_str("\n");
}
_ => {} }
}
migration
}
pub fn generate_index_change_sql(
index_name: &str,
old_index: &IndexMeta,
new_index: &IndexMeta,
) -> Vec<String> {
let mut changes = Vec::new();
if old_index.columns != new_index.columns {
let old_cols: Vec<String> = old_index.columns.iter().map(|s| s.to_string()).collect();
let new_cols: Vec<String> = new_index.columns.iter().map(|s| s.to_string()).collect();
for old_col in old_cols {
changes.push(format!(
"ALTER INDEX \"{}\" DROP COLUMN \"{}\";\n",
index_name, old_col
));
}
for new_col in new_cols {
changes.push(format!(
"ALTER INDEX \"{}\" ADD COLUMN \"{}\";\n",
index_name, new_col
));
}
}
if old_index.index_type != new_index.index_type {
changes.push(format!(
"-- Index {} type changed from {} to {}\n",
index_name, old_index.index_type, new_index.index_type
));
}
if old_index.unique != new_index.unique {
if old_index.unique && !new_index.unique {
changes.push(format!("-- Index {} is no longer UNIQUE\n", index_name));
} else if !old_index.unique && new_index.unique {
changes.push(format!("-- Index {} is now UNIQUE\n", index_name));
}
}
if old_index.concurrent != new_index.concurrent {
if old_index.concurrent && !new_index.concurrent {
changes.push(format!(
"-- Index {} is no longer CONCURRENTLY\n",
index_name
));
} else if !old_index.concurrent && new_index.concurrent {
changes.push(format!("-- Index {} is now CONCURRENTLY\n", index_name));
}
}
if old_index.table != new_index.table {
changes.push(format!(
"-- Index {} table changed from {} to {}\n",
index_name, old_index.table, new_index.table
));
}
if old_index.schema != new_index.schema {
let old_schema = old_index.schema.as_ref().map_or("", |v| v);
let new_schema = new_index.schema.as_ref().map_or("", |v| v);
changes.push(format!(
"-- Index {} schema changed from {} to {}\n",
index_name, old_schema, new_schema
));
}
changes
}
pub fn generate_event_change_sql(
event_name: &str,
old_event: &Event,
new_event: &Event,
) -> Vec<String> {
let mut changes = Vec::new();
if old_event.schedule != new_event.schedule {
changes.push(format!(
"-- Event {} schedule changed from {} to {}\n",
event_name, old_event.schedule, new_event.schedule
));
}
if old_event.command != new_event.command {
changes.push(format!(
"-- Event {} command changed from {} to {}\n",
event_name, old_event.command, new_event.command
));
}
if old_event.database != new_event.database {
let mut sql = String::new();
if let Some(old_db) = &old_event.database {
sql.push_str(&format!(
"ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
event_name, old_db
));
}
if let Some(new_db) = &new_event.database {
sql.push_str(&format!(
"ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
event_name, new_db
));
}
changes.push(sql);
}
if old_event.username != new_event.username {
let mut sql = String::new();
if let Some(old_user) = &old_event.username {
sql.push_str(&format!(
"ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
event_name, old_user
));
}
if let Some(new_user) = &new_event.username {
sql.push_str(&format!(
"ALTER EVENT \"{}\" RENAME TO \"{}\";\n",
event_name, new_user
));
}
changes.push(sql);
}
if old_event.ddl != new_event.ddl {
changes.push(format!(
"-- Event {} DDL changed from {} to {}\n",
event_name, old_event.ddl, new_event.ddl
));
}
if old_event.enabled != new_event.enabled {
if old_event.enabled && !new_event.enabled {
changes.push(format!("-- Event {} is now DISABLED\n", event_name));
} else if !old_event.enabled && new_event.enabled {
changes.push(format!("-- Event {} is now ENABLED\n", event_name));
}
}
changes
}
pub fn generate_role_change_sql(
role_name: &str,
old_role: &Role,
new_role: &Role,
) -> Vec<String> {
let mut changes = Vec::new();
if old_role.password != new_role.password {
let mut sql = String::new();
if let Some(_old_password) = &old_role.password {
sql.push_str(&format!("ALTER ROLE \"{}\" PASSWORD NULL;\n", role_name));
}
if let Some(new_password) = &new_role.password {
sql.push_str(&format!(
"ALTER ROLE \"{}\" PASSWORD '{}';\n",
role_name, new_password
));
}
changes.push(sql);
}
if old_role.superuser != new_role.superuser {
let mut sql = String::new();
if !old_role.superuser && new_role.superuser {
sql.push_str(&format!("ALTER ROLE \"{}\" SUPERUSER;\n", role_name));
} else if old_role.superuser && !new_role.superuser {
sql.push_str(&format!("ALTER ROLE \"{}\" NOSUPERUSER;\n", role_name));
}
changes.push(sql);
}
if old_role.login != new_role.login {
let mut sql = String::new();
if !old_role.login && new_role.login {
sql.push_str(&format!("ALTER ROLE \"{}\" LOGIN;\n", role_name));
} else if old_role.login && !new_role.login {
sql.push_str(&format!("ALTER ROLE \"{}\" NOLOGIN;\n", role_name));
}
changes.push(sql);
}
if old_role.member_of != new_role.member_of || old_role.members != new_role.members {
let mut sql = String::new();
let mut old_members: Vec<String> =
old_role.member_of.iter().map(|s| s.clone()).collect();
old_members.extend(old_role.members.iter().map(|s| s.clone()));
let mut new_members: Vec<String> =
new_role.member_of.iter().map(|s| s.clone()).collect();
new_members.extend(new_role.members.iter().map(|s| s.clone()));
let added: Vec<_> = new_members
.iter()
.filter(|d| !old_members.contains(d))
.collect();
let removed: Vec<_> = old_members
.iter()
.filter(|d| !new_members.contains(d))
.collect();
if !added.is_empty() {
let added_names: Vec<String> = added.iter().map(|&s| s.clone()).collect();
sql.push_str(&format!(
"ALTER ROLE \"{}\" ADD MEMBER \"{}\";\n",
role_name,
added_names.join(", ")
));
}
if !removed.is_empty() {
let removed_names: Vec<String> = removed.iter().map(|&s| s.clone()).collect();
sql.push_str(&format!(
"ALTER ROLE \"{}\" DROP MEMBER \"{}\";\n",
role_name,
removed_names.join(", ")
));
}
changes.push(sql);
}
if old_role.connection_limit != new_role.connection_limit {
let mut sql = String::new();
if let Some(_old_limit) = &old_role.connection_limit {
sql.push_str(&format!(
"ALTER ROLE \"{}\" CONNECTION LIMIT NULL;\n",
role_name
));
}
if let Some(new_limit) = &new_role.connection_limit {
sql.push_str(&format!(
"ALTER ROLE \"{}\" CONNECTION LIMIT {};\n",
role_name, new_limit
));
}
changes.push(sql);
}
if old_role.valid_until != new_role.valid_until {
let mut sql = String::new();
if let Some(_old_until) = &old_role.valid_until {
sql.push_str(&format!("ALTER ROLE \"{}\" VALID UNTIL NULL;\n", role_name));
}
if let Some(new_until) = &new_role.valid_until {
sql.push_str(&format!(
"ALTER ROLE \"{}\" VALID UNTIL '{}';\n",
role_name, new_until
));
}
changes.push(sql);
}
changes
}
pub fn generate_grant_change_sql(
grant_name: &str,
old_grant: &Grant,
new_grant: &Grant,
) -> Vec<String> {
let mut changes = Vec::new();
if old_grant.privilege != new_grant.privilege {
changes.push(format!(
"-- Grant {} privilege changed from {:?} to {:?}\n",
grant_name, old_grant.privilege, new_grant.privilege
));
}
if old_grant.target != new_grant.target {
changes.push(format!(
"-- Grant {} target changed from {:?} to {:?}\n",
grant_name, old_grant.target, new_grant.target
));
}
if old_grant.grantee != new_grant.grantee {
changes.push(format!(
"-- Grant {} grantee changed from {} to {}\n",
grant_name, old_grant.grantee, new_grant.grantee
));
}
if old_grant.with_grant_option != new_grant.with_grant_option {
if old_grant.with_grant_option && !new_grant.with_grant_option {
changes.push(format!(
"-- Grant {} no longer has GRANT OPTION\n",
grant_name
));
} else if !old_grant.with_grant_option && new_grant.with_grant_option {
changes.push(format!("-- Grant {} now has GRANT OPTION\n", grant_name));
}
}
if old_grant.grantor != new_grant.grantor {
changes.push(format!(
"-- Grant {} grantor changed from {:?} to {:?}\n",
grant_name, old_grant.grantor, new_grant.grantor
));
}
changes
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::{Column, ColumnType, Table};
#[test]
fn test_table_added_diff() {
let old_tables = HashMap::new();
let mut new_tables = HashMap::new();
let users_table = Table::new("users")
.add_column(Column::new("id", ColumnType::Int4))
.set_primary_key("id");
new_tables.insert("users".to_string(), users_table);
let diffs = SchemaDiffEngine::compare_tables(&old_tables, &new_tables);
assert_eq!(diffs.len(), 1);
match &diffs[0] {
SchemaDiff::TableAdded { name, .. } => assert_eq!(name, "users"),
diff => unreachable!("Expected TableAdded but got {:?}", diff),
}
}
#[test]
fn test_column_added_diff() {
let mut old_tables = HashMap::new();
let mut new_tables = HashMap::new();
let old_users = Table::new("users")
.add_column(Column::new("id", ColumnType::Int4))
.set_primary_key("id");
let new_users = Table::new("users")
.add_column(Column::new("id", ColumnType::Int4))
.add_column(Column::new("email", ColumnType::Varchar(None)))
.set_primary_key("id");
old_tables.insert("users".to_string(), old_users);
new_tables.insert("users".to_string(), new_users);
let diffs = SchemaDiffEngine::compare_tables(&old_tables, &new_tables);
assert_eq!(diffs.len(), 1);
match &diffs[0] {
SchemaDiff::TableModified {
name,
old_table,
new_table,
} => {
assert_eq!(name, "users");
let changes = SchemaDiffEngine::compare_table(old_table, new_table);
assert_eq!(changes.len(), 1);
match &changes[0] {
TableChange::ColumnAdded { name, .. } => assert_eq!(name, "email"),
change => unreachable!("Expected ColumnAdded but got {:?}", change),
}
}
diff => unreachable!("Expected TableModified but got {:?}", diff),
}
}
}
#[derive(Debug, Clone)]
pub struct SchemaSnapshot {
pub timestamp: DateTime<Utc>,
pub checksum: String,
pub tables: HashMap<String, Table>,
pub views: HashMap<String, crate::schema::View>,
pub indexes: HashMap<String, IndexMeta>,
pub statistics: SchemaStatistics,
}
pub struct IntelligentMigrationGenerator {
pool: sqlx::PgPool,
}
impl IntelligentMigrationGenerator {
pub fn new(pool: sqlx::PgPool) -> Self {
Self { pool }
}
pub async fn generate_migration_from_current_state(
&self,
migrations_dir: &std::path::Path,
) -> Result<Option<String>> {
let baseline_snapshot = self
.get_latest_baseline_snapshot()
.await
.context("Failed to get baseline snapshot from migration history")?;
let current_snapshot = self
.capture_current_schema_snapshot()
.await
.context("Failed to capture current database schema")?;
let schema_changes = self
.intelligent_schema_compare(&baseline_snapshot, ¤t_snapshot)
.context("Failed to compare schema states")?;
if schema_changes.is_empty() {
return Ok(None);
}
let migration_file = self
.generate_migration_file(&schema_changes, migrations_dir)
.await
.context("Failed to generate migration file")?;
Ok(Some(migration_file))
}
async fn get_latest_baseline_snapshot(&self) -> Result<SchemaSnapshot> {
let baseline_record = sqlx::query(
r#"
SELECT name, checksum, applied_at
FROM __ignis_migrations
WHERE name LIKE '%baseline%'
ORDER BY applied_at DESC
LIMIT 1
"#,
)
.fetch_one(&self.pool)
.await
.context("No baseline migration found. Run 'ignis-cli migrate baseline' first")?;
let baseline_name: String = baseline_record.get("name");
let baseline_json_path = format!("./migrations/{}.json", baseline_name);
let baseline_json = std::fs::read_to_string(&baseline_json_path).context(format!(
"Failed to read baseline JSON file: {}",
baseline_json_path
))?;
let baseline_data: serde_json::Value =
serde_json::from_str(&baseline_json).context("Failed to parse baseline JSON")?;
let stats = &baseline_data["statistics"];
let statistics = crate::migrate::baseline::SchemaStatistics {
table_count: stats["table_count"].as_u64().unwrap_or(0) as usize,
view_count: stats["view_count"].as_u64().unwrap_or(0) as usize,
index_count: stats["index_count"].as_u64().unwrap_or(0) as usize,
function_count: stats["function_count"].as_u64().unwrap_or(0) as usize,
trigger_count: stats["trigger_count"].as_u64().unwrap_or(0) as usize,
composite_type_count: stats["composite_type_count"].as_u64().unwrap_or(0) as usize,
total_columns: stats["total_columns"].as_u64().unwrap_or(0) as usize,
total_constraints: stats["total_constraints"].as_u64().unwrap_or(0) as usize,
};
let baseline_sql = baseline_data["baseline_sql"]
.as_str()
.context("Missing baseline_sql in JSON")?;
let baseline_tables = self
.extract_tables_from_baseline_sql(baseline_sql)
.await
.context("Failed to extract tables from baseline SQL")?;
let snapshot = SchemaSnapshot {
timestamp: baseline_record.get::<chrono::DateTime<chrono::Utc>, _>("applied_at"),
checksum: baseline_record.get::<String, _>("checksum"),
tables: baseline_tables,
views: HashMap::new(), indexes: HashMap::new(), statistics,
};
Ok(snapshot)
}
async fn capture_current_schema_snapshot(&self) -> Result<SchemaSnapshot> {
let introspector = crate::introspection::DatabaseIntrospector::new(self.pool.clone());
let current_tables = introspector
.introspect_tables()
.await
.context("Failed to introspect current database schema")?;
let tables: HashMap<String, Table> = current_tables
.into_iter()
.map(|table| (table.name.clone(), table))
.collect();
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
let mut sorted_tables: Vec<_> = tables.iter().collect();
sorted_tables.sort_by(|a, b| a.0.cmp(b.0));
for (name, table) in sorted_tables {
name.hash(&mut hasher);
table.columns.len().hash(&mut hasher);
}
let checksum = format!("{:x}", hasher.finish());
let table_count = tables.len();
let total_columns = tables.values().map(|t| t.columns.len()).sum();
let snapshot = SchemaSnapshot {
timestamp: Utc::now(),
checksum,
tables,
views: HashMap::new(), indexes: HashMap::new(), statistics: crate::migrate::baseline::SchemaStatistics {
table_count,
view_count: 0,
index_count: 0,
function_count: 0,
trigger_count: 0,
composite_type_count: 0,
total_columns,
total_constraints: 0,
},
};
Ok(snapshot)
}
async fn extract_tables_from_baseline_sql(
&self,
baseline_sql: &str,
) -> Result<HashMap<String, Table>> {
let mut baseline_table_names = HashSet::new();
for line in baseline_sql.lines() {
let line = line.trim();
if line.starts_with("-- Table: ") {
if let Some(table_name) = line.strip_prefix("-- Table: ") {
baseline_table_names.insert(table_name.to_string());
}
}
}
if baseline_table_names.is_empty() {
for line in baseline_sql.lines() {
let line = line.trim().to_uppercase();
if line.starts_with("CREATE TABLE ") {
if let Some(rest) = line.strip_prefix("CREATE TABLE ") {
if let Some(table_name) = rest.split_whitespace().next() {
let clean_name = table_name.trim_end_matches('(');
baseline_table_names.insert(clean_name.to_lowercase());
}
}
}
}
}
let introspector = crate::introspection::DatabaseIntrospector::new(self.pool.clone());
let all_current_tables = introspector
.introspect_tables()
.await
.context("Failed to introspect current database schema")?;
let baseline_tables: HashMap<String, Table> = all_current_tables
.into_iter()
.filter(|table| baseline_table_names.contains(&table.name))
.map(|table| (table.name.clone(), table))
.collect();
Ok(baseline_tables)
}
fn intelligent_schema_compare(
&self,
baseline: &SchemaSnapshot,
current: &SchemaSnapshot,
) -> Result<Vec<IntelligentSchemaDiff>> {
let mut changes = Vec::new();
for (table_name, current_table) in ¤t.tables {
match baseline.tables.get(table_name) {
None => {
changes.push(IntelligentSchemaDiff::TableAdded {
name: table_name.clone(),
table: current_table.clone(),
safety_level: SafetyLevel::Safe,
impact: ImpactLevel::Low,
});
}
Some(baseline_table) => {
if let Some(table_changes) =
self.compare_table_structures(baseline_table, current_table)?
{
changes.push(IntelligentSchemaDiff::TableModified {
name: table_name.clone(),
changes: table_changes.changes,
safety_level: table_changes.safety_level,
impact: table_changes.impact,
});
}
}
}
}
for (table_name, baseline_table) in &baseline.tables {
if !current.tables.contains_key(table_name) {
changes.push(IntelligentSchemaDiff::TableDropped {
name: table_name.clone(),
table: baseline_table.clone(),
safety_level: SafetyLevel::Dangerous,
impact: ImpactLevel::High,
});
}
}
Ok(changes)
}
fn compare_table_structures(
&self,
baseline_table: &Table,
current_table: &Table,
) -> Result<Option<TableModification>> {
let mut changes = Vec::new();
let mut max_safety = SafetyLevel::Safe;
let mut max_impact = ImpactLevel::Low;
let current_cols: HashMap<String, &Column> = current_table
.columns
.iter()
.map(|col| (col.name.clone(), col))
.collect();
let baseline_cols: HashMap<String, &Column> = baseline_table
.columns
.iter()
.map(|col| (col.name.clone(), col))
.collect();
for (col_name, current_col) in ¤t_cols {
match baseline_cols.get(col_name) {
None => {
let safety = if current_col.nullable {
SafetyLevel::Safe
} else {
SafetyLevel::Risky
};
changes.push(DetailedTableChange::ColumnAdded {
name: col_name.clone(),
column: (*current_col).clone(),
safety_level: safety.clone(),
});
if safety > max_safety {
max_safety = safety;
}
}
Some(baseline_col) => {
if baseline_col != current_col {
let (safety, impact) =
self.analyze_column_change(baseline_col, current_col);
changes.push(DetailedTableChange::ColumnModified {
name: col_name.clone(),
old_column: (*baseline_col).clone(),
new_column: (*current_col).clone(),
safety_level: safety.clone(),
impact: impact.clone(),
});
if safety > max_safety {
max_safety = safety;
}
if impact > max_impact {
max_impact = impact;
}
}
}
}
}
for (col_name, baseline_col) in &baseline_cols {
if !current_cols.contains_key(col_name) {
changes.push(DetailedTableChange::ColumnDropped {
name: col_name.clone(),
column: (*baseline_col).clone(),
safety_level: SafetyLevel::Dangerous,
});
max_safety = SafetyLevel::Dangerous;
max_impact = ImpactLevel::High;
}
}
if changes.is_empty() {
Ok(None)
} else {
Ok(Some(TableModification {
changes,
safety_level: max_safety,
impact: max_impact,
}))
}
}
fn analyze_column_change(
&self,
old_col: &Column,
new_col: &Column,
) -> (SafetyLevel, ImpactLevel) {
let mut safety = SafetyLevel::Safe;
let mut impact = ImpactLevel::Low;
if old_col.nullable && !new_col.nullable {
safety = SafetyLevel::Dangerous; impact = ImpactLevel::High;
}
if old_col.column_type != new_col.column_type {
safety = SafetyLevel::Risky; impact = ImpactLevel::Medium;
}
if old_col.default != new_col.default {
safety = std::cmp::max(safety, SafetyLevel::Risky);
impact = std::cmp::max(impact, ImpactLevel::Medium);
}
(safety, impact)
}
async fn generate_migration_file(
&self,
changes: &[IntelligentSchemaDiff],
migrations_dir: &std::path::Path,
) -> Result<String> {
let timestamp = Utc::now().format("%Y%m%d_%H%M%S").to_string();
let migration_name = format!("{}_schema_changes_generated", timestamp);
let migration_file = migrations_dir.join(format!("{}.sql", migration_name));
let mut migration_content = String::new();
migration_content.push_str(&format!("-- Migration: {}\n", migration_name));
migration_content.push_str(&format!(
"-- Generated at: {} UTC\n",
Utc::now().format("%Y-%m-%d %H:%M:%S")
));
migration_content.push_str("-- AUTOMATICALLY GENERATED - Review before applying!\n\n");
let dangerous_changes: Vec<_> = changes
.iter()
.filter(|c| c.safety_level() >= SafetyLevel::Dangerous)
.collect();
if !dangerous_changes.is_empty() {
migration_content.push_str(
"-- ⚠️ DANGER: This migration contains potentially destructive changes!\n",
);
migration_content.push_str("-- Review carefully before applying to production.\n");
for change in &dangerous_changes {
migration_content.push_str(&format!("-- DANGEROUS: {}\n", change.description()));
}
migration_content.push_str("\n");
}
migration_content.push_str("-- UP\n");
for change in changes {
migration_content.push_str(&change.generate_up_sql());
migration_content.push_str("\n");
}
migration_content.push_str("\n-- DOWN\n");
for change in changes.iter().rev() {
migration_content.push_str(&change.generate_down_sql());
migration_content.push_str("\n");
}
std::fs::write(&migration_file, migration_content)
.context("Failed to write migration file")?;
Ok(migration_file.to_string_lossy().to_string())
}
}
#[derive(Debug, Clone)]
pub enum IntelligentSchemaDiff {
TableAdded {
name: String,
table: Table,
safety_level: SafetyLevel,
impact: ImpactLevel,
},
TableDropped {
name: String,
table: Table,
safety_level: SafetyLevel,
impact: ImpactLevel,
},
TableModified {
name: String,
changes: Vec<DetailedTableChange>,
safety_level: SafetyLevel,
impact: ImpactLevel,
},
}
impl IntelligentSchemaDiff {
pub fn safety_level(&self) -> SafetyLevel {
match self {
Self::TableAdded { safety_level, .. } => safety_level.clone(),
Self::TableDropped { safety_level, .. } => safety_level.clone(),
Self::TableModified { safety_level, .. } => safety_level.clone(),
}
}
pub fn description(&self) -> String {
match self {
Self::TableAdded { name, .. } => format!("Add table '{}'", name),
Self::TableDropped { name, .. } => format!("Drop table '{}'", name),
Self::TableModified { name, changes, .. } => {
format!("Modify table '{}' ({} changes)", name, changes.len())
}
}
}
pub fn generate_up_sql(&self) -> String {
match self {
Self::TableAdded { name, table, .. } => {
format!("-- Add table {}\n{}", name, table.generate_ddl())
}
Self::TableDropped { name, .. } => {
format!("-- Drop table {}\nDROP TABLE IF EXISTS {};", name, name)
}
Self::TableModified { name, changes, .. } => {
let mut sql = format!("-- Modify table {}\n", name);
for change in changes {
sql.push_str(&change.generate_up_sql(name));
sql.push_str("\n");
}
sql
}
}
}
pub fn generate_down_sql(&self) -> String {
match self {
Self::TableAdded { name, .. } => {
format!(
"-- Reverse: Drop table {}\nDROP TABLE IF EXISTS {};",
name, name
)
}
Self::TableDropped { name, table, .. } => {
format!("-- Reverse: Add table {}\n{}", name, table.generate_ddl())
}
Self::TableModified { name, changes, .. } => {
let mut sql = format!("-- Reverse: Modify table {}\n", name);
for change in changes.iter().rev() {
sql.push_str(&change.generate_down_sql(name));
sql.push_str("\n");
}
sql
}
}
}
}
#[derive(Debug, Clone)]
pub struct TableModification {
pub changes: Vec<DetailedTableChange>,
pub safety_level: SafetyLevel,
pub impact: ImpactLevel,
}
#[derive(Debug, Clone)]
pub enum DetailedTableChange {
ColumnAdded {
name: String,
column: Column,
safety_level: SafetyLevel,
},
ColumnDropped {
name: String,
column: Column,
safety_level: SafetyLevel,
},
ColumnModified {
name: String,
old_column: Column,
new_column: Column,
safety_level: SafetyLevel,
impact: ImpactLevel,
},
}
impl DetailedTableChange {
pub fn generate_up_sql(&self, table_name: &str) -> String {
match self {
Self::ColumnAdded { name, column, .. } => {
format!(
"ALTER TABLE {} ADD COLUMN {} {};",
table_name,
name,
column.generate_column_definition()
)
}
Self::ColumnDropped { name, .. } => {
format!("ALTER TABLE {} DROP COLUMN IF EXISTS {};", table_name, name)
}
Self::ColumnModified {
name, new_column, ..
} => {
format!(
"ALTER TABLE {} ALTER COLUMN {} TYPE {};",
table_name,
name,
new_column.column_type.to_sql()
)
}
}
}
pub fn generate_down_sql(&self, table_name: &str) -> String {
match self {
Self::ColumnAdded { name, .. } => {
format!("ALTER TABLE {} DROP COLUMN IF EXISTS {};", table_name, name)
}
Self::ColumnDropped { name, column, .. } => {
format!(
"ALTER TABLE {} ADD COLUMN {} {};",
table_name,
name,
column.generate_column_definition()
)
}
Self::ColumnModified {
name, old_column, ..
} => {
format!(
"ALTER TABLE {} ALTER COLUMN {} TYPE {};",
table_name,
name,
old_column.column_type.to_sql()
)
}
}
}
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq)]
pub enum SafetyLevel {
Safe, Risky, Dangerous, }
#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq)]
pub enum ImpactLevel {
Low, Medium, High, }