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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! Schema history visualization tools
//!
//! This module provides tools for visualizing migration history and schema evolution,
//! inspired by tools like Rails schema visualizers and Flyway's schema history reporting.
//!
//! # Example
//!
//! ```rust
//! use reinhardt_db::migrations::visualization::{MigrationVisualizer, OutputFormat};
//! use reinhardt_db::migrations::Migration;
//!
//! 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 visualizer = MigrationVisualizer::new();
//! let graph = visualizer.generate_dependency_graph(&migrations, OutputFormat::Text);
//! ```

use super::Migration;
use super::recorder::MigrationRecord;
use std::collections::{HashMap, HashSet};

/// Output format for visualization
///
/// # Example
///
/// ```rust
/// use reinhardt_db::migrations::visualization::OutputFormat;
///
/// let format = OutputFormat::Text;
/// assert_eq!(format.extension(), "txt");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
	/// Plain text output
	Text,
	/// Markdown format
	Markdown,
	/// DOT graph format (for Graphviz)
	Dot,
	/// JSON format
	Json,
}

impl OutputFormat {
	/// Get file extension for this format
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_db::migrations::visualization::OutputFormat;
	///
	/// assert_eq!(OutputFormat::Text.extension(), "txt");
	/// assert_eq!(OutputFormat::Markdown.extension(), "md");
	/// assert_eq!(OutputFormat::Dot.extension(), "dot");
	/// assert_eq!(OutputFormat::Json.extension(), "json");
	/// ```
	pub fn extension(&self) -> &str {
		match self {
			OutputFormat::Text => "txt",
			OutputFormat::Markdown => "md",
			OutputFormat::Dot => "dot",
			OutputFormat::Json => "json",
		}
	}
}

/// Migration history entry
///
/// # Example
///
/// ```rust
/// use reinhardt_db::migrations::visualization::HistoryEntry;
///
/// let entry = HistoryEntry {
///     app_label: "myapp".to_string(),
///     migration_name: "0001_initial".to_string(),
///     applied_at: "2025-01-01 00:00:00".to_string(),
///     operations_count: 5,
/// };
/// ```
#[derive(Debug, Clone)]
pub struct HistoryEntry {
	/// The app label.
	pub app_label: String,
	/// The migration name.
	pub migration_name: String,
	/// The applied at.
	pub applied_at: String,
	/// The operations count.
	pub operations_count: usize,
}

impl HistoryEntry {
	/// Create from MigrationRecord
	pub fn from_record(record: &MigrationRecord, operations_count: usize) -> Self {
		Self {
			app_label: record.app.clone(),
			migration_name: record.name.clone(),
			applied_at: record.applied.to_rfc3339(),
			operations_count,
		}
	}
}

