1use std::any::Any;
13use std::collections::BTreeMap;
14use std::sync::Arc;
15use std::sync::atomic::{AtomicBool, Ordering};
16
17use luxid_core::error::{Error, Result};
18use serde::{Serialize, Serializer};
19use serde_json::Value;
20
21static STRICT: AtomicBool = AtomicBool::new(cfg!(debug_assertions));
27
28pub fn set_strict_relations(strict: bool) {
33 STRICT.store(strict, Ordering::Relaxed);
34}
35
36pub fn strict_relations() -> bool {
37 STRICT.load(Ordering::Relaxed)
38}
39
40#[derive(Clone)]
41struct Entry {
42 typed: Arc<dyn Any + Send + Sync>,
44 json: Value,
45}
46
47#[derive(Clone, Default)]
49pub struct Relations {
50 entries: BTreeMap<String, Entry>,
51}
52
53impl Relations {
54 pub fn new() -> Self {
55 Self::default()
56 }
57
58 pub fn is_loaded(&self, name: &str) -> bool {
59 self.entries.contains_key(name)
60 }
61
62 pub fn loaded_names(&self) -> impl Iterator<Item = &str> {
63 self.entries.keys().map(String::as_str)
64 }
65
66 pub fn is_empty(&self) -> bool {
67 self.entries.is_empty()
68 }
69
70 pub fn insert_many<T>(&mut self, name: impl Into<String>, values: Vec<T>)
71 where
72 T: Any + Send + Sync + Serialize,
73 {
74 let json = serde_json::to_value(&values).unwrap_or(Value::Null);
75 self.entries.insert(
76 name.into(),
77 Entry {
78 typed: Arc::new(values),
79 json,
80 },
81 );
82 }
83
84 pub fn insert_one<T>(&mut self, name: impl Into<String>, value: Option<T>)
85 where
86 T: Any + Send + Sync + Serialize,
87 {
88 let json = serde_json::to_value(&value).unwrap_or(Value::Null);
89 self.entries.insert(
90 name.into(),
91 Entry {
92 typed: Arc::new(value),
93 json,
94 },
95 );
96 }
97
98 pub fn many<T: Any + Send + Sync>(&self, model: &str, name: &str) -> Result<&[T]> {
99 match self.entries.get(name) {
100 Some(entry) => entry
101 .typed
102 .downcast_ref::<Vec<T>>()
103 .map(Vec::as_slice)
104 .ok_or_else(|| mismatched(model, name)),
105 None if strict_relations() => Err(not_loaded(model, name)),
106 None => Ok(&[]),
107 }
108 }
109
110 pub fn one<T: Any + Send + Sync>(&self, model: &str, name: &str) -> Result<Option<&T>> {
111 match self.entries.get(name) {
112 Some(entry) => entry
113 .typed
114 .downcast_ref::<Option<T>>()
115 .map(Option::as_ref)
116 .ok_or_else(|| mismatched(model, name)),
117 None if strict_relations() => Err(not_loaded(model, name)),
118 None => Ok(None),
119 }
120 }
121}
122
123fn not_loaded(model: &str, name: &str) -> Error {
124 Error::internal(format!(
125 "the `{name}` relation of `{model}` was not loaded. \
126 Add `.with(\"{name}\")` to the query, or call \
127 `luxid::set_strict_relations(false)` to read unloaded relations as empty."
128 ))
129}
130
131fn mismatched(model: &str, name: &str) -> Error {
132 Error::internal(format!(
133 "the `{name}` relation of `{model}` was loaded as a different type than it was read as"
134 ))
135}
136
137impl Serialize for Relations {
140 fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
141 use serde::ser::SerializeMap;
142
143 let mut map = serializer.serialize_map(Some(self.entries.len()))?;
144 for (name, entry) in &self.entries {
145 map.serialize_entry(name, &entry.json)?;
146 }
147 map.end()
148 }
149}
150
151impl PartialEq for Relations {
154 fn eq(&self, other: &Self) -> bool {
155 self.entries.len() == other.entries.len()
156 && self
157 .entries
158 .iter()
159 .zip(other.entries.iter())
160 .all(|((a_name, a), (b_name, b))| a_name == b_name && a.json == b.json)
161 }
162}
163
164impl Eq for Relations {}
165
166impl std::fmt::Debug for Relations {
167 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168 f.debug_struct("Relations")
169 .field("loaded", &self.entries.keys().collect::<Vec<_>>())
170 .finish()
171 }
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177
178 static TOGGLE: std::sync::Mutex<()> = std::sync::Mutex::new(());
183
184 #[derive(Debug, Clone, PartialEq, Serialize)]
185 struct Post {
186 id: i64,
187 title: String,
188 }
189
190 fn post(id: i64) -> Post {
191 Post {
192 id,
193 title: format!("Post {id}"),
194 }
195 }
196
197 #[test]
198 fn round_trips_a_to_many_relation() {
199 let mut relations = Relations::new();
200 relations.insert_many("posts", vec![post(1), post(2)]);
201
202 assert!(relations.is_loaded("posts"));
203 assert_eq!(
204 relations
205 .many::<Post>("User", "posts")
206 .expect("loaded")
207 .len(),
208 2
209 );
210 }
211
212 #[test]
213 fn round_trips_a_to_one_relation() {
214 let mut relations = Relations::new();
215 relations.insert_one("author", Some(post(9)));
216
217 assert_eq!(
218 relations.one::<Post>("Comment", "author").expect("loaded"),
219 Some(&post(9))
220 );
221 }
222
223 #[test]
224 fn an_unloaded_relation_errors_under_strict_mode() {
225 let _guard = TOGGLE.lock().expect("not poisoned");
226
227 set_strict_relations(true);
228 let relations = Relations::new();
229
230 let err = relations.many::<Post>("User", "posts").unwrap_err();
231 let message = format!("{err}");
232
233 assert!(message.contains("was not loaded"), "{message}");
234 assert!(message.contains(".with(\"posts\")"), "{message}");
235 }
236
237 #[test]
238 fn an_unloaded_relation_reads_as_empty_when_not_strict() {
239 let _guard = TOGGLE.lock().expect("not poisoned");
240
241 set_strict_relations(false);
242 let relations = Relations::new();
243
244 assert!(
245 relations
246 .many::<Post>("User", "posts")
247 .expect("lenient")
248 .is_empty()
249 );
250 assert_eq!(
251 relations.one::<Post>("User", "team").expect("lenient"),
252 None
253 );
254
255 set_strict_relations(true);
256 }
257
258 #[test]
259 fn loaded_relations_serialize_inline() {
260 let mut relations = Relations::new();
261 relations.insert_many("posts", vec![post(1)]);
262 relations.insert_one("team", Some(post(3)));
263
264 let json = serde_json::to_value(&relations).expect("serializes");
265
266 assert_eq!(json["posts"][0]["id"], 1);
267 assert_eq!(json["team"]["id"], 3);
268 }
269
270 #[test]
271 fn an_empty_bag_serializes_to_an_empty_map() {
272 let json = serde_json::to_value(Relations::new()).expect("serializes");
273 assert_eq!(json, serde_json::json!({}));
274 }
275}