Skip to main content

waratah_exec/
column.rs

1//! Columnar TermId frames (`Vec<u32>` per variable).
2//!
3//! Each cell is a query-local [`crate::TermId`]: `0` is SPARQL unbound,
4//! other ids are interned in the query [`crate::TermDict`]. Join equality
5//! is TermId identity — no fingerprints, no Arrow.
6
7use waratah_storage::EncodedTerm;
8
9use crate::ExecError;
10use crate::term_dict::{TermDict, TermId};
11
12/// One variable's column: packed TermIds (`0` = unbound).
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct TermColumn {
15    ids: Vec<u32>,
16}
17
18impl TermColumn {
19    /// Build a column from interned TermIds.
20    pub fn from_ids(ids: Vec<u32>) -> Self {
21        Self { ids }
22    }
23
24    /// Intern bound terms into `dict` and store their ids.
25    pub fn from_terms(dict: &TermDict, values: Vec<EncodedTerm>) -> Result<Self, ExecError> {
26        Ok(Self {
27            ids: dict.intern_column(values.into_iter().map(Some))?,
28        })
29    }
30
31    /// Intern optional terms (`None` = unbound, stored as `0`).
32    pub fn from_optional_terms(
33        dict: &TermDict,
34        values: Vec<Option<EncodedTerm>>,
35    ) -> Result<Self, ExecError> {
36        Ok(Self {
37            ids: dict.intern_column(values.into_iter())?,
38        })
39    }
40
41    /// Empty column.
42    pub fn empty() -> Self {
43        Self { ids: Vec::new() }
44    }
45
46    /// `len` unbound cells (`0`).
47    pub fn unbound(len: usize) -> Self {
48        Self { ids: vec![0; len] }
49    }
50
51    /// Number of rows.
52    pub fn len(&self) -> usize {
53        self.ids.len()
54    }
55
56    /// Whether the column has no rows.
57    pub fn is_empty(&self) -> bool {
58        self.ids.is_empty()
59    }
60
61    /// Whether row `i` is SPARQL-bound (`id != 0`).
62    pub fn is_bound(&self, row: usize) -> bool {
63        row < self.len() && self.ids[row] != 0
64    }
65
66    /// Whether any cell is bound (`id != 0`). Short-circuits at the
67    /// first bound cell — the join filter emptiness gates ask exactly
68    /// this question and must not pay a full dedupe scan for it.
69    /// Column ids are interned by construction, so `id != 0` is the
70    /// authoritative boundness test; no dict lookup is needed to
71    /// confirm it.
72    pub fn any_bound(&self) -> bool {
73        self.ids.iter().any(|&id| id != 0)
74    }
75
76    /// TermId at `row` (`0` if OOB).
77    pub fn id_at(&self, row: usize) -> u32 {
78        self.ids.get(row).copied().unwrap_or(0)
79    }
80
81    /// Borrow the id buffer.
82    pub fn ids(&self) -> &[u32] {
83        &self.ids
84    }
85
86    /// Resolve the encoded term at `row` (`None` if unbound).
87    pub fn term_at(&self, dict: &TermDict, row: usize) -> Option<EncodedTerm> {
88        if !self.is_bound(row) {
89            return None;
90        }
91        dict.get(TermId(self.ids[row]))
92    }
93
94    /// Resolve every cell under one dict lock (`None` = unbound).
95    pub fn terms(&self, dict: &TermDict) -> Vec<Option<EncodedTerm>> {
96        let mut out = vec![None; self.len()];
97        dict.get_many(self.ids(), &mut out);
98        out
99    }
100
101    /// Gather rows by index into a new column (preserves unbound ids).
102    pub fn gather(&self, indices: &[usize]) -> Self {
103        Self {
104            ids: indices.iter().map(|&i| self.id_at(i)).collect(),
105        }
106    }
107
108    /// Gather via `u32` row indexes (same as [`Self::gather`], no re-intern).
109    ///
110    /// Unlike a term-level gather, this does **not** touch the dictionary:
111    /// the id buffer is remapped by index.
112    pub fn gather_take(&self, indices: &[u32]) -> Self {
113        Self {
114            ids: indices.iter().map(|&i| self.id_at(i as usize)).collect(),
115        }
116    }
117
118    /// Like [`Self::gather_take`], but null index slots become unbound output rows.
119    ///
120    /// Used by left outer join to attach right-carry columns where unmatched
121    /// probe rows have a null right index.
122    pub fn gather_take_nullable(&self, indices: &[Option<u32>]) -> Self {
123        let mut ids = Vec::with_capacity(indices.len());
124        for idx in indices {
125            match idx {
126                Some(i) => ids.push(self.id_at(*i as usize)),
127                // OPTIONAL miss → unbound cell
128                None => ids.push(0),
129            }
130        }
131        Self { ids }
132    }
133
134    /// Coalesce two columns at parallel index arrays: left if bound, else right.
135    ///
136    /// This is the soft-shared gather path after a join: if OPTIONAL left `?x`
137    /// unbound, take the right's `?x`; if left already bound, keep it.
138    /// Soft coalesce is SPARQL compatible mapping on **term identity** = TermId.
139    pub fn gather_coalesce(
140        &self,
141        left_indices: &[u32],
142        other: &Self,
143        right_indices: &[u32],
144    ) -> Result<Self, ExecError> {
145        if left_indices.len() != right_indices.len() {
146            return Err(ExecError::LengthMismatch(format!(
147                "coalesce index lens {} vs {}",
148                left_indices.len(),
149                right_indices.len()
150            )));
151        }
152        let mut ids = Vec::with_capacity(left_indices.len());
153        for i in 0..left_indices.len() {
154            let l = left_indices[i] as usize;
155            if self.is_bound(l) {
156                ids.push(self.id_at(l));
157            } else {
158                ids.push(other.id_at(right_indices[i] as usize));
159            }
160        }
161        Ok(Self { ids })
162    }
163
164    /// Coalesce with nullable right indexes (`None` = unbound when left is unbound).
165    pub fn gather_coalesce_nullable(
166        &self,
167        left_indices: &[u32],
168        other: &Self,
169        right_indices: &[Option<u32>],
170    ) -> Result<Self, ExecError> {
171        if left_indices.len() != right_indices.len() {
172            return Err(ExecError::LengthMismatch(format!(
173                "coalesce index lens {} vs {}",
174                left_indices.len(),
175                right_indices.len()
176            )));
177        }
178        let mut ids = Vec::with_capacity(left_indices.len());
179        for i in 0..left_indices.len() {
180            let l = left_indices[i] as usize;
181            if self.is_bound(l) {
182                ids.push(self.id_at(l));
183            } else if let Some(r) = right_indices[i] {
184                ids.push(other.id_at(r as usize));
185            } else {
186                // Both sides unbound (left miss and null right index)
187                ids.push(0);
188            }
189        }
190        Ok(Self { ids })
191    }
192}
193
194/// Columnar batch: each column is one bound variable.
195///
196/// A zero-column batch can still have rows: SPARQL's empty group `{ }` is one
197/// solution with no bindings (the join identity). [`Self::len`] is stored
198/// explicitly so that table is not confused with an empty (zero-row) result.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct TermBatch {
201    columns: Vec<TermColumn>,
202    n_rows: usize,
203}
204
205impl TermBatch {
206    /// Construct from columns; all must share the same length.
207    pub fn try_new(columns: Vec<TermColumn>) -> Result<Self, ExecError> {
208        if let Some(first) = columns.first() {
209            let n = first.len();
210            for (i, col) in columns.iter().enumerate().skip(1) {
211                if col.len() != n {
212                    return Err(ExecError::LengthMismatch(format!(
213                        "column 0 has {n} rows, column {i} has {}",
214                        col.len()
215                    )));
216                }
217            }
218        }
219        let n_rows = columns.first().map(TermColumn::len).unwrap_or(0);
220        Ok(Self { columns, n_rows })
221    }
222
223    /// Empty batch with `width` zero-length columns (zero rows).
224    pub fn empty(width: usize) -> Self {
225        Self {
226            columns: (0..width).map(|_| TermColumn::empty()).collect(),
227            n_rows: 0,
228        }
229    }
230
231    /// Empty batch with `width` columns, each reserving `rows` cells.
232    ///
233    /// The exact-size constructor for a stack whose total height is known
234    /// before its inputs are read: [`Self::concat`] grows its accumulator by
235    /// doubling because an `IntoIterator` gives it no length, while a UNION's
236    /// collected arm list knows the sum, so every column can be allocated once
237    /// at its final height and never reallocated.
238    ///
239    /// A zero-width batch with a non-zero height exists only via
240    /// [`Self::zero_width`] or a merge that kept one ([`Self::extend_aligned`],
241    /// [`Self::concat`]); this constructor starts at height 0 even when
242    /// `width == 0`, because `try_new` of an empty column vec is defined as
243    /// zero rows while a batch with no columns has nothing but its height to
244    /// carry SPARQL's empty group (`{ }` / `ASK {}`, one solution with no
245    /// bindings).
246    pub fn with_capacity_rows(width: usize, rows: usize) -> Self {
247        Self {
248            columns: (0..width)
249                .map(|_| TermColumn {
250                    ids: Vec::with_capacity(rows),
251                })
252                .collect(),
253            n_rows: 0,
254        }
255    }
256
257    /// Append `source`'s rows under a column map.
258    ///
259    /// `map[out] = Some(i)` fills output column `out` from source column `i`;
260    /// `None` appends `source.n_rows` unbound cells. A zero-width source still
261    /// adds its height, so a unit table (SPARQL's empty group `{ }`, one
262    /// solution with no columns) survives a merge. The source is read in
263    /// place — one `extend_from_slice` per output column — so a caller never
264    /// materialises a re-ordered intermediate batch first. Pair it with
265    /// [`Self::with_capacity_rows`] to make the whole stack one allocation and
266    /// one copy per column.
267    ///
268    /// `map` must carry one entry per output column and every `Some` index must
269    /// name a source column; both are checked before anything is appended, so a
270    /// rejected map leaves the batch untouched.
271    pub fn extend_aligned(
272        &mut self,
273        source: &Self,
274        map: &[Option<usize>],
275    ) -> Result<(), ExecError> {
276        if map.len() != self.width() {
277            return Err(ExecError::LengthMismatch(format!(
278                "extend_aligned map {} vs width {}",
279                map.len(),
280                self.width()
281            )));
282        }
283        for index in map.iter().flatten() {
284            if *index >= source.width() {
285                return Err(ExecError::BadColumn {
286                    index: *index,
287                    width: source.width(),
288                });
289            }
290        }
291        debug_assert!(
292            self.columns
293                .first()
294                .is_none_or(|column| column.len() == self.n_rows),
295            "TermBatch height disagrees with its columns"
296        );
297        debug_assert!(
298            source
299                .columns
300                .first()
301                .is_none_or(|column| column.len() == source.n_rows),
302            "source TermBatch height disagrees with its columns"
303        );
304        for (column, source_index) in self.columns.iter_mut().zip(map) {
305            match source_index {
306                Some(index) => column.ids.extend_from_slice(&source.columns[*index].ids),
307                None => column.ids.resize(column.ids.len() + source.n_rows, 0),
308            }
309        }
310        self.n_rows = self.n_rows.saturating_add(source.n_rows);
311        Ok(())
312    }
313
314    /// Append `count` all-unbound columns, each `self.n_rows` cells tall.
315    ///
316    /// For a merge whose schema grows after rows have already been stacked:
317    /// a variable that only a later input binds is unbound for every row
318    /// collected so far. The caller appends the new input's rows afterwards
319    /// with [`Self::extend_aligned`], which fills the new columns from that
320    /// input while leaving the zeros already written here in place.
321    pub fn push_unbound_columns(&mut self, count: usize) {
322        let rows = self.n_rows;
323        self.columns
324            .extend((0..count).map(|_| TermColumn { ids: vec![0; rows] }));
325    }
326
327    /// Append one column to the right edge. Its height must equal `self.n_rows`.
328    ///
329    /// The O(1) schema extension used when an operator adds a column to a table
330    /// it already holds (an `Extend` whose expression the executor evaluated
331    /// once). The ids are taken as they are, so the caller interns.
332    pub fn push_column(&mut self, column: TermColumn) -> Result<(), ExecError> {
333        if column.len() != self.n_rows {
334            return Err(ExecError::LengthMismatch(format!(
335                "push_column height {} vs {}",
336                column.len(),
337                self.n_rows
338            )));
339        }
340        self.columns.push(column);
341        Ok(())
342    }
343
344    /// Zero columns and `n_rows` solutions (grounded scans, ASK-style pages).
345    ///
346    /// [`Self::try_new`] of an empty column vec is always zero rows; a fully
347    /// grounded pattern still has a row count.
348    pub fn zero_width(n_rows: usize) -> Self {
349        Self {
350            columns: Vec::new(),
351            n_rows,
352        }
353    }
354
355    /// Number of columns.
356    pub fn width(&self) -> usize {
357        self.columns.len()
358    }
359
360    /// Number of rows.
361    ///
362    /// For a zero-column batch this is the stored height, so a unit table
363    /// (one empty mapping) reports `1` rather than `0`.
364    pub fn len(&self) -> usize {
365        self.n_rows
366    }
367
368    /// Whether there are no rows.
369    pub fn is_empty(&self) -> bool {
370        self.len() == 0
371    }
372
373    /// Borrow columns.
374    pub fn columns(&self) -> &[TermColumn] {
375        &self.columns
376    }
377
378    /// Borrow one column.
379    pub fn column(&self, index: usize) -> Result<&TermColumn, ExecError> {
380        self.columns.get(index).ok_or(ExecError::BadColumn {
381            index,
382            width: self.width(),
383        })
384    }
385
386    /// Whether any row binds the column at `index` (`false` when the
387    /// batch has no such column — an absent column binds nothing).
388    /// One short-circuiting id scan, no dedupe and no promotion.
389    pub fn any_bound(&self, index: usize) -> bool {
390        self.columns.get(index).is_some_and(TermColumn::any_bound)
391    }
392
393    /// Build from row-oriented bound terms (`rows[r][c]`), interned into `dict`.
394    ///
395    /// Moves each cell into one `Vec<EncodedTerm>` per column, then
396    /// [`TermColumn::from_terms`] (`intern_column` once per column). Unbound
397    /// cells belong in [`Self::from_optional_rows`].
398    pub fn from_rows(
399        dict: &TermDict,
400        width: usize,
401        rows: Vec<Vec<EncodedTerm>>,
402    ) -> Result<Self, ExecError> {
403        let n_rows = rows.len();
404        if width == 0 {
405            return Ok(Self::zero_width(n_rows));
406        }
407        let mut columns: Vec<Vec<EncodedTerm>> =
408            (0..width).map(|_| Vec::with_capacity(n_rows)).collect();
409        for (r, row) in rows.into_iter().enumerate() {
410            if row.len() != width {
411                return Err(ExecError::LengthMismatch(format!(
412                    "row {r} has {} cells, expected {width}",
413                    row.len()
414                )));
415            }
416            for (c, term) in row.into_iter().enumerate() {
417                columns[c].push(term);
418            }
419        }
420        let mut interned = Vec::with_capacity(width);
421        for col in columns {
422            interned.push(TermColumn::from_terms(dict, col)?);
423        }
424        Self::try_new(interned)
425    }
426
427    /// Build from row-oriented optional terms (`None` = unbound).
428    pub fn from_optional_rows(
429        dict: &TermDict,
430        width: usize,
431        rows: Vec<Vec<Option<EncodedTerm>>>,
432    ) -> Result<Self, ExecError> {
433        let n_rows = rows.len();
434        if width == 0 {
435            return Ok(Self {
436                columns: Vec::new(),
437                n_rows,
438            });
439        }
440        let mut columns: Vec<Vec<Option<EncodedTerm>>> =
441            (0..width).map(|_| Vec::with_capacity(n_rows)).collect();
442        for (r, row) in rows.iter().enumerate() {
443            if row.len() != width {
444                return Err(ExecError::LengthMismatch(format!(
445                    "row {r} has {} cells, expected {width}",
446                    row.len()
447                )));
448            }
449            for (c, term) in row.iter().enumerate() {
450                columns[c].push(term.clone());
451            }
452        }
453        let mut interned = Vec::with_capacity(width);
454        for col in columns {
455            interned.push(TermColumn::from_optional_terms(dict, col)?);
456        }
457        Self::try_new(interned)
458    }
459
460    /// Build from already-interned id rows (`rows[r][c]` is a TermId).
461    pub fn from_id_rows(width: usize, rows: Vec<Vec<u32>>) -> Result<Self, ExecError> {
462        let n_rows = rows.len();
463        if width == 0 {
464            return Ok(Self {
465                columns: Vec::new(),
466                n_rows,
467            });
468        }
469        let mut columns: Vec<Vec<u32>> = (0..width).map(|_| Vec::with_capacity(n_rows)).collect();
470        for (r, row) in rows.iter().enumerate() {
471            if row.len() != width {
472                return Err(ExecError::LengthMismatch(format!(
473                    "row {r} has {} cells, expected {width}",
474                    row.len()
475                )));
476            }
477            for (c, id) in row.iter().enumerate() {
478                columns[c].push(*id);
479            }
480        }
481        Self::try_new(columns.into_iter().map(TermColumn::from_ids).collect())
482    }
483
484    /// Fill `out` with this row's encoded terms (one dict lock).
485    ///
486    /// `out.len()` must equal [`Self::width`].
487    pub fn fill_optional_row(&self, dict: &TermDict, row: usize, out: &mut [Option<EncodedTerm>]) {
488        assert_eq!(out.len(), self.width());
489        if self.width() == 0 {
490            return;
491        }
492        let mut ids = vec![0u32; self.width()];
493        for (c, col) in self.columns.iter().enumerate() {
494            ids[c] = col.id_at(row);
495        }
496        dict.get_many(&ids, out);
497    }
498
499    /// Row-oriented view with resolved terms (`None` = unbound).
500    ///
501    /// Packs every cell's TermId then one [`TermDict::get_many`] for the frame
502    /// (one mutex, not one lock per cell).
503    pub fn to_optional_rows(&self, dict: &TermDict) -> Vec<Vec<Option<EncodedTerm>>> {
504        let n = self.len();
505        let w = self.width();
506        if w == 0 {
507            return vec![Vec::new(); n];
508        }
509        let mut ids = Vec::with_capacity(n.saturating_mul(w));
510        for r in 0..n {
511            for col in &self.columns {
512                ids.push(col.id_at(r));
513            }
514        }
515        let mut flat = vec![None; ids.len()];
516        dict.get_many(&ids, &mut flat);
517        let mut rows = Vec::with_capacity(n);
518        for chunk in flat.chunks_exact(w) {
519            rows.push(chunk.to_vec());
520        }
521        rows
522    }
523
524    /// Row-oriented view; unbound cells panic — prefer
525    /// [`Self::to_optional_rows`] when OPTIONAL is in play. Bound-only helper
526    /// for tests and callers that never produce unbound mid-pipeline.
527    pub fn to_rows(&self, dict: &TermDict) -> Vec<Vec<EncodedTerm>> {
528        self.to_optional_rows(dict)
529            .into_iter()
530            .map(|row| {
531                row.into_iter()
532                    .map(|cell| cell.expect("to_rows requires all cells bound"))
533                    .collect()
534            })
535            .collect()
536    }
537
538    /// Concatenate owned batches of one `width` into a single batch.
539    ///
540    /// Every input must have exactly `width` columns — a mismatch is an error —
541    /// and nothing is re-interned: ids are copied as they are. The first
542    /// non-empty batch **moves** into the accumulator, so its column buffers
543    /// are reused rather than copied; every later batch appends its ids.
544    ///
545    /// A zero-width input contributes only its height, which is how SPARQL's
546    /// empty group (`{ }`, one solution with no bindings) survives a
547    /// concatenation with a populated table.
548    ///
549    /// This is the owning form and needs no length up front. Callers that hold
550    /// borrowed sources and already know the total height want
551    /// [`Self::with_capacity_rows`] plus [`Self::extend_aligned`]: one
552    /// allocation at the final size and one copy per row.
553    pub fn concat(
554        width: usize,
555        batches: impl IntoIterator<Item = TermBatch>,
556    ) -> Result<Self, ExecError> {
557        let mut acc: Option<Self> = None;
558        for next in batches {
559            if next.width() != width {
560                return Err(ExecError::LengthMismatch(format!(
561                    "concat width {width} vs {}",
562                    next.width()
563                )));
564            }
565            if next.is_empty() {
566                continue;
567            }
568            if let Some(current) = acc.as_mut() {
569                let added = next.n_rows;
570                for (column, next_column) in current.columns.iter_mut().zip(next.columns) {
571                    column.ids.extend_from_slice(&next_column.ids);
572                }
573                current.n_rows = current.n_rows.saturating_add(added);
574            } else {
575                acc = Some(next);
576            }
577        }
578        let acc = acc.unwrap_or_else(|| Self::empty(width));
579        debug_assert!(
580            acc.columns
581                .first()
582                .is_none_or(|column| column.len() == acc.n_rows),
583            "concat height disagrees with its columns"
584        );
585        Ok(acc)
586    }
587
588    /// Append `other`'s rows onto this batch (same width). Copies ids only.
589    ///
590    /// Used by [`crate`]-external park accumulators that grow a RAM tail
591    /// page-by-page. Empty `other` is a no-op. Zero-width batches add height
592    /// without columns (SPARQL empty-mapping tables).
593    pub fn append(&mut self, other: &TermBatch) -> Result<(), ExecError> {
594        if self.width() != other.width() {
595            return Err(ExecError::LengthMismatch(format!(
596                "append width {} vs {}",
597                self.width(),
598                other.width()
599            )));
600        }
601        if other.is_empty() {
602            return Ok(());
603        }
604        if self.width() == 0 {
605            self.n_rows = self.n_rows.saturating_add(other.n_rows);
606            return Ok(());
607        }
608        if self.is_empty() {
609            *self = other.clone();
610            return Ok(());
611        }
612        for (col, next) in self.columns.iter_mut().zip(other.columns.iter()) {
613            col.ids.extend_from_slice(&next.ids);
614        }
615        self.n_rows = self.n_rows.saturating_add(other.n_rows);
616        Ok(())
617    }
618
619    /// Drop all rows; keep column width (empty `Vec<u32>` buffers).
620    pub fn clear_rows(&mut self) {
621        for col in &mut self.columns {
622            col.ids.clear();
623        }
624        self.n_rows = 0;
625    }
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631    use pretty_assertions::assert_eq;
632    use waratah_storage::{Literal, NamedNode};
633
634    fn iri(local: &str) -> EncodedTerm {
635        EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap())
636    }
637
638    #[test]
639    fn interned_named_node_round_trips() {
640        let dict = TermDict::new();
641        let col = TermColumn::from_terms(&dict, vec![iri("alice")]).unwrap();
642        assert!(col.is_bound(0));
643        assert_ne!(col.id_at(0), 0);
644        assert_eq!(col.term_at(&dict, 0), Some(iri("alice")));
645    }
646
647    #[test]
648    fn literal_interns_and_resolves() {
649        let dict = TermDict::new();
650        let lit = EncodedTerm::from(&Literal::from("Sunny"));
651        let col = TermColumn::from_terms(&dict, vec![lit.clone()]).unwrap();
652        assert_eq!(col.term_at(&dict, 0), Some(lit));
653    }
654
655    #[test]
656    fn unbound_is_zero_id() {
657        let dict = TermDict::new();
658        let col = TermColumn::from_optional_terms(&dict, vec![None, Some(iri("a"))]).unwrap();
659        assert!(!col.is_bound(0));
660        assert!(col.is_bound(1));
661        assert_eq!(col.id_at(0), 0);
662        assert_eq!(col.term_at(&dict, 0), None);
663        assert_eq!(col.term_at(&dict, 1), Some(iri("a")));
664    }
665
666    #[test]
667    fn any_bound_scans_column_ids() {
668        let dict = TermDict::new();
669        let mixed =
670            TermColumn::from_optional_terms(&dict, vec![None, None, Some(iri("a"))]).unwrap();
671        let all_unbound = TermColumn::from_optional_terms(&dict, vec![None, None]).unwrap();
672        assert!(mixed.any_bound());
673        assert!(!all_unbound.any_bound());
674        assert!(!TermColumn::empty().any_bound());
675    }
676
677    #[test]
678    fn term_batch_any_bound_by_index() {
679        let dict = TermDict::new();
680        let bound = TermColumn::from_terms(&dict, vec![iri("a"), iri("b")]).unwrap();
681        let unbound = TermColumn::unbound(2);
682        let batch = TermBatch::try_new(vec![unbound, bound]).unwrap();
683        assert!(!batch.any_bound(0));
684        assert!(batch.any_bound(1));
685        // An absent column binds nothing — same answer the emptiness
686        // gates got from `distinct_values(missing).is_empty()`.
687        assert!(!batch.any_bound(2));
688        assert!(!TermBatch::zero_width(3).any_bound(0));
689    }
690
691    #[test]
692    fn terms_and_to_optional_rows_match_term_at() {
693        let dict = TermDict::new();
694        let col =
695            TermColumn::from_optional_terms(&dict, vec![Some(iri("a")), None, Some(iri("c"))])
696                .unwrap();
697        let via_terms = col.terms(&dict);
698        assert_eq!(via_terms[0], col.term_at(&dict, 0));
699        assert_eq!(via_terms[1], col.term_at(&dict, 1));
700        assert_eq!(via_terms[2], col.term_at(&dict, 2));
701        let batch = TermBatch::try_new(vec![col.clone()]).unwrap();
702        let rows = batch.to_optional_rows(&dict);
703        assert_eq!(rows[0][0], col.term_at(&dict, 0));
704        assert_eq!(rows[1][0], None);
705        assert_eq!(rows[2][0], Some(iri("c")));
706        let mut row = vec![None];
707        batch.fill_optional_row(&dict, 2, &mut row);
708        assert_eq!(row[0], Some(iri("c")));
709    }
710
711    #[test]
712    fn reserved_default_graph_and_rdf_type() {
713        let dict = TermDict::new();
714        let col = TermColumn::from_terms(
715            &dict,
716            vec![EncodedTerm::DefaultGraph, waratah_storage::RDF_TYPE],
717        )
718        .unwrap();
719        assert_eq!(col.id_at(0), TermId::DEFAULT_GRAPH.as_u32());
720        assert_eq!(col.id_at(1), TermId::RDF_TYPE.as_u32());
721    }
722
723    #[test]
724    fn batch_round_trips_rows() {
725        let dict = TermDict::new();
726        let rows = vec![vec![iri("a"), iri("x")], vec![iri("b"), iri("y")]];
727        let batch = TermBatch::from_rows(&dict, 2, rows.clone()).unwrap();
728        assert_eq!(batch.len(), 2);
729        assert_eq!(batch.width(), 2);
730        assert_eq!(batch.to_rows(&dict), rows);
731    }
732
733    #[test]
734    fn from_rows_matches_optional_rows_of_bound_cells() {
735        let dict = TermDict::new();
736        let rows = vec![vec![iri("a"), iri("x")], vec![iri("b"), iri("y")]];
737        let bound = TermBatch::from_rows(&dict, 2, rows.clone()).unwrap();
738        let optional = TermBatch::from_optional_rows(
739            &dict,
740            2,
741            rows.into_iter()
742                .map(|row| row.into_iter().map(Some).collect())
743                .collect(),
744        )
745        .unwrap();
746        assert_eq!(bound.to_rows(&dict), optional.to_rows(&dict));
747        assert_eq!(
748            bound.column(0).unwrap().ids(),
749            optional.column(0).unwrap().ids()
750        );
751        assert_eq!(
752            bound.column(1).unwrap().ids(),
753            optional.column(1).unwrap().ids()
754        );
755    }
756
757    #[test]
758    fn from_rows_shares_term_ids_for_duplicate_cells() {
759        let dict = TermDict::new();
760        let batch =
761            TermBatch::from_rows(&dict, 1, vec![vec![iri("brisbane")], vec![iri("brisbane")]])
762                .unwrap();
763        let col = batch.column(0).unwrap();
764        assert_ne!(col.id_at(0), 0);
765        assert_eq!(col.id_at(0), col.id_at(1));
766    }
767
768    #[test]
769    fn from_rows_rejects_a_jagged_row() {
770        let dict = TermDict::new();
771        let err = TermBatch::from_rows(&dict, 2, vec![vec![iri("a"), iri("b")], vec![iri("c")]])
772            .unwrap_err();
773        assert!(matches!(err, ExecError::LengthMismatch(_)));
774    }
775
776    #[test]
777    fn from_rows_zero_width_keeps_row_count() {
778        let dict = TermDict::new();
779        let batch = TermBatch::from_rows(&dict, 0, vec![vec![], vec![]]).unwrap();
780        assert_eq!(batch.width(), 0);
781        assert_eq!(batch.len(), 2);
782        assert!(!batch.is_empty());
783    }
784
785    #[test]
786    fn gather_preserves_named_node_and_unbound() {
787        let dict = TermDict::new();
788        let col =
789            TermColumn::from_optional_terms(&dict, vec![Some(iri("a")), None, Some(iri("c"))])
790                .unwrap();
791        let g = col.gather(&[2, 1, 0]);
792        assert_eq!(g.term_at(&dict, 0), Some(iri("c")));
793        assert_eq!(g.term_at(&dict, 1), None);
794        assert_eq!(g.term_at(&dict, 2), Some(iri("a")));
795        assert_eq!(g.id_at(1), 0);
796    }
797
798    #[test]
799    fn zero_column_unit_table_has_one_row() {
800        let dict = TermDict::new();
801        let unit = TermBatch::from_optional_rows(&dict, 0, vec![vec![]]).unwrap();
802        assert_eq!(unit.width(), 0);
803        assert_eq!(unit.len(), 1);
804        assert!(!unit.is_empty());
805        assert_eq!(
806            unit.to_optional_rows(&dict),
807            vec![Vec::<Option<EncodedTerm>>::new()]
808        );
809
810        let empty = TermBatch::from_optional_rows(&dict, 0, Vec::new()).unwrap();
811        assert_eq!(empty.len(), 0);
812        assert!(empty.is_empty());
813    }
814
815    #[test]
816    fn concat_concats_ids_without_reintern() {
817        let dict = TermDict::new();
818        let a = TermBatch::from_rows(&dict, 1, vec![vec![iri("a")]]).unwrap();
819        let b = TermBatch::from_rows(&dict, 1, vec![vec![iri("b")]]).unwrap();
820        let stacked = TermBatch::concat(1, [a, b]).unwrap();
821        assert_eq!(stacked.len(), 2);
822        assert_eq!(stacked.column(0).unwrap().term_at(&dict, 0), Some(iri("a")));
823        assert_eq!(stacked.column(0).unwrap().term_at(&dict, 1), Some(iri("b")));
824    }
825
826    #[test]
827    fn concat_keeps_zero_width_height() {
828        // The generic path replaces the old width-0 special case: unit tables
829        // contribute height and no columns.
830        let unit = TermBatch::zero_width(2);
831        let more = TermBatch::zero_width(3);
832        let stacked = TermBatch::concat(0, [unit, more]).unwrap();
833        assert_eq!(stacked.width(), 0);
834        assert_eq!(stacked.len(), 5);
835    }
836
837    #[test]
838    fn with_capacity_rows_reserves_each_column() {
839        let batch = TermBatch::with_capacity_rows(3, 128);
840        assert_eq!(batch.width(), 3);
841        assert_eq!(batch.len(), 0);
842        for column in batch.columns() {
843            assert_eq!(column.len(), 0);
844            assert_eq!(column.ids.capacity(), 128);
845        }
846    }
847
848    #[test]
849    fn extend_aligned_maps_reorders_and_pads() {
850        let dict = TermDict::new();
851        let source = TermBatch::from_rows(&dict, 2, vec![vec![iri("a"), iri("b")]]).unwrap();
852        let mut out = TermBatch::with_capacity_rows(3, 1);
853        out.extend_aligned(&source, &[Some(1), None, Some(0)])
854            .unwrap();
855        assert_eq!(out.len(), 1);
856        assert_eq!(
857            out.to_optional_rows(&dict),
858            vec![vec![Some(iri("b")), None, Some(iri("a"))]]
859        );
860        // Exact-size stack: appending the one row never grew a column.
861        for column in out.columns() {
862            assert_eq!(column.ids.capacity(), 1);
863        }
864    }
865
866    #[test]
867    fn extend_aligned_zero_width_source_adds_height_only() {
868        let mut out = TermBatch::with_capacity_rows(1, 2);
869        out.extend_aligned(&TermBatch::zero_width(2), &[None])
870            .unwrap();
871        assert_eq!(out.len(), 2);
872        assert_eq!(out.column(0).unwrap().len(), 2);
873        assert!(!out.any_bound(0));
874    }
875
876    #[test]
877    fn extend_aligned_rejects_a_bad_map_without_mutating() {
878        let dict = TermDict::new();
879        let source = TermBatch::from_rows(&dict, 1, vec![vec![iri("a")]]).unwrap();
880        let mut out = TermBatch::with_capacity_rows(2, 2);
881        // A good row first: on an empty batch "unchanged" would hold even if a
882        // rejected map had already extended every column.
883        out.extend_aligned(&source, &[Some(0), None]).unwrap();
884        let expected: Vec<Vec<Option<EncodedTerm>>> = vec![vec![Some(iri("a")), None]];
885
886        // Wrong arity for the output width.
887        assert!(out.extend_aligned(&source, &[Some(0)]).is_err());
888        assert_eq!(out.len(), 1);
889        assert_eq!(out.to_optional_rows(&dict), expected);
890
891        // Out-of-range source column.
892        assert!(out.extend_aligned(&source, &[Some(0), Some(9)]).is_err());
893        assert_eq!(out.len(), 1);
894        assert_eq!(out.to_optional_rows(&dict), expected);
895    }
896
897    #[test]
898    fn push_unbound_columns_keeps_height() {
899        let dict = TermDict::new();
900        let mut batch =
901            TermBatch::from_rows(&dict, 1, vec![vec![iri("a")], vec![iri("b")]]).unwrap();
902        batch.push_unbound_columns(2);
903        assert_eq!(batch.width(), 3);
904        assert_eq!(batch.len(), 2);
905        for index in 1..3 {
906            assert_eq!(batch.column(index).unwrap().len(), 2);
907            assert!(!batch.any_bound(index));
908        }
909        assert_eq!(batch.column(0).unwrap().term_at(&dict, 0), Some(iri("a")));
910    }
911
912    #[test]
913    fn push_column_extends_the_right_edge() {
914        let dict = TermDict::new();
915        let mut batch =
916            TermBatch::from_rows(&dict, 1, vec![vec![iri("a")], vec![iri("b")]]).unwrap();
917        let id = dict.intern_ref(&iri("x")).unwrap().as_u32();
918        batch
919            .push_column(TermColumn::from_ids(vec![id, id]))
920            .unwrap();
921        assert_eq!(batch.width(), 2);
922        assert_eq!(batch.len(), 2);
923        assert_eq!(batch.column(0).unwrap().term_at(&dict, 0), Some(iri("a")));
924        assert_eq!(batch.column(1).unwrap().term_at(&dict, 1), Some(iri("x")));
925    }
926
927    #[test]
928    fn push_column_rejects_a_height_mismatch() {
929        let dict = TermDict::new();
930        let mut batch = TermBatch::from_rows(&dict, 1, vec![vec![iri("a")]]).unwrap();
931        assert!(batch.push_column(TermColumn::from_ids(vec![0, 0])).is_err());
932        assert_eq!(batch.width(), 1, "a rejected column is not appended");
933    }
934}