Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/src/facts.rs

use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;

use arrow_array::{Array, ArrayRef, RecordBatch, UInt32Array, UInt64Array, cast::AsArray, types};
use arrow_buffer::ScalarBuffer;
use arrow_schema::DataType;
use datafusion::catalog::TableProvider;
use kleene_sparse::Csr;

use crate::External;
use crate::rules::{RelId, Value};
use crate::{PlanError, Result};

/// One column of facts: `u32` storage while every value fits, `u64` once one does not (a
/// value is never cut). The values sit in Arrow buffers: a column read from an Arrow array
/// shares its buffer, and cloning a column (or [`Facts`]) copies no values.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Column {
    /// Every value fits 32 bits.
    U32(ScalarBuffer<u32>),
    /// 64-bit values.
    U64(ScalarBuffer<u64>),
}

impl Default for Column {
    fn default() -> Self {
        Column::U32(ScalarBuffer::from(Vec::<u32>::new()))
    }
}

impl From<Vec<u32>> for Column {
    fn from(v: Vec<u32>) -> Self {
        Column::U32(ScalarBuffer::from(v))
    }
}

impl From<Vec<u64>> for Column {
    fn from(v: Vec<u64>) -> Self {
        Column::U64(ScalarBuffer::from(v))
    }
}

impl From<ScalarBuffer<u32>> for Column {
    fn from(v: ScalarBuffer<u32>) -> Self {
        Column::U32(v)
    }
}

impl From<ScalarBuffer<u64>> for Column {
    fn from(v: ScalarBuffer<u64>) -> Self {
        Column::U64(v)
    }
}

impl PartialEq for Column {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Column::U32(a), Column::U32(b)) => a[..] == b[..],
            (Column::U64(a), Column::U64(b)) => a[..] == b[..],
            _ => self.len() == other.len() && self.iter().eq(other.iter()),
        }
    }
}

impl Eq for Column {}

impl Column {
    /// The number of values.
    pub fn len(&self) -> usize {
        match self {
            Column::U32(v) => v.len(),
            Column::U64(v) => v.len(),
        }
    }

    /// True when there are none.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Value `k`.
    #[inline]
    pub fn get(&self, k: usize) -> Value {
        match self {
            Column::U32(v) => v[k] as Value,
            Column::U64(v) => v[k],
        }
    }

    /// Every value, in order.
    pub fn iter(&self) -> impl Iterator<Item = Value> + '_ {
        let (a, b) = match self {
            Column::U32(v) => (Some(v.iter().map(|&x| x as Value)), None),
            Column::U64(v) => (None, Some(v.iter().copied())),
        };
        a.into_iter().flatten().chain(b.into_iter().flatten())
    }

    /// True when the storage is 64 bits.
    pub fn is_wide(&self) -> bool {
        matches!(self, Column::U64(_))
    }

    /// The values, when stored as `u32`.
    pub fn as_u32(&self) -> Option<&[u32]> {
        match self {
            Column::U32(v) => Some(v),
            Column::U64(_) => None,
        }
    }

    /// The values, when stored as `u64`.
    pub fn as_u64(&self) -> Option<&[u64]> {
        match self {
            Column::U32(_) => None,
            Column::U64(v) => Some(v),
        }
    }

    /// The values as `u32` (vertex ids): borrowed when stored so, else narrowed, and
    /// refused when one does not fit.
    pub fn to_u32(&self) -> Result<Cow<'_, [u32]>> {
        match self {
            Column::U32(v) => Ok(Cow::Borrowed(v)),
            Column::U64(v) => v
                .iter()
                .map(|&x| u32::try_from(x).map_err(|_| too_big_for_id(x)))
                .collect::<Result<Vec<u32>>>()
                .map(Cow::Owned),
        }
    }

    /// The values as `u64`.
    pub fn to_u64(&self) -> Vec<u64> {
        self.iter().collect()
    }

    /// The largest value (0 when empty).
    pub fn max(&self) -> Value {
        match self {
            Column::U32(v) => v.iter().copied().max().unwrap_or(0) as Value,
            Column::U64(v) => v.iter().copied().max().unwrap_or(0),
        }
    }

    /// The values at `rows`, in that order (a gather into a new column).
    pub fn take(&self, rows: &[u32]) -> Column {
        match self {
            Column::U32(v) => {
                Column::from(rows.iter().map(|&r| v[r as usize]).collect::<Vec<u32>>())
            }
            Column::U64(v) => {
                Column::from(rows.iter().map(|&r| v[r as usize]).collect::<Vec<u64>>())
            }
        }
    }

    /// The column as an Arrow array sharing its buffer: `UInt32` or `UInt64` as stored.
    pub fn to_arrow(&self) -> ArrayRef {
        match self {
            Column::U32(v) => Arc::new(UInt32Array::new(v.clone(), None)),
            Column::U64(v) => Arc::new(UInt64Array::new(v.clone(), None)),
        }
    }

    /// The column as an Arrow `UInt64` array (shared when stored so, else widened).
    pub fn to_arrow_u64(&self) -> ArrayRef {
        match self {
            Column::U32(_) => Arc::new(UInt64Array::from(self.to_u64())),
            Column::U64(v) => Arc::new(UInt64Array::new(v.clone(), None)),
        }
    }
}

