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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use crate::errors::ErrorVm;
use spacetimedb_lib::relation::{FieldExpr, Header, RelValue, RelValueRef, RowCount};
use spacetimedb_sats::product_value::ProductValue;
use std::collections::HashMap;

pub(crate) trait ResultExt<T> {
    fn unpack_fold(self) -> Result<T, ErrorVm>;
}

/// A trait for dealing with fallible iterators for the database.
pub trait RelOps {
    fn head(&self) -> &Header;
    fn row_count(&self) -> RowCount;
    /// Advances the `iterator` and returns the next [RelValue].
    fn next(&mut self) -> Result<Option<RelValue>, ErrorVm>;

    /// Applies a function over the elements of the iterator, producing a single final value.
    ///
    /// This is used as the "base" of many methods on `FallibleIterator`.
    #[inline]
    fn try_fold<B, E, F>(&mut self, mut init: B, mut f: F) -> Result<B, E>
    where
        Self: Sized,
        E: From<ErrorVm>,
        F: FnMut(B, RelValue) -> Result<B, ErrorVm>,
    {
        while let Some(v) = self.next()? {
            init = f(init, v)?;
        }
        Ok(init)
    }

    /// Creates an `Iterator` which uses a closure to determine if a [RelValueRef] should be yielded.
    ///
    /// Given a [RelValueRef] the closure must return true or false.
    /// The returned iterator will yield only the elements for which the closure returns true.
    ///
    /// Note:
    ///
    /// It is the equivalent of a `WHERE` clause on SQL.
    #[inline]
    fn select<P>(self, predicate: P) -> Select<Self, P>
    where
        P: FnMut(RelValueRef) -> Result<bool, ErrorVm>,
        Self: Sized,
    {
        let count = self.row_count();
        let head = self.head().clone();
        Select::new(self, count, head, predicate)
    }

    /// Creates an `Iterator` which uses a closure that project a new [ProductValue] extracted from the current.
    ///
    /// Given a [ProductValue] the closure must return a subset of the current one.
    ///
    /// The [Header] is pre-checked that all the fields exist and return a error if any field is not found.
    ///
    /// Note:
    ///
    /// It is the equivalent of a `SELECT` clause on SQL.
    #[inline]
    fn project<P>(self, cols: &[FieldExpr], extractor: P) -> Result<Project<Self, P>, ErrorVm>
    where
        P: FnMut(RelValueRef) -> Result<ProductValue, ErrorVm>,
        Self: Sized,
    {
        let count = self.row_count();
        let head = self.head().project(cols)?;
        Ok(Project::new(self, count, head, extractor))
    }

    /// Intersection between the left and the right, both (non-sorted) `iterators`.
    ///
    /// The hash join strategy requires the right iterator can be collected to a `HashMap`.
    /// The left iterator can be arbitrarily long.
    ///
    /// It is therefore asymmetric (you can't flip the iterators to get a right_outer join).
    ///    
    /// Note:
    ///
    /// It is the equivalent of a `INNER JOIN` clause on SQL.
    #[inline]
    fn join_inner<Pred, Proj, KeyLhs, KeyRhs, Rhs>(
        self,
        with: Rhs,
        head: Header,
        key_lhs: KeyLhs,
        key_rhs: KeyRhs,
        predicate: Pred,
        project: Proj,
    ) -> Result<JoinInner<Self, Rhs, KeyLhs, KeyRhs, Pred, Proj>, ErrorVm>
    where
        Self: Sized,
        Pred: FnMut(RelValueRef, RelValueRef) -> Result<bool, ErrorVm>,
        Proj: FnMut(RelValue, RelValue) -> RelValue,
        KeyLhs: FnMut(RelValueRef) -> Result<ProductValue, ErrorVm>,
        KeyRhs: FnMut(RelValueRef) -> Result<ProductValue, ErrorVm>,
        Rhs: RelOps,
    {
        Ok(JoinInner::new(head, self, with, key_lhs, key_rhs, predicate, project))
    }

    /// Utility to collect the results into a [Vec]
    #[inline]
    fn collect_vec(mut self) -> Result<Vec<RelValue>, ErrorVm>
    where
        Self: Sized,
    {
        let count = self.row_count();
        let estimate = count.max.unwrap_or(count.min);
        let mut result = Vec::with_capacity(estimate);

        while let Some(row) = self.next()? {
            result.push(row);
        }

        Ok(result)
    }
}

impl<I: RelOps + ?Sized> RelOps for Box<I> {
    fn head(&self) -> &Header {
        (**self).head()
    }

    fn row_count(&self) -> RowCount {
        (**self).row_count()
    }

    fn next(&mut self) -> Result<Option<RelValue>, ErrorVm> {
        (**self).next()
    }
}

#[derive(Clone, Debug)]
pub struct Select<I, P> {
    pub(crate) head: Header,
    pub(crate) count: RowCount,
    pub(crate) iter: I,
    pub(crate) predicate: P,
}

impl<I, P> Select<I, P> {
    pub fn new(iter: I, count: RowCount, head: Header, predicate: P) -> Select<I, P> {
        Select {
            iter,
            count,
            predicate,
            head,
        }
    }
}

