reinhardt-db 0.1.0

Django-style database layer for Reinhardt framework
Documentation
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Migration squashing
//!
//! This module provides functionality to combine multiple migrations into a single migration,
//! inspired by Django's `squashmigrations` command.
//!
//! # Example
//!
//! ```rust
//! use reinhardt_db::migrations::squash::{MigrationSquasher, SquashOptions};
//! use reinhardt_db::migrations::Migration;
//!
//! // Create migrations to squash
//! let migration1 = Migration::new("0001_initial", "myapp");
//! let migration2 = Migration::new("0002_add_field", "myapp")
//!     .add_dependency("myapp", "0001_initial");
//! let migration3 = Migration::new("0003_alter_field", "myapp")
//!     .add_dependency("myapp", "0002_add_field");
//!
//! let migrations = vec![migration1, migration2, migration3];
//!
//! // Squash them into a single migration
//! let squasher = MigrationSquasher::new();
//! let options = SquashOptions::default();
//! let squashed = squasher.squash(&migrations, "0001_squashed_0003", options).unwrap();
//!
//! assert_eq!(squashed.name, "0001_squashed_0003");
//! assert_eq!(squashed.replaces.len(), 3);
//! ```

use super::{Migration, MigrationError, Operation, Result};
use std::collections::HashSet;

/// Options for migration squashing
///
/// # Example
///
/// ```rust
/// use reinhardt_db::migrations::squash::SquashOptions;
///
/// let options = SquashOptions::default();
/// assert!(options.optimize);
/// assert!(!options.no_optimize);
/// ```
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct SquashOptions {
	/// Enable operation optimization (remove redundant operations)
	pub optimize: bool,
	/// Disable optimization (keep all operations)
	pub no_optimize: bool,
}

impl Default for SquashOptions {
	fn default() -> Self {
		Self {
			optimize: true,
			no_optimize: false,
		}
	}
}

/// Migration squasher
///
/// Combines multiple sequential migrations into a single migration.
///
/// # Example
///
/// ```rust
/// use reinhardt_db::migrations::squash::MigrationSquasher;
/// use reinhardt_db::migrations::Migration;
///
/// let squasher = MigrationSquasher::new();
/// let migrations = vec![Migration::new("0001_initial", "myapp")];
/// let squashed = squasher.squash(&migrations, "0001_squashed", Default::default()).unwrap();
/// ```
pub struct MigrationSquasher {
	_private: (),
}

impl MigrationSquasher {
	/// Create a new migration squasher
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_db::migrations::squash::MigrationSquasher;
	///
	/// let squasher = MigrationSquasher::new();
	/// ```
	pub fn new() -> Self {
		Self { _private: () }
	}

	/// Squash multiple migrations into one
	///
	/// # Arguments
	///
	/// * `migrations` - List of migrations to squash (must be sequential)
	/// * `squashed_name` - Name for the squashed migration
	/// * `options` - Squashing options
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_db::migrations::squash::{MigrationSquasher, SquashOptions};
	/// use reinhardt_db::migrations::Migration;
	///
	/// let migration1 = Migration::new("0001_initial", "myapp");
	/// let migration2 = Migration::new("0002_add_field", "myapp");
	/// let migrations = vec![migration1, migration2];
	///
	/// let squasher = MigrationSquasher::new();
	/// let squashed = squasher.squash(&migrations, "0001_squashed_0002", SquashOptions::default()).unwrap();
	///
	/// assert_eq!(squashed.name, "0001_squashed_0002");
	/// ```
	pub fn squash(
		&self,
		migrations: &[Migration],
		squashed_name: impl Into<String>,
		options: SquashOptions,
	) -> Result<Migration> {
		if migrations.is_empty() {
			return Err(MigrationError::InvalidMigration(
				"Cannot squash empty migration list".to_string(),
			));
		}

		// Validate all migrations belong to the same app
		let app_label = &migrations[0].app_label;
		if !migrations.iter().all(|m| m.app_label == *app_label) {
			return Err(MigrationError::InvalidMigration(
				"All migrations must belong to the same app".to_string(),
			));
		}

		// Collect all operations
		let mut operations = Vec::new();
		for migration in migrations {
			operations.extend(migration.operations.clone());
		}

		// Optimize operations if enabled
		if options.optimize && !options.no_optimize {
			operations = self.optimize_operations(operations);
		}

		// Create squashed migration
		let mut squashed = Migration::new(squashed_name, app_label.clone());
		squashed.operations = operations;

		// Record which migrations this replaces
		for migration in migrations {
			squashed
				.replaces
				.push((migration.app_label.clone(), migration.name.clone()));
		}

		// Build a HashSet of squashed migration identities for O(1) lookup
		let squashed_set: HashSet<(&str, &str)> = migrations
			.iter()
			.map(|m| (m.app_label.as_str(), m.name.as_str()))
			.collect();

		// Collect dependencies from all migrations (external dependencies only)
		let mut seen_deps: HashSet<(&str, &str)> = HashSet::new();
		for migration in migrations {
			for (dep_app, dep_name) in &migration.dependencies {
				// Only include dependencies outside the squashed range
				if *dep_app != *app_label
					|| !squashed_set.contains(&(dep_app.as_str(), dep_name.as_str()))
				{
					// Avoid duplicate dependencies via HashSet lookup
					if seen_deps.insert((dep_app.as_str(), dep_name.as_str())) {
						squashed
							.dependencies
							.push((dep_app.clone(), dep_name.clone()));
					}
				}
			}
		}

		Ok(squashed)
	}

