1use anyhow::Result;
7use std::collections::HashMap;
8
9#[derive(Debug, Clone)]
11pub struct MigrationFile {
12 pub filename: String,
13 pub up_sql: String,
14 pub down_sql: String,
15 pub description: String,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub enum SchemaChangeType {
21 CreateTable,
22 DropTable,
23 AddColumn,
24 DropColumn,
25 AlterColumn,
26 CreateIndex,
27 DropIndex,
28 CreateCompositeType,
29 DropCompositeType,
30 CreateEnum,
31 DropEnum,
32}
33
34#[derive(Debug, Clone)]
36pub struct SchemaChange {
37 pub change_type: SchemaChangeType,
38 pub table_name: String,
39 pub object_name: Option<String>, pub up_sql: String,
41 pub down_sql: String,
42 pub description: String,
43}
44
45pub trait MigrationStrategy {
47 fn generate_migrations(&self, changes: Vec<SchemaChange>) -> Result<Vec<MigrationFile>>;
49
50 fn name(&self) -> &'static str;
52
53 fn description(&self) -> &'static str;
55}
56
57pub struct ConservativeStrategy;
59
60impl MigrationStrategy for ConservativeStrategy {
61 fn generate_migrations(&self, changes: Vec<SchemaChange>) -> Result<Vec<MigrationFile>> {
62 let mut migrations = Vec::new();
63 let base_timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
64
65 for (index, change) in changes.into_iter().enumerate() {
66 let timestamp = if index == 0 {
67 base_timestamp.to_string()
68 } else {
69 let time_offset = chrono::Utc::now() + chrono::Duration::seconds(index as i64);
71 time_offset.format("%Y%m%d_%H%M%S").to_string()
72 };
73
74 let filename = match change.change_type {
75 SchemaChangeType::CreateTable => {
76 format!("{}_create_table_{}.sql", timestamp, change.table_name)
77 }
78 SchemaChangeType::DropTable => {
79 format!("{}_drop_table_{}.sql", timestamp, change.table_name)
80 }
81 SchemaChangeType::AddColumn => {
82 let column_name = change.object_name.as_deref().unwrap_or("unknown");
83 format!(
84 "{}_add_column_{}_{}.sql",
85 timestamp, change.table_name, column_name
86 )
87 }
88 SchemaChangeType::DropColumn => {
89 let column_name = change.object_name.as_deref().unwrap_or("unknown");
90 format!(
91 "{}_drop_column_{}_{}.sql",
92 timestamp, change.table_name, column_name
93 )
94 }
95 SchemaChangeType::AlterColumn => {
96 let column_name = change.object_name.as_deref().unwrap_or("unknown");
97 format!(
98 "{}_alter_column_{}_{}.sql",
99 timestamp, change.table_name, column_name
100 )
101 }
102 SchemaChangeType::CreateIndex => {
103 let index_name = change.object_name.as_deref().unwrap_or("unknown");
104 format!("{}_create_index_{}.sql", timestamp, index_name)
105 }
106 SchemaChangeType::DropIndex => {
107 let index_name = change.object_name.as_deref().unwrap_or("unknown");
108 format!("{}_drop_index_{}.sql", timestamp, index_name)
109 }
110 SchemaChangeType::CreateCompositeType => {
111 let type_name = change.object_name.as_deref().unwrap_or("unknown");
112 format!("{}_create_composite_{}.sql", timestamp, type_name)
113 }
114 SchemaChangeType::DropCompositeType => {
115 let type_name = change.object_name.as_deref().unwrap_or("unknown");
116 format!("{}_drop_composite_{}.sql", timestamp, type_name)
117 }
118 SchemaChangeType::CreateEnum => {
119 let enum_name = change.object_name.as_deref().unwrap_or("unknown");
120 format!("{}_create_enum_{}.sql", timestamp, enum_name)
121 }
122 SchemaChangeType::DropEnum => {
123 let enum_name = change.object_name.as_deref().unwrap_or("unknown");
124 format!("{}_drop_enum_{}.sql", timestamp, enum_name)
125 }
126 };
127
128 migrations.push(MigrationFile {
129 filename,
130 up_sql: change.up_sql,
131 down_sql: change.down_sql,
132 description: change.description,
133 });
134 }
135
136 Ok(migrations)
137 }
138
139 fn name(&self) -> &'static str {
140 "Conservative"
141 }
142
143 fn description(&self) -> &'static str {
144 "Generate separate migration files per change type (safer, more granular)"
145 }
146}
147
148pub struct GroupedStrategy;
150
151impl MigrationStrategy for GroupedStrategy {
152 fn generate_migrations(&self, changes: Vec<SchemaChange>) -> Result<Vec<MigrationFile>> {
153 let mut grouped_changes: HashMap<String, Vec<SchemaChange>> = HashMap::new();
154
155 for change in changes {
157 let group_key = match change.change_type {
158 SchemaChangeType::CreateTable | SchemaChangeType::DropTable => {
159 "table_operations".to_string()
160 }
161 SchemaChangeType::AddColumn
162 | SchemaChangeType::DropColumn
163 | SchemaChangeType::AlterColumn => {
164 format!("column_changes_{}", change.table_name)
165 }
166 SchemaChangeType::CreateIndex | SchemaChangeType::DropIndex => {
167 format!("index_changes_{}", change.table_name)
168 }
169 SchemaChangeType::CreateCompositeType | SchemaChangeType::DropCompositeType => {
170 "composite_type_changes".to_string()
171 }
172 SchemaChangeType::CreateEnum | SchemaChangeType::DropEnum => {
173 "enum_changes".to_string()
174 }
175 };
176
177 grouped_changes
178 .entry(group_key)
179 .or_insert_with(Vec::new)
180 .push(change);
181 }
182
183 let mut migrations = Vec::new();
185 let base_timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
186
187 for (index, (group_key, group_changes)) in grouped_changes.into_iter().enumerate() {
188 let timestamp = if index == 0 {
189 base_timestamp.to_string()
190 } else {
191 let time_offset = chrono::Utc::now() + chrono::Duration::minutes(index as i64);
193 time_offset.format("%Y%m%d_%H%M%S").to_string()
194 };
195
196 let filename = format!("{}_{}.sql", timestamp, group_key);
197
198 let mut up_sql = String::new();
200 let mut down_sql = String::new();
201 let mut descriptions = Vec::new();
202
203 for change in &group_changes {
204 up_sql.push_str(&format!("-- {}\n", change.description));
205 up_sql.push_str(&change.up_sql);
206 up_sql.push_str("\n\n");
207
208 down_sql.push_str(&format!("-- Rollback: {}\n", change.description));
209 down_sql.push_str(&change.down_sql);
210 down_sql.push_str("\n\n");
211
212 descriptions.push(change.description.clone());
213 }
214
215 let description = if group_changes.len() == 1 {
216 descriptions[0].clone()
217 } else {
218 format!("Grouped changes: {}", descriptions.join(", "))
219 };
220
221 migrations.push(MigrationFile {
222 filename,
223 up_sql,
224 down_sql,
225 description,
226 });
227 }
228
229 migrations.sort_by(|a, b| a.filename.cmp(&b.filename));
231
232 Ok(migrations)
233 }
234
235 fn name(&self) -> &'static str {
236 "Grouped"
237 }
238
239 fn description(&self) -> &'static str {
240 "Group related changes into single migrations (fewer files, faster deployment)"
241 }
242}
243
244pub fn create_strategy(strategy_name: &str) -> Result<Box<dyn MigrationStrategy>> {
246 match strategy_name.to_lowercase().as_str() {
247 "conservative" => Ok(Box::new(ConservativeStrategy)),
248 "grouped" => Ok(Box::new(GroupedStrategy)),
249 _ => Err(anyhow::anyhow!(
250 "Unknown migration strategy: {}",
251 strategy_name
252 )),
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 fn create_sample_changes() -> Vec<SchemaChange> {
261 vec![
262 SchemaChange {
263 change_type: SchemaChangeType::CreateTable,
264 table_name: "users".to_string(),
265 object_name: None,
266 up_sql: "CREATE TABLE users (id SERIAL PRIMARY KEY);".to_string(),
267 down_sql: "DROP TABLE users;".to_string(),
268 description: "Create users table".to_string(),
269 },
270 SchemaChange {
271 change_type: SchemaChangeType::AddColumn,
272 table_name: "users".to_string(),
273 object_name: Some("email".to_string()),
274 up_sql: "ALTER TABLE users ADD COLUMN email VARCHAR(255);".to_string(),
275 down_sql: "ALTER TABLE users DROP COLUMN email;".to_string(),
276 description: "Add email column to users".to_string(),
277 },
278 ]
279 }
280
281 #[test]
282 fn test_conservative_strategy() {
283 let strategy = ConservativeStrategy;
284 let changes = create_sample_changes();
285 let migrations = strategy.generate_migrations(changes).unwrap();
286
287 assert_eq!(migrations.len(), 2);
288 assert!(migrations[0].filename.contains("create_table_users"));
289 assert!(migrations[1].filename.contains("add_column_users_email"));
290 }
291
292 #[test]
293 fn test_grouped_strategy() {
294 let strategy = GroupedStrategy;
295 let changes = create_sample_changes();
296 let migrations = strategy.generate_migrations(changes).unwrap();
297
298 assert!(migrations.len() <= 2);
300
301 for migration in migrations {
303 assert!(!migration.up_sql.is_empty());
304 assert!(!migration.down_sql.is_empty());
305 }
306 }
307
308 #[test]
309 fn test_strategy_factory() {
310 let conservative = create_strategy("conservative").unwrap();
311 assert_eq!(conservative.name(), "Conservative");
312
313 let grouped = create_strategy("grouped").unwrap();
314 assert_eq!(grouped.name(), "Grouped");
315
316 assert!(create_strategy("unknown").is_err());
317 }
318}