/// A column being written value by value: `u32` until a value does not fit, then `u64`.
#[derive(Clone, Debug)]
pub(crate) enum ColumnBuilder {
    U32(Vec<u32>),
    U64(Vec<u64>),
}

impl Default for ColumnBuilder {
    fn default() -> Self {
        ColumnBuilder::U32(Vec::new())
    }
}

impl ColumnBuilder {
    pub(crate) fn with_capacity(n: usize) -> Self {
        ColumnBuilder::U32(Vec::with_capacity(n))
    }

    #[inline]
    pub(crate) fn push(&mut self, x: Value) {
        match self {
            ColumnBuilder::U32(v) => match u32::try_from(x) {
                Ok(y) => v.push(y),
                Err(_) => {
                    let mut w: Vec<u64> = Vec::with_capacity(v.capacity().max(v.len() + 1));
                    w.extend(v.iter().map(|&y| y as u64));
                    w.push(x);
                    *self = ColumnBuilder::U64(w);
                }
            },
            ColumnBuilder::U64(v) => v.push(x),
        }
    }

    pub(crate) fn finish(self) -> Column {
        match self {
            ColumnBuilder::U32(v) => Column::from(v),
            ColumnBuilder::U64(v) => Column::from(v),
        }
    }
}

/// Facts being written row by row.
#[derive(Clone, Debug, Default)]
pub(crate) struct FactsBuilder {
    cols: Vec<ColumnBuilder>,
    held: bool,
}

impl FactsBuilder {
    pub(crate) fn new(arity: usize) -> Self {
        FactsBuilder {
            cols: vec![ColumnBuilder::default(); arity],
            held: false,
        }
    }

    #[inline]
    pub(crate) fn push(&mut self, row: &[Value]) {
        self.held = true;
        for (c, &v) in self.cols.iter_mut().zip(row) {
            c.push(v);
        }
    }

    pub(crate) fn finish(self) -> Facts {
        Facts {
            held: self.cols.is_empty() && self.held,
            cols: self.cols.into_iter().map(ColumnBuilder::finish).collect(),
        }
    }
}

/// The refusal of a value that is not a `u32` id.
pub(crate) fn too_big_for_id(x: Value) -> PlanError {
    PlanError::Input(format!(
        "value {x} is not a vertex id (over u32); a graph stratum takes u32 ids and does not cut values"
    ))
}

/// The facts of one relation: `arity` columns of values ([`Column`]), one row per fact.
/// A relation of no column (a flag) holds at most one fact, its empty row
/// ([`Facts::flag`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Facts {
    cols: Vec<Column>,
    /// Of no column: whether the one empty row is there (false when there are columns).
    held: bool,
}