	/// Optimize operations by removing redundant ones
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_db::migrations::squash::MigrationSquasher;
	/// use reinhardt_db::migrations::{Operation, ColumnDefinition, FieldType};
	///
	/// let squasher = MigrationSquasher::new();
	///
	/// // Create table then drop it - both can be removed
	/// let ops = vec![
	///     Operation::CreateTable {
	///         name: "temp".to_string(),
	///         columns: vec![ColumnDefinition::new("id", FieldType::Integer)],
	///         constraints: vec![],
	///         without_rowid: None,
	///         interleave_in_parent: None,
	///         partition: None,
	///     },
	///     Operation::DropTable {
	///         name: "temp".to_string(),
	///     },
	/// ];
	///
	/// let optimized = squasher.optimize_operations(ops);
	/// assert_eq!(optimized.len(), 0);
	/// ```
	pub fn optimize_operations(&self, operations: Vec<Operation>) -> Vec<Operation> {
		let mut optimized = Vec::new();
		let mut created_tables = HashSet::new();
		let mut dropped_tables = HashSet::new();

		for operation in operations {
			let should_push = match &operation {
				Operation::CreateTable { name, .. } => {
					// Remove from dropped_tables if re-created
					dropped_tables.remove(name);
					created_tables.insert(name.clone());
					true
				}
				Operation::DropTable { name } => {
					// If table was just created, remove both operations
					if created_tables.contains(name) {
						optimized.retain(
							|op| !matches!(op, Operation::CreateTable { name: table_name, .. } if table_name == name),
						);
						created_tables.remove(name);
						false
					} else {
						dropped_tables.insert(name.clone());
						true
					}
				}
				Operation::AddColumn { table, .. } => {
					// Skip if table was dropped
					!dropped_tables.contains(table)
				}
				Operation::DropColumn { table, column } => {
					// Remove corresponding AddColumn if exists
					let had_add = optimized.iter().any(|op| {
						matches!(op, Operation::AddColumn { table: t, column: c, .. } if t == table && c.name == *column)
					});

					if had_add {
						optimized.retain(|op| {
							!matches!(op, Operation::AddColumn { table: t, column: c, .. } if t == table && c.name == *column)
						});
						false
					} else {
						!dropped_tables.contains(table)
					}
				}
				Operation::AlterColumn { table, .. } => {
					// Skip if table was dropped
					!dropped_tables.contains(table)
				}
				Operation::RenameTable { old_name, .. } => {
					// Skip if table was dropped
					!dropped_tables.contains(old_name)
				}
				Operation::RenameColumn { table, .. } => {
					// Skip if table was dropped
					!dropped_tables.contains(table)
				}
				_ => true,
			};

			if should_push {
				optimized.push(operation);
			}
		}

		optimized
	}
}

impl Default for MigrationSquasher {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::migrations::{ColumnDefinition, FieldType};

