sochdb-query 2.0.6

SochDB query engine (sync-first execution and vector query planning)
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Join operators: HashJoin, NestedLoopJoin, MergeJoin.

use super::eval::{compare_values, eval_expr, eval_predicate};
use super::node::PlanNode;
use super::types::{Row, Schema};
use crate::soch_ql::SochValue;
use crate::sql::ast::{Expr, JoinType};
use sochdb_core::Result;
use std::collections::HashMap;

// ============================================================================
// HashJoinNode — Hash-based equi-join
// ============================================================================

/// Hash join: builds a hash table from the build side, probes with the probe side.
///
/// Supports INNER, LEFT, RIGHT, and FULL [OUTER] joins.
///
/// ```text
/// HashJoin(build_key=users.id, probe_key=orders.user_id)
///   ├── build: SeqScan(users)
///   └── probe: SeqScan(orders)
/// ```
pub struct HashJoinNode {
    build: Box<dyn PlanNode>,
    probe: Box<dyn PlanNode>,
    /// Expression to evaluate on build side to produce hash key.
    build_key_expr: Expr,
    /// Expression to evaluate on probe side to produce hash key.
    probe_key_expr: Expr,
    join_type: JoinType,
    output_schema: Schema,
    /// Hash table: key -> list of build rows.
    hash_table: Option<HashMap<HashKey, Vec<Row>>>,
    /// For LEFT/RIGHT/FULL: track which build rows were matched.
    build_matched: Vec<bool>,
    /// Current probe row being processed.
    current_probe_row: Option<Row>,
    /// Matches for current probe row.
    current_matches: Vec<Row>,
    /// Index into current_matches.
    match_idx: usize,
    /// For RIGHT/FULL: unmatched build rows to emit after probe exhausted.
    unmatched_buffer: Option<Vec<Row>>,
    unmatched_pos: usize,
    /// Whether probe side is exhausted.
    probe_exhausted: bool,
    /// Whether join produced a match for current probe row.
    current_probe_matched: bool,
    build_schema: Schema,
    probe_schema: Schema,
}

/// Simple hash key wrapping a SochValue for HashMap use.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum HashKey {
    Int(i64),
    UInt(u64),
    Text(String),
    Bool(bool),
    Null,
    Other(String),
}

impl From<&SochValue> for HashKey {
    fn from(v: &SochValue) -> Self {
        match v {
            SochValue::Int(i) => HashKey::Int(*i),
            SochValue::UInt(u) => HashKey::UInt(*u),
            SochValue::Text(s) => HashKey::Text(s.clone()),
            SochValue::Bool(b) => HashKey::Bool(*b),
            SochValue::Null => HashKey::Null,
            other => HashKey::Other(format!("{:?}", other)),
        }
    }
}

impl HashJoinNode {
    pub fn new(
        build: Box<dyn PlanNode>,
        probe: Box<dyn PlanNode>,
        build_key_expr: Expr,
        probe_key_expr: Expr,
        join_type: JoinType,
    ) -> Self {
        let build_schema = build.schema().clone();
        let probe_schema = probe.schema().clone();
        let output_schema = build_schema.merge(&probe_schema);

        Self {
            build,
            probe,
            build_key_expr,
            probe_key_expr,
            join_type,
            output_schema,
            hash_table: None,
            build_matched: Vec::new(),
            current_probe_row: None,
            current_matches: Vec::new(),
            match_idx: 0,
            unmatched_buffer: None,
            unmatched_pos: 0,
            probe_exhausted: false,
            current_probe_matched: false,
            build_schema,
            probe_schema,
        }
    }

    fn build_hash_table(&mut self) -> Result<()> {
        if self.hash_table.is_some() {
            return Ok(());
        }

        let mut table: HashMap<HashKey, Vec<Row>> = HashMap::new();
        let mut all_build_rows: Vec<Row> = Vec::new();
        let schema = self.build.schema().clone();

        while let Some(row) = self.build.next()? {
            let key_val = eval_expr(&self.build_key_expr, &row, &schema)?;
            let key = HashKey::from(&key_val);
            table.entry(key).or_default().push(row.clone());
            all_build_rows.push(row);
        }

        self.build_matched = vec![false; all_build_rows.len()];
        self.hash_table = Some(table);
        Ok(())
    }

