semilattice_database/
relation.rs

1mod index;
2
3pub use index::RelationIndex;
4
5use std::{
6    num::{NonZeroI32, NonZeroU32},
7    ops::Deref,
8    sync::Arc,
9};
10
11use serde::{ser::SerializeStruct, Serialize};
12
13use crate::{collection::CollectionRow, Database};
14
15#[derive(Clone, PartialEq, Eq, Debug)]
16pub struct Depend {
17    key: Arc<String>,
18    collection_row: CollectionRow,
19}
20impl Depend {
21    pub fn new(key: Arc<String>, collection_row: CollectionRow) -> Self {
22        Self {
23            key,
24            collection_row,
25        }
26    }
27
28    pub fn key(&self) -> &Arc<String> {
29        &self.key
30    }
31}
32impl Deref for Depend {
33    type Target = CollectionRow;
34    fn deref(&self) -> &Self::Target {
35        &self.collection_row
36    }
37}
38impl Serialize for Depend {
39    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
40    where
41        S: serde::Serializer,
42    {
43        let mut state = serializer.serialize_struct("Depend", 3)?;
44        state.serialize_field("key", self.key.as_str())?;
45        state.serialize_field("collection_id", &self.collection_row.collection_id())?;
46        state.serialize_field("row", &self.collection_row.row())?;
47        state.end()
48    }
49}
50
51impl Database {
52    pub fn relation(&self) -> &RelationIndex {
53        &self.relation
54    }
55
56    pub fn relation_mut(&mut self) -> &mut RelationIndex {
57        &mut self.relation
58    }
59
60    pub async fn register_relation(
61        &mut self,
62        key_name: &str,
63        depend: &CollectionRow,
64        pend: &CollectionRow,
65    ) {
66        self.relation.insert(key_name, depend, pend).await
67    }
68
69    pub async fn register_relations(
70        &mut self,
71        depend: &CollectionRow,
72        pends: Vec<(Arc<String>, CollectionRow)>,
73    ) {
74        for (key_name, pend) in pends.iter() {
75            self.register_relation(key_name.as_str(), depend, pend)
76                .await;
77        }
78    }
79
80    pub fn depends(
81        &self,
82        key: Option<Arc<String>>,
83        pend_collection_id: NonZeroI32,
84        pend_row: NonZeroU32,
85    ) -> Vec<Depend> {
86        self.relation
87            .depends(key, &CollectionRow::new(pend_collection_id, pend_row))
88            .into_iter()
89            .collect()
90    }
91}