uqa-execution 0.6.2

Volcano physical operators with row-batch pipelines
Documentation
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Correlated physical join operator.

use uqa_sql::ast::JoinKind;
use uqa_sql::ResultRow;

use crate::batch::DEFAULT_BATCH_SIZE;
use crate::{
    Batch, ExecError, ExecResult, OwnedPhysicalRow, PhysicalOperator, PhysicalRow, RowSchema,
};

/// Execution source for a correlated right-hand relation.
///
/// The physical operator owns join iteration, `ON` filtering, and outer-row preservation. The source only evaluates the right relation, the predicates placed on that relation, and the scalar join predicate in the current correlated scope.
pub type LateralRows<'a> = crate::SQLRowStream<'a, OwnedPhysicalRow>;

pub trait LateralSource<'a>: Send {
    fn rows_for(&mut self, left: &OwnedPhysicalRow) -> ExecResult<LateralRows<'a>>;

    /// Whether a produced right row satisfies the predicates placed on the right relation itself. A rejected row is absent from the join input: it neither matches a left row nor produces a NULL-extended row.
    fn admits(&mut self, right: &OwnedPhysicalRow) -> ExecResult<bool>;

    fn matches(&mut self, joined: &OwnedPhysicalRow) -> ExecResult<bool>;

    /// Release a source prepared while binding its runtime descriptor, even
    /// when the consumer never requests the first joined row.
    fn close(&mut self) -> ExecResult<()> {
        Ok(())
    }
}

fn output_schema(
    left: &RowSchema,
    right: &RowSchema,
    left_nulls: &ResultRow,
    right_nulls: &ResultRow,
) -> RowSchema {
    RowSchema::join(
        left,
        right,
        left_nulls.keys().chain(right_nulls.keys()).cloned(),
    )
}

/// Streaming physical implementation of a SQL `LATERAL` join.
///
/// The left child is pulled in batches. The correlated right relation is
/// evaluated once per left row, and produced rows are drained in bounded
/// output batches instead of materialising the complete join result.
pub struct LateralJoin<'a> {
    left: Box<dyn PhysicalOperator + 'a>,
    source: Box<dyn LateralSource<'a> + 'a>,
    kind: JoinKind,
    schema: RowSchema,
    left_schema: RowSchema,
    right_presence: crate::join::presence::NullableRow,
    left_rows: std::vec::IntoIter<OwnedPhysicalRow>,
    current_left: Option<OwnedPhysicalRow>,
    right_rows: Option<LateralRows<'a>>,
    matched_left: bool,
    exhausted: bool,
}

impl<'a> LateralJoin<'a> {
    pub fn new(
        left: Box<dyn PhysicalOperator + 'a>,
        source: Box<dyn LateralSource<'a> + 'a>,
        kind: JoinKind,
        left_nulls: ResultRow,
        right_nulls: ResultRow,
    ) -> Self {
        let right_schema = RowSchema::new(right_nulls.keys().cloned().collect());
        Self::new_with_right_schema(left, source, kind, left_nulls, right_nulls, right_schema)
    }

    pub fn new_with_right_schema(
        left: Box<dyn PhysicalOperator + 'a>,
        source: Box<dyn LateralSource<'a> + 'a>,
        kind: JoinKind,
        left_nulls: ResultRow,
        right_nulls: ResultRow,
        right_schema: RowSchema,
    ) -> Self {
        let left =
            crate::join::presence::input(left, matches!(kind, JoinKind::Right | JoinKind::Full));
        let right_presence = crate::join::presence::NullableRow::new(
            &right_schema,
            matches!(kind, JoinKind::Left | JoinKind::Full),
        );
        let schema = output_schema(
            left.row_schema(),
            &right_presence.schema,
            &left_nulls,
            &right_nulls,
        );
        let left_schema = left.row_schema().clone();
        Self {
            left,
            source,
            kind,
            schema,
            left_schema,
            right_presence,
            left_rows: Vec::new().into_iter(),
            current_left: None,
            right_rows: None,
            matched_left: false,
            exhausted: false,
        }
    }

    fn next_left(&mut self) -> ExecResult<Option<OwnedPhysicalRow>> {
        loop {
            if let Some(row) = self.left_rows.next() {
                return Ok(Some(row));
            }
            let Some(batch) = self.left.next_with_demand(crate::physical::demand::ONE)? else {
                return Ok(None);
            };
            self.left_rows = batch.into_owned_rows().into_iter();
        }
    }

    fn begin_left_row(&mut self, left: OwnedPhysicalRow) -> ExecResult<()> {
        self.right_rows = Some(self.source.rows_for(&left)?);
        self.current_left = Some(left);
        self.matched_left = false;
        Ok(())
    }
}

