1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
use std::{collections::HashMap, sync::Arc};
use sqlx::{Pool, Postgres};
use crate::{
data_definition::{
database_definition::DatabaseDefinition,
table::{
DatabaseTableDefinition, ForeignKeyConstraint, Identifier, TableColumn,
TableConstraint, TableConstraintDetail,
},
},
migration::{AlterColumn, AlterColumnAction, AlterTableAction},
BuildSql,
};
use super::{AlterTable, CreateTable};
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum MigrationAction<T> {
AlterTable(AlterTable),
CreateTable(CreateTable<T>),
DropTable(Identifier),
}
impl<T> BuildSql for MigrationAction<T> {
fn build_sql(
&self,
builder: &mut sqlx::QueryBuilder<'_, Postgres>,
) {
match self {
MigrationAction::AlterTable(alter_table) => alter_table.build_sql(builder),
MigrationAction::CreateTable(create_table) => create_table.build_sql(builder),
MigrationAction::DropTable(table_ident) => {
builder.push("DROP TABLE IF EXISTS ").push(&**table_ident);
},
};
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Migration<T> {
pub actions: Vec<MigrationAction<T>>,
}
impl<T> Migration<T> {
pub async fn run(
self,
db_pool: &Pool<Postgres>,
) -> Result<(), crate::Error> {
let mut builder = sqlx::QueryBuilder::new("");
self.build_sql(&mut builder);
builder.build().execute(db_pool).await?;
Ok(())
}
}
impl<T> BuildSql for Migration<T> {
fn build_sql(
&self,
builder: &mut sqlx::QueryBuilder<'_, Postgres>,
) {
for alter_table in &self.actions {
alter_table.build_sql(builder);
builder.push("\n");
}
}
}
impl<T> Migration<T>
where
T: std::fmt::Debug + Clone,
{
pub fn compare(
before: Option<&DatabaseDefinition<T>>,
after: &DatabaseDefinition<T>,
) -> Option<Self> {
let mut actions: Vec<MigrationAction<T>> = Vec::new();
fn build_table_map<T>(
db_def: &DatabaseDefinition<T>
) -> HashMap<&Identifier, &DatabaseTableDefinition<T>> {
let map = db_def.tables.iter().fold(HashMap::new(), |mut acc, table| {
acc.insert(&table.table_name, table);
acc
});
map
}
if let Some(before) = before {
// Build a map for quick lookup of after_tables, then compare each
let mut after_tables = build_table_map(after);
for table_before in &before.tables {
match after_tables
.remove(&table_before.table_name)
.map(|after_table| Self::compare_tables(table_before, after_table))
{
Some(None) => {
println!("NO CHANGES");
// No changes to the table
// Do nothing
},
Some(Some(mut table_diff)) => {
println!("[MODIFY TABLE]");
println!("before: {:?}", table_before);
// Table has been modified
actions.append(&mut table_diff.actions);
},
None => {
println!("[DELETE TABLE] {:?}", table_before);
// Table was not found in new tables, meaning it was deleted
// TODO: At the end, compare any deleted/added tables to see if there was just some renaming done.
let action = MigrationAction::DropTable(table_before.table_name.clone());
actions.push(action);
},
};
}
// Any remaining tables are new - add the CreateTable actions
actions.append(
&mut after_tables
.values()
.map(|table| MigrationAction::CreateTable(CreateTable::new((*table).clone())))
.collect(),
)
} else {
// New database - only creates!
let mut create_table_actions = after
.tables
.iter()
.map(|t| MigrationAction::CreateTable(CreateTable::new(t.clone())))
.collect();
actions.append(&mut create_table_actions);
}
if !actions.is_empty() {
Some(Self {
actions,
})
} else {
None
}
}
/// Returns `Some<Migration>` representing the steps required to go from `before` to `after`, or None if the inputs are the same.
///
/// # Arguments
///
/// * `before` - The existing table definition, before the new changes are applied.
/// * `after` - The new table definition, currently in use.
///
/// # Returns
///
fn compare_tables(
before: &DatabaseTableDefinition<T>,
after: &DatabaseTableDefinition<T>,
) -> Option<Self> {
let mut actions = Vec::<AlterTableAction>::new();
// Name changed
if before.table_name != after.table_name {
actions.push(AlterTableAction::Rename(after.table_name.clone()));
}
// Build a map for quick lookup of after_tables, then compare each
let mut after_columns: HashMap<&Identifier, &TableColumn> = after.columns.iter().collect();
for old_column in before.columns.values() {
match after_columns.remove(&old_column.column_name) {
Some(new_column) => {
let mut alter_column_actions = Vec::new();
if !old_column.column_type.eq(&new_column.column_type) {
alter_column_actions
.push(AlterColumnAction::SetType(new_column.column_type.clone()));
}
// * NONNULL calculation - Compares `NotNull`
{
// Uggggh this is really hacky. Wanna clean this up later.
// Find the existence of a `NotNull` constraint. If it does *not* exist (`.is_none()`) then the field *is* nullable.
// A confusing mess of double negative magic going on here.
let old_is_nullable = !old_column.constraints.iter().any(|c| match *c.detail {
// Allowed null unless NOT NULL
crate::data_definition::table::TableColumnConstraintDetail::NotNull => true,
_ => false,
});
let new_is_nullable = !new_column.constraints.iter().any(|c| {
matches!(
*c.detail,
crate::data_definition::table::TableColumnConstraintDetail::NotNull
)
});
if old_is_nullable != new_is_nullable {
alter_column_actions
.push(AlterColumnAction::SetNullability(new_is_nullable));
}
}
// * TODO: Foreign Key Changes
// We compare the columns, and add the _TABLE'S_ FK constraint, because we can't add the constraint to column except at creation.
// TODO: Do another pass for the FK constraints.
{
let old_fk = old_column.constraints.iter().find_map(|c| match &*c.detail {
crate::data_definition::table::TableColumnConstraintDetail::References(fk) => Some(fk),
_ => None,
});
let new_fk = new_column.constraints.iter().find_map(|c| match &*c.detail {
crate::data_definition::table::TableColumnConstraintDetail::References(fk) => Some(fk),
_ => None,
});
match (old_fk, new_fk) {
(None, None) => None,
(None, Some(new_fk)) => {
// FK was added
Some(AlterTableAction::AddConstraint(TableConstraint {
name: None, // TODO: Infer name. I might need to rework how these constraints work :facepalm:
detail: Arc::new(TableConstraintDetail::ForeignKey(
ForeignKeyConstraint {
ref_table: new_fk.ref_table.clone(),
ref_columns: vec![new_fk
.ref_column
.as_ref()
.unwrap()
.clone()],
columns: vec![new_column.clone()],
match_type: new_fk.match_type.clone(),
on_delete_action: new_fk.on_delete_action.clone(),
on_update_action: new_fk.on_update_action.clone(),
},
)),
}))
},
(Some(_), None) => todo!(), // DELETE constraint from column. Need a consistent way to name constraints in order to do this.
(Some(old_fk), Some(new_fk)) => {
if old_fk.ne(new_fk) {
todo!("Support for updating FKs not yet implemented")
} else {
None
}
}, // COMPARE constraints
};
}
if !alter_column_actions.is_empty() {
actions.push(AlterTableAction::AlterColumn(AlterColumn {
column_name: new_column.column_name.clone(),
actions: alter_column_actions,
}));
}
},
None => {
// Column Deleted
actions.push(AlterTableAction::DropColumn(old_column.column_name.clone()));
},
}
}
// Any remianing columns are new
for column in after_columns.values() {
actions.push(AlterTableAction::AddColumn((*column).clone()));
}
if !actions.is_empty() {
Some(Self {
actions: vec![MigrationAction::AlterTable(AlterTable {
table_name: after.table_name.clone(),
actions,
})],
})
} else {
None
}
}
}