reinhardt-db 0.1.2

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
//! Cross-database constraint validation
//!
//! This module provides validation for foreign key relationships across different databases,
//! detecting potential issues that cannot be enforced at the database level.
//!
//! ## Django Limitation
//!
//! Django does not support foreign keys or many-to-many relationships across different databases.
//! If you attempt to use such relationships, Django will not enforce referential integrity.
//!
//! ## Reinhardt Approach
//!
//! Reinhardt provides explicit validation and clear error messages when cross-database
//! relationships are detected, helping developers understand and work around database limitations.

use super::database_routing::DatabaseRouter;
use std::sync::Arc;
use thiserror::Error;

/// Errors related to cross-database constraints
#[non_exhaustive]
#[derive(Debug, Error, Clone, PartialEq)]
pub enum CrossDbError {
	/// Foreign key relationship spans multiple databases
	#[error(
		"Foreign key '{field}' from {source_model} ({source_db}) to {target_model} ({target_db}) \
         crosses database boundaries. Cross-database foreign keys are not supported by most databases."
	)]
	ForeignKeyAcrossDatabase {
		/// The source model.
		source_model: String,
		/// The target model.
		target_model: String,
		/// The field.
		field: String,
		/// The source db.
		source_db: String,
		/// The target db.
		target_db: String,
	},

	/// Many-to-many relationship spans multiple databases
	#[error(
		"Many-to-many relationship '{field}' between {source_model} ({source_db}) and \
         {target_model} ({target_db}) crosses database boundaries. Cross-database many-to-many \
         relationships are not supported."
	)]
	ManyToManyAcrossDatabase {
		/// The source model.
		source_model: String,
		/// The target model.
		target_model: String,
		/// The field.
		field: String,
		/// The source db.
		source_db: String,
		/// The target db.
		target_db: String,
	},

	/// One-to-one relationship spans multiple databases
	#[error(
		"One-to-one relationship '{field}' between {source_model} ({source_db}) and \
         {target_model} ({target_db}) crosses database boundaries."
	)]
	OneToOneAcrossDatabase {
		/// The source model.
		source_model: String,
		/// The target model.
		target_model: String,
		/// The field.
		field: String,
		/// The source db.
		source_db: String,
		/// The target db.
		target_db: String,
	},
}

/// Validation mode for cross-database constraints
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidationMode {
	/// Raise an error when cross-database constraints are detected
	Strict,
	/// Log a warning but allow the relationship
	Warn,
	/// Silently allow cross-database relationships (not recommended)
	Allow,
}

/// Validator for cross-database constraints
///
/// # Examples
///
/// ```
/// use reinhardt_db::orm::cross_db_constraints::{CrossDbConstraintValidator, ValidationMode};
/// use reinhardt_db::orm::database_routing::DatabaseRouter;
/// use std::sync::Arc;
///
/// let router = DatabaseRouter::new("default")
///     .add_rule("User", "users_db")
///     .add_rule("Order", "orders_db");
///
/// let validator = CrossDbConstraintValidator::new(Arc::new(router))
///     .with_mode(ValidationMode::Strict);
///
/// // This will return an error because User and Order are in different databases
/// let result = validator.validate_foreign_key("Order", "User", "user_id");
/// assert!(result.is_err());
/// ```
#[derive(Debug, Clone)]
pub struct CrossDbConstraintValidator {
	router: Arc<DatabaseRouter>,
	mode: ValidationMode,
}

impl CrossDbConstraintValidator {
	/// Create a new validator with the given database router
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::cross_db_constraints::CrossDbConstraintValidator;
	/// use reinhardt_db::orm::database_routing::DatabaseRouter;
	/// use std::sync::Arc;
	///
	/// let router = DatabaseRouter::new("default");
	/// let validator = CrossDbConstraintValidator::new(Arc::new(router));
	/// ```
	pub fn new(router: Arc<DatabaseRouter>) -> Self {
		Self {
			router,
			mode: ValidationMode::Strict,
		}
	}

	/// Set the validation mode
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::cross_db_constraints::{CrossDbConstraintValidator, ValidationMode};
	/// use reinhardt_db::orm::database_routing::DatabaseRouter;
	/// use std::sync::Arc;
	///
	/// let router = DatabaseRouter::new("default");
	/// let validator = CrossDbConstraintValidator::new(Arc::new(router))
	///     .with_mode(ValidationMode::Warn);
	/// ```
	pub fn with_mode(mut self, mode: ValidationMode) -> Self {
		self.mode = mode;
		self
	}

	/// Get the current validation mode
	pub fn mode(&self) -> ValidationMode {
		self.mode
	}