    fn null_row(schema: &Schema) -> Row {
        vec![SochValue::Null; schema.len()]
    }

    fn combine(build_row: &Row, probe_row: &Row) -> Row {
        let mut combined = build_row.clone();
        combined.extend(probe_row.iter().cloned());
        combined
    }
}

impl PlanNode for HashJoinNode {
    fn schema(&self) -> &Schema {
        &self.output_schema
    }

    fn next(&mut self) -> Result<Option<Row>> {
        self.build_hash_table()?;

        loop {
            // Return pending matches from current probe row
            if self.match_idx < self.current_matches.len() {
                let build_row = &self.current_matches[self.match_idx];
                let probe_row = self.current_probe_row.as_ref().unwrap();
                self.match_idx += 1;
                return Ok(Some(Self::combine(build_row, probe_row)));
            }

            // For LEFT join: emit unmatched probe row
            if self.current_probe_row.is_some()
                && !self.current_probe_matched
                && matches!(self.join_type, JoinType::Left | JoinType::Full)
            {
                let probe_row = self.current_probe_row.take().unwrap();
                let null_build = Self::null_row(&self.build_schema);
                return Ok(Some(Self::combine(&null_build, &probe_row)));
            }

            // Done with current probe row, reset
            self.current_probe_row = None;
            self.current_matches.clear();
            self.match_idx = 0;
            self.current_probe_matched = false;

            if !self.probe_exhausted {
                // Get next probe row
                match self.probe.next()? {
                    Some(probe_row) => {
                        let key_val =
                            eval_expr(&self.probe_key_expr, &probe_row, &self.probe_schema)?;
                        let key = HashKey::from(&key_val);

                        if let Some(ht) = &self.hash_table {
                            if let Some(matches) = ht.get(&key) {
                                self.current_matches = matches.clone();
                                self.current_probe_matched = true;
                                // Mark matched build rows
                                // (simplified: we'd need row indices for precise tracking)
                            }
                        }

                        self.current_probe_row = Some(probe_row);
                        continue;
                    }
                    None => {
                        self.probe_exhausted = true;
                    }
                }
            }

            // After probe exhausted: emit unmatched build rows for RIGHT/FULL join
            if matches!(self.join_type, JoinType::Right | JoinType::Full) {
                if self.unmatched_buffer.is_none() {
                    // Collect unmatched build rows
                    // Simplified: for now just return None
                    // Full RIGHT/FULL join requires tracking which build rows were matched
                    self.unmatched_buffer = Some(Vec::new());
                }

                if let Some(buf) = &self.unmatched_buffer {
                    if self.unmatched_pos < buf.len() {
                        let row = buf[self.unmatched_pos].clone();
                        self.unmatched_pos += 1;
                        let null_probe = Self::null_row(&self.probe_schema);
                        return Ok(Some(Self::combine(&row, &null_probe)));
                    }
                }
            }

            return Ok(None);
        }
    }

    fn reset(&mut self) -> Result<()> {
        self.hash_table = None;
        self.current_probe_row = None;
        self.current_matches.clear();
        self.match_idx = 0;
        self.probe_exhausted = false;
        self.unmatched_buffer = None;
        self.unmatched_pos = 0;
        self.build.reset()?;
        self.probe.reset()
    }
}

// ============================================================================
// NestedLoopJoinNode — Theta join (any join condition)
// ============================================================================

/// Nested loop join: for each outer row, scans all inner rows testing condition.
///
/// Supports all join types and arbitrary join conditions.
pub struct NestedLoopJoinNode {
    outer: Box<dyn PlanNode>,
    inner: Box<dyn PlanNode>,
    condition: Option<Expr>,
    join_type: JoinType,
    output_schema: Schema,
    /// Current outer row.
    current_outer: Option<Row>,
    /// Whether current outer row has matched any inner row.
    current_matched: bool,
    /// Whether join is exhausted.
    outer_exhausted: bool,
    _outer_schema: Schema,
    inner_schema: Schema,
}

