1use std::any::Any;
5use std::borrow::Cow;
6use std::fmt;
7
8use navree_kernel::BoxFuture;
9use serde::Serialize;
10
11use crate::collection::Collection;
12use crate::error::Result;
13use crate::exec::Target;
14use crate::model::Model;
15use crate::record::Record;
16use crate::relations::any::AnyRecord;
17use crate::value::Value;
18
19type AnyValue = dyn Any + Send + Sync;
20
21type PushFn = for<'a, 'b> fn(&'a mut AnyValue, &'a Target<'b>) -> BoxFuture<'a, Result<bool>>;
23
24type ColumnFn = fn(&AnyValue, &str) -> Option<Value>;
26
27pub(crate) mod sealed {
28 pub trait Sealed {}
30}
31
32pub trait RelationValue: Clone + Serialize + Send + Sync + 'static + sealed::Sealed {
43 #[doc(hidden)]
45 fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>>;
46
47 #[doc(hidden)]
50 fn column(&self, column: &str) -> Option<Value> {
51 let _ = column;
52 None
53 }
54}
55
56impl<R: Model> sealed::Sealed for Option<Record<R>> {}
57
58impl<R: Model> RelationValue for Option<Record<R>> {
59 fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>> {
60 Box::pin(async move {
61 match self {
62 Some(record) => crate::relations::lazy::push_record(record, target).await,
63 None => Ok(true),
64 }
65 })
66 }
67}
68
69impl<R: Model> sealed::Sealed for Record<R> {}
70
71impl<R: Model> RelationValue for Record<R> {
72 fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>> {
73 crate::relations::lazy::push_record(self, target)
74 }
75
76 fn column(&self, column: &str) -> Option<Value> {
77 self.model.value(column).ok().flatten()
78 }
79}
80
81impl<R: Model> sealed::Sealed for Collection<R> {}
82
83impl<R: Model> RelationValue for Collection<R> {
84 fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>> {
85 Box::pin(async move {
86 for record in self.iter_mut() {
87 if !crate::relations::lazy::push_record(record, target).await? {
88 return Ok(false);
89 }
90 }
91 Ok(true)
92 })
93 }
94}
95
96impl sealed::Sealed for Option<AnyRecord> {}
97
98impl RelationValue for Option<AnyRecord> {
99 fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>> {
100 Box::pin(async move {
101 match self {
102 Some(record) => record.push_on(target).await,
103 None => Ok(true),
104 }
105 })
106 }
107}
108
109struct Slot {
113 name: Cow<'static, str>,
114 value: Box<AnyValue>,
115 clone: fn(&AnyValue) -> Box<AnyValue>,
116 to_json: fn(&AnyValue) -> Result<serde_json::Value, serde_json::Error>,
117 push: Option<PushFn>,
118 column: Option<ColumnFn>,
119}
120
121impl Slot {
122 fn duplicate(&self) -> Slot {
124 Slot {
125 name: self.name.clone(),
126 value: (self.clone)(&*self.value),
127 clone: self.clone,
128 to_json: self.to_json,
129 push: self.push,
130 column: self.column,
131 }
132 }
133}
134
135fn column_of<V: RelationValue>(value: &AnyValue, column: &str) -> Option<Value> {
136 value.downcast_ref::<V>()?.column(column)
137}
138
139fn clone_value<T: Clone + Send + Sync + 'static>(value: &AnyValue) -> Box<AnyValue> {
140 match value.downcast_ref::<T>() {
141 Some(value) => Box::new(value.clone()),
142 None => Box::new(()),
144 }
145}
146
147fn value_to_json<T: Serialize + 'static>(
148 value: &AnyValue,
149) -> Result<serde_json::Value, serde_json::Error> {
150 match value.downcast_ref::<T>() {
151 Some(value) => serde_json::to_value(value),
152 None => Ok(serde_json::Value::Null),
153 }
154}
155
156fn push_value<'a, 'b, V: RelationValue>(
157 value: &'a mut AnyValue,
158 target: &'a Target<'b>,
159) -> BoxFuture<'a, Result<bool>> {
160 match value.downcast_mut::<V>() {
161 Some(value) => value.push_on(target),
162 None => Box::pin(async { Ok(true) }),
163 }
164}
165
166#[derive(Default)]
185pub struct Relations {
186 slots: Vec<Slot>,
187}
188
189impl Relations {
190 pub fn new() -> Self {
192 Relations::default()
193 }
194
195 fn put(&mut self, slot: Slot) {
196 match self
197 .slots
198 .iter_mut()
199 .find(|existing| existing.name == slot.name)
200 {
201 Some(existing) => *existing = slot,
202 None => self.slots.push(slot),
203 }
204 }
205
206 pub fn set<T>(&mut self, name: impl Into<Cow<'static, str>>, value: T)
211 where
212 T: Clone + Serialize + Send + Sync + 'static,
213 {
214 self.put(Slot {
215 name: name.into(),
216 value: Box::new(value),
217 clone: clone_value::<T>,
218 to_json: value_to_json::<T>,
219 push: None,
220 column: None,
221 });
222 }
223
224 pub fn set_relation<V: RelationValue>(&mut self, name: impl Into<Cow<'static, str>>, value: V) {
227 self.put(Slot {
228 name: name.into(),
229 value: Box::new(value),
230 clone: clone_value::<V>,
231 to_json: value_to_json::<V>,
232 push: Some(push_value::<V>),
233 column: Some(column_of::<V>),
234 });
235 }
236
237 pub(crate) fn column(&self, name: &str, column: &str) -> Option<Value> {
240 let slot = self.slots.iter().find(|slot| slot.name == name)?;
241 (slot.column?)(&*slot.value, column)
242 }
243
244 pub fn get<T: 'static>(&self, name: &str) -> Option<&T> {
246 self.slots
247 .iter()
248 .find(|slot| slot.name == name)
249 .and_then(|slot| slot.value.downcast_ref::<T>())
250 }
251
252 pub fn get_mut<T: 'static>(&mut self, name: &str) -> Option<&mut T> {
254 self.slots
255 .iter_mut()
256 .find(|slot| slot.name == name)
257 .and_then(|slot| slot.value.downcast_mut::<T>())
258 }
259
260 pub fn take<T: 'static>(&mut self, name: &str) -> Option<T> {
263 let index = self.slots.iter().position(|slot| slot.name == name)?;
264 if !self.slots[index].value.is::<T>() {
265 return None;
266 }
267 let slot = self.slots.remove(index);
268 slot.value.downcast::<T>().ok().map(|value| *value)
269 }
270
271 pub fn is_loaded(&self, name: &str) -> bool {
273 self.slots.iter().any(|slot| slot.name == name)
274 }
275
276 pub fn unset(&mut self, name: &str) {
278 self.slots.retain(|slot| slot.name != name);
279 }
280
281 pub fn clear(&mut self) {
283 self.slots.clear();
284 }
285
286 pub fn names(&self) -> impl Iterator<Item = &str> {
288 self.slots.iter().map(|slot| slot.name.as_ref())
289 }
290
291 pub fn len(&self) -> usize {
293 self.slots.len()
294 }
295
296 pub fn is_empty(&self) -> bool {
298 self.slots.is_empty()
299 }
300
301 pub fn to_json(&self) -> Result<serde_json::Value, serde_json::Error> {
303 let mut object = serde_json::Map::with_capacity(self.slots.len());
304 for slot in &self.slots {
305 object.insert(slot.name.to_string(), (slot.to_json)(&*slot.value)?);
306 }
307 Ok(serde_json::Value::Object(object))
308 }
309
310 pub(crate) fn copy_from(&mut self, other: &Relations, name: &str) {
313 if let Some(slot) = other.slots.iter().find(|slot| slot.name == name) {
314 self.put(slot.duplicate());
315 }
316 }
317
318 pub(crate) fn push_all<'a, 'b>(
321 &'a mut self,
322 target: &'a Target<'b>,
323 ) -> BoxFuture<'a, Result<bool>> {
324 Box::pin(async move {
325 for slot in &mut self.slots {
326 if let Some(push) = slot.push
327 && !push(&mut *slot.value, target).await?
328 {
329 return Ok(false);
330 }
331 }
332 Ok(true)
333 })
334 }
335}
336
337impl Clone for Relations {
338 fn clone(&self) -> Self {
339 Relations {
340 slots: self.slots.iter().map(Slot::duplicate).collect(),
341 }
342 }
343}
344
345impl fmt::Debug for Relations {
346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347 f.debug_list().entries(self.names()).finish()
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354
355 #[test]
356 fn values_are_typed_replaced_cloned_and_taken() {
357 let mut relations = Relations::new();
358 relations.set("owner", Some("anu".to_owned()));
359 relations.set("owner", Some("gauri".to_owned()));
360 assert_eq!(relations.names().collect::<Vec<_>>(), ["owner"]);
361 let copy = relations.clone();
362 relations
363 .get_mut::<Option<String>>("owner")
364 .unwrap()
365 .replace("laksh".into());
366 assert_eq!(
367 copy.get::<Option<String>>("owner").unwrap().as_deref(),
368 Some("gauri")
369 );
370 assert!(relations.take::<u8>("owner").is_none());
371 assert_eq!(relations.len(), 1, "a take of another type leaves it");
372 assert_eq!(
373 relations
374 .take::<Option<String>>("owner")
375 .unwrap()
376 .as_deref(),
377 Some("laksh")
378 );
379 assert!(relations.is_empty());
380 assert_eq!(format!("{copy:?}"), r#"["owner"]"#);
381 }
382}