ColumnarBatch

Struct ColumnarBatch 

Source
pub struct ColumnarBatch { /* private fields */ }
Expand description

A columnar batch stores data in column-oriented format for efficient SIMD processing

Unlike row-oriented storage (Vec), columnar batches store each column in a contiguous array, enabling:

  • SIMD vectorization (process 4-8 values per instruction)
  • Better cache locality (columns accessed together are stored together)
  • Type-specialized code paths (no SqlValue enum matching)
  • Efficient NULL handling with separate bitmasks

§Example

// Convert rows to columnar batch
let batch = ColumnarBatch::from_rows(&rows, &schema)?;

// Access columns with zero-copy
if let ColumnArray::Int64(values, nulls) = &batch.columns[0] {
    // Process with SIMD operations
    let sum = simd_sum_i64(values);
}

Implementations§

Source§

impl ColumnarBatch

Source

pub fn from_arrow_batch(batch: &RecordBatch) -> Result<Self, ExecutorError>

Convert from Arrow RecordBatch to ColumnarBatch (zero-copy when possible)

This provides integration with Arrow-based storage engines, enabling zero-copy columnar query execution. Arrow’s columnar format maps directly to our ColumnarBatch structure.

§Performance
  • Zero-copy: Numeric types (Int64, Float64) are converted with minimal overhead
  • < 1ms overhead: Conversion time negligible compared to query execution
  • Memory efficient: Reuses Arrow’s allocated memory where possible
§Arguments
  • batch - Arrow RecordBatch from storage layer
§Returns

A ColumnarBatch ready for SIMD-accelerated query execution

Source§

impl ColumnarBatch

Source

pub fn new(column_count: usize) -> Self

Create a new empty columnar batch

Source

pub fn with_capacity(_row_count: usize, column_count: usize) -> Self

Create a columnar batch with specified capacity

Source

pub fn empty(column_count: usize) -> Result<Self, ExecutorError>

Create an empty batch with the specified number of columns

Source

pub fn from_columns( columns: Vec<ColumnArray>, column_names: Option<Vec<String>>, ) -> Result<Self, ExecutorError>

Create a batch from a list of columns

Source

pub fn from_rows(rows: &[Row]) -> Result<Self, ExecutorError>

Convert from row-oriented storage to columnar batch

This analyzes the first row to infer column types, then materializes all values into type-specialized column arrays.

Source

pub fn from_rows_selective( rows: &[Row], column_indices: &[usize], ) -> Result<Self, ExecutorError>

Convert selected columns from row-oriented storage to columnar batch

This is an optimized version of from_rows that only extracts the specified columns. This is critical for predicate evaluation on wide tables where only a few columns are referenced by the WHERE clause.

§Arguments
  • rows - The rows to convert
  • column_indices - Which column indices to extract (must be sorted)
§Returns

A sparse columnar batch where column(i) returns the data for column_indices[i]. The caller must map original column indices to batch positions using the column_indices array.

§Performance

For a table with 16 columns where only 1 column is needed:

  • from_rows: extracts all 16 columns (100% work)
  • from_rows_selective: extracts only 1 column (6% work)
Source§

impl ColumnarBatch

Source

pub fn row_count(&self) -> usize

Get the number of rows in this batch

Source

pub fn column_count(&self) -> usize

Get the number of columns in this batch

Source

pub fn column(&self, index: usize) -> Option<&ColumnArray>

Get a reference to a column array

Source

pub fn column_mut(&mut self, index: usize) -> Option<&mut ColumnArray>

Get a mutable reference to a column array

Source

pub fn add_column(&mut self, column: ColumnArray) -> Result<(), ExecutorError>

Add a column to the batch

Source

pub fn set_column_names(&mut self, names: Vec<String>)

Set column names (for debugging)

Source

pub fn column_names(&self) -> Option<&[String]>

Get column names

Source

pub fn column_index_by_name(&self, name: &str) -> Option<usize>

Get column index by name

Source

pub fn get_value( &self, row_idx: usize, col_idx: usize, ) -> Result<SqlValue, ExecutorError>

Get a value at a specific (row, column) position

Source

pub fn to_rows(&self) -> Result<Vec<Row>, ExecutorError>

Convert columnar batch back to row-oriented storage

This implementation uses column-outer, row-inner iteration for better cache locality. Instead of calling get_value() for each cell (O(n*m) enum matches), we match on each column once and iterate through all its values sequentially.

§Performance

For a 60,000 row × 15 column batch:

  • Old approach: 900,000 get_value() calls with enum matching per cell
  • New approach: 15 enum matches total, sequential memory access per column

Expected 2-3x speedup due to:

  • Single enum match per column (not per cell)
  • Sequential memory access within each column array
  • Better CPU cache utilization
Source

pub fn deduplicate(&self) -> Result<Self, ExecutorError>

Deduplicate rows in the batch, returning a new batch with unique rows only

Uses hash-based deduplication on all columns, preserving insertion order. This implements DISTINCT semantics: NULL == NULL for uniqueness purposes.

§Performance
  • O(n) time complexity where n is the number of rows
  • Uses AHashSet for efficient duplicate detection
  • Preserves the first occurrence of each unique row combination
§Example
// Original batch:
// [1, "A"], [2, "B"], [1, "A"], [3, "C"]

// After deduplicate():
// [1, "A"], [2, "B"], [3, "C"]
Source

pub fn select_rows(&self, indices: &[usize]) -> Result<Self, ExecutorError>

Select specific rows from the batch by index, returning a new batch

§Arguments
  • indices - Row indices to select (must be valid for this batch)
§Returns

A new ColumnarBatch containing only the selected rows

Source§

impl ColumnarBatch

Source

pub fn from_storage_columnar( storage_columnar: &ColumnarTable, ) -> Result<Self, ExecutorError>

Convert from storage layer ColumnarTable to executor ColumnarBatch

This method provides true zero-copy conversion from the storage layer’s columnar format to the executor’s columnar format. This is the key integration point for native columnar table scans.

§Performance
  • O(1) for numeric/string columns: Arc::clone is just a reference count bump
  • < 1 microsecond for millions of rows (vs O(n) with data copy)
  • Directly shares storage ColumnData with executor ColumnArray
  • Critical path for TPC-H Q6 and other analytical queries
§Zero-Copy Design

Both vibesql_storage::ColumnData and executor ColumnArray use Arc<Vec<T>> for column data. Calling Arc::clone() only increments a reference count, avoiding any data copying:

Storage: Arc<Vec<i64>> ─┬─> [1, 2, 3, 4, ...]  (shared memory)
                        │
Executor: Arc<Vec<i64>> ┘
§Arguments
  • storage_columnar - ColumnarTable from storage layer (vibesql-storage)
§Returns
  • Ok(ColumnarBatch) - Executor-ready columnar batch with shared Arc references
  • Err(ExecutorError) - If type conversion fails

Trait Implementations§

Source§

impl Clone for ColumnarBatch

Source§

fn clone(&self) -> ColumnarBatch

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ColumnarBatch

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<G1, G2> Within<G2> for G1
where G2: Contains<G1>,

Source§

fn is_within(&self, b: &G2) -> bool

Source§

impl<T> Allocation for T
where T: RefUnwindSafe + Send + Sync,