/// Migration visualizer
///
/// Generates visual representations of migration history and dependencies.
///
/// # Example
///
/// ```rust
/// use reinhardt_db::migrations::visualization::MigrationVisualizer;
///
/// let visualizer = MigrationVisualizer::new();
/// ```
pub struct MigrationVisualizer {
	_private: (),
}

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

	/// Generate dependency graph
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_db::migrations::visualization::{MigrationVisualizer, OutputFormat};
	/// use reinhardt_db::migrations::Migration;
	///
	/// 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 visualizer = MigrationVisualizer::new();
	/// let graph = visualizer.generate_dependency_graph(&migrations, OutputFormat::Text);
	/// assert!(graph.contains("0001_initial"));
	/// assert!(graph.contains("0002_add_field"));
	/// ```
	pub fn generate_dependency_graph(
		&self,
		migrations: &[Migration],
		format: OutputFormat,
	) -> String {
		match format {
			OutputFormat::Text => self.generate_text_graph(migrations),
			OutputFormat::Markdown => self.generate_markdown_graph(migrations),
			OutputFormat::Dot => self.generate_dot_graph(migrations),
			OutputFormat::Json => self.generate_json_graph(migrations),
		}
	}

	/// Generate timeline view of migrations
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_db::migrations::visualization::{MigrationVisualizer, HistoryEntry};
	///
	/// let entries = vec![
	///     HistoryEntry {
	///         app_label: "myapp".to_string(),
	///         migration_name: "0001_initial".to_string(),
	///         applied_at: "2025-01-01 00:00:00".to_string(),
	///         operations_count: 3,
	///     },
	/// ];
	///
	/// let visualizer = MigrationVisualizer::new();
	/// let timeline = visualizer.generate_timeline(&entries);
	/// assert!(timeline.contains("0001_initial"));
	/// ```
	pub fn generate_timeline(&self, history: &[HistoryEntry]) -> String {
		let mut output = String::new();
		output.push_str("Migration Timeline\n");
		output.push_str("==================\n\n");

		for entry in history {
			output.push_str(&format!(
				"[{}] {}.{} ({} operations)\n",
				entry.applied_at, entry.app_label, entry.migration_name, entry.operations_count
			));
		}

		output
	}

	/// Generate schema evolution report
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_db::migrations::visualization::MigrationVisualizer;
	/// use reinhardt_db::migrations::Migration;
	///
	/// let migrations = vec![Migration::new("0001_initial", "myapp")];
	/// let visualizer = MigrationVisualizer::new();
	/// let report = visualizer.generate_evolution_report(&migrations);
	/// assert!(report.contains("Schema Evolution"));
	/// ```
	pub fn generate_evolution_report(&self, migrations: &[Migration]) -> String {
		let mut output = String::new();
		output.push_str("Schema Evolution Report\n");
		output.push_str("=======================\n\n");

		// Group by app
		let mut by_app: HashMap<String, Vec<&Migration>> = HashMap::new();
		for migration in migrations {
			by_app
				.entry(migration.app_label.to_string())
				.or_default()
				.push(migration);
		}

		for (app, app_migrations) in by_app {
			output.push_str(&format!("\nApp: {}\n", app));
			output.push_str(&format!("{}\n", "-".repeat(app.len() + 5)));

			for migration in app_migrations {
				output.push_str(&format!(
					"  - {}: {} operations\n",
					migration.name,
					migration.operations.len()
				));
			}
		}

		output
	}

	fn generate_text_graph(&self, migrations: &[Migration]) -> String {
		let mut output = String::new();
		output.push_str("Migration Dependency Graph\n");
		output.push_str("==========================\n\n");

		for migration in migrations {
			output.push_str(&format!("{}.{}\n", migration.app_label, migration.name));

			if !migration.dependencies.is_empty() {
				output.push_str("  Dependencies:\n");
				for (app, name) in &migration.dependencies {
					output.push_str(&format!("    - {}.{}\n", app, name));
				}
			}

			output.push('\n');
		}

		output
	}

	fn generate_markdown_graph(&self, migrations: &[Migration]) -> String {
		let mut output = String::new();
		output.push_str("# Migration Dependency Graph\n\n");

		for migration in migrations {
			output.push_str(&format!(
				"## {}.{}\n\n",
				migration.app_label, migration.name
			));

			if !migration.dependencies.is_empty() {
				output.push_str("**Dependencies:**\n\n");
				for (app, name) in &migration.dependencies {
					output.push_str(&format!("- {}.{}\n", app, name));
				}
			}

			output.push_str(&format!(
				"\n**Operations:** {}\n\n",
				migration.operations.len()
			));
		}

		output
	}

	fn generate_dot_graph(&self, migrations: &[Migration]) -> String {
		let mut output = String::new();
		output.push_str("digraph migrations {\n");
		output.push_str("  rankdir=LR;\n");
		output.push_str("  node [shape=box];\n\n");

		// Generate nodes
		for migration in migrations {
			let node_id = format!("{}_{}", migration.app_label, migration.name);
			output.push_str(&format!(
				"  {} [label=\"{}.{}\"];\n",
				node_id.replace('-', "_"),
				migration.app_label,
				migration.name
			));
		}

		output.push('\n');

		// Generate edges
		for migration in migrations {
			let to_id = format!("{}_{}", migration.app_label, migration.name);
			for (dep_app, dep_name) in &migration.dependencies {
				let from_id = format!("{}_{}", dep_app, dep_name);
				output.push_str(&format!(
					"  {} -> {};\n",
					from_id.replace('-', "_"),
					to_id.replace('-', "_")
				));
			}
		}

		output.push_str("}\n");
		output
	}

	fn generate_json_graph(&self, migrations: &[Migration]) -> String {
		use serde_json::json;

		let nodes: Vec<_> = migrations
			.iter()
			.map(|m| {
				json!({
					"id": format!("{}.{}", m.app_label, m.name),
					"app": m.app_label,
					"name": m.name,
					"operations": m.operations.len(),
				})
			})
			.collect();

		let edges: Vec<_> = migrations
			.iter()
			.flat_map(|m| {
				m.dependencies.iter().map(move |(dep_app, dep_name)| {
					json!({
						"from": format!("{}.{}", dep_app, dep_name),
						"to": format!("{}.{}", m.app_label, m.name),
					})
				})
			})
			.collect();

		let graph = json!({
			"nodes": nodes,
			"edges": edges,
		});

		serde_json::to_string_pretty(&graph).unwrap_or_default()
	}
}

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