	#[test]
	fn test_squash_basic() {
		let migration1 = Migration::new("0001_initial", "myapp");
		let migration2 =
			Migration::new("0002_add_field", "myapp").add_dependency("myapp", "0001_initial");

		let migrations = vec![migration1, migration2];

		let squasher = MigrationSquasher::new();
		let squashed = squasher
			.squash(&migrations, "0001_squashed_0002", SquashOptions::default())
			.unwrap();

		assert_eq!(squashed.name, "0001_squashed_0002");
		assert_eq!(squashed.app_label, "myapp");
		assert_eq!(squashed.replaces.len(), 2);
	}

	#[test]
	fn test_squash_empty_migrations() {
		let squasher = MigrationSquasher::new();
		let result = squasher.squash(&[], "squashed", SquashOptions::default());

		assert!(result.is_err());
	}

	#[test]
	fn test_squash_different_apps() {
		let migration1 = Migration::new("0001_initial", "app1");
		let migration2 = Migration::new("0002_add_field", "app2");

		let migrations = vec![migration1, migration2];

		let squasher = MigrationSquasher::new();
		let result = squasher.squash(&migrations, "squashed", SquashOptions::default());

		assert!(result.is_err());
	}

	#[test]
	fn test_optimize_create_drop_table() {
		let squasher = MigrationSquasher::new();

		let ops = vec![
			Operation::CreateTable {
				name: "temp".to_string(),
				columns: vec![ColumnDefinition::new("id", FieldType::Integer)],
				constraints: vec![],
				without_rowid: None,
				partition: None,
				interleave_in_parent: None,
			},
			Operation::DropTable {
				name: "temp".to_string(),
			},
		];

		let optimized = squasher.optimize_operations(ops);
		assert_eq!(optimized.len(), 0);
	}

	#[test]
	fn test_optimize_add_drop_column() {
		let squasher = MigrationSquasher::new();

		let ops = vec![
			Operation::AddColumn {
				table: "users".to_string(),
				column: ColumnDefinition::new("temp_field", FieldType::VarChar(100)),
				mysql_options: None,
			},
			Operation::DropColumn {
				table: "users".to_string(),
				column: "temp_field".to_string(),
			},
		];

		let optimized = squasher.optimize_operations(ops);
		assert_eq!(optimized.len(), 0);
	}

	#[test]
	fn test_optimize_no_optimization() {
		let squasher = MigrationSquasher::new();

		let ops = vec![
			Operation::CreateTable {
				name: "users".to_string(),
				columns: vec![ColumnDefinition::new("id", FieldType::Integer)],
				constraints: vec![],
				without_rowid: None,
				partition: None,
				interleave_in_parent: None,
			},
			Operation::AddColumn {
				table: "users".to_string(),
				column: ColumnDefinition::new("name", FieldType::VarChar(100)),
				mysql_options: None,
			},
		];

		let optimized = squasher.optimize_operations(ops.clone());
		assert_eq!(optimized.len(), ops.len());
	}

	#[test]
	fn test_squash_with_operations() {
		let migration1 =
			Migration::new("0001_initial", "myapp").add_operation(Operation::CreateTable {
				name: "users".to_string(),
				columns: vec![ColumnDefinition::new(
					"id",
					FieldType::Custom("INTEGER PRIMARY KEY".to_string()),
				)],
				constraints: vec![],
				without_rowid: None,
				partition: None,
				interleave_in_parent: None,
			});

		let migration2 = Migration::new("0002_add_field", "myapp")
			.add_dependency("myapp", "0001_initial")
			.add_operation(Operation::AddColumn {
				table: "users".to_string(),
				column: ColumnDefinition::new("name", FieldType::VarChar(100)),
				mysql_options: None,
			});

		let migrations = vec![migration1, migration2];

		let squasher = MigrationSquasher::new();
		let squashed = squasher
			.squash(&migrations, "0001_squashed_0002", SquashOptions::default())
			.unwrap();

		assert_eq!(squashed.operations.len(), 2);
	}

	#[test]
	fn test_squash_external_dependencies() {
		let migration1 =
			Migration::new("0001_initial", "myapp").add_dependency("other_app", "0001_initial");

		let migration2 =
			Migration::new("0002_add_field", "myapp").add_dependency("myapp", "0001_initial");

		let migrations = vec![migration1, migration2];

		let squasher = MigrationSquasher::new();
		let squashed = squasher
			.squash(&migrations, "0001_squashed_0002", SquashOptions::default())
			.unwrap();

		// Should keep external dependency
		assert_eq!(squashed.dependencies.len(), 1);
		assert_eq!(squashed.dependencies[0].0, "other_app");
	}
}