crates/kleene-gar/src/catalog.rs
//! A set's schema as kleene-plan's [`Catalog`], read where the set is opened.
//!
//! | Name | Here |
//! |---|---|
//! | Node label `T` | vertex type `T`: its ids in the set's id space ([`GarGraph::id_space`]: `base..base + count`), an id block ([`Catalog::id_block`]) |
//! | Edge label `src_edge_dst` | that edge type, shared from its files in both orders, read in the id space by its ends' bases (kleene-plan's [`Source::GraphAt`]: a walk over it copies nothing) |
//! | Edge label `edge` | the same, when one edge type alone has that edge name ([`Catalog::edge_alias`] of the table name) |
//! | Property `T.c` | unsigned integer column `c` of vertex type `T`: id to value (a row whose value is null left out) |
//! | Property `T.c`, signed or float | a signed integer (`Int8`..`Int64`) or float (`Float32`, `Float64`) column, read by its type; a null slot is null |
//! | Property `T.c`, a boolean | a `Boolean` column; a null slot is null |
//! | Property `T.c`, a string | a string column (a set's `Binary` string table read as UTF-8 over the same buffers), or a dictionary-encoded one (`Dictionary` of strings or bytes) read through its keys |
//! | Property `T.c`, bytes | a `Binary`, `LargeBinary` or `BinaryView` column with values that are not UTF-8: its text, such a value null; a `FixedSizeBinary` column: its hex; `T.c@hex` every value's hex (kleene-plan's [`Catalog::relation`]) |
//! | Edge property `E.p` | unsigned integer property `p` of edge type `E` (both its names): (source, destination, value), listed from the mapped files when a run reads it; with nulls, as the typed ones below, an edge whose value is null left out |
//! | Edge counts of `E` | an edge type with some pair of nodes joined by two edges or more: (source, destination, number of edges) of every pair ([`Catalog::edge_counts`]), so each edge is a match of its own: whether a pair repeats found when the catalog is made, the counts made when a run first reads them and kept; none for a type whose pairs have one edge each |
//! | Edge rows `E@row` | that edge type by its rows: (row, source, destination), one row per edge (two edges between the same ends two rows), the row the edge's place in by-source order ([`Catalog::edge_rows`]), listed from the mapped files when a run reads it |
//! | Edge property by row `E@row.p` | property `p` of edge type `E`: (row, value), the row of `E@row`, the value read by its type as `E.p`'s ([`Catalog::edge_row_property`]) |
//! | Edge property `E.p`, signed, float, boolean or string | read by its Arrow type as vertex columns are (a null slot null): (source, destination, value) columns, the ends listed once per edge type in by-source order, the destinations' base added only when a run reads them ([`Source::ColumnsAt`]) |
//! | Property `T.c`, a list | a `List`, `LargeList` or `FixedSizeList` column of a type above: (id, position, value) rows ([`Catalog::list_property`], [`list_rows`]), the position from 0; an empty or null list no row, a null element null (unsigned: its row left out, the others keeping their positions) |
//! | Edge property `E.p`, a list | the same per edge: (source, destination, position, value) rows ([`Catalog::list_edge_property`]); by row, `E@row.p`: (row, position, value) ([`Catalog::list_edge_row_property`]) |
//! | Property `T.c` or edge property `E.p`, a date or timestamp | `I64`: a date (`Date32`, `Date64`) its days since 1970-01-01, a timestamp (any unit and time zone) its nanoseconds since 1970-01-01T00:00Z (kleene-plan's [`time_value`]) |
//!
//! A column of any other type (a decimal, a time of day), on a vertex or an edge, is a
//! property refused by name and type ([`Catalog::refused_property`]) when a query reads it.
//! The catalog holds no index: kleene-index's `indexed` builds them over it.
use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};
use arrow_array::cast::AsArray;
use arrow_array::types::{
Date32Type, Date64Type, Float32Type, Float64Type, Int8Type, Int16Type, Int32Type, Int64Type,
TimestampMicrosecondType, TimestampMillisecondType, TimestampNanosecondType,
TimestampSecondType, UInt8Type, UInt16Type, UInt32Type, UInt64Type,
};
use arrow_array::{Array, ArrayRef, UInt32Array, UInt64Array};
use arrow_buffer::ScalarBuffer;
use arrow_schema::{DataType, TimeUnit};
use datafusion::error::{DataFusionError, Result};
use kleene_plan::{Catalog, Datum, External, Producer, Source, Type, time_value};
use kleene_sparse::{Csr, Pattern};
use crate::graph::{EdgeAdjacency, GarGraph};
fn plan_err(e: impl std::fmt::Display) -> DataFusionError {
DataFusionError::Execution(e.to_string())
}
impl GarGraph {
/// The set's schema as a [`Catalog`]: its vertex types as node labels (each an id block
/// of the set's one id space), its edge types as edge labels (by table name, and by
/// bare edge name when one type alone has it), its vertex columns as node properties,
/// its edge properties as edge properties, each by its Arrow type; columns of types no
/// reader takes refused by name. Every node is its id in [`GarGraph::id_space`].
pub fn catalog(&self) -> Result<Catalog> {
let mut c = Catalog::new();
let space = self.id_space()?;
for v in self.vertex_types() {
let ids = self.vertex_ids(v)?;
c.label(v, Source::Columns(vec![ids.clone()]));
let (base, count) = space.of(v).expect("a type of the set");
c.id_block(v, base, count);
for col in self.vertex_columns(v)? {
let values = self.vertex_column(v, &col)?;
if list_property(&mut c, v, &col, base, &values) {
continue;
}
match column_type(&values, "column") {
Ok((Type::U64, values)) => {
c.property(v, &col, Source::Columns(vec![ids.clone(), values]));
}
Ok((ty, values)) => {
c.typed_property(v, &col, Source::Columns(vec![ids.clone(), values]), ty);
}
Err(why) => {
c.refused_property(v, &col, &why);
}
}
}
}
let mut by_edge: BTreeMap<String, usize> = BTreeMap::new();
for (_, t) in self.edge_types() {
*by_edge.entry(t.edge.clone()).or_default() += 1;
}
let types: Vec<_> = self
.edge_types()
.map(|(n, t)| (n.to_string(), t.clone()))
.collect();
for (name, t) in types {
let adj = self.adjacency(&t)?;
let missing = |what: &str| DataFusionError::Plan(format!("no {what} of `{name}`"));
let sb = space.base(&t.src).ok_or_else(|| missing("source type"))?;
let db = space
.base(&t.dst)
.ok_or_else(|| missing("destination type"))?;
let out = Csr::<u8>::with_pattern(
Pattern::trusted(
adj.sources,
adj.destinations,
adj.out_offsets.clone(),
adj.out_neighbours.clone(),
"by source",
)
.map_err(plan_err)?,
None,
)
.map_err(plan_err)?;
let inn = Csr::<u8>::with_pattern(
Pattern::trusted(
adj.destinations,
adj.sources,
adj.in_offsets.clone(),
adj.in_neighbours.clone(),
"by destination",
)
.map_err(plan_err)?,
None,
)
.map_err(plan_err)?;
let source = Source::GraphAt {
out,
inn: Some(inn),
bases: (sb, db),
};
let unique = by_edge.get(&t.edge) == Some(&1) && t.edge != name;
if unique {
c.edge(&t.edge, source.clone());
c.edge_alias(&t.edge, &name);
}
c.edge(&name, source);
let row_names: Vec<&str> = if unique {
vec![t.edge.as_str(), name.as_str()]
} else {
vec![name.as_str()]
};
edge_rows(&mut c, &row_names, &adj, (sb, db));
if let Some(counts) = parallel_counts(&adj, (sb, db)) {
for n in &row_names {
c.edge_counts(n, counts.clone());
}
}
let mut row_column: Option<ArrayRef> = None;
// (source, destination) of each edge in by-source order, made at the first typed
// property of the type
let mut ends: Option<(ArrayRef, ArrayRef)> = None;
for p in self.edge_properties(&t)? {
let refuse = |c: &mut Catalog, why: &str| {
if unique {
c.refused_edge_property(&t.edge, &p, why);
}
c.refused_edge_property(&name, &p, why);
};
let values = match self.edge_property(&t, &p) {
Ok(v) => v,
Err(e) => {
refuse(&mut c, &format!("not read ({e})"));
continue;
}
};
if list_edge_property(&mut c, &row_names, &p, &adj, (sb, db), &values) {
continue;
}
let (ty, values) = match column_type(&values, "edge property") {
// (with nulls: as the typed ones below, kleene-plan leaving a row with a
// null out)
Ok((Type::U64, values)) if values.null_count() == 0 => {
unsigned_row_property(&mut c, &row_names, &p, &values);
// listed from the mapped files when a run reads it
let (offsets, dst) = (adj.out_offsets.clone(), adj.out_neighbours.clone());
let rows = move |out: &mut dyn FnMut(&[u64])| -> kleene_plan::Result<()> {
for v in 0..offsets.len().saturating_sub(1) {
for k in offsets[v] as usize..offsets[v + 1] as usize {
out(&[
sb + v as u64,
db + dst[k] as u64,
unsigned_value(&values, k),
]);
}
}
Ok(())
};
let ext: Arc<dyn External> = Arc::new(Producer::new(3, rows));
if unique {
c.edge_property(&t.edge, &p, Source::External(ext.clone()));
}
c.edge_property(&name, &p, Source::External(ext));
continue;
}
Ok(typed) => typed,
Err(why) => {
refuse(&mut c, &why);
continue;
}
};
typed_row_property(&mut c, &row_names, &p, &mut row_column, &values, ty);
let (src, dst) = ends
.get_or_insert_with(|| {
let offsets = &adj.out_offsets;
let src: Vec<u64> = (0..offsets.len().saturating_sub(1))
.flat_map(|v| {
std::iter::repeat_n(
sb + v as u64,
(offsets[v + 1] - offsets[v]) as usize,
)
})
.collect();
let src: ArrayRef = Arc::new(UInt64Array::from(src));
// (the destinations shared from the files, their base added only
// when a run reads the property)
let dst: ArrayRef =
Arc::new(UInt32Array::new(adj.out_neighbours.clone(), None));
(src, dst)
})
.clone();
let source = Source::ColumnsAt {
columns: vec![src, dst, values],
bases: vec![0, db, 0],
};
if unique {
c.typed_edge_property(&t.edge, &p, source.clone(), ty);
}
c.typed_edge_property(&name, &p, source, ty);
}
}
Ok(c)
}
}
/// Edge type `names` by its rows ([`Catalog::edge_rows`]): (row, source, destination), the
/// row the edge's place in by-source order, the ends in the id space (`bases`), listed from
/// the offsets when a run reads it.
fn edge_rows(c: &mut Catalog, names: &[&str], adj: &EdgeAdjacency, (sb, db): (u64, u64)) {
let (offsets, dst) = (adj.out_offsets.clone(), adj.out_neighbours.clone());
let rows = move |out: &mut dyn FnMut(&[u64])| -> kleene_plan::Result<()> {
for v in 0..offsets.len().saturating_sub(1) {
for k in offsets[v] as usize..offsets[v + 1] as usize {
out(&[k as u64, sb + v as u64, db + dst[k] as u64]);
}
}
Ok(())
};
let ext: Arc<dyn External> = Arc::new(Producer::new(3, rows));
for n in names {
c.edge_rows(n, Source::External(ext.clone()));
}
}
/// The edge counts of an edge type with some pair of nodes joined by two edges or more
/// ([`Catalog::edge_counts`]): (source, destination, number of edges) for every pair, in the
/// id space (`bases`); `None` when each pair has one edge (the catalog then has no counts
/// and a query's plan reads none). Whether a pair repeats is found when the catalog is
/// made, by a pass over the by-source neighbours that stops at the first repeat; the counts
/// themselves are made the first time a run reads them, and kept ([`PairCounts`]).
fn parallel_counts(adj: &EdgeAdjacency, bases: (u64, u64)) -> Option<Source> {
let (offsets, dst) = (adj.out_offsets.clone(), adj.out_neighbours.clone());
let rows = offsets.len().saturating_sub(1);
let mut scratch: Vec<u32> = Vec::new();
let repeated = (0..rows).any(|v| {
let r = &dst[offsets[v] as usize..offsets[v + 1] as usize];
!r.windows(2).all(|w| w[0] < w[1])
&& in_order(r, &mut scratch).windows(2).any(|w| w[0] == w[1])
});
if !repeated {
return None;
}
let counts = Arc::new(PairCounts {
offsets,
dst,
bases,
made: OnceLock::new(),
});
let rows = move |out: &mut dyn FnMut(&[u64])| -> kleene_plan::Result<()> {
let (sb, db) = counts.bases;
for &(v, d, n) in counts.pairs() {
out(&[sb + v as u64, db + d as u64, n as u64]);
}
Ok(())
};
let ext: Arc<dyn External> = Arc::new(Producer::new(3, rows));
Some(Source::External(ext))
}
/// The pairs of an edge type with their numbers of edges, made from its by-source
/// neighbours the first time they are read and kept: (source row, destination column,
/// number of edges), 12 bytes a pair.
struct PairCounts {
offsets: ScalarBuffer<u64>,
dst: ScalarBuffer<u32>,
bases: (u64, u64),
made: OnceLock<Vec<(u32, u32, u32)>>,
}
impl PairCounts {
fn pairs(&self) -> &[(u32, u32, u32)] {
self.made.get_or_init(|| {
let mut scratch: Vec<u32> = Vec::new();
let mut pairs = Vec::new();
for v in 0..self.offsets.len().saturating_sub(1) {
let r = &self.dst[self.offsets[v] as usize..self.offsets[v + 1] as usize];
for run in in_order(r, &mut scratch).chunk_by(|a, b| a == b) {
pairs.push((v as u32, run[0], run.len() as u32));
}
}
pairs
})
}
}
/// `r` in order: itself when it is, else sorted in `scratch`.
fn in_order<'a>(r: &'a [u32], scratch: &'a mut Vec<u32>) -> &'a [u32] {
if r.is_sorted() {
return r;
}
scratch.clear();
scratch.extend_from_slice(r);
scratch.sort_unstable();
scratch
}
/// Unsigned property `key` of edge type `names` by row ([`Catalog::edge_row_property`]):
/// (row, value), listed from the mapped column when a run reads it.
fn unsigned_row_property(c: &mut Catalog, names: &[&str], key: &str, values: &ArrayRef) {
let values = values.clone();
let rows = move |out: &mut dyn FnMut(&[u64])| -> kleene_plan::Result<()> {
for k in 0..values.len() {
out(&[k as u64, unsigned_value(&values, k)]);
}
Ok(())
};
let ext: Arc<dyn External> = Arc::new(Producer::new(2, rows));
for n in names {
c.edge_row_property(n, key, Source::External(ext.clone()), Type::U64);
}
}
/// Property `key` of type `ty` of edge type `names` by row ([`Catalog::edge_row_property`]):
/// (row, value) columns, the row column `0..edges` made once per edge type (`rows`).
fn typed_row_property(
c: &mut Catalog,
names: &[&str],
key: &str,
rows: &mut Option<ArrayRef>,
values: &ArrayRef,
ty: Type,
) {
let row = rows
.get_or_insert_with(|| Arc::new(UInt64Array::from_iter_values(0..values.len() as u64)))
.clone();
let source = Source::Columns(vec![row, values.clone()]);
for n in names {
c.edge_row_property(n, key, source.clone(), ty);
}
}
/// Vertex column `col` of type `v` (ids from `base`) as a list property of the catalog when
/// it is a list column ([`list_rows`]): (id, position, value) rows, the ids added only when a
/// run reads them; refused by name when its elements are not read. False for a column that
/// is no list.
fn list_property(c: &mut Catalog, v: &str, col: &str, base: u64, values: &ArrayRef) -> bool {
match list_rows(values, "column") {
None => false,
Some(Ok(l)) => {
let source = Source::ColumnsAt {
columns: vec![u64s(l.rows), u64s(l.positions), l.values],
bases: vec![base, 0, 0],
};
c.list_property(v, col, source, l.ty);
true
}
Some(Err(why)) => {
c.refused_property(v, col, &why);
true
}
}
}
/// Edge property `p` of an edge type (`names`: its table name and, when it alone has its
/// edge name, that name) as a list property of the catalog when it is a list column:
/// (source, destination, position, value) rows ([`Catalog::list_edge_property`]) and (row,
/// position, value) rows ([`Catalog::list_edge_row_property`], the row of `E@row`), each
/// element's edge in by-source order, the ends' bases added only when a run reads them;
/// refused by name when its elements are not read. False for a property that is no list.
fn list_edge_property(
c: &mut Catalog,
names: &[&str],
p: &str,
adj: &EdgeAdjacency,
(sb, db): (u64, u64),
values: &ArrayRef,
) -> bool {
let l = match list_rows(values, "edge property") {
None => return false,
Some(Ok(l)) => l,
Some(Err(why)) => {
for n in names {
c.refused_edge_property(n, p, &why);
}
return true;
}
};
// the source row of each edge, by-source order
let offsets = &adj.out_offsets;
let mut src_of: Vec<u64> = Vec::with_capacity(adj.out_neighbours.len());
for v in 0..offsets.len().saturating_sub(1) {
let n = (offsets[v + 1] - offsets[v]) as usize;
src_of.extend(std::iter::repeat_n(v as u64, n));
}
let src: Vec<u64> = l.rows.iter().map(|&e| src_of[e as usize]).collect();
let dst: Vec<u64> = l
.rows
.iter()
.map(|&e| adj.out_neighbours[e as usize] as u64)
.collect();
let (rows, positions) = (u64s(l.rows), u64s(l.positions));
let pairs = Source::ColumnsAt {
columns: vec![u64s(src), u64s(dst), positions.clone(), l.values.clone()],
bases: vec![sb, db, 0, 0],
};
let by_row = Source::Columns(vec![rows, positions, l.values]);
for n in names {
c.list_edge_property(n, p, pairs.clone(), l.ty);
c.list_edge_row_property(n, p, by_row.clone(), l.ty);
}
true
}
fn u64s(v: Vec<u64>) -> ArrayRef {
Arc::new(UInt64Array::from(v))
}
/// The elements of a list column as rows: element `i` is at position `positions[i]` (from
/// 0) of the list of row `rows[i]`, its value `values[i]`, read as [`column_type`] reads a
/// plain column of the element type (`ty`; a null element null).
#[derive(Clone, Debug)]
pub struct ListRows {
/// The row of each element's list.
pub rows: Vec<u64>,
/// Each element's position in its list, from 0.
pub positions: Vec<u64>,
/// The elements, one per row.
pub values: ArrayRef,
/// The elements' type.
pub ty: Type,
}
/// A `List`, `LargeList` or `FixedSizeList` column as [`ListRows`], in row order, each
/// list's elements in order; an empty or null list gives no row. `None` for a column of
/// another type. Refused, with why (`what` naming it, "column" or "edge property"): a list
/// of a type [`column_type`] does not read (a list of lists, a decimal). An unsigned element
/// that is null is a row with a null value, which kleene-plan leaves out (an unsigned value
/// has none), the other elements keeping their positions. Shared with every reader that
/// fills a [`Catalog`].
pub fn list_rows(list: &ArrayRef, what: &str) -> Option<std::result::Result<ListRows, String>> {
// (child, the (start, end) of each row's elements in it)
let (child, ranges): (ArrayRef, Vec<(usize, usize)>) = match list.data_type() {
DataType::List(_) => {
let l = list.as_list::<i32>();
let o = l.value_offsets();
let r = (0..l.len()).map(|i| (o[i] as usize, o[i + 1] as usize));
(l.values().clone(), r.collect())
}
DataType::LargeList(_) => {
let l = list.as_list::<i64>();
let o = l.value_offsets();
let r = (0..l.len()).map(|i| (o[i] as usize, o[i + 1] as usize));
(l.values().clone(), r.collect())
}
DataType::FixedSizeList(_, _) => {
let l = list.as_fixed_size_list();
let n = l.value_length() as usize;
let r = (0..l.len()).map(|i| {
let at = l.value_offset_at(i);
(at, at + n)
});
(l.values().clone(), r.collect())
}
_ => return None,
};
let (mut rows, mut positions, mut taken) = (Vec::new(), Vec::new(), Vec::new());
for (r, &(a, b)) in ranges.iter().enumerate() {
if list.is_null(r) {
continue;
}
for (k, at) in (a..b).enumerate() {
rows.push(r as u64);
positions.push(k as u64);
taken.push(at as u64);
}
}
// the child as it is when the elements are all of it, in order; else the elements taken
let whole = taken.len() == child.len() && taken.iter().enumerate().all(|(i, &t)| t == i as u64);
let values = if whole {
child
} else {
match datafusion::arrow::compute::take(&child, &UInt64Array::from(taken), None) {
Ok(v) => v,
Err(e) => {
return Some(Err(format!(
"an Arrow {} {what}, not read ({e})",
list.data_type()
)));
}
}
};
let element = format!("list {what}'s element");
Some(match values.data_type() {
d if d.is_nested() => Err(format!(
"an Arrow {} {what}, a list of {d}, not read",
list.data_type()
)),
_ => column_type(&values, &element).map(|(ty, values)| ListRows {
rows,
positions,
values,
ty,
}),
})
}
/// The order-keeping code ([`Type::encode`]) of value `k` of a signed integer, float, date
/// or timestamp column (a date as days, a timestamp as nanoseconds: kleene-plan's
/// [`time_value`]); `None` for a null (or `i64::MAX`, which is the null code, or a value
/// `time_value` refuses) or a column of another type.
pub fn value_code(values: &ArrayRef, k: usize) -> Option<u64> {
if values.is_null(k) {
return None;
}
let d = match values.data_type() {
DataType::Int8 => Datum::I64(values.as_primitive::<Int8Type>().value(k) as i64),
DataType::Int16 => Datum::I64(values.as_primitive::<Int16Type>().value(k) as i64),
DataType::Int32 => Datum::I64(values.as_primitive::<Int32Type>().value(k) as i64),
DataType::Int64 => Datum::I64(values.as_primitive::<Int64Type>().value(k)),
d @ DataType::Date32 => {
let raw = values.as_primitive::<Date32Type>().value(k) as i64;
Datum::I64(time_value(d, raw).ok()?)
}
d @ DataType::Date64 => {
let raw = values.as_primitive::<Date64Type>().value(k);
Datum::I64(time_value(d, raw).ok()?)
}
d @ DataType::Timestamp(unit, _) => {
let raw = match unit {
TimeUnit::Second => values.as_primitive::<TimestampSecondType>().value(k),
TimeUnit::Millisecond => values.as_primitive::<TimestampMillisecondType>().value(k),
TimeUnit::Microsecond => values.as_primitive::<TimestampMicrosecondType>().value(k),
TimeUnit::Nanosecond => values.as_primitive::<TimestampNanosecondType>().value(k),
};
Datum::I64(time_value(d, raw).ok()?)
}
DataType::Float32 => Datum::F64(values.as_primitive::<Float32Type>().value(k) as f64),
DataType::Float64 => Datum::F64(values.as_primitive::<Float64Type>().value(k)),
_ => return None,
};
let ty = if matches!(d, Datum::I64(_)) {
Type::I64
} else {
Type::F64
};
ty.encode(&d, None)
}
/// Value `k` of an unsigned integer column (0 for a column of another type).
pub fn unsigned_value(values: &ArrayRef, k: usize) -> u64 {
match values.data_type() {
DataType::UInt8 => values.as_primitive::<UInt8Type>().value(k) as u64,
DataType::UInt16 => values.as_primitive::<UInt16Type>().value(k) as u64,
DataType::UInt32 => values.as_primitive::<UInt32Type>().value(k) as u64,
DataType::UInt64 => values.as_primitive::<UInt64Type>().value(k),
_ => 0,
}
}
/// The [`Type`] a property column is read as, and the column as it is read (a set's
/// `Binary` string table as `Utf8`): an unsigned integer column `U64` (a row whose value is
/// null has none: kleene-plan leaves it out), a signed integer column `I64`, a float column
/// `F64`, a date or timestamp column `I64` (days; nanoseconds), a boolean column `Bool`, a UTF-8 column `Str` (dictionary-encoded too), a bytes
/// column `Str` (`Binary`, `LargeBinary`, `BinaryView` read as text, a value that is not
/// UTF-8 null; `FixedSizeBinary` read as hex: kleene-plan's `Catalog::relation`); any other
/// column (a
/// decimal, a time of day) refused with why, `what` naming it in the why ("column", "edge
/// property"). The one typing of a property column, for every reader that fills a
/// [`Catalog`] (kleene-iceberg's too).
pub fn column_type(values: &ArrayRef, what: &str) -> std::result::Result<(Type, ArrayRef), String> {
match values.data_type() {
d if d.is_unsigned_integer() => Ok((Type::U64, values.clone())),
d if d.is_signed_integer() => Ok((Type::I64, values.clone())),
// dates as days, timestamps as nanoseconds (kleene-plan's `time_value`)
DataType::Date32 | DataType::Date64 | DataType::Timestamp(..) => {
Ok((Type::I64, values.clone()))
}
DataType::Float32 | DataType::Float64 => Ok((Type::F64, values.clone())),
DataType::Boolean => Ok((Type::Bool, values.clone())),
// a dictionary of strings or bytes: read through its keys as its values are
DataType::Dictionary(_, v)
if matches!(
**v,
DataType::Utf8
| DataType::LargeUtf8
| DataType::Utf8View
| DataType::Binary
| DataType::LargeBinary
| DataType::BinaryView
| DataType::FixedSizeBinary(_)
) =>
{
Ok((Type::Str, values.clone()))
}
d => match as_strings(values) {
Some(strings) => Ok((Type::Str, strings)),
// bytes: their text (a value that is not UTF-8 none) or, fixed size, their hex,
// as kleene-plan reads a str column of them; `@hex` by name for every row's hex
None if matches!(
d,
DataType::Binary
| DataType::LargeBinary
| DataType::BinaryView
| DataType::FixedSizeBinary(_)
) =>
{
Ok((Type::Str, values.clone()))
}
None => Err(format!("an Arrow {d} {what}, not read")),
},
}
}
/// A string column as Arrow strings: `Utf8` as it is, a set's `Binary` string table as
/// `Utf8` over the same buffers (checked once to be UTF-8); `None` for any other column or
/// bytes that are not UTF-8.
fn as_strings(values: &ArrayRef) -> Option<ArrayRef> {
match values.data_type() {
DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => Some(values.clone()),
DataType::Binary => {
let b = values.as_binary::<i32>().clone();
Some(Arc::new(arrow_array::StringArray::try_from_binary(b).ok()?))
}
DataType::LargeBinary => {
let b = values.as_binary::<i64>().clone();
Some(Arc::new(
arrow_array::LargeStringArray::try_from_binary(b).ok()?,
))
}
_ => None,
}
}