/// Migration statistics
///
/// # Example
///
/// ```rust
/// use reinhardt_db::migrations::visualization::MigrationStats;
/// use reinhardt_db::migrations::Migration;
///
/// let migrations = vec![
///     Migration::new("0001_initial", "app1"),
///     Migration::new("0002_add_field", "app1"),
///     Migration::new("0001_initial", "app2"),
/// ];
///
/// let stats = MigrationStats::from_migrations(&migrations);
/// assert_eq!(stats.total_migrations, 3);
/// assert_eq!(stats.apps_count, 2);
/// ```
#[derive(Debug, Clone)]
pub struct MigrationStats {
	/// The total migrations.
	pub total_migrations: usize,
	/// The apps count.
	pub apps_count: usize,
	/// The total operations.
	pub total_operations: usize,
	/// The by app.
	pub by_app: HashMap<String, usize>,
}

impl MigrationStats {
	/// Calculate statistics from migrations
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_db::migrations::visualization::MigrationStats;
	/// use reinhardt_db::migrations::Migration;
	///
	/// let migrations = vec![Migration::new("0001_initial", "myapp")];
	/// let stats = MigrationStats::from_migrations(&migrations);
	/// assert_eq!(stats.total_migrations, 1);
	/// ```
	pub fn from_migrations(migrations: &[Migration]) -> Self {
		let mut by_app = HashMap::new();
		let mut total_operations = 0;

		for migration in migrations {
			*by_app.entry(migration.app_label.to_string()).or_insert(0) += 1;
			total_operations += migration.operations.len();
		}

		let apps: HashSet<_> = migrations.iter().map(|m| m.app_label.clone()).collect();

		Self {
			total_migrations: migrations.len(),
			apps_count: apps.len(),
			total_operations,
			by_app,
		}
	}

