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
//! Foreign key relationship definition
//!
//! Provides Foreign Key relationship types for defining one-to-many and many-to-one
//! relationships between models.

use serde::{Deserialize, Serialize};
use std::marker::PhantomData;

use super::reverse::{ReverseRelationship, generate_reverse_accessor};

/// Cascade action when the referenced object is deleted or updated
///
/// # Examples
///
/// ```
/// use reinhardt_db::associations::CascadeAction;
///
/// let action = CascadeAction::Cascade;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum CascadeAction {
	/// Do nothing (default behavior, may cause constraint violations)
	#[default]
	NoAction,
	/// Restrict deletion/update if dependent objects exist
	Restrict,
	/// Set foreign key to NULL when referenced object is deleted/updated
	SetNull,
	/// Set foreign key to its default value
	SetDefault,
	/// Cascade deletion/update to dependent objects
	Cascade,
}

/// Foreign key field configuration
///
/// # Type Parameters
///
/// * `T` - The type of the referenced model
/// * `K` - The type of the foreign key field
///
/// # Examples
///
/// ```
/// use reinhardt_db::associations::{ForeignKey, CascadeAction};
///
/// #[derive(Clone)]
/// struct User {
///     id: i64,
///     name: String,
/// }
///
/// #[derive(Clone)]
/// struct Post {
///     id: i64,
///     title: String,
///     author_id: i64,
/// }
///
/// // Define foreign key relationship
/// let fk: ForeignKey<User, i64> = ForeignKey::new("author_id")
///     .related_name("posts")
///     .on_delete(CascadeAction::Cascade);
/// ```
#[derive(Debug, Clone)]
pub struct ForeignKey<T, K> {
	/// The name of the foreign key field
	pub field_name: String,
	/// The name of the related field on the target model (usually "id")
	pub to_field: String,
	/// The name of the reverse relation accessor on the target model
	pub related_name: Option<String>,
	/// Action to take when referenced object is deleted
	pub on_delete: CascadeAction,
	/// Action to take when referenced object is updated
	pub on_update: CascadeAction,
	/// Whether the foreign key can be null
	pub null: bool,
	/// Database index creation
	pub db_index: bool,
	/// Database constraint name
	pub db_constraint: Option<String>,
	/// Phantom data for type parameters
	_phantom_t: PhantomData<T>,
	_phantom_k: PhantomData<K>,
}

impl<T, K> ForeignKey<T, K> {
	/// Create a new foreign key field
	///
	/// # Arguments
	///
	/// * `field_name` - The name of the foreign key field
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::ForeignKey;
	///
	/// #[derive(Clone)]
	/// struct User {
	///     id: i64,
	/// }
	///
	/// let fk: ForeignKey<User, i64> = ForeignKey::new("user_id");
	/// assert_eq!(fk.field_name(), "user_id");
	/// ```
	pub fn new(field_name: impl Into<String>) -> Self {
		Self {
			field_name: field_name.into(),
			to_field: "id".to_string(),
			related_name: None,
			on_delete: CascadeAction::default(),
			on_update: CascadeAction::default(),
			null: false,
			db_index: true,
			db_constraint: None,
			_phantom_t: PhantomData,
			_phantom_k: PhantomData,
		}
	}

	/// Set the related field name on the target model
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::ForeignKey;
	///
	/// #[derive(Clone)]
	/// struct User {
	///     id: i64,
	/// }
	///
	/// let fk: ForeignKey<User, i64> = ForeignKey::new("author_id")
	///     .to_field("user_id");
	/// assert_eq!(fk.get_to_field(), "user_id");
	/// ```
	pub fn to_field(mut self, to_field: impl Into<String>) -> Self {
		self.to_field = to_field.into();
		self
	}

	/// Set the reverse relation accessor name
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::ForeignKey;
	///
	/// #[derive(Clone)]
	/// struct User {
	///     id: i64,
	/// }
	///
	/// let fk: ForeignKey<User, i64> = ForeignKey::new("author_id")
	///     .related_name("posts");
	/// assert_eq!(fk.get_related_name(), Some("posts"));
	/// ```
	pub fn related_name(mut self, name: impl Into<String>) -> Self {
		self.related_name = Some(name.into());
		self
	}

	/// Set the on_delete cascade action
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::{ForeignKey, CascadeAction};
	///
	/// #[derive(Clone)]
	/// struct User {
	///     id: i64,
	/// }
	///
	/// let fk: ForeignKey<User, i64> = ForeignKey::new("author_id")
	///     .on_delete(CascadeAction::Cascade);
	/// assert_eq!(fk.get_on_delete(), CascadeAction::Cascade);
	/// ```
	pub fn on_delete(mut self, action: CascadeAction) -> Self {
		self.on_delete = action;
		self
	}

	/// Set the on_update cascade action
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::{ForeignKey, CascadeAction};
	///
	/// #[derive(Clone)]
	/// struct User {
	///     id: i64,
	/// }
	///
	/// let fk: ForeignKey<User, i64> = ForeignKey::new("author_id")
	///     .on_update(CascadeAction::Cascade);
	/// assert_eq!(fk.get_on_update(), CascadeAction::Cascade);
	/// ```
	pub fn on_update(mut self, action: CascadeAction) -> Self {
		self.on_update = action;
		self
	}