impl NestedLoopJoinNode {
    pub fn new(
        outer: Box<dyn PlanNode>,
        inner: Box<dyn PlanNode>,
        condition: Option<Expr>,
        join_type: JoinType,
    ) -> Self {
        let outer_schema = outer.schema().clone();
        let inner_schema = inner.schema().clone();
        let output_schema = outer_schema.merge(&inner_schema);

        Self {
            outer,
            inner,
            condition,
            join_type,
            output_schema,
            current_outer: None,
            current_matched: false,
            outer_exhausted: false,
            _outer_schema: outer_schema,
            inner_schema,
        }
    }

    fn combine(outer_row: &Row, inner_row: &Row) -> Row {
        let mut combined = outer_row.clone();
        combined.extend(inner_row.iter().cloned());
        combined
    }

    fn null_row(schema: &Schema) -> Row {
        vec![SochValue::Null; schema.len()]
    }
}

impl PlanNode for NestedLoopJoinNode {
    fn schema(&self) -> &Schema {
        &self.output_schema
    }

    fn next(&mut self) -> Result<Option<Row>> {
        loop {
            // Get current outer row (or advance to next)
            if self.current_outer.is_none() {
                if self.outer_exhausted {
                    return Ok(None);
                }
                match self.outer.next()? {
                    Some(row) => {
                        self.current_outer = Some(row);
                        self.current_matched = false;
                        self.inner.reset()?;
                    }
                    None => {
                        self.outer_exhausted = true;
                        return Ok(None);
                    }
                }
            }

            let outer_row = self.current_outer.as_ref().unwrap();

            // Try to find next matching inner row
            match self.inner.next()? {
                Some(inner_row) => {
                    let combined = Self::combine(outer_row, &inner_row);

                    // Evaluate join condition
                    let matched = match &self.condition {
                        Some(cond) => eval_predicate(cond, &combined, &self.output_schema)?,
                        None => true, // CROSS JOIN
                    };

                    if matched {
                        self.current_matched = true;
                        return Ok(Some(combined));
                    }
                    // Not matched, try next inner row
                    continue;
                }
                None => {
                    // Inner side exhausted for this outer row
                    let need_null_row = !self.current_matched
                        && matches!(self.join_type, JoinType::Left | JoinType::Full);

                    let outer_row = self.current_outer.take().unwrap();

                    if need_null_row {
                        let null_inner = Self::null_row(&self.inner_schema);
                        return Ok(Some(Self::combine(&outer_row, &null_inner)));
                    }
                    // Move to next outer row
                    continue;
                }
            }
        }
    }

    fn reset(&mut self) -> Result<()> {
        self.current_outer = None;
        self.current_matched = false;
        self.outer_exhausted = false;
        self.outer.reset()?;
        self.inner.reset()
    }
}

// ============================================================================
// MergeJoinNode — Merge join on sorted inputs
// ============================================================================

/// Merge join: requires both inputs sorted on join keys.
///
/// For INNER JOIN, produces output only when keys match.
pub struct MergeJoinNode {
    left: Box<dyn PlanNode>,
    right: Box<dyn PlanNode>,
    left_key_expr: Expr,
    right_key_expr: Expr,
    join_type: JoinType,
    output_schema: Schema,
    left_schema: Schema,
    right_schema: Schema,
    /// Buffered rows from right side with same key (for many-to-many).
    right_buffer: Vec<Row>,
    right_buffer_key: Option<SochValue>,
    right_buf_idx: usize,
    current_left: Option<Row>,
    current_left_key: Option<SochValue>,
    right_exhausted: bool,
    pending_right: Option<Row>,
}

impl MergeJoinNode {
    pub fn new(
        left: Box<dyn PlanNode>,
        right: Box<dyn PlanNode>,
        left_key_expr: Expr,
        right_key_expr: Expr,
        join_type: JoinType,
    ) -> Self {
        let left_schema = left.schema().clone();
        let right_schema = right.schema().clone();
        let output_schema = left_schema.merge(&right_schema);

        Self {
            left,
            right,
            left_key_expr,
            right_key_expr,
            join_type,
            output_schema,
            left_schema,
            right_schema,
            right_buffer: Vec::new(),
            right_buffer_key: None,
            right_buf_idx: 0,
            current_left: None,
            current_left_key: None,
            right_exhausted: false,
            pending_right: None,
        }
    }

