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
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
//! Polymorphic associations
//!
//! This module provides support for polymorphic associations, allowing a model
//! to belong to multiple different model types through a single association.
//! This is similar to Rails' polymorphic associations and Django's GenericForeignKey.

use std::marker::PhantomData;

use super::foreign_key::CascadeAction;

/// Polymorphic association field
///
/// Represents a polymorphic relationship where the foreign key can point to
/// multiple different model types. This is achieved by storing both the ID
/// of the related object and a type discriminator.
///
/// # Type Parameters
///
/// * `K` - The type of the foreign key field (usually i64)
///
/// # Examples
///
/// ```
/// use reinhardt_db::associations::PolymorphicAssociation;
///
/// #[derive(Clone)]
/// struct Comment {
///     id: i64,
///     content: String,
///     commentable_id: i64,
///     commentable_type: String,
/// }
///
/// // A comment can belong to either a Post or a Video
/// let rel: PolymorphicAssociation<i64> = PolymorphicAssociation::new("commentable")
///     .id_field("commentable_id")
///     .type_field("commentable_type");
/// ```
#[derive(Debug, Clone)]
pub struct PolymorphicAssociation<K> {
	/// The base name of the association (e.g., "commentable")
	pub association_name: String,
	/// The name of the ID field (e.g., "commentable_id")
	pub id_field: String,
	/// The name of the type discriminator field (e.g., "commentable_type")
	pub type_field: String,
	/// Action to take when referenced object is deleted
	pub on_delete: CascadeAction,
	/// Whether the foreign key can be null
	pub null: bool,
	/// Database index creation for the ID field
	pub db_index: bool,
	/// Phantom data for type parameter
	_phantom: PhantomData<K>,
}

impl<K> PolymorphicAssociation<K> {
	/// Create a new polymorphic association
	///
	/// # Arguments
	///
	/// * `association_name` - The base name of the association
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicAssociation;
	///
	/// let rel: PolymorphicAssociation<i64> = PolymorphicAssociation::new("commentable");
	/// assert_eq!(rel.association_name(), "commentable");
	/// assert_eq!(rel.get_id_field(), "commentable_id");
	/// assert_eq!(rel.get_type_field(), "commentable_type");
	/// ```
	pub fn new(association_name: impl Into<String>) -> Self {
		let name = association_name.into();
		Self {
			id_field: format!("{}_id", name),
			type_field: format!("{}_type", name),
			association_name: name,
			on_delete: CascadeAction::default(),
			null: false,
			db_index: true,
			_phantom: PhantomData,
		}
	}

	/// Set the ID field name
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicAssociation;
	///
	/// let rel: PolymorphicAssociation<i64> = PolymorphicAssociation::new("taggable")
	///     .id_field("object_id");
	/// assert_eq!(rel.get_id_field(), "object_id");
	/// ```
	pub fn id_field(mut self, field_name: impl Into<String>) -> Self {
		self.id_field = field_name.into();
		self
	}

	/// Set the type discriminator field name
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicAssociation;
	///
	/// let rel: PolymorphicAssociation<i64> = PolymorphicAssociation::new("taggable")
	///     .type_field("content_type");
	/// assert_eq!(rel.get_type_field(), "content_type");
	/// ```
	pub fn type_field(mut self, field_name: impl Into<String>) -> Self {
		self.type_field = field_name.into();
		self
	}

	/// Set the on_delete cascade action
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::{PolymorphicAssociation, CascadeAction};
	///
	/// let rel: PolymorphicAssociation<i64> = PolymorphicAssociation::new("commentable")
	///     .on_delete(CascadeAction::Cascade);
	/// assert_eq!(rel.get_on_delete(), CascadeAction::Cascade);
	/// ```
	pub fn on_delete(mut self, action: CascadeAction) -> Self {
		self.on_delete = action;
		self
	}

	/// Set whether the association can be null
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicAssociation;
	///
	/// let rel: PolymorphicAssociation<i64> = PolymorphicAssociation::new("commentable")
	///     .null(true);
	/// assert!(rel.is_null());
	/// ```
	pub fn null(mut self, null: bool) -> Self {
		self.null = null;
		self
	}

	/// Set whether to create database index
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicAssociation;
	///
	/// let rel: PolymorphicAssociation<i64> = PolymorphicAssociation::new("commentable")
	///     .db_index(false);
	/// assert!(!rel.has_db_index());
	/// ```
	pub fn db_index(mut self, db_index: bool) -> Self {
		self.db_index = db_index;
		self
	}

	/// Get the association name
	pub fn association_name(&self) -> &str {
		&self.association_name
	}

	/// Get the ID field name
	pub fn get_id_field(&self) -> &str {
		&self.id_field
	}

	/// Get the type field name
	pub fn get_type_field(&self) -> &str {
		&self.type_field
	}

	/// Get the on_delete action
	pub fn get_on_delete(&self) -> CascadeAction {
		self.on_delete
	}

	/// Check if null is allowed
	pub fn is_null(&self) -> bool {
		self.null
	}

	/// Check if database index should be created
	pub fn has_db_index(&self) -> bool {
		self.db_index
	}
}