impl Facts {
    /// No facts, `arity` columns.
    pub fn empty(arity: usize) -> Self {
        Facts {
            cols: vec![Column::default(); arity],
            held: false,
        }
    }

    /// The facts of a relation of no column: its one empty row when `holds`, else none.
    ///
    /// ```
    /// use kleene_plan::Facts;
    /// assert_eq!((Facts::flag(true).len(), Facts::flag(true).arity()), (1, 0));
    /// assert!(Facts::flag(false).is_empty());
    /// ```
    pub fn flag(holds: bool) -> Self {
        Facts {
            cols: Vec::new(),
            held: holds,
        }
    }

    /// Facts from equally long columns (`Vec<u32>`, `Vec<u64>` or [`Column`]); none of no
    /// column ([`Facts::flag`] gives its one row).
    pub fn from_columns<C: Into<Column>>(cols: Vec<C>) -> Result<Self> {
        let cols: Vec<Column> = cols.into_iter().map(Into::into).collect();
        if let Some(c) = cols.first()
            && cols.iter().any(|d| d.len() != c.len())
        {
            return Err(PlanError::Input("columns of different lengths".into()));
        }
        Ok(Facts { cols, held: false })
    }

    /// Facts from rows (of `u32` or `u64` values). Of no column, any empty row is its one
    /// fact.
    pub fn from_rows<R, V>(arity: usize, rows: impl IntoIterator<Item = R>) -> Result<Self>
    where
        R: AsRef<[V]>,
        V: Copy + Into<Value>,
    {
        let mut f = vec![ColumnBuilder::default(); arity];
        let mut held = false;
        for r in rows {
            let r = r.as_ref();
            held = true;
            if r.len() != arity {
                return Err(PlanError::Input(format!(
                    "a row of {} for a relation of {arity}",
                    r.len()
                )));
            }
            for (c, &v) in f.iter_mut().zip(r) {
                c.push(v.into());
            }
        }
        Ok(Facts {
            held: arity == 0 && held,
            cols: f.into_iter().map(ColumnBuilder::finish).collect(),
        })
    }

    /// The number of columns.
    pub fn arity(&self) -> usize {
        self.cols.len()
    }

    /// The number of facts (of no column: 1 when its row is there, else 0).
    pub fn len(&self) -> usize {
        self.cols.first().map_or(self.held as usize, Column::len)
    }

    /// True when there are none.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Column `i`.
    pub fn column(&self, i: usize) -> &Column {
        &self.cols[i]
    }

    /// Value `k` of column `i`.
    #[inline]
    pub fn value(&self, i: usize, k: usize) -> Value {
        self.cols[i].get(k)
    }

    /// Fact `k`.
    pub fn row(&self, k: usize) -> Vec<Value> {
        self.cols.iter().map(|c| c.get(k)).collect()
    }

    /// Fact `k` written into `out` (cleared first): no allocation once `out` has grown.
    #[inline]
    pub fn row_into(&self, k: usize, out: &mut Vec<Value>) {
        out.clear();
        out.extend(self.cols.iter().map(|c| c.get(k)));
    }

    /// Every fact, in storage order.
    pub fn rows(&self) -> impl Iterator<Item = Vec<Value>> + '_ {
        (0..self.len()).map(|k| self.row(k))
    }

    /// Every fact, sorted.
    pub fn sorted_rows(&self) -> Vec<Vec<Value>> {
        let mut r: Vec<Vec<Value>> = self.rows().collect();
        r.sort_unstable();
        r
    }

    /// Column `i` as an Arrow array sharing its buffer: `UInt32` or `UInt64` as stored.
    pub fn to_arrow(&self, i: usize) -> ArrayRef {
        self.cols[i].to_arrow()
    }

    /// Facts from batches whose columns hold the relation's columns in order (any
    /// integer type up to 64 bits; negative values are refused). One batch of `UInt32` or
    /// `UInt64` columns is used in place.
    pub(crate) fn from_batches(arity: usize, batches: &[RecordBatch]) -> Result<Self> {
        for b in batches {
            if b.num_columns() != arity {
                return Err(PlanError::Input(format!(
                    "{} columns for a relation of {arity}",
                    b.num_columns()
                )));
            }
        }
        if arity == 0 {
            return Ok(Facts::flag(batches.iter().any(|b| b.num_rows() > 0)));
        }
        if let [b] = batches {
            return Facts::from_columns(columns_of(b.columns())?);
        }
        let mut cols = vec![ColumnBuilder::default(); arity];
        for b in batches {
            let kept = without_nulls(b.columns())?;
            for (i, c) in cols.iter_mut().enumerate() {
                extend_column(c, &kept[i])?;
            }
        }
        Facts::from_columns(cols.into_iter().map(ColumnBuilder::finish).collect())
    }
}