    fn combine(left_row: &Row, right_row: &Row) -> Row {
        let mut combined = left_row.clone();
        combined.extend(right_row.iter().cloned());
        combined
    }

    fn advance_right(&mut self) -> Result<Option<(SochValue, Row)>> {
        if let Some(row) = self.pending_right.take() {
            let key = eval_expr(&self.right_key_expr, &row, &self.right_schema)?;
            return Ok(Some((key, row)));
        }
        match self.right.next()? {
            Some(row) => {
                let key = eval_expr(&self.right_key_expr, &row, &self.right_schema)?;
                Ok(Some((key, row)))
            }
            None => {
                self.right_exhausted = true;
                Ok(None)
            }
        }
    }
}

impl PlanNode for MergeJoinNode {
    fn schema(&self) -> &Schema {
        &self.output_schema
    }

    fn next(&mut self) -> Result<Option<Row>> {
        loop {
            // If we have buffered right matches, emit them
            if self.right_buf_idx < self.right_buffer.len() {
                if let Some(left_row) = &self.current_left {
                    let right_row = &self.right_buffer[self.right_buf_idx];
                    self.right_buf_idx += 1;
                    return Ok(Some(Self::combine(left_row, right_row)));
                }
            }

            // Need new left row
            let left_row = match self.left.next()? {
                Some(row) => row,
                None => return Ok(None),
            };
            let left_key = eval_expr(&self.left_key_expr, &left_row, &self.left_schema)?;

            // Check if right buffer has same key
            if self.right_buffer_key.as_ref().map_or(false, |k| {
                compare_values(k, &left_key) == Some(std::cmp::Ordering::Equal)
            }) {
                self.current_left = Some(left_row);
                self.current_left_key = Some(left_key);
                self.right_buf_idx = 0;
                continue;
            }

            // Need to advance right side to match left key
            self.right_buffer.clear();
            self.right_buf_idx = 0;

            if self.right_exhausted {
                if matches!(self.join_type, JoinType::Left | JoinType::Full) {
                    let null_right = vec![SochValue::Null; self.right_schema.len()];
                    return Ok(Some(Self::combine(&left_row, &null_right)));
                }
                return Ok(None);
            }

            // Advance right until we find matching or greater key
            loop {
                match self.advance_right()? {
                    Some((right_key, right_row)) => {
                        match compare_values(&right_key, &left_key) {
                            Some(std::cmp::Ordering::Equal) => {
                                self.right_buffer.push(right_row);
                                self.right_buffer_key = Some(right_key);
                                // Collect all right rows with same key
                                break;
                            }
                            Some(std::cmp::Ordering::Greater) => {
                                // Right key is past left key
                                self.pending_right = Some(right_row);
                                break;
                            }
                            _ => {
                                // Right key is less than left key, skip
                                continue;
                            }
                        }
                    }
                    None => break,
                }
            }

            // Collect remaining right rows with same key
            if !self.right_buffer.is_empty() {
                loop {
                    match self.advance_right()? {
                        Some((right_key, right_row)) => {
                            if compare_values(&right_key, &left_key)
                                == Some(std::cmp::Ordering::Equal)
                            {
                                self.right_buffer.push(right_row);
                            } else {
                                self.pending_right = Some(right_row);
                                break;
                            }
                        }
                        None => break,
                    }
                }
            }

            self.current_left = Some(left_row);
            self.current_left_key = Some(left_key);
            self.right_buf_idx = 0;

            if self.right_buffer.is_empty() {
                if matches!(self.join_type, JoinType::Left | JoinType::Full) {
                    let left_row = self.current_left.take().unwrap();
                    let null_right = vec![SochValue::Null; self.right_schema.len()];
                    return Ok(Some(Self::combine(&left_row, &null_right)));
                }
                // Inner join, no match => skip this left row
                continue;
            }
        }
    }

    fn reset(&mut self) -> Result<()> {
        self.right_buffer.clear();
        self.right_buffer_key = None;
        self.right_buf_idx = 0;
        self.current_left = None;
        self.current_left_key = None;
        self.right_exhausted = false;
        self.pending_right = None;
        self.left.reset()?;
        self.right.reset()
    }
}