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
use core::fmt;
use std::fmt::{Debug, Display};

use serde::{de::Visitor, Deserialize, Serialize, Serializer};

use crate::{PrimaryKey, TableBuilder};

/// Foreign Key Type
///
/// ```rust
/// use geekorm::prelude::*;
/// use geekorm::{ForeignKey, PrimaryKeyInteger};
///
/// #[derive(Clone, Default, GeekTable)]
/// struct Users {
///     id: PrimaryKeyInteger,
///     name: String,
/// }
///
/// #[derive(Default, Clone, GeekTable)]
/// struct Posts {
///     id: PrimaryKeyInteger,
///     title: String,
///     /// Foreign Key to the Users table
///     /// i32 as the key type, and Users as the data type
///     #[geekorm(foreign_key = "Users.id")]
///     user: ForeignKey<i32, Users>,
/// }
///
/// // Create the Posts table with the foreign key referencing the Users table (Users.id)
/// let create_posts_query = Posts::create().build()
///     .expect("Failed to build query");
/// # assert_eq!(
/// #     create_posts_query.to_str(),
/// #     "CREATE TABLE IF NOT EXISTS Posts (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, user INTEGER NOT NULL, FOREIGN KEY (user) REFERENCES Users(id));"
/// # );
///
/// // Use the foreign key to and join the tables together
/// // to get the user posts
/// let user_posts = Users::select()
///     .order_by("name", geekorm::QueryOrder::Asc)
///     .build()
///     .expect("Failed to build query");
///
/// println!("User posts query: {:?}", user_posts);
/// // ...
/// ```
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct ForeignKey<T, D>
where
    T: Display + 'static,
    D: TableBuilder,
{
    /// Foreign Key Value
    pub key: T,
    /// Foreign Key Data Type
    pub data: D,
}

/// Foreign Key as an Integer
pub type ForeignKeyInteger<T> = ForeignKey<i32, T>;

/// Foreign Key as a String
pub type ForeignKeyString<T> = ForeignKey<String, T>;

/// Foreign Key as an Uuid
#[cfg(feature = "uuid")]
pub type ForeignKeyUuid<T> = ForeignKey<uuid::Uuid, T>;

impl<T, D> Debug for ForeignKey<T, D>
where
    T: Debug + Display + 'static,
    D: TableBuilder,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ForeignKey({})", self.key)
    }
}

impl<T, D> Display for ForeignKey<T, D>
where
    T: Display + 'static,
    D: TableBuilder,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({})", self.data.get_table().name, self.key)
    }
}

impl<D> Default for ForeignKey<i32, D>
where
    D: TableBuilder + Default,
{
    fn default() -> Self {
        Self {
            key: Default::default(),
            data: Default::default(),
        }
    }
}

impl<D> Default for ForeignKey<String, D>
where
    D: TableBuilder + Default,
{
    fn default() -> Self {
        Self {
            key: Default::default(),
            data: Default::default(),
        }
    }
}
impl<D> ForeignKey<i32, D>
where
    D: TableBuilder + Default,
{
    /// Create a new foreign key with an integer
    pub fn new(value: i32) -> Self {
        Self {
            key: value,
            data: Default::default(),
        }
    }
}

impl<D> ForeignKey<String, D>
where
    D: TableBuilder + Default,
{
    /// Create a new foreign key with a String
    pub fn new(value: String) -> Self {
        Self {
            key: value,
            data: Default::default(),
        }
    }
}

impl<D> From<i32> for ForeignKey<i32, D>
where
    D: TableBuilder + Default,
{
    fn from(value: i32) -> Self {
        Self::new(value)
    }
}

impl<D> From<String> for ForeignKey<String, D>
where
    D: TableBuilder + Default,
{
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl<D> From<&str> for ForeignKey<String, D>
where
    D: TableBuilder + Default,
{
    fn from(value: &str) -> Self {
        Self::new(value.to_string())
    }
}

impl<D> From<ForeignKey<i32, D>> for i32
where
    D: TableBuilder,
{
    fn from(value: ForeignKey<i32, D>) -> Self {
        value.key
    }
}

impl<D> From<PrimaryKey<i32>> for ForeignKey<i32, D>
where
    D: TableBuilder + Default,
{
    fn from(value: PrimaryKey<i32>) -> Self {
        Self::new(value.value)
    }
}

impl<D> From<PrimaryKey<String>> for ForeignKey<String, D>
where
    D: TableBuilder + Default,
{
    fn from(value: PrimaryKey<String>) -> Self {
        Self::new(value.value)
    }
}

impl<D> Serialize for ForeignKeyInteger<D>
where
    D: TableBuilder + Default,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i32(self.key)
    }
}

impl<'de, T> Deserialize<'de> for ForeignKeyInteger<T>
where
    T: TableBuilder + Default + Serialize + Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<ForeignKeyInteger<T>, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct PrimaryKeyVisitor;

        impl<'de> Visitor<'de> for PrimaryKeyVisitor {
            type Value = i32;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("an integer representing a foreign key")
            }

            fn visit_i32<E>(self, value: i32) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(value)
            }

            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(v as i32)
            }

            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(v as i32)
            }
        }

        Ok(ForeignKey::from(
            deserializer.deserialize_i32(PrimaryKeyVisitor)?,
        ))
    }
}