	/// Validate a foreign key relationship
	///
	/// Checks if the source and target models are in the same database.
	/// Returns an error if they are in different databases and validation mode is Strict.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::cross_db_constraints::{CrossDbConstraintValidator, ValidationMode};
	/// use reinhardt_db::orm::database_routing::DatabaseRouter;
	/// use std::sync::Arc;
	///
	/// let router = DatabaseRouter::new("default")
	///     .add_rule("User", "db1")
	///     .add_rule("Post", "db1");  // Same database
	///
	/// let validator = CrossDbConstraintValidator::new(Arc::new(router));
	///
	/// // This is OK - both in db1
	/// assert!(validator.validate_foreign_key("Post", "User", "author_id").is_ok());
	/// ```
	pub fn validate_foreign_key(
		&self,
		source_model: &str,
		target_model: &str,
		field: &str,
	) -> Result<(), CrossDbError> {
		let source_db = self.router.db_for_write(source_model);
		let target_db = self.router.db_for_read(target_model);

		if source_db != target_db {
			let error = CrossDbError::ForeignKeyAcrossDatabase {
				source_model: source_model.to_string(),
				target_model: target_model.to_string(),
				field: field.to_string(),
				source_db,
				target_db,
			};

			match self.mode {
				ValidationMode::Strict => Err(error),
				ValidationMode::Warn => {
					eprintln!("WARNING: {}", error);
					Ok(())
				}
				ValidationMode::Allow => Ok(()),
			}
		} else {
			Ok(())
		}
	}

	/// Validate a many-to-many relationship
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::cross_db_constraints::CrossDbConstraintValidator;
	/// use reinhardt_db::orm::database_routing::DatabaseRouter;
	/// use std::sync::Arc;
	///
	/// let router = DatabaseRouter::new("default")
	///     .add_rule("User", "db1")
	///     .add_rule("Group", "db2");  // Different database!
	///
	/// let validator = CrossDbConstraintValidator::new(Arc::new(router));
	///
	/// // This will error - different databases
	/// let result = validator.validate_many_to_many("User", "Group", "groups");
	/// assert!(result.is_err());
	/// ```
	pub fn validate_many_to_many(
		&self,
		source_model: &str,
		target_model: &str,
		field: &str,
	) -> Result<(), CrossDbError> {
		let source_db = self.router.db_for_write(source_model);
		let target_db = self.router.db_for_write(target_model);

		if source_db != target_db {
			let error = CrossDbError::ManyToManyAcrossDatabase {
				source_model: source_model.to_string(),
				target_model: target_model.to_string(),
				field: field.to_string(),
				source_db,
				target_db,
			};

			match self.mode {
				ValidationMode::Strict => Err(error),
				ValidationMode::Warn => {
					eprintln!("WARNING: {}", error);
					Ok(())
				}
				ValidationMode::Allow => Ok(()),
			}
		} else {
			Ok(())
		}
	}

	/// Validate a one-to-one relationship
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::cross_db_constraints::CrossDbConstraintValidator;
	/// use reinhardt_db::orm::database_routing::DatabaseRouter;
	/// use std::sync::Arc;
	///
	/// let router = DatabaseRouter::new("default");
	/// let validator = CrossDbConstraintValidator::new(Arc::new(router));
	///
	/// // Both use default database
	/// assert!(validator.validate_one_to_one("User", "Profile", "profile").is_ok());
	/// ```
	pub fn validate_one_to_one(
		&self,
		source_model: &str,
		target_model: &str,
		field: &str,
	) -> Result<(), CrossDbError> {
		let source_db = self.router.db_for_write(source_model);
		let target_db = self.router.db_for_write(target_model);

		if source_db != target_db {
			let error = CrossDbError::OneToOneAcrossDatabase {
				source_model: source_model.to_string(),
				target_model: target_model.to_string(),
				field: field.to_string(),
				source_db,
				target_db,
			};

			match self.mode {
				ValidationMode::Strict => Err(error),
				ValidationMode::Warn => {
					eprintln!("WARNING: {}", error);
					Ok(())
				}
				ValidationMode::Allow => Ok(()),
			}
		} else {
			Ok(())
		}
	}

	/// Batch validate multiple relationships
	///
	/// Returns all errors encountered during validation.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::cross_db_constraints::{CrossDbConstraintValidator, RelationshipType};
	/// use reinhardt_db::orm::database_routing::DatabaseRouter;
	/// use std::sync::Arc;
	///
	/// let router = DatabaseRouter::new("default")
	///     .add_rule("User", "db1")
	///     .add_rule("Post", "db2")
	///     .add_rule("Comment", "db3");
	///
	/// let validator = CrossDbConstraintValidator::new(Arc::new(router));
	///
	/// let relationships = vec![
	///     ("Post", "User", "author_id", RelationshipType::ForeignKey),
	///     ("Comment", "Post", "post_id", RelationshipType::ForeignKey),
	/// ];
	///
	/// let errors = validator.validate_batch(&relationships);
	/// assert_eq!(errors.len(), 2);  // Both cross database boundaries
	/// ```
	pub fn validate_batch(
		&self,
		relationships: &[(&str, &str, &str, RelationshipType)],
	) -> Vec<CrossDbError> {
		relationships
			.iter()
			.filter_map(|(source, target, field, rel_type)| {
				let result = match rel_type {
					RelationshipType::ForeignKey => {
						self.validate_foreign_key(source, target, field)
					}
					RelationshipType::ManyToMany => {
						self.validate_many_to_many(source, target, field)
					}
					RelationshipType::OneToOne => self.validate_one_to_one(source, target, field),
				};
				result.err()
			})
			.collect()
	}
}