	/// Set whether the foreign key can be null
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::ForeignKey;
	///
	/// #[derive(Clone)]
	/// struct User {
	///     id: i64,
	/// }
	///
	/// let fk: ForeignKey<User, i64> = ForeignKey::new("author_id")
	///     .null(true);
	/// assert!(fk.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::ForeignKey;
	///
	/// #[derive(Clone)]
	/// struct User {
	///     id: i64,
	/// }
	///
	/// let fk: ForeignKey<User, i64> = ForeignKey::new("author_id")
	///     .db_index(false);
	/// assert!(!fk.has_db_index());
	/// ```
	pub fn db_index(mut self, db_index: bool) -> Self {
		self.db_index = db_index;
		self
	}

	/// Set the database constraint name
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::ForeignKey;
	///
	/// #[derive(Clone)]
	/// struct User {
	///     id: i64,
	/// }
	///
	/// let fk: ForeignKey<User, i64> = ForeignKey::new("author_id")
	///     .db_constraint("fk_posts_author");
	/// assert_eq!(fk.get_db_constraint(), Some("fk_posts_author"));
	/// ```
	pub fn db_constraint(mut self, name: impl Into<String>) -> Self {
		self.db_constraint = Some(name.into());
		self
	}

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

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

	/// Get the related_name
	pub fn get_related_name(&self) -> Option<&str> {
		self.related_name.as_deref()
	}

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

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

	/// 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
	}

	/// Get the database constraint name
	pub fn get_db_constraint(&self) -> Option<&str> {
		self.db_constraint.as_deref()
	}
}

impl<T, K> Default for ForeignKey<T, K> {
	fn default() -> Self {
		Self::new("id")
	}
}

impl<T, K> ReverseRelationship for ForeignKey<T, K> {
	/// Get the reverse accessor name, generating one if not explicitly set
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::associations::{ForeignKey, ReverseRelationship};
	///
	/// #[derive(Clone)]
	/// struct User {
	///     id: i64,
	/// }
	///
	/// let fk: ForeignKey<User, i64> = ForeignKey::new("author_id");
	/// assert_eq!(fk.get_or_generate_reverse_name("Post"), "post_set");
	///
	/// let fk_with_name: ForeignKey<User, i64> = ForeignKey::new("author_id")
	///     .related_name("posts");
	/// assert_eq!(fk_with_name.get_or_generate_reverse_name("Post"), "posts");
	/// ```
	fn get_or_generate_reverse_name(&self, model_name: &str) -> String {
		self.related_name
			.clone()
			.unwrap_or_else(|| generate_reverse_accessor(model_name))
	}

	fn explicit_reverse_name(&self) -> Option<&str> {
		self.related_name.as_deref()
	}
}

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

	// Allow dead_code: test model struct used for trait implementation verification
	#[allow(dead_code)]
	#[derive(Clone)]
	struct User {
		id: i64,
		name: String,
	}

	#[test]
	fn test_foreign_key_creation() {
		let fk: ForeignKey<User, i64> = ForeignKey::new("author_id");
		assert_eq!(fk.field_name(), "author_id");
		assert_eq!(fk.get_to_field(), "id");
		assert_eq!(fk.get_related_name(), None);
		assert_eq!(fk.get_on_delete(), CascadeAction::NoAction);
		assert_eq!(fk.get_on_update(), CascadeAction::NoAction);
		assert!(!fk.is_null());
		assert!(fk.has_db_index());
	}

	#[test]
	fn test_foreign_key_builder() {
		let fk: ForeignKey<User, i64> = ForeignKey::new("author_id")
			.related_name("posts")
			.on_delete(CascadeAction::Cascade)
			.on_update(CascadeAction::SetNull)
			.null(true)
			.db_index(false)
			.db_constraint("fk_posts_author");

		assert_eq!(fk.field_name(), "author_id");
		assert_eq!(fk.get_related_name(), Some("posts"));
		assert_eq!(fk.get_on_delete(), CascadeAction::Cascade);
		assert_eq!(fk.get_on_update(), CascadeAction::SetNull);
		assert!(fk.is_null());
		assert!(!fk.has_db_index());
		assert_eq!(fk.get_db_constraint(), Some("fk_posts_author"));
	}

	#[test]
	fn test_cascade_action_default() {
		assert_eq!(CascadeAction::default(), CascadeAction::NoAction);
	}

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

		for action in actions {
			let fk: ForeignKey<User, i64> = ForeignKey::new("test_id").on_delete(action);
			assert_eq!(fk.get_on_delete(), action);
		}
	}

	#[test]
	fn test_to_field_customization() {
		let fk: ForeignKey<User, i64> = ForeignKey::new("author_id").to_field("user_id");
		assert_eq!(fk.get_to_field(), "user_id");
	}

	#[test]
	fn test_null_configuration() {
		let fk1: ForeignKey<User, i64> = ForeignKey::new("author_id").null(true);
		assert!(fk1.is_null());

		let fk2: ForeignKey<User, i64> = ForeignKey::new("author_id").null(false);
		assert!(!fk2.is_null());
	}

	#[test]
	fn test_db_index_configuration() {
		let fk1: ForeignKey<User, i64> = ForeignKey::new("author_id").db_index(true);
		assert!(fk1.has_db_index());

		let fk2: ForeignKey<User, i64> = ForeignKey::new("author_id").db_index(false);
		assert!(!fk2.has_db_index());
	}
}