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
/// Trait for types that can be converted into a model's primary key.
///
/// This trait enables flexible function signatures in generated builder setters,
/// allowing both model instances and raw primary key values to be passed.
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt::db::orm::{Model, IntoPrimaryKey};
/// use uuid::Uuid;
///
/// // Pass a primary key value directly
/// let user_id = Uuid::now_v7();
/// let message = DMMessage::build()
/// .room(room_id)
/// .sender(user_id)
/// .content("Hello")
/// .finish();
///
/// // Pass model instances by reference
/// let message = DMMessage::build()
/// .room(&room)
/// .sender(&user)
/// .content("Hello")
/// .finish();
/// ```
pub trait IntoPrimaryKey<T: super::Model> {
/// Convert this value into the primary key of model `T`.
fn into_primary_key(self) -> T::PrimaryKey;
}
// Implementation for model references (borrows the model)
impl<T: super::Model> IntoPrimaryKey<T> for &T {
fn into_primary_key(self) -> T::PrimaryKey {
self.primary_key().expect(
"Model instance must have a primary key set. \
Ensure the model was loaded from database or constructed with a PK.",
)
}
}
// Implementations for common primary key types
// This avoids conflicts with the blanket impl for T: Model
// UUID (most common in examples)
impl<T: super::Model<PrimaryKey = uuid::Uuid>> IntoPrimaryKey<T> for uuid::Uuid {
fn into_primary_key(self) -> T::PrimaryKey {
self
}
}
// i32
impl<T: super::Model<PrimaryKey = i32>> IntoPrimaryKey<T> for i32 {
fn into_primary_key(self) -> T::PrimaryKey {
self
}
}
// i64
impl<T: super::Model<PrimaryKey = i64>> IntoPrimaryKey<T> for i64 {
fn into_primary_key(self) -> T::PrimaryKey {
self
}
}
// Option<Uuid>
impl<T: super::Model<PrimaryKey = uuid::Uuid>> IntoPrimaryKey<T> for Option<uuid::Uuid> {
fn into_primary_key(self) -> T::PrimaryKey {
self.expect("Primary key value must be provided")
}
}
// Option<i32>
impl<T: super::Model<PrimaryKey = i32>> IntoPrimaryKey<T> for Option<i32> {
fn into_primary_key(self) -> T::PrimaryKey {
self.expect("Primary key value must be provided")
}
}
// Option<i64>
impl<T: super::Model<PrimaryKey = i64>> IntoPrimaryKey<T> for Option<i64> {
fn into_primary_key(self) -> T::PrimaryKey {
self.expect("Primary key value must be provided")
}
}