/// The columns of [`Source::ColumnsAt`] as they are read: each of a base other than 0 an
/// unsigned column with the base added (a value past `u64` refused), the rest as they are.
pub(crate) fn columns_at(columns: &[ArrayRef], bases: &[Value]) -> Result<Vec<ArrayRef>> {
    if columns.len() != bases.len() {
        return Err(PlanError::Input(format!(
            "{} columns and {} bases",
            columns.len(),
            bases.len()
        )));
    }
    columns
        .iter()
        .zip(bases)
        .map(|(a, &b)| {
            if b == 0 {
                return Ok(a.clone());
            }
            let c = column_of(a)?;
            let mut out = Vec::with_capacity(c.len());
            for k in 0..c.len() {
                let v = c.get(k).checked_add(b).ok_or_else(|| {
                    PlanError::Input(format!("a value plus base {b} is past u64"))
                })?;
                out.push(v);
            }
            Ok(Arc::new(arrow_array::UInt64Array::from(out)) as ArrayRef)
        })
        .collect()
}

/// The columns of an input relation as [`Column`]s ([`column_of`] each): a row with a null
/// in any column has no value there, so it is left out (an unsigned value has no null, as a
/// node with no row has no value).
pub(crate) fn columns_of(columns: &[ArrayRef]) -> Result<Vec<Column>> {
    without_nulls(columns)?.iter().map(column_of).collect()
}

/// `columns` (of one length) with every row that holds a null in any of them left out: the
/// same arrays when none has a null.
pub(crate) fn without_nulls(columns: &[ArrayRef]) -> Result<Vec<ArrayRef>> {
    if columns.iter().all(|c| c.null_count() == 0) {
        return Ok(columns.to_vec());
    }
    let n = columns[0].len();
    if columns.iter().any(|c| c.len() != n) {
        return Err(PlanError::Input("columns of different lengths".into()));
    }
    let keep: arrow_array::BooleanArray = (0..n)
        .map(|r| Some(columns.iter().all(|c| c.is_valid(r))))
        .collect();
    columns
        .iter()
        .map(|c| Ok(datafusion::arrow::compute::filter(c.as_ref(), &keep)?))
        .collect()
}

/// An integer column as a [`Column`]: `UInt32` and `UInt64` share the array's buffer (no
/// copy), and so do `Int32` and `Int64` when no value is negative (the same bits read
/// unsigned); `UInt8` and `UInt16` become `u32`; a negative value is refused.
pub(crate) fn column_of(a: &ArrayRef) -> Result<Column> {
    if a.null_count() > 0 {
        return Err(PlanError::Input("a column with nulls".into()));
    }
    let negative = |v: i64| PlanError::Input(format!("value {v} is negative; values are unsigned"));
    match a.data_type() {
        DataType::UInt32 => Ok(Column::U32(
            a.as_primitive::<types::UInt32Type>().values().clone(),
        )),
        DataType::UInt64 => Ok(Column::U64(
            a.as_primitive::<types::UInt64Type>().values().clone(),
        )),
        DataType::Int32 => {
            let v = a.as_primitive::<types::Int32Type>().values();
            if let Some(&x) = v.iter().find(|&&x| x < 0) {
                return Err(negative(x as i64));
            }
            Ok(Column::U32(ScalarBuffer::from(v.inner().clone())))
        }
        DataType::Int64 => {
            let v = a.as_primitive::<types::Int64Type>().values();
            if let Some(&x) = v.iter().find(|&&x| x < 0) {
                return Err(negative(x));
            }
            Ok(Column::U64(ScalarBuffer::from(v.inner().clone())))
        }
        _ => {
            let mut c = ColumnBuilder::with_capacity(a.len());
            extend_column(&mut c, a)?;
            Ok(c.finish())
        }
    }
}

