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
use std::{io, ops::Deref, path::Path};

use serde::{ser::SerializeStruct, Serialize};
use versatile_data::{anyhow::Result, IdxFile, RowFragment};

use crate::{collection::CollectionRow, BinarySet};

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Depend {
    key: String,
    collection_row: CollectionRow,
}
impl Depend {
    pub fn new(key: impl Into<String>, collection_row: CollectionRow) -> Self {
        Self {
            key: key.into(),
            collection_row,
        }
    }
    pub fn key(&self) -> &str {
        &self.key
    }
}
impl Deref for Depend {
    type Target = CollectionRow;
    fn deref(&self) -> &Self::Target {
        &self.collection_row
    }
}
impl Serialize for Depend {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut state = serializer.serialize_struct("Depend", 3)?;
        state.serialize_field("key", &self.key)?;
        state.serialize_field("collection_id", &self.collection_row.collection_id())?;
        state.serialize_field("row", &self.collection_row.row())?;
        state.end()
    }
}

struct RelationIndexRows {
    key: IdxFile<u32>,
    depend: IdxFile<CollectionRow>,
    pend: IdxFile<CollectionRow>,
}
pub struct RelationIndex {
    fragment: RowFragment,
    key_names: BinarySet,
    rows: RelationIndexRows,
}
impl RelationIndex {
    pub fn new(root_dir: &Path) -> io::Result<Self> {
        let mut dir = root_dir.to_path_buf();
        dir.push("relation");
        if !dir.exists() {
            std::fs::create_dir_all(&dir)?;
        }
        Ok(Self {
            key_names: BinarySet::new({
                let mut path = dir.clone();
                path.push("key_name");
                path
            })?,
            fragment: RowFragment::new({
                let mut path = dir.clone();
                path.push("fragment.f");
                path
            })?,
            rows: RelationIndexRows {
                key: IdxFile::new({
                    let mut path = dir.clone();
                    path.push("key.i");
                    path
                })?,
                depend: IdxFile::new({
                    let mut path = dir.clone();
                    path.push("depend.i");
                    path
                })?,
                pend: IdxFile::new({
                    let mut path = dir.clone();
                    path.push("pend.i");
                    path
                })?,
            },
        })
    }
    pub fn insert(
        &mut self,
        relation_key: &str,
        depend: CollectionRow,
        pend: CollectionRow,
    ) -> Result<()> {
        if let Ok(key_id) = self.key_names.row_or_insert(relation_key.as_bytes()) {
            if let Some(row) = self.fragment.pop()? {
                self.rows.key.update(row, key_id)?;
                self.rows.depend.update(row, depend)?;
                self.rows.pend.update(row, pend)?;
            } else {
                self.rows.key.insert(key_id)?;
                self.rows.depend.insert(depend)?;
                self.rows.pend.insert(pend)?;
            }
        }
        Ok(())
    }
    pub fn delete(&mut self, row: u32) -> io::Result<u64> {
        self.rows.key.delete(row)?;
        self.rows.depend.delete(row)?;
        self.rows.pend.delete(row)?;
        self.fragment.insert_blank(row)
    }
    pub fn delete_pends_by_collection_row(
        &mut self,
        collection_row: &CollectionRow,
    ) -> io::Result<()> {
        for row in self
            .rows
            .pend
            .iter_by(|v| v.cmp(collection_row))
            .map(|x| x.row())
            .collect::<Vec<u32>>()
        {
            self.delete(row)?;
        }
        Ok(())
    }
    pub fn pends(&self, key: Option<&str>, depend: &CollectionRow) -> Vec<CollectionRow> {
        let mut ret: Vec<CollectionRow> = Vec::new();
        if let Some(key) = key {
            if let Some(key) = self.key_names.row(key.as_bytes()) {
                for i in self.rows.depend.iter_by(|v| v.cmp(depend)).map(|x| x.row()) {
                    if let (Some(key_row), Some(collection_row)) =
                        (self.rows.key.value(i), self.rows.pend.value(i))
                    {
                        if *key_row == key {
                            ret.push(collection_row.clone());
                        }
                    }
                }
            }
        } else {
            for i in self.rows.depend.iter_by(|v| v.cmp(depend)).map(|x| x.row()) {
                if let Some(collection_row) = self.rows.pend.value(i) {
                    ret.push(collection_row.clone());
                }
            }
        }
        ret
    }
    pub fn depends(&self, key: Option<&str>, pend: &CollectionRow) -> Vec<Depend> {
        let mut ret: Vec<Depend> = Vec::new();
        if let Some(key_name) = key {
            if let Some(key) = self.key_names.row(key_name.as_bytes()) {
                for i in self.rows.pend.iter_by(|v| v.cmp(pend)).map(|x| x.row()) {
                    if let (Some(key_row), Some(collection_row)) =
                        (self.rows.key.value(i), self.rows.depend.value(i))
                    {
                        if *key_row == key {
                            ret.push(Depend::new(key_name, collection_row.clone()));
                        }
                    }
                }
            }
        } else {
            for i in self.rows.pend.iter_by(|v| v.cmp(pend)).map(|x| x.row()) {
                if let (Some(key), Some(collection_row)) =
                    (self.rows.key.value(i), self.rows.pend.value(i))
                {
                    ret.push(Depend::new(
                        unsafe { std::str::from_utf8_unchecked(self.key_names.bytes(*key)) },
                        collection_row.clone(),
                    ));
                }
            }
        }
        ret
    }
    pub fn index_depend(&self) -> &IdxFile<CollectionRow> {
        &self.rows.depend
    }
    pub fn index_pend(&self) -> &IdxFile<CollectionRow> {
        &self.rows.pend
    }
    pub fn depend(&self, row: u32) -> Option<&CollectionRow> {
        self.rows.depend.value(row)
    }
    pub unsafe fn key(&self, row: u32) -> Result<&str, std::str::Utf8Error> {
        Ok(if let Some(key_row) = self.rows.key.value(row) {
            std::str::from_utf8(self.key_names.bytes(*key_row))?
        } else {
            ""
        })
    }
}