impl<I, P> RelOps for Select<I, P>
where
    I: RelOps,
    P: FnMut(RelValueRef) -> Result<bool, ErrorVm>,
{
    fn head(&self) -> &Header {
        &self.head
    }

    fn row_count(&self) -> RowCount {
        self.count
    }

    #[tracing::instrument(skip_all)]
    fn next(&mut self) -> Result<Option<RelValue>, ErrorVm> {
        let filter = &mut self.predicate;
        while let Some(v) = self.iter.next()? {
            if filter(v.as_val_ref())? {
                return Ok(Some(v));
            }
        }
        Ok(None)
    }
}

#[derive(Clone, Debug)]
pub struct Project<I, P> {
    pub(crate) head: Header,
    pub(crate) count: RowCount,
    pub(crate) iter: I,
    pub(crate) extractor: P,
}

impl<I, P> Project<I, P> {
    pub fn new(iter: I, count: RowCount, head: Header, extractor: P) -> Project<I, P> {
        Project {
            iter,
            count,
            extractor,
            head,
        }
    }
}

impl<I, P> RelOps for Project<I, P>
where
    I: RelOps,
    P: FnMut(RelValueRef) -> Result<ProductValue, ErrorVm>,
{
    fn head(&self) -> &Header {
        &self.head
    }

    fn row_count(&self) -> RowCount {
        self.count
    }

    #[tracing::instrument(skip_all)]
    fn next(&mut self) -> Result<Option<RelValue>, ErrorVm> {
        let extract = &mut self.extractor;
        if let Some(v) = self.iter.next()? {
            let row = extract(v.as_val_ref())?;
            return Ok(Some(RelValue::new(row, None)));
        }
        Ok(None)
    }
}

#[derive(Clone, Debug)]
pub struct JoinInner<Lhs, Rhs, KeyLhs, KeyRhs, Pred, Proj> {
    pub(crate) head: Header,
    pub(crate) count: RowCount,
    pub(crate) lhs: Lhs,
    pub(crate) rhs: Rhs,
    pub(crate) key_lhs: KeyLhs,
    pub(crate) key_rhs: KeyRhs,
    pub(crate) predicate: Pred,
    pub(crate) projection: Proj,
    map: HashMap<ProductValue, Vec<RelValue>>,
    filled: bool,
    left: Option<RelValue>,
}

impl<Lhs, Rhs, KeyLhs, KeyRhs, Pred, Proj> JoinInner<Lhs, Rhs, KeyLhs, KeyRhs, Pred, Proj> {
    pub fn new(
        head: Header,
        lhs: Lhs,
        rhs: Rhs,
        key_lhs: KeyLhs,
        key_rhs: KeyRhs,
        predicate: Pred,
        projection: Proj,
    ) -> Self {
        Self {
            head,
            count: RowCount::unknown(),
            map: HashMap::new(),
            lhs,
            rhs,
            key_lhs,
            key_rhs,
            predicate,
            projection,
            filled: false,
            left: None,
        }
    }
}

impl<Lhs, Rhs, KeyLhs, KeyRhs, Pred, Proj> RelOps for JoinInner<Lhs, Rhs, KeyLhs, KeyRhs, Pred, Proj>
where
    Lhs: RelOps,
    Rhs: RelOps,
    KeyLhs: FnMut(RelValueRef) -> Result<ProductValue, ErrorVm>,
    KeyRhs: FnMut(RelValueRef) -> Result<ProductValue, ErrorVm>,
    Pred: FnMut(RelValueRef, RelValueRef) -> Result<bool, ErrorVm>,
    Proj: FnMut(RelValue, RelValue) -> RelValue,
{
    fn head(&self) -> &Header {
        &self.head
    }

    fn row_count(&self) -> RowCount {
        self.count
    }

    #[tracing::instrument(skip_all)]
    fn next(&mut self) -> Result<Option<RelValue>, ErrorVm> {
        if !self.filled {
            self.map = HashMap::with_capacity(self.rhs.row_count().min);
            while let Some(v) = self.rhs.next()? {
                let k = (self.key_rhs)(v.as_val_ref())?;
                let values = self.map.entry(k).or_insert_with(|| Vec::with_capacity(1));
                values.push(v);
            }
            self.filled = true;
        }
        loop {
            let lhs = if let Some(left) = &self.left {
                left.clone()
            } else {
                match self.lhs.next()? {
                    None => return Ok(None),
                    Some(x) => {
                        self.left = Some(x.clone());
                        x
                    }
                }
            };

            let k = (self.key_lhs)(lhs.as_val_ref())?;
            if let Some(rvv) = self.map.get_mut(&k) {
                if let Some(rhs) = rvv.pop() {
                    if (self.predicate)(lhs.as_val_ref(), rhs.as_val_ref())? {
                        self.count.add_exact(1);
                        return Ok(Some((self.projection)(lhs, rhs)));
                    }
                }
            }
            self.left = None;
            continue;
        }
    }
}