/// Append an integer column: unsigned up to 32 bits stays `u32`, `UInt64` is kept as
/// 64-bit values, signed columns are taken when no value is negative.
pub(crate) fn extend_column(out: &mut ColumnBuilder, a: &ArrayRef) -> Result<()> {
    if a.null_count() > 0 {
        return Err(PlanError::Input("a column with nulls".into()));
    }
    let negative = |v: i64| PlanError::Input(format!("value {v} is negative; values are unsigned"));
    match a.data_type() {
        DataType::UInt32 => {
            let vals = a.as_primitive::<types::UInt32Type>().values();
            match out {
                ColumnBuilder::U32(v) => v.extend_from_slice(vals),
                ColumnBuilder::U64(v) => v.extend(vals.iter().map(|&x| x as u64)),
            }
        }
        DataType::UInt8 => {
            for &x in a.as_primitive::<types::UInt8Type>().values() {
                out.push(x as Value);
            }
        }
        DataType::UInt16 => {
            for &x in a.as_primitive::<types::UInt16Type>().values() {
                out.push(x as Value);
            }
        }
        DataType::UInt64 => {
            let vals = a.as_primitive::<types::UInt64Type>().values();
            match out {
                ColumnBuilder::U64(v) => v.extend_from_slice(vals),
                ColumnBuilder::U32(v) if v.is_empty() => *out = ColumnBuilder::U64(vals.to_vec()),
                _ => {
                    for &x in vals.iter() {
                        out.push(x);
                    }
                }
            }
        }
        DataType::Int32 => {
            for &x in a.as_primitive::<types::Int32Type>().values() {
                out.push(u64::try_from(x).map_err(|_| negative(x as i64))?);
            }
        }
        DataType::Int64 => {
            for &x in a.as_primitive::<types::Int64Type>().values() {
                out.push(u64::try_from(x).map_err(|_| negative(x))?);
            }
        }
        other => {
            return Err(PlanError::Input(format!(
                "a column of {other}; values are unsigned integers"
            )));
        }
    }
    Ok(())
}

/// Where an input relation's facts come from.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Source {
    /// Facts in hand.
    Facts(Facts),
    /// Arrow columns in hand (an X.gar table's mapped columns), in the relation's column
    /// order: read with no query planned. A row with a null in a `u64` column is left out
    /// (an unsigned value has no null; a column of another type keeps its null).
    Columns(Vec<ArrayRef>),
    /// [`Source::Columns`] in an id space: column `i`'s values are the array's plus
    /// `bases[i]` (0 for a column that is no node), added only when a run reads the
    /// relation (an X.gar edge property's end columns, its rows shared from the files, in
    /// the set's one id space: kleene-gar's `IdSpace`). A column of base 0 is read in place.
    ColumnsAt {
        /// The columns.
        columns: Vec<ArrayRef>,
        /// Per column, the number added to each value.
        bases: Vec<Value>,
    },
    /// Columns of a DataFusion table, in the relation's column order.
    Table {
        /// The table.
        table: Arc<dyn TableProvider>,
        /// Its columns, one per relation column.
        columns: Vec<String>,
    },
    /// Rows answered by Rust code when a rule runs ([`External`]).
    External(Arc<dyn External>),
    /// A two-column relation as a graph: row `x` of `out` lists every `y` with `rel(x, y)`
    /// (and `inn` is its transpose, if stored). Shared, not copied: an X.gar edge type
    /// hands both orders straight from its files.
    Graph {
        /// By the first column.
        out: Csr<u8>,
        /// By the second column.
        inn: Option<Csr<u8>>,
    },
    /// [`Source::Graph`] in an id space: row `x` of `out` is id `bases.0 + x` and column
    /// `y` id `bases.1 + y` (an X.gar edge type's rows in its set's one id space, its two
    /// vertex types numbered one after the other: kleene-gar's `IdSpace`). Shared, not
    /// copied: a walk over a graph of one vertex type (equal bases) numbers its vertices
    /// from the base; another lists its pairs as ids.
    GraphAt {
        /// By the first column.
        out: Csr<u8>,
        /// By the second column.
        inn: Option<Csr<u8>>,
        /// The ids of row 0 and of column 0.
        bases: (Value, Value),
    },
}

