use relate_core::{Error, NodeId, Result};
use rustc_hash::FxHashMap;
use vortex::array::arrays::primitive::PrimitiveArray;
use vortex::array::arrays::struct_::StructArray;
use vortex::array::arrays::varbin::VarBinArray;
use vortex::array::validity::Validity;
use vortex::array::ArrayRef;
use vortex::array::IntoArray;
use vortex::buffer::{Buffer, ByteBuffer};
use vortex::file::{OpenOptionsSessionExt, VortexFile, WriteOptionsSessionExt};
use vortex::io::runtime::current::CurrentThreadRuntime;
use vortex::io::runtime::BlockingRuntime;
use vortex::io::session::RuntimeSessionExt;
use vortex::session::VortexSession;
use vortex::VortexSessionDefault;
use super::{column_name, vortex_error, BitSet, Column, ColumnState, Graph};
const ROW_COLUMN: &str = "__row";
const MAX_DENSE_CELLS: usize = 1 << 24;
pub(super) struct Gathered {
pub(super) visible: BitSet,
pub(super) label_bits: FxHashMap<u32, BitSet>,
pub(super) columns: FxHashMap<u32, Column>,
}
pub(super) fn row_space(ids: &[NodeId]) -> Result<usize> {
let row_count = ids.iter().copied().max().map_or(0, |id| id + 1) as usize;
let live = ids.len();
if row_count > live.saturating_mul(4).max(1 << 16) {
return Err(Error::storage(format!(
"the graph's node-id space ({row_count} rows over {live} live nodes) \
is too sparse for the store's row-indexed layout"
)));
}
Ok(row_count)
}
pub(super) fn gather(
graph: &Graph,
ts: u64,
ids: Vec<NodeId>,
row_count: usize,
) -> Result<Gathered> {
let mut visible = BitSet::new(row_count);
let mut label_bits: FxHashMap<u32, BitSet> = FxHashMap::default();
let mut columns: FxHashMap<u32, Column> = FxHashMap::default();
for id in ids {
let row = id as usize;
visible.set(row);
let node = graph
.node_at(id, ts)
.expect("all_node_ids_at yields visible ids");
for label in node.labels.iter() {
if let Some(lid) = graph.interned_id(label) {
if !label_bits.contains_key(&lid) {
admit_dense(row_count, label_bits.len() + columns.len() + 1)?;
}
label_bits
.entry(lid)
.or_insert_with(|| BitSet::new(row_count))
.set(row);
}
}
for (name, value) in node.properties.iter() {
let Some(kid) = graph.interned_id(name) else {
continue;
};
if !columns.contains_key(&kid) {
admit_dense(row_count, label_bits.len() + columns.len() + 1)?;
}
columns
.entry(kid)
.or_default()
.state
.push(row, value, row_count);
}
}
Ok(Gathered {
visible,
label_bits,
columns,
})
}
pub(super) fn admit_dense(row_count: usize, structures: usize) -> Result<()> {
let cells = row_count.saturating_mul(structures);
if cells > MAX_DENSE_CELLS {
return Err(Error::storage(format!(
"the graph's {structures} property keys and labels over {row_count} rows \
exceed the store's dense-column budget"
)));
}
Ok(())
}
pub(super) fn columnar_table(
columns: &FxHashMap<u32, Column>,
row_count: usize,
) -> Result<ArrayRef> {
let mut kids: Vec<u32> = columns.keys().copied().collect();
kids.sort_unstable();
let mut names: Vec<String> = vec![ROW_COLUMN.to_string()];
let mut children: Vec<ArrayRef> = vec![PrimitiveArray::new(
Buffer::from((0..row_count as i64).collect::<Vec<_>>()),
Validity::NonNullable,
)
.into_array()];
for kid in &kids {
names.push(column_name(*kid));
children.push(match &columns[kid].state {
ColumnState::Int(values) => int_column(values),
ColumnState::Str(values) => str_column(values),
ColumnState::Empty | ColumnState::Poisoned => {
return Err(vortex_error(format!(
"key {kid} reached the table without a faithful column state"
)))
}
});
}
let name_refs: Vec<&str> = names.iter().map(String::as_str).collect();
let array = StructArray::try_new(name_refs.into(), children, row_count, Validity::NonNullable)
.map_err(vortex_error)?;
Ok(array.into_array())
}
pub(super) fn seal_table(
array: ArrayRef,
) -> Result<(VortexSession, CurrentThreadRuntime, VortexFile)> {
let rt = CurrentThreadRuntime::new();
let session = VortexSession::default().with_handle(rt.handle());
let mut bytes = Vec::new();
session
.write_options()
.blocking(&rt)
.write(&mut bytes, array.to_array_iterator())
.map_err(vortex_error)?;
let vfile = session
.open_options()
.open_buffer(ByteBuffer::copy_from(&bytes))
.map_err(vortex_error)?;
Ok((session, rt, vfile))
}
fn int_column(values: &[Option<i64>]) -> ArrayRef {
let data: Vec<i64> = values.iter().map(|value| value.unwrap_or(0)).collect();
let valid: Vec<bool> = values.iter().map(Option::is_some).collect();
PrimitiveArray::new(Buffer::from(data), Validity::from_iter(valid)).into_array()
}
fn str_column(values: &[Option<String>]) -> ArrayRef {
let data: Vec<Option<&str>> = values.iter().map(|value| value.as_deref()).collect();
VarBinArray::from_nullable_strs(data).into_array()
}