	/// Generate statistics report
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_db::migrations::visualization::MigrationStats;
	/// use reinhardt_db::migrations::Migration;
	///
	/// let migrations = vec![Migration::new("0001_initial", "myapp")];
	/// let stats = MigrationStats::from_migrations(&migrations);
	/// let report = stats.generate_report();
	/// assert!(report.contains("Total Migrations"));
	/// ```
	pub fn generate_report(&self) -> String {
		let mut output = String::new();
		output.push_str("Migration Statistics\n");
		output.push_str("===================\n\n");

		output.push_str(&format!("Total Migrations: {}\n", self.total_migrations));
		output.push_str(&format!("Total Apps: {}\n", self.apps_count));
		output.push_str(&format!("Total Operations: {}\n\n", self.total_operations));

		output.push_str("By App:\n");
		for (app, count) in &self.by_app {
			output.push_str(&format!("  {}: {} migrations\n", app, count));
		}

		output
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_output_format_extension() {
		assert_eq!(OutputFormat::Text.extension(), "txt");
		assert_eq!(OutputFormat::Markdown.extension(), "md");
		assert_eq!(OutputFormat::Dot.extension(), "dot");
		assert_eq!(OutputFormat::Json.extension(), "json");
	}

	#[test]
	fn test_visualizer_text_graph() {
		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 visualizer = MigrationVisualizer::new();
		let graph = visualizer.generate_dependency_graph(&migrations, OutputFormat::Text);

		assert!(graph.contains("Migration Dependency Graph"));
		assert!(graph.contains("myapp.0001_initial"));
		assert!(graph.contains("myapp.0002_add_field"));
	}

	#[test]
	fn test_visualizer_markdown_graph() {
		let migration = Migration::new("0001_initial", "myapp");
		let migrations = vec![migration];

		let visualizer = MigrationVisualizer::new();
		let graph = visualizer.generate_dependency_graph(&migrations, OutputFormat::Markdown);

		assert!(graph.contains("# Migration Dependency Graph"));
		assert!(graph.contains("## myapp.0001_initial"));
	}

	#[test]
	fn test_visualizer_dot_graph() {
		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 visualizer = MigrationVisualizer::new();
		let graph = visualizer.generate_dependency_graph(&migrations, OutputFormat::Dot);

		assert!(graph.contains("digraph migrations"));
		assert!(graph.contains("myapp_0001_initial"));
		assert!(graph.contains("myapp_0002_add_field"));
		assert!(graph.contains("->"));
	}

	#[test]
	fn test_visualizer_json_graph() {
		let migration = Migration::new("0001_initial", "myapp");
		let migrations = vec![migration];

		let visualizer = MigrationVisualizer::new();
		let graph = visualizer.generate_dependency_graph(&migrations, OutputFormat::Json);

		assert!(graph.contains("nodes"));
		assert!(graph.contains("edges"));
		assert!(graph.contains("myapp.0001_initial"));
	}

	#[test]
	fn test_generate_timeline() {
		let entries = vec![
			HistoryEntry {
				app_label: "myapp".to_string(),
				migration_name: "0001_initial".to_string(),
				applied_at: "2025-01-01 00:00:00".to_string(),
				operations_count: 3,
			},
			HistoryEntry {
				app_label: "myapp".to_string(),
				migration_name: "0002_add_field".to_string(),
				applied_at: "2025-01-02 00:00:00".to_string(),
				operations_count: 1,
			},
		];

		let visualizer = MigrationVisualizer::new();
		let timeline = visualizer.generate_timeline(&entries);

		assert!(timeline.contains("Migration Timeline"));
		assert!(timeline.contains("0001_initial"));
		assert!(timeline.contains("0002_add_field"));
		assert!(timeline.contains("3 operations"));
	}

	#[test]
	fn test_generate_evolution_report() {
		let migrations = vec![
			Migration::new("0001_initial", "app1"),
			Migration::new("0002_add_field", "app1"),
			Migration::new("0001_initial", "app2"),
		];

		let visualizer = MigrationVisualizer::new();
		let report = visualizer.generate_evolution_report(&migrations);

		assert!(report.contains("Schema Evolution Report"));
		assert!(report.contains("App: app1"));
		assert!(report.contains("App: app2"));
	}

	#[test]
	fn test_migration_stats() {
		let migrations = vec![
			Migration::new("0001_initial", "app1"),
			Migration::new("0002_add_field", "app1"),
			Migration::new("0001_initial", "app2"),
		];

		let stats = MigrationStats::from_migrations(&migrations);

		assert_eq!(stats.total_migrations, 3);
		assert_eq!(stats.apps_count, 2);
		assert_eq!(stats.by_app.get("app1"), Some(&2));
		assert_eq!(stats.by_app.get("app2"), Some(&1));
	}

	#[test]
	fn test_stats_report() {
		let migrations = vec![
			Migration::new("0001_initial", "myapp"),
			Migration::new("0002_add_field", "myapp"),
		];

		let stats = MigrationStats::from_migrations(&migrations);
		let report = stats.generate_report();

		assert!(report.contains("Migration Statistics"));
		assert!(report.contains("Total Migrations: 2"));
		assert!(report.contains("myapp: 2 migrations"));
	}
}