egglog_core_relations/table_spec.rs
1//! High-level types for specifying the behavior and layout of tables.
2//!
3//! Tables are a mapping from some set of keys to another set of values. Tables
4//! can also be "sorted by" a columna dn "partitioned by" another. This can help
5//! speed up queries.
6
7use std::{
8 any::Any,
9 marker::PhantomData,
10 ops::{Deref, DerefMut},
11};
12
13use crate::numeric_id::{DenseIdMap, NumericId, define_id};
14use smallvec::SmallVec;
15
16use crate::{
17 QueryEntry, TableId, Variable,
18 action::{
19 Bindings, ExecutionState,
20 mask::{Mask, MaskIter, ValueSource},
21 },
22 common::Value,
23 offsets::{RowId, Subset, SubsetRef},
24 pool::{PoolSet, Pooled, with_pool_set},
25 row_buffer::{RowBuffer, RowSink, TaggedRowBuffer},
26};
27
28define_id!(pub ColumnId, u32, "a particular column in a table", pretty "Col");
29define_id!(
30 pub Generation,
31 u64,
32 "the current version of a table -- used to invalidate any existing RowIds"
33);
34define_id!(
35 pub Offset,
36 u64,
37 "an opaque offset token -- used to encode iterations over a table (within a generation). These always start at 0."
38);
39
40/// The version of a table.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct TableVersion {
43 /// New major generations invalidate all existing RowIds for a table.
44 pub major: Generation,
45 /// New minor generations within a major generation do not invalidate
46 /// existing RowIds, but they may indicate that `all` can return a larger
47 /// subset than before.
48 pub minor: Offset,
49 // NB: we may want to make `Offset` and `RowId` the same.
50}
51
52#[derive(Clone)]
53pub struct TableSpec {
54 /// The number of key columns for the table.
55 pub n_keys: usize,
56
57 /// The number of non-key (i.e. value) columns in the table.
58 ///
59 /// The total "arity" of the table is `n_keys + n_vals`.
60 pub n_vals: usize,
61
62 /// Columns that cannot be cached across generations.
63 ///
64 /// These columns should (e.g.) never have indexes built for them, as they
65 /// will go out of date too quickly.
66 pub uncacheable_columns: DenseIdMap<ColumnId, bool>,
67}
68
69impl TableSpec {
70 /// The total number of columns stored by the table.
71 pub fn arity(&self) -> usize {
72 self.n_keys + self.n_vals
73 }
74}
75
76/// Whether a table gained rows after a merge operation.
77#[derive(Eq, PartialEq, Copy, Clone)]
78pub struct TableChange {
79 /// Whether or not rows were added to the table.
80 pub added: bool,
81}
82
83/// A constraint on the values within a row.
84#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
85pub enum Constraint {
86 Eq { l_col: ColumnId, r_col: ColumnId },
87 EqConst { col: ColumnId, val: Value },
88 LtConst { col: ColumnId, val: Value },
89 GtConst { col: ColumnId, val: Value },
90 LeConst { col: ColumnId, val: Value },
91 GeConst { col: ColumnId, val: Value },
92}
93
94/// Remap individual values (e.g. to their union-find leaders) — the value-level
95/// half of rebuilding, enough to rebuild a single container's contents (see
96/// [`crate::ContainerValue::rebuild_contents`]).
97pub trait ValueRebuilder: Send + Sync {
98 /// Rebuild a single value.
99 fn rebuild_val(&self, val: Value) -> Value;
100 /// Rebuild a slice of values in place, returning true if any values were changed.
101 ///
102 /// Defaults to mapping each value through [`ValueRebuilder::rebuild_val`];
103 /// implementors may override for efficiency.
104 fn rebuild_slice(&self, vals: &mut [Value]) -> bool {
105 let mut changed = false;
106 for val in vals.iter_mut() {
107 let new = self.rebuild_val(*val);
108 if new != *val {
109 *val = new;
110 changed = true;
111 }
112 }
113 changed
114 }
115}
116
117/// Custom functions used for tables that encode a bulk value-level rebuild of other tables.
118///
119/// Extends [`ValueRebuilder`] with table-level (bulk) operations.
120///
121/// The initial use-case for this trait is to support optimized implementations of rebuilding,
122/// where `Rebuilder` is implemented as a Union-find.
123///
124/// Value-level rebuilds are difficult to implement efficiently using rules as they require
125/// searching for changes to any column for a table: while it is possible to do, implementing this
126/// custom is more efficient in the case of rebuilding.
127pub trait Rebuilder: ValueRebuilder {
128 /// The column that contains values that should be rebuilt. If this is set, callers can use
129 /// this functionality to perform rebuilds incrementally.
130 fn hint_col(&self) -> Option<ColumnId>;
131 /// Rebuild a contiguous slice of rows in the table.
132 fn rebuild_buf(
133 &self,
134 buf: &RowBuffer,
135 start: RowId,
136 end: RowId,
137 out: &mut TaggedRowBuffer,
138 exec_state: &mut ExecutionState,
139 );
140 /// Rebuild an arbitrary subset of the table.
141 fn rebuild_subset(
142 &self,
143 other: WrappedTableRef,
144 subset: SubsetRef,
145 out: &mut TaggedRowBuffer,
146 exec_state: &mut ExecutionState,
147 );
148}
149
150/// A row in a table.
151pub struct Row {
152 /// The id associated with the row.
153 pub id: RowId,
154 /// The Row itself.
155 pub vals: Pooled<Vec<Value>>,
156}
157
158/// An interface for a table.
159pub trait Table: Any + Send + Sync {
160 /// A variant of clone that returns a boxed trait object; this trait object
161 /// must contain all of the data associated with the current table.
162 fn dyn_clone(&self) -> Box<dyn Table>;
163
164 /// If this table can perform a table-level rebuild, construct a [`Rebuilder`] for it.
165 fn rebuilder<'a>(&'a self, _cols: &[ColumnId]) -> Option<Box<dyn Rebuilder + 'a>> {
166 None
167 }
168
169 /// Rebuild the table according to the given [`Rebuilder`] implemented by `table`, if
170 /// there is one. Applying a rebuild can cause more mutations to be buffered, which can in turn
171 /// be flushed by a call to [`Table::merge`].
172 ///
173 /// Note that value-level rebuilds are only relevant for tables that opt into it. As a result,
174 /// tables do nothing by default.
175 ///
176 /// Returns whether any rows may be removed or inserted.
177 fn apply_rebuild(
178 &mut self,
179 _table_id: TableId,
180 _table: &WrappedTable,
181 _next_ts: Value,
182 _exec_state: &mut ExecutionState,
183 ) -> bool {
184 // Default implementation does nothing.
185 false
186 }
187
188 /// Refresh rows whose rebuildable columns mention one of `dirty_ids` by re-inserting the same
189 /// logical row with a fresh timestamp.
190 ///
191 /// This is the narrow escape hatch used when some external rebuild step
192 /// changes the semantics of an id in place, so seminaive needs a new
193 /// parent-row delta even though the row's key columns do not otherwise
194 /// change.
195 ///
196 /// One source of such ids is [`crate::ContainerRebuildSummary::dirty_ids`].
197 ///
198 /// Tables that do not maintain rebuildable id columns can use the default
199 /// no-op implementation.
200 fn refresh_rows_for_values(&mut self, _dirty_ids: &[Value], _next_ts: Value) -> bool {
201 false
202 }
203
204 /// A boilerplate method to make it easier to downcast values of `Table`.
205 ///
206 /// Implementors should be able to implement this method by returning
207 /// `self`.
208 fn as_any(&self) -> &dyn Any;
209
210 /// The schema of the table.
211 ///
212 /// These are immutable properties of the table; callers can assume they
213 /// will never change.
214 fn spec(&self) -> TableSpec;
215
216 /// Clear all table contents. If the table is nonempty, this will change the
217 /// generation of the table. This method also clears any pending data.
218 fn clear(&mut self);
219
220 // Used in queries:
221
222 /// Get a subset corresponding to all rows in the table.
223 fn all(&self) -> Subset;
224
225 /// Get the length of the table.
226 ///
227 /// This is not in general equal to the length of the `all` subset: the size
228 /// of a subset is allowed to be larger than the number of table entries in
229 /// range of the subset.
230 fn len(&self) -> usize;
231
232 /// Check if the table is empty.
233 fn is_empty(&self) -> bool {
234 self.len() == 0
235 }
236
237 /// Get the current version for the table. [`RowId`]s and [`Subset`]s are
238 /// only valid for a given major generation.
239 fn version(&self) -> TableVersion;
240
241 /// Get the subset of the table that has appeared since the last offset.
242 fn updates_since(&self, offset: Offset) -> Subset;
243
244 /// Iterate over the given subset of the table, starting at an opaque
245 /// `start` token, ending after up to `n` rows, returning the next start
246 /// token if more rows remain. Only invoke `f` on rows that match the given
247 /// constraints.
248 ///
249 /// An implementation must not invoke `f` on a stale row, constrained or
250 /// not, so callers need not filter stale rows back out.
251 /// `tests/repro-stale-rows.egg` guards the constrained path.
252 ///
253 /// This method is _not_ object safe, but it is used to define various
254 /// "default" implementations of object-safe methods like `scan` and
255 /// `pivot`.
256 fn scan_generic_bounded(
257 &self,
258 subset: SubsetRef,
259 start: Offset,
260 n: usize,
261 cs: &[Constraint],
262 f: impl FnMut(RowId, &[Value]),
263 ) -> Option<Offset>
264 where
265 Self: Sized;
266
267 /// Iterate over the given subset of the table.
268 ///
269 /// This is a variant of [`Table::scan_generic_bounded`] that iterates over
270 /// the entire table.
271 fn scan_generic(&self, subset: SubsetRef, mut f: impl FnMut(RowId, &[Value]))
272 where
273 Self: Sized,
274 {
275 let mut cur = Offset::new(0);
276 while let Some(next) = self.scan_generic_bounded(subset, cur, usize::MAX, &[], |id, row| {
277 f(id, row);
278 }) {
279 cur = next;
280 }
281 }
282
283 /// Returns true if the table contains any stale rows (rows whose first column
284 /// has been set to [`Value::stale()`]). The default implementation returns `true`
285 /// (conservative). Tables that track stale-row counts should override this.
286 fn has_stale_rows(&self) -> bool {
287 true
288 }
289
290 /// Filter a given subset of the table for the rows that are live
291 fn refine_live(&self, subset: Subset) -> Subset {
292 // NB: This relies on Value::stale() being strictly larger than any other value in the table.
293 self.refine_one(
294 subset,
295 &Constraint::LtConst {
296 col: ColumnId::new_const(0),
297 val: Value::stale(),
298 },
299 )
300 }
301
302 /// Filter a given subset of the table for the rows matching the single constraint.
303 ///
304 /// Implementors must provide at least one of `refine_one` or `refine`.`
305 fn refine_one(&self, subset: Subset, c: &Constraint) -> Subset {
306 self.refine(subset, std::slice::from_ref(c))
307 }
308
309 /// Filter a given subset of the table for the rows matching the given constraints.
310 ///
311 /// Implementors must provide at least one of `refine_one` or `refine`.`
312 fn refine(&self, subset: Subset, cs: &[Constraint]) -> Subset {
313 cs.iter()
314 .fold(subset, |subset, c| self.refine_one(subset, c))
315 }
316
317 /// Filter a borrowed `subset` to the rows matching `cs` — and, when
318 /// `check_live` is set, to live rows — returning an owned subset.
319 ///
320 /// Equivalent to `to_owned` + [`Table::refine_live`] + [`Table::refine`];
321 /// implementors may fuse the copy and filter into a single pass.
322 fn refine_ref(&self, subset: SubsetRef, cs: &[Constraint], check_live: bool) -> Subset {
323 let mut owned = subset.to_owned(&with_pool_set(|ps| ps.get_pool()));
324 if check_live {
325 owned = self.refine_live(owned);
326 }
327 if cs.is_empty() {
328 owned
329 } else {
330 self.refine(owned, cs)
331 }
332 }
333
334 /// Whether `subset` contains at least one live row matching `cs`.
335 ///
336 /// Equivalent to checking that [`Table::refine_ref`] with `check_live` set
337 /// returns a nonempty subset; implementors may stop at the first match.
338 fn contains_match(&self, subset: SubsetRef, cs: &[Constraint]) -> bool {
339 self.refine_ref(subset, cs, true).size() != 0
340 }
341
342 /// An optional method for quickly generating a subset from a constraint.
343 /// The standard use-case here is to apply constraints based on a column
344 /// that is known to be sorted.
345 ///
346 /// These constraints are very helpful for query planning; it is a good idea
347 /// to implement them.
348 fn fast_subset(&self, _: &Constraint) -> Option<Subset> {
349 None
350 }
351
352 /// A helper routine that leverages the existing `fast_subset` method to
353 /// preprocess a set of constraints into "fast" and "slow" ones, returning
354 /// the subet of indexes that match the fast one.
355 fn split_fast_slow(
356 &self,
357 cs: &[Constraint],
358 ) -> (
359 Subset, /* the subset of the table matching all fast constraints */
360 Pooled<Vec<Constraint>>, /* the fast constraints */
361 Pooled<Vec<Constraint>>, /* the slow constraints */
362 ) {
363 with_pool_set(|ps| {
364 let mut fast = ps.get::<Vec<Constraint>>();
365 let mut slow = ps.get::<Vec<Constraint>>();
366 let mut subset = self.all();
367 for c in cs {
368 if let Some(sub) = self.fast_subset(c) {
369 subset.intersect(sub.as_ref(), &ps.get_pool());
370 fast.push(c.clone());
371 } else {
372 slow.push(c.clone());
373 }
374 }
375 (subset, fast, slow)
376 })
377 }
378
379 // Used in actions:
380
381 /// Look up a single row by the given key values, if it is in the table.
382 ///
383 /// The number of values specified by `keys` should match the number of
384 /// primary keys for the table.
385 fn get_row(&self, key: &[Value]) -> Option<Row>;
386
387 /// Look up the given column of single row by the given key values, if it is
388 /// in the table.
389 ///
390 /// The number of values specified by `keys` should match the number of
391 /// primary keys for the table.
392 fn get_row_column(&self, key: &[Value], col: ColumnId) -> Option<Value> {
393 self.get_row(key).map(|row| row.vals[col.index()])
394 }
395
396 /// Merge any updates to the table, and potentially update the generation for
397 /// the table.
398 fn merge(&mut self, exec_state: &mut ExecutionState) -> TableChange;
399
400 /// Create a new buffer for staging mutations on this table. Mutations staged to a
401 /// MutationBuffer that is then dropped may not take effect until the next call to
402 /// [`Table::merge`].
403 fn new_buffer(&self) -> Box<dyn MutationBuffer>;
404}
405
406/// A trait specifying a buffer of pending mutations for a [`Table`].
407///
408/// Dropping an object implementing this trait should "flush" the pending
409/// mutations to the table. Calling [`Table::merge`] on that table would then
410/// apply those mutations, making them visible for future readers.
411pub trait MutationBuffer: Any + Send + Sync {
412 /// Stage the keyed entries for insertion. Changes may not be visible until
413 /// this buffer is dropped, and after `merge` is called on the underlying
414 /// table.
415 fn stage_insert(&mut self, row: &[Value]);
416
417 /// Stage the keyed entries for removal. Changes may not be visible until
418 /// this buffer is dropped, and after `merge` is called on the underlying
419 /// table.
420 fn stage_remove(&mut self, key: &[Value]);
421
422 /// Get a fresh handle to the same table.
423 fn fresh_handle(&self) -> Box<dyn MutationBuffer>;
424}
425
426struct WrapperImpl<T>(PhantomData<T>);
427
428pub(crate) fn wrapper<T: Table>() -> Box<dyn TableWrapper> {
429 Box::new(WrapperImpl::<T>(PhantomData))
430}
431
432impl<T: Table> TableWrapper for WrapperImpl<T> {
433 fn dyn_clone(&self) -> Box<dyn TableWrapper> {
434 Box::new(Self(PhantomData))
435 }
436 fn scan_bounded(
437 &self,
438 table: &dyn Table,
439 subset: SubsetRef,
440 start: Offset,
441 n: usize,
442 out: &mut TaggedRowBuffer,
443 ) -> Option<Offset> {
444 let table = table.as_any().downcast_ref::<T>().unwrap();
445 table.scan_generic_bounded(subset, start, n, &[], |row_id, row| {
446 out.add_row(row_id, row);
447 })
448 }
449 fn for_each_col(
450 &self,
451 table: &dyn Table,
452 subset: SubsetRef,
453 col: ColumnId,
454 f: &mut dyn FnMut(RowId, Value),
455 ) {
456 let table = table.as_any().downcast_ref::<T>().unwrap();
457 let col_idx = col.index();
458 table.scan_generic(subset, |row_id, row| {
459 f(row_id, row[col_idx]);
460 });
461 }
462
463 fn collect_col_pairs(
464 &self,
465 table: &dyn Table,
466 subset: SubsetRef,
467 col: ColumnId,
468 out: &mut Vec<(Value, RowId)>,
469 ) {
470 let table = table.as_any().downcast_ref::<T>().unwrap();
471 let col_idx = col.index();
472 out.reserve(subset.size());
473 table.scan_generic(subset, |row_id, row| {
474 out.push((row[col_idx], row_id));
475 });
476 }
477
478 fn scan_project(
479 &self,
480 table: &dyn Table,
481 subset: SubsetRef,
482 cols: &[ColumnId],
483 start: Offset,
484 n: usize,
485 cs: &[Constraint],
486 out: &mut dyn RowSink,
487 ) -> Option<Offset> {
488 let table = table.as_any().downcast_ref::<T>().unwrap();
489 match cols {
490 [] => None,
491 [col] => table.scan_generic_bounded(subset, start, n, cs, |id, row| {
492 out.add_row(id, &[row[col.index()]]);
493 }),
494 [x, y] => table.scan_generic_bounded(subset, start, n, cs, |id, row| {
495 out.add_row(id, &[row[x.index()], row[y.index()]]);
496 }),
497 [x, y, z] => table.scan_generic_bounded(subset, start, n, cs, |id, row| {
498 out.add_row(id, &[row[x.index()], row[y.index()], row[z.index()]]);
499 }),
500 _ => {
501 let mut scratch = SmallVec::<[Value; 8]>::with_capacity(cols.len());
502 table.scan_generic_bounded(subset, start, n, cs, |id, row| {
503 for col in cols {
504 scratch.push(row[col.index()]);
505 }
506 out.add_row(id, &scratch);
507 scratch.clear();
508 })
509 }
510 }
511 }
512
513 fn lookup_row_vectorized(
514 &self,
515 table: &dyn Table,
516 mask: &mut Mask,
517 bindings: &mut Bindings,
518 args: &[QueryEntry],
519 col: ColumnId,
520 out_var: Variable,
521 ) {
522 let table = table.as_any().downcast_ref::<T>().unwrap();
523 let mut out = with_pool_set(PoolSet::get::<Vec<Value>>);
524 for_each_binding_with_mask!(mask, args, bindings, |iter| {
525 iter.fill_vec(&mut out, Value::stale, |_, args| {
526 table.get_row_column(args.as_slice(), col)
527 })
528 });
529 bindings.insert(out_var, &out);
530 }
531
532 fn lookup_with_default_vectorized(
533 &self,
534 table: &dyn Table,
535 mask: &mut Mask,
536 bindings: &mut Bindings,
537 args: &[QueryEntry],
538 col: ColumnId,
539 default: QueryEntry,
540 out_var: Variable,
541 ) {
542 let table = table.as_any().downcast_ref::<T>().unwrap();
543 let mut out = with_pool_set(|ps| ps.get::<Vec<Value>>());
544 for_each_binding_with_mask!(mask, args, bindings, |iter| {
545 match default {
546 QueryEntry::Var(default) => iter.zip(&bindings[default]).fill_vec(
547 &mut out,
548 Value::stale,
549 |_, (args, default)| {
550 Some(
551 table
552 .get_row_column(args.as_slice(), col)
553 .unwrap_or(*default),
554 )
555 },
556 ),
557 QueryEntry::Const(default) => iter.fill_vec(&mut out, Value::stale, |_, args| {
558 Some(
559 table
560 .get_row_column(args.as_slice(), col)
561 .unwrap_or(default),
562 )
563 }),
564 }
565 });
566 bindings.insert(out_var, &out);
567 }
568}
569
570/// A WrappedTable takes a Table and extends it with a number of helpful,
571/// object-safe methods for accessing a table.
572///
573/// It essentially acts like an extension trait: it is a separate type to allow
574/// object-safe extension methods to call methods that require `Self: Sized`.
575/// The implementations here downcast manually to the type used when
576/// constructing the WrappedTable.
577pub struct WrappedTable {
578 inner: Box<dyn Table>,
579 wrapper: Box<dyn TableWrapper>,
580}
581
582impl WrappedTable {
583 pub(crate) fn new<T: Table>(inner: T) -> Self {
584 let wrapper = wrapper::<T>();
585 let inner = Box::new(inner);
586 Self { inner, wrapper }
587 }
588
589 /// Clone the contents of the table.
590 pub fn dyn_clone(&self) -> Self {
591 WrappedTable {
592 inner: self.inner.dyn_clone(),
593 wrapper: self.wrapper.dyn_clone(),
594 }
595 }
596
597 pub(crate) fn as_ref(&self) -> WrappedTableRef<'_> {
598 WrappedTableRef {
599 inner: &*self.inner,
600 wrapper: &*self.wrapper,
601 }
602 }
603
604 /// Starting at the given [`Offset`] into `subset`, scan up to `n` rows and
605 /// write them to `out`. Return the next starting offset. If no offset is
606 /// returned then the subset has been scanned completely.
607 /// Rows written to `out` are never stale, so callers can take the buffer's
608 /// full contents.
609 pub fn scan_bounded(
610 &self,
611 subset: SubsetRef,
612 start: Offset,
613 n: usize,
614 out: &mut TaggedRowBuffer,
615 ) -> Option<Offset> {
616 self.as_ref().scan_bounded(subset, start, n, out)
617 }
618
619 /// A variant fo [`WrappedTable::scan_bounded`] that projects a subset of
620 /// columns and only appends rows that match the given constraints.
621 /// Rows written to `out` are never stale, so callers can take the buffer's
622 /// full contents.
623 pub fn scan_project(
624 &self,
625 subset: SubsetRef,
626 cols: &[ColumnId],
627 start: Offset,
628 n: usize,
629 cs: &[Constraint],
630 out: &mut dyn RowSink,
631 ) -> Option<Offset> {
632 self.as_ref().scan_project(subset, cols, start, n, cs, out)
633 }
634
635 /// Return the contents of the subset as a [`TaggedRowBuffer`].
636 pub fn scan(&self, subset: SubsetRef) -> TaggedRowBuffer {
637 self.as_ref().scan(subset)
638 }
639
640 pub(crate) fn lookup_row_vectorized(
641 &self,
642 mask: &mut Mask,
643 bindings: &mut Bindings,
644 args: &[QueryEntry],
645 col: ColumnId,
646 out_var: Variable,
647 ) {
648 self.as_ref()
649 .lookup_row_vectorized(mask, bindings, args, col, out_var)
650 }
651
652 #[allow(clippy::too_many_arguments)]
653 pub(crate) fn lookup_with_default_vectorized(
654 &self,
655 mask: &mut Mask,
656 bindings: &mut Bindings,
657 args: &[QueryEntry],
658 col: ColumnId,
659 default: QueryEntry,
660 out_var: Variable,
661 ) {
662 self.as_ref()
663 .lookup_with_default_vectorized(mask, bindings, args, col, default, out_var)
664 }
665}
666
667impl Deref for WrappedTable {
668 type Target = dyn Table;
669
670 fn deref(&self) -> &Self::Target {
671 &*self.inner
672 }
673}
674
675impl DerefMut for WrappedTable {
676 fn deref_mut(&mut self) -> &mut Self::Target {
677 &mut *self.inner
678 }
679}
680
681pub(crate) trait TableWrapper: Send + Sync {
682 fn dyn_clone(&self) -> Box<dyn TableWrapper>;
683 fn scan_bounded(
684 &self,
685 table: &dyn Table,
686 subset: SubsetRef,
687 start: Offset,
688 n: usize,
689 out: &mut TaggedRowBuffer,
690 ) -> Option<Offset>;
691 /// Scan each row in `subset`, calling `f(row_id, col_value)` for each.
692 /// Unlike `scan_project`, this writes directly to the callback with no
693 /// intermediate buffer.
694 fn for_each_col(
695 &self,
696 table: &dyn Table,
697 subset: SubsetRef,
698 col: ColumnId,
699 f: &mut dyn FnMut(RowId, Value),
700 );
701
702 /// Append `(col_value, row_id)` for each row in `subset` to `out`.
703 ///
704 /// Equivalent to [`TableWrapper::for_each_col`] pushing into `out`, but the
705 /// scan loop is monomorphized, avoiding a virtual callback per row.
706 fn collect_col_pairs(
707 &self,
708 table: &dyn Table,
709 subset: SubsetRef,
710 col: ColumnId,
711 out: &mut Vec<(Value, RowId)>,
712 );
713
714 #[allow(clippy::too_many_arguments)]
715 fn scan_project(
716 &self,
717 table: &dyn Table,
718 subset: SubsetRef,
719 cols: &[ColumnId],
720 start: Offset,
721 n: usize,
722 cs: &[Constraint],
723 out: &mut dyn RowSink,
724 ) -> Option<Offset>;
725
726 fn scan(&self, table: &dyn Table, subset: SubsetRef) -> TaggedRowBuffer {
727 let arity = table.spec().arity();
728 let mut buf = TaggedRowBuffer::new(arity);
729 assert!(
730 self.scan_bounded(table, subset, Offset::new(0), usize::MAX, &mut buf)
731 .is_none()
732 );
733 buf
734 }
735
736 #[allow(clippy::too_many_arguments)]
737 fn lookup_row_vectorized(
738 &self,
739 table: &dyn Table,
740 mask: &mut Mask,
741 bindings: &mut Bindings,
742 args: &[QueryEntry],
743 col: ColumnId,
744 out_var: Variable,
745 );
746
747 #[allow(clippy::too_many_arguments)]
748 fn lookup_with_default_vectorized(
749 &self,
750 table: &dyn Table,
751 mask: &mut Mask,
752 bindings: &mut Bindings,
753 args: &[QueryEntry],
754 col: ColumnId,
755 default: QueryEntry,
756 out_var: Variable,
757 );
758}
759
760/// An extra layer of indirection over a [`WrappedTable`] that does not require that the caller
761/// actually own the table. This is useful when a table implementation needs to construct a
762/// WrappedTable on its own.
763#[derive(Clone, Copy)]
764pub struct WrappedTableRef<'a> {
765 inner: &'a dyn Table,
766 wrapper: &'a dyn TableWrapper,
767}
768
769impl WrappedTableRef<'_> {
770 pub(crate) fn with_wrapper<T: Table, R>(
771 inner: &T,
772 f: impl for<'a> FnOnce(WrappedTableRef<'a>) -> R,
773 ) -> R {
774 let wrapper = WrapperImpl::<T>(PhantomData);
775 f(WrappedTableRef {
776 inner,
777 wrapper: &wrapper,
778 })
779 }
780
781 /// Starting at the given [`Offset`] into `subset`, scan up to `n` rows and
782 /// write them to `out`. Return the next starting offset. If no offset is
783 /// returned then the subset has been scanned completely.
784 pub fn scan_bounded(
785 &self,
786 subset: SubsetRef,
787 start: Offset,
788 n: usize,
789 out: &mut TaggedRowBuffer,
790 ) -> Option<Offset> {
791 self.wrapper.scan_bounded(self.inner, subset, start, n, out)
792 }
793
794 /// Scan each row in `subset` and call `f(row_id, col_value)` for each.
795 /// This is a zero-copy alternative to `scan_project` for single-column
796 /// scans over small subsets where an intermediate buffer is wasteful.
797 pub(crate) fn for_each_col(
798 &self,
799 subset: SubsetRef,
800 col: ColumnId,
801 f: &mut dyn FnMut(RowId, Value),
802 ) {
803 self.wrapper.for_each_col(self.inner, subset, col, f);
804 }
805
806 /// Append `(col_value, row_id)` for each row in `subset` to `out`, using a
807 /// monomorphized scan loop (no per-row virtual call).
808 pub(crate) fn collect_col_pairs(
809 &self,
810 subset: SubsetRef,
811 col: ColumnId,
812 out: &mut Vec<(Value, RowId)>,
813 ) {
814 self.wrapper.collect_col_pairs(self.inner, subset, col, out);
815 }
816
817 /// A variant fo [`WrappedTable::scan_bounded`] that projects a subset of
818 /// columns and only appends rows that match the given constraints.
819 pub fn scan_project(
820 &self,
821 subset: SubsetRef,
822 cols: &[ColumnId],
823 start: Offset,
824 n: usize,
825 cs: &[Constraint],
826 out: &mut dyn RowSink,
827 ) -> Option<Offset> {
828 self.wrapper
829 .scan_project(self.inner, subset, cols, start, n, cs, out)
830 }
831
832 /// Return the contents of the subset as a [`TaggedRowBuffer`].
833 pub fn scan(&self, subset: SubsetRef) -> TaggedRowBuffer {
834 self.wrapper.scan(self.inner, subset)
835 }
836
837 pub(crate) fn lookup_row_vectorized(
838 &self,
839 mask: &mut Mask,
840 bindings: &mut Bindings,
841 args: &[QueryEntry],
842 col: ColumnId,
843 out_var: Variable,
844 ) {
845 self.wrapper
846 .lookup_row_vectorized(self.inner, mask, bindings, args, col, out_var);
847 }
848
849 #[allow(clippy::too_many_arguments)]
850 pub(crate) fn lookup_with_default_vectorized(
851 &self,
852 mask: &mut Mask,
853 bindings: &mut Bindings,
854 args: &[QueryEntry],
855 col: ColumnId,
856 default: QueryEntry,
857 out_var: Variable,
858 ) {
859 self.wrapper.lookup_with_default_vectorized(
860 self.inner, mask, bindings, args, col, default, out_var,
861 );
862 }
863}
864
865impl Deref for WrappedTableRef<'_> {
866 type Target = dyn Table;
867
868 fn deref(&self) -> &Self::Target {
869 self.inner
870 }
871}