/// The inputs of a run: a source per input relation.
#[derive(Clone, Debug, Default)]
pub struct Inputs {
    map: HashMap<RelId, Source>,
    /// The indexes of input relations, for the index choice.
    indexes: crate::index::Indexes,
}

impl Inputs {
    /// No inputs yet.
    pub fn new() -> Self {
        Inputs::default()
    }

    /// Give `rel` its facts (their width is checked when a run starts).
    pub fn facts(&mut self, rel: RelId, facts: Facts) -> &mut Self {
        self.map.insert(rel, Source::Facts(facts));
        self
    }

    /// Give `rel`, a relation of no column, its one fact when `holds`, else none
    /// ([`Facts::flag`]).
    pub fn flag(&mut self, rel: RelId, holds: bool) -> &mut Self {
        self.facts(rel, Facts::flag(holds))
    }

    /// Read `rel` from Arrow columns in hand (any integer type up to 64 bits, kept whole),
    /// one per relation column.
    pub fn columns(&mut self, rel: RelId, columns: Vec<ArrayRef>) -> &mut Self {
        self.map.insert(rel, Source::Columns(columns));
        self
    }

    /// Read `rel` from `columns` of a DataFusion table, one per relation column.
    pub fn table(
        &mut self,
        rel: RelId,
        table: Arc<dyn TableProvider>,
        columns: Vec<String>,
    ) -> &mut Self {
        self.map.insert(rel, Source::Table { table, columns });
        self
    }

    /// Give a two-column `rel` as a graph (and its transpose, if stored).
    pub fn graph(&mut self, rel: RelId, out: Csr<u8>, inn: Option<Csr<u8>>) -> &mut Self {
        self.map.insert(rel, Source::Graph { out, inn });
        self
    }

    /// Give a two-column `rel` as a graph in an id space ([`Source::GraphAt`]).
    pub fn graph_at(
        &mut self,
        rel: RelId,
        out: Csr<u8>,
        inn: Option<Csr<u8>>,
        bases: (Value, Value),
    ) -> &mut Self {
        self.map.insert(rel, Source::GraphAt { out, inn, bases });
        self
    }

    /// Let `ext` answer `rel` (an external relation, or an input listed whole).
    pub fn external(&mut self, rel: RelId, ext: Arc<dyn External>) -> &mut Self {
        self.map.insert(rel, Source::External(ext));
        self
    }

    /// Give `rel` any source.
    pub fn set(&mut self, rel: RelId, source: Source) -> &mut Self {
        self.map.insert(rel, source);
        self
    }

    /// The source of a relation.
    pub fn source(&self, rel: RelId) -> Option<&Source> {
        self.map.get(&rel)
    }