impl<K> Default for PolymorphicAssociation<K> {
	fn default() -> Self {
		Self::new("polymorphic")
	}
}

/// Polymorphic many-to-many association
///
/// Represents a many-to-many relationship where the target can be multiple
/// different model types. This uses a junction table with a polymorphic foreign key.
///
/// # Type Parameters
///
/// * `K` - The type of the foreign key field (usually i64)
///
/// # Examples
///
/// ```
/// use reinhardt_db::associations::PolymorphicManyToMany;
///
/// #[derive(Clone)]
/// struct Tag {
///     id: i64,
///     name: String,
/// }
///
/// // Tags can be applied to Posts, Videos, or any other content type
/// let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable")
///     .through("taggings")
///     .source_field("tag_id")
///     .target_id_field("taggable_id")
///     .target_type_field("taggable_type");
/// ```
#[derive(Debug, Clone)]
pub struct PolymorphicManyToMany<K> {
	/// The base name of the association
	pub association_name: String,
	/// The name of the junction/through table
	pub through: Option<String>,
	/// The name of the source foreign key field in the junction table
	pub source_field: String,
	/// The name of the target ID field in the junction table
	pub target_id_field: String,
	/// The name of the target type discriminator field in the junction table
	pub target_type_field: String,
	/// Action to take when source object is deleted
	pub on_delete: CascadeAction,
	/// Whether to use lazy loading by default
	pub lazy: bool,
	/// Database constraint name prefix
	pub db_constraint_prefix: Option<String>,
	/// Phantom data for type parameter
	_phantom: PhantomData<K>,
}

impl<K> PolymorphicManyToMany<K> {
	/// Create a new polymorphic many-to-many association
	///
	/// # Arguments
	///
	/// * `association_name` - The base name of the association
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicManyToMany;
	///
	/// let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable");
	/// assert_eq!(rel.association_name(), "taggable");
	/// ```
	pub fn new(association_name: impl Into<String>) -> Self {
		let name = association_name.into();
		Self {
			association_name: name.clone(),
			through: None,
			source_field: String::new(),
			target_id_field: format!("{}_id", name),
			target_type_field: format!("{}_type", name),
			on_delete: CascadeAction::Cascade,
			lazy: true,
			db_constraint_prefix: None,
			_phantom: PhantomData,
		}
	}

	/// Set the junction/through table name
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicManyToMany;
	///
	/// let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable")
	///     .through("taggings");
	/// assert_eq!(rel.get_through(), Some("taggings"));
	/// ```
	pub fn through(mut self, table_name: impl Into<String>) -> Self {
		self.through = Some(table_name.into());
		self
	}

	/// Set the source foreign key field name in the junction table
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicManyToMany;
	///
	/// let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable")
	///     .source_field("tag_id");
	/// assert_eq!(rel.get_source_field(), "tag_id");
	/// ```
	pub fn source_field(mut self, field_name: impl Into<String>) -> Self {
		self.source_field = field_name.into();
		self
	}

	/// Set the target ID field name in the junction table
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicManyToMany;
	///
	/// let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable")
	///     .target_id_field("object_id");
	/// assert_eq!(rel.get_target_id_field(), "object_id");
	/// ```
	pub fn target_id_field(mut self, field_name: impl Into<String>) -> Self {
		self.target_id_field = field_name.into();
		self
	}

	/// Set the target type discriminator field name in the junction table
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicManyToMany;
	///
	/// let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable")
	///     .target_type_field("content_type");
	/// assert_eq!(rel.get_target_type_field(), "content_type");
	/// ```
	pub fn target_type_field(mut self, field_name: impl Into<String>) -> Self {
		self.target_type_field = field_name.into();
		self
	}

	/// Set the on_delete cascade action
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::{PolymorphicManyToMany, CascadeAction};
	///
	/// let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable")
	///     .on_delete(CascadeAction::Restrict);
	/// assert_eq!(rel.get_on_delete(), CascadeAction::Restrict);
	/// ```
	pub fn on_delete(mut self, action: CascadeAction) -> Self {
		self.on_delete = action;
		self
	}

	/// Set whether to use lazy loading
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicManyToMany;
	///
	/// let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable")
	///     .lazy(false);
	/// assert!(!rel.is_lazy());
	/// ```
	pub fn lazy(mut self, lazy: bool) -> Self {
		self.lazy = lazy;
		self
	}

	/// Set the database constraint name prefix
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::PolymorphicManyToMany;
	///
	/// let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable")
	///     .db_constraint_prefix("poly_taggings");
	/// assert_eq!(rel.get_db_constraint_prefix(), Some("poly_taggings"));
	/// ```
	pub fn db_constraint_prefix(mut self, prefix: impl Into<String>) -> Self {
		self.db_constraint_prefix = Some(prefix.into());
		self
	}

	/// Get the association name
	pub fn association_name(&self) -> &str {
		&self.association_name
	}

	/// Get the through table name
	pub fn get_through(&self) -> Option<&str> {
		self.through.as_deref()
	}

	/// Get the source field name
	pub fn get_source_field(&self) -> &str {
		&self.source_field
	}