/// Type of relationship between models
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelationshipType {
	/// Foreign key relationship
	ForeignKey,
	/// Many-to-many relationship
	ManyToMany,
	/// One-to-one relationship
	OneToOne,
}

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

	fn create_router() -> Arc<DatabaseRouter> {
		Arc::new(
			DatabaseRouter::new("default")
				.add_rule("User", "users_db")
				.add_rule("Post", "posts_db")
				.add_rule("Comment", "default"),
		)
	}

	#[test]
	fn test_foreign_key_same_database() {
		let router = Arc::new(DatabaseRouter::new("default"));
		let validator = CrossDbConstraintValidator::new(router);

		let result = validator.validate_foreign_key("Post", "User", "author_id");
		assert!(result.is_ok());
	}

	#[test]
	fn test_foreign_key_different_databases_strict() {
		let router = create_router();
		let validator = CrossDbConstraintValidator::new(router).with_mode(ValidationMode::Strict);

		let result = validator.validate_foreign_key("Post", "User", "author_id");
		assert!(result.is_err());
		match result.unwrap_err() {
			CrossDbError::ForeignKeyAcrossDatabase {
				source_model,
				target_model,
				field,
				source_db,
				target_db,
			} => {
				assert_eq!(source_model, "Post");
				assert_eq!(target_model, "User");
				assert_eq!(field, "author_id");
				assert_eq!(source_db, "posts_db");
				assert_eq!(target_db, "users_db");
			}
			_ => panic!("Expected ForeignKeyAcrossDatabase error"),
		}
	}

	#[test]
	fn test_foreign_key_different_databases_warn() {
		let router = create_router();
		let validator = CrossDbConstraintValidator::new(router).with_mode(ValidationMode::Warn);

		let result = validator.validate_foreign_key("Post", "User", "author_id");
		assert!(result.is_ok()); // Warn mode allows the relationship
	}

	#[test]
	fn test_foreign_key_different_databases_allow() {
		let router = create_router();
		let validator = CrossDbConstraintValidator::new(router).with_mode(ValidationMode::Allow);

		let result = validator.validate_foreign_key("Post", "User", "author_id");
		assert!(result.is_ok());
	}

	#[test]
	fn test_many_to_many_different_databases() {
		let router = create_router();
		let validator = CrossDbConstraintValidator::new(router);

		let result = validator.validate_many_to_many("User", "Post", "favorite_posts");
		assert!(result.is_err());
		match result.unwrap_err() {
			CrossDbError::ManyToManyAcrossDatabase { .. } => {}
			_ => panic!("Expected ManyToManyAcrossDatabase error"),
		}
	}

	#[test]
	fn test_one_to_one_same_database() {
		let router = Arc::new(DatabaseRouter::new("default"));
		let validator = CrossDbConstraintValidator::new(router);

		let result = validator.validate_one_to_one("User", "Profile", "profile");
		assert!(result.is_ok());
	}

	#[test]
	fn test_one_to_one_different_databases() {
		let router = create_router();
		let validator = CrossDbConstraintValidator::new(router);

		let result = validator.validate_one_to_one("User", "Post", "featured_post");
		assert!(result.is_err());
	}

	#[test]
	fn test_batch_validation() {
		let router = create_router();
		let validator = CrossDbConstraintValidator::new(router);

		let relationships = vec![
			("Post", "User", "author_id", RelationshipType::ForeignKey), // posts_db -> users_db (cross)
			("Comment", "Post", "post_id", RelationshipType::ForeignKey), // default -> posts_db (cross)
			(
				"User",
				"Post",
				"favorite_posts",
				RelationshipType::ManyToMany,
			), // users_db -> posts_db (cross)
		];

		let errors = validator.validate_batch(&relationships);
		assert_eq!(errors.len(), 3); // All three relationships cross database boundaries
	}

	#[test]
	fn test_error_display() {
		let error = CrossDbError::ForeignKeyAcrossDatabase {
			source_model: "Post".to_string(),
			target_model: "User".to_string(),
			field: "author_id".to_string(),
			source_db: "posts_db".to_string(),
			target_db: "users_db".to_string(),
		};

		let message = error.to_string();
		assert!(message.contains("Post"));
		assert!(message.contains("User"));
		assert!(message.contains("author_id"));
		assert!(message.contains("posts_db"));
		assert!(message.contains("users_db"));
	}

	#[test]
	fn test_validation_mode_getter() {
		let router = Arc::new(DatabaseRouter::new("default"));
		let validator = CrossDbConstraintValidator::new(router).with_mode(ValidationMode::Warn);

		assert_eq!(validator.mode(), ValidationMode::Warn);
	}
}