    /// Input `rel` (columns of `types`) given by typed rows, such as the rows another run
    /// returned (a stage feeding the next: GQL's `WITH`): one Arrow column per type, a null
    /// where the type has one. With `counted`, `rel` is a counted relation and each distinct
    /// row comes once with the number of times it is given (its count column last).
    /// Refused: a value of another type, a null in a `u64` column, a signed value below 0
    /// for a `u64` column (an `u64` value for an `i64` column is taken while it fits).
    pub fn datums(
        &mut self,
        rel: RelId,
        types: &[crate::Type],
        rows: &[Vec<crate::Datum>],
        counted: bool,
    ) -> crate::Result<&mut Self> {
        use crate::Datum;
        // the distinct rows with their counts (floats told apart by their bits)
        let key = |r: &[Datum]| format!("{r:?}");
        let (rows, counts): (Vec<&Vec<Datum>>, Vec<u64>) = if counted {
            let mut keyed: Vec<(String, &Vec<Datum>)> = rows.iter().map(|r| (key(r), r)).collect();
            keyed.sort_by(|a, b| a.0.cmp(&b.0));
            let mut out: Vec<(String, &Vec<Datum>, u64)> = Vec::new();
            for (k, r) in keyed {
                match out.last_mut() {
                    Some(last) if last.0 == k => last.2 += 1,
                    _ => out.push((k, r, 1)),
                }
            }
            out.into_iter().map(|x| (x.1, x.2)).unzip()
        } else {
            (rows.iter().collect(), Vec::new())
        };
        let mut columns: Vec<ArrayRef> = Vec::with_capacity(types.len() + 1);
        for (c, &ty) in types.iter().enumerate() {
            let bad = |d: &Datum| {
                crate::PlanError::Input(format!("column {c}: {d} where a {} belongs", ty.name()))
            };
            let cells = rows.iter().map(|r| &r[c]);
            let array: ArrayRef = match ty {
                crate::Type::U64 => Arc::new(UInt64Array::from(
                    cells
                        .map(|d| match d {
                            Datum::U64(x) => Ok(*x),
                            Datum::I64(x) => u64::try_from(*x).map_err(|_| bad(d)),
                            d => Err(bad(d)),
                        })
                        .collect::<crate::Result<Vec<u64>>>()?,
                )),
                crate::Type::I64 => Arc::new(arrow_array::Int64Array::from(
                    cells
                        .map(|d| match d {
                            Datum::I64(x) => Ok(Some(*x)),
                            Datum::U64(x) => i64::try_from(*x).map(Some).map_err(|_| bad(d)),
                            Datum::Null => Ok(None),
                            d => Err(bad(d)),
                        })
                        .collect::<crate::Result<Vec<_>>>()?,
                )),
                crate::Type::F64 => Arc::new(arrow_array::Float64Array::from(
                    cells
                        .map(|d| match d {
                            Datum::F64(x) => Ok(Some(*x)),
                            Datum::Null => Ok(None),
                            d => Err(bad(d)),
                        })
                        .collect::<crate::Result<Vec<_>>>()?,
                )),
                crate::Type::Bool => Arc::new(arrow_array::BooleanArray::from(
                    cells
                        .map(|d| match d {
                            Datum::Bool(x) => Ok(Some(*x)),
                            Datum::Null => Ok(None),
                            d => Err(bad(d)),
                        })
                        .collect::<crate::Result<Vec<_>>>()?,
                )),
                crate::Type::Str => Arc::new(arrow_array::StringArray::from(
                    cells
                        .map(|d| match d {
                            Datum::Str(x) => Ok(Some(x.as_str())),
                            Datum::Null => Ok(None),
                            d => Err(bad(d)),
                        })
                        .collect::<crate::Result<Vec<_>>>()?,
                )),
            };
            columns.push(array);
        }
        if counted {
            columns.push(Arc::new(UInt64Array::from(counts)));
        }
        Ok(self.set(rel, Source::Columns(columns)))
    }

    /// Give input relation `rel` an index: the engine's index choice
    /// ([`crate::Engine::index_choice`]) finds a rule's ids by it where the rule's
    /// comparisons with constants allow ([`crate::Lookup::choose`]).
    pub fn index(&mut self, rel: RelId, index: crate::Index) -> &mut Self {
        self.indexes.insert(rel, index);
        self
    }

    /// The index of a relation.
    pub fn index_of(&self, rel: RelId) -> Option<&crate::Index> {
        self.indexes.get(&rel)
    }
}