	/// Get the target ID field name
	pub fn get_target_id_field(&self) -> &str {
		&self.target_id_field
	}

	/// Get the target type field name
	pub fn get_target_type_field(&self) -> &str {
		&self.target_type_field
	}

	/// Get the on_delete action
	pub fn get_on_delete(&self) -> CascadeAction {
		self.on_delete
	}

	/// Check if lazy loading is enabled
	pub fn is_lazy(&self) -> bool {
		self.lazy
	}

	/// Get the database constraint prefix
	pub fn get_db_constraint_prefix(&self) -> Option<&str> {
		self.db_constraint_prefix.as_deref()
	}
}

impl<K> Default for PolymorphicManyToMany<K> {
	fn default() -> Self {
		Self::new("polymorphic")
	}
}

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

	#[test]
	fn test_polymorphic_association_creation() {
		let rel: PolymorphicAssociation<i64> = PolymorphicAssociation::new("commentable");
		assert_eq!(rel.association_name(), "commentable");
		assert_eq!(rel.get_id_field(), "commentable_id");
		assert_eq!(rel.get_type_field(), "commentable_type");
		assert_eq!(rel.get_on_delete(), CascadeAction::NoAction);
		assert!(!rel.is_null());
		assert!(rel.has_db_index());
	}

	#[test]
	fn test_polymorphic_association_builder() {
		let rel: PolymorphicAssociation<i64> = PolymorphicAssociation::new("taggable")
			.id_field("object_id")
			.type_field("content_type")
			.on_delete(CascadeAction::Cascade)
			.null(true)
			.db_index(false);

		assert_eq!(rel.association_name(), "taggable");
		assert_eq!(rel.get_id_field(), "object_id");
		assert_eq!(rel.get_type_field(), "content_type");
		assert_eq!(rel.get_on_delete(), CascadeAction::Cascade);
		assert!(rel.is_null());
		assert!(!rel.has_db_index());
	}

	#[test]
	fn test_polymorphic_association_default_field_names() {
		let rel: PolymorphicAssociation<i64> = PolymorphicAssociation::new("imageable");
		assert_eq!(rel.get_id_field(), "imageable_id");
		assert_eq!(rel.get_type_field(), "imageable_type");
	}

	#[test]
	fn test_polymorphic_many_to_many_creation() {
		let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable");
		assert_eq!(rel.association_name(), "taggable");
		assert_eq!(rel.get_through(), None);
		assert_eq!(rel.get_source_field(), "");
		assert_eq!(rel.get_target_id_field(), "taggable_id");
		assert_eq!(rel.get_target_type_field(), "taggable_type");
		assert_eq!(rel.get_on_delete(), CascadeAction::Cascade);
		assert!(rel.is_lazy());
	}

	#[test]
	fn test_polymorphic_many_to_many_builder() {
		let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("taggable")
			.through("taggings")
			.source_field("tag_id")
			.target_id_field("object_id")
			.target_type_field("content_type")
			.on_delete(CascadeAction::Restrict)
			.lazy(false)
			.db_constraint_prefix("poly_tag");

		assert_eq!(rel.association_name(), "taggable");
		assert_eq!(rel.get_through(), Some("taggings"));
		assert_eq!(rel.get_source_field(), "tag_id");
		assert_eq!(rel.get_target_id_field(), "object_id");
		assert_eq!(rel.get_target_type_field(), "content_type");
		assert_eq!(rel.get_on_delete(), CascadeAction::Restrict);
		assert!(!rel.is_lazy());
		assert_eq!(rel.get_db_constraint_prefix(), Some("poly_tag"));
	}

	#[test]
	fn test_polymorphic_many_to_many_default_field_names() {
		let rel: PolymorphicManyToMany<i64> = PolymorphicManyToMany::new("likeable");
		assert_eq!(rel.get_target_id_field(), "likeable_id");
		assert_eq!(rel.get_target_type_field(), "likeable_type");
	}

	#[test]
	fn test_cascade_actions_polymorphic() {
		let actions = vec![
			CascadeAction::NoAction,
			CascadeAction::Restrict,
			CascadeAction::SetNull,
			CascadeAction::SetDefault,
			CascadeAction::Cascade,
		];

		for action in actions {
			let rel: PolymorphicAssociation<i64> =
				PolymorphicAssociation::new("commentable").on_delete(action);
			assert_eq!(rel.get_on_delete(), action);
		}
	}

	#[test]
	fn test_null_configuration_polymorphic() {
		let rel1: PolymorphicAssociation<i64> =
			PolymorphicAssociation::new("commentable").null(true);
		assert!(rel1.is_null());

		let rel2: PolymorphicAssociation<i64> =
			PolymorphicAssociation::new("commentable").null(false);
		assert!(!rel2.is_null());
	}

	#[test]
	fn test_db_index_configuration_polymorphic() {
		let rel1: PolymorphicAssociation<i64> =
			PolymorphicAssociation::new("commentable").db_index(true);
		assert!(rel1.has_db_index());

		let rel2: PolymorphicAssociation<i64> =
			PolymorphicAssociation::new("commentable").db_index(false);
		assert!(!rel2.has_db_index());
	}
}