impl LateralJoin<'_> {
    fn close_right(&mut self) -> ExecResult<()> {
        self.right_rows
            .take()
            .map_or(Ok(()), |mut rows| rows.close().map_err(Into::into))
    }

    fn pull(&mut self, batch_size: usize) -> ExecResult<Option<Batch>> {
        if self.exhausted && self.current_left.is_none() {
            return Ok(None);
        }

        let mut output = Vec::with_capacity(batch_size);
        while output.len() < batch_size {
            if self.current_left.is_none() {
                match self.next_left()? {
                    Some(left) => self.begin_left_row(left)?,
                    None => {
                        self.exhausted = true;
                        break;
                    }
                }
            }

            let next_right = self
                .right_rows
                .as_mut()
                .and_then(Iterator::next)
                .transpose()?;
            if let Some(right) = next_right {
                if !self.source.admits(&right)? {
                    continue;
                }
                let right = self.right_presence.owned_row(right)?;
                let left = self.current_left.as_ref().ok_or_else(|| {
                    ExecError::Other(
                        "lateral join produced a right row without a current left row".into(),
                    )
                })?;
                let joined = OwnedPhysicalRow::new(
                    self.schema.clone(),
                    PhysicalRow::concat(&left.row, &right),
                );
                let matched =
                    matches!(self.kind, JoinKind::Cross) || self.source.matches(&joined)?;
                if matched {
                    self.matched_left = true;
                    output.push(joined.row);
                } else if matches!(self.kind, JoinKind::Right | JoinKind::Full) {
                    output.push(PhysicalRow::concat(
                        &PhysicalRow::nulls(self.left_schema.physical_width()),
                        &right,
                    ));
                }
                continue;
            }

            self.close_right()?;
            if !self.matched_left && matches!(self.kind, JoinKind::Left | JoinKind::Full) {
                let left = self.current_left.take().ok_or_else(|| {
                    ExecError::Other(
                        "lateral join completed a right stream without a current left row".into(),
                    )
                })?;
                output.push(PhysicalRow::concat(
                    &left.row,
                    &PhysicalRow::nulls(self.right_presence.schema.physical_width()),
                ));
            } else {
                self.current_left = None;
            }
        }

        if output.is_empty() {
            return Ok(None);
        }
        Ok(Some(Batch::from_physical_rows(self.schema.clone(), output)))
    }
}

impl PhysicalOperator for LateralJoin<'_> {
    fn row_schema(&self) -> &RowSchema {
        &self.schema
    }

    fn open(&mut self) -> ExecResult<()> {
        self.left_rows = Vec::new().into_iter();
        self.current_left = None;
        self.close_right()?;
        self.matched_left = false;
        self.exhausted = false;
        self.left.open()
    }

    fn next(&mut self) -> ExecResult<Option<Batch>> {
        self.pull(DEFAULT_BATCH_SIZE)
    }

    fn next_with_demand(&mut self, rows: std::num::NonZeroUsize) -> ExecResult<Option<Batch>> {
        self.pull(rows.get().min(DEFAULT_BATCH_SIZE))
    }

    fn close(&mut self) -> ExecResult<()> {
        self.left_rows = Vec::new().into_iter();
        self.current_left = None;
        let right = self.close_right();
        let right =
            crate::physical::with_cleanup(right, self.source.close(), "close lateral source");
        self.matched_left = false;
        self.exhausted = true;
        crate::physical::with_cleanup(right, self.left.close(), "close lateral left input")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::physical::run_to_rows;
    use crate::scan::TableScan;
    use uqa_core::Value;

    fn row(values: &[(&str, Value)]) -> ResultRow {
        values
            .iter()
            .map(|(column, value)| ((*column).to_string(), value.clone()))
            .collect()
    }

    fn right_row(value: i64) -> OwnedPhysicalRow {
        let schema = RowSchema::new(vec!["r.n".into()]);
        let row = PhysicalRow::from_values(vec![Value::Int(value)]);
        OwnedPhysicalRow::new(schema, row)
    }

    struct RangeSource;

    impl<'a> LateralSource<'a> for RangeSource {
        fn rows_for(&mut self, left: &OwnedPhysicalRow) -> ExecResult<LateralRows<'a>> {
            let Value::Int(end) = left.get("l.n").cloned().unwrap_or(Value::Null) else {
                return Ok(crate::SQLRowStream::new(std::iter::empty()));
            };
            Ok(crate::SQLRowStream::new(
                (1..=end).map(|value| Ok(right_row(value))),
            ))
        }

        fn admits(&mut self, _right: &OwnedPhysicalRow) -> ExecResult<bool> {
            Ok(true)
        }

        fn matches(&mut self, joined: &OwnedPhysicalRow) -> ExecResult<bool> {
            Ok(joined.get("r.n") == Some(&Value::Int(2)))
        }
    }

    #[test]
    fn left_lateral_preserves_a_left_row_without_an_on_match() {
        let left = TableScan::from_rows(
            vec!["l.n".into()],
            vec![
                row(&[("l.n", Value::Int(1))]),
                row(&[("l.n", Value::Int(2))]),
            ],
        );
        let mut join = LateralJoin::new(
            Box::new(left),
            Box::new(RangeSource),
            JoinKind::Left,
            row(&[("l.n", Value::Null)]),
            row(&[("r.n", Value::Null)]),
        );
        let (_, rows) = run_to_rows(&mut join).unwrap();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].get("l.n"), Some(&Value::Int(1)));
        assert_eq!(rows[0].get("r.n"), Some(&Value::Null));
        assert_eq!(rows[1].get("l.n"), Some(&Value::Int(2)));
        assert_eq!(rows[1].get("r.n"), Some(&Value::Int(2)));
    }

    /// The right relation `1..=l.n` with `r.n <> 2` placed on it, joined on `r.n = 2`.
    struct RejectingRangeSource;

    impl<'a> LateralSource<'a> for RejectingRangeSource {
        fn rows_for(&mut self, left: &OwnedPhysicalRow) -> ExecResult<LateralRows<'a>> {
            RangeSource.rows_for(left)
        }

        fn admits(&mut self, right: &OwnedPhysicalRow) -> ExecResult<bool> {
            Ok(right.get("r.n") != Some(&Value::Int(2)))
        }

        fn matches(&mut self, joined: &OwnedPhysicalRow) -> ExecResult<bool> {
            RangeSource.matches(joined)
        }
    }

    /// The planner places conjuncts on the right relation of inner and cross joins, and propagates join-key constants into the right relation of a left join, whose left rows then lose every rejected match.
    #[test]
    fn rejected_right_rows_are_absent_from_inner_and_left_lateral_joins() {
        let n = |value: i64| Value::Int(value);
        for (kind, expected) in [
            (JoinKind::Cross, vec![(n(1), n(1)), (n(2), n(1))]),
            (JoinKind::Inner, Vec::new()),
            (
                JoinKind::Left,
                vec![(n(1), Value::Null), (n(2), Value::Null)],
            ),
        ] {
            let left = TableScan::from_rows(
                vec!["l.n".into()],
                vec![
                    row(&[("l.n", Value::Int(1))]),
                    row(&[("l.n", Value::Int(2))]),
                ],
            );
            let mut join = LateralJoin::new(
                Box::new(left),
                Box::new(RejectingRangeSource),
                kind,
                row(&[("l.n", Value::Null)]),
                row(&[("r.n", Value::Null)]),
            );
            let (_, rows) = run_to_rows(&mut join).unwrap();
            let actual = rows
                .iter()
                .map(|row| (row["l.n"].clone(), row["r.n"].clone()))
                .collect::<Vec<_>>();
            assert_eq!(actual, expected, "{kind:?}");
        }
    }

    struct LargeRangeSource;

    impl<'a> LateralSource<'a> for LargeRangeSource {
        fn rows_for(&mut self, _left: &OwnedPhysicalRow) -> ExecResult<LateralRows<'a>> {
            Ok(crate::SQLRowStream::new(
                (0..10_000).map(|value| Ok(right_row(value))),
            ))
        }

        fn admits(&mut self, _right: &OwnedPhysicalRow) -> ExecResult<bool> {
            Ok(true)
        }

        fn matches(&mut self, _joined: &OwnedPhysicalRow) -> ExecResult<bool> {
            Ok(true)
        }
    }

    #[test]
    fn large_correlated_relation_is_pulled_one_output_batch_at_a_time() {
        let left = TableScan::from_rows(vec!["l.n".into()], vec![row(&[("l.n", Value::Int(1))])]);
        let mut join = LateralJoin::new(
            Box::new(left),
            Box::new(LargeRangeSource),
            JoinKind::Cross,
            row(&[("l.n", Value::Null)]),
            row(&[("r.n", Value::Null)]),
        );
        join.open().unwrap();
        assert_eq!(join.next().unwrap().unwrap().len(), DEFAULT_BATCH_SIZE);
        assert_eq!(join.next().unwrap().unwrap().len(), DEFAULT_BATCH_SIZE);
        join.close().unwrap();
    }

    struct FailingSource;

    impl<'a> LateralSource<'a> for FailingSource {
        fn rows_for(&mut self, _left: &OwnedPhysicalRow) -> ExecResult<LateralRows<'a>> {
            Ok(crate::SQLRowStream::new(
                vec![
                    Ok(right_row(1)),
                    Err(uqa_sql::SQLError::Internal(
                        "injected lateral failure".into(),
                    )),
                ]
                .into_iter(),
            ))
        }

        fn admits(&mut self, _right: &OwnedPhysicalRow) -> ExecResult<bool> {
            Ok(true)
        }

        fn matches(&mut self, _joined: &OwnedPhysicalRow) -> ExecResult<bool> {
            Ok(true)
        }
    }

    #[test]
    fn late_correlated_source_error_is_propagated() {
        let left = TableScan::from_rows(vec!["l.n".into()], vec![row(&[("l.n", Value::Int(1))])]);
        let mut join = LateralJoin::new(
            Box::new(left),
            Box::new(FailingSource),
            JoinKind::Cross,
            row(&[("l.n", Value::Null)]),
            row(&[("r.n", Value::Null)]),
        );
        join.open().unwrap();
        let error = join.next().unwrap_err();
        assert!(error.to_string().contains("injected lateral failure"));
    }
}