crates/kleene-plan/src/catalog.rs
//! The catalog of a set: what its names stand for, each a relation's source.
//!
//! A [`Catalog`] holds a graph's schema as both query clients read it: node labels (one
//! column of ids), edge labels (two columns, from and to), properties of a label's nodes
//! (id, value) and of a label's edges (from, to, value), each with its [`Type`]; the ids of
//! labels that are blocks of one id space, vertex tables, edge ends, edge aliases, labels of
//! some of another's nodes; the indexes that exist (range, name, reach, kinds) and the
//! properties a reader refused (by name, with why). kleene-gar fills one from an X.gar set
//! where the set is opened (`GarGraph::catalog`); a test fills one by hand.
//!
//! Inputs by name: [`Catalog::relation`] gives the source and column types of a name
//! (`L` a node label, `E` an edge label, `L.k` a node property, `E.k` an edge property;
//! `E@row` an edge label by its rows and `E@row.k` an edge property by row, each edge a row),
//! [`Plan::input_from`] declares an input relation of that name, width and types, and
//! [`Inputs::bind`] gives every input relation the catalog names its source, so a rule
//! program binds a set's relations and properties by name, with no hand binding.
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use crate::{Inputs, Plan, PlanError, RelId, RelKind, Result, Source, Type};
/// The nodes of a string property by value: a name index ([`Catalog::name_index`]), such
/// as kleene's `NameRowsRel` on kleene-index's minimal perfect hash.
pub trait NameIndex: Send + Sync + fmt::Debug {
/// Call `out` once for each node whose value is `name` (none for a name no node has).
fn nodes(&self, name: &str, out: &mut dyn FnMut(u32)) -> crate::Result<()>;
}
/// What the names in a query stand for, each a relation's source: a node label is the set of
/// node ids that carry it (one column), an edge label its edges (two columns: from, to), a
/// property of the nodes of a label a map from node id to value (two columns: id, value).
/// Node ids are one id space: a label, an edge's ends and a property's ids must agree; or,
/// with vertex tables ([`Catalog::vertex_table`]), rows of a table, told apart by `id(n)`.
#[derive(Clone, Debug, Default)]
pub struct Catalog {
labels: BTreeMap<String, Source>,
edges: BTreeMap<String, Source>,
edge_counts: BTreeMap<String, Source>,
props: BTreeMap<(String, String), Source>,
edge_props: BTreeMap<(String, String), Source>,
types: BTreeMap<(String, String), Type>,
edge_types: BTreeMap<(String, String), Type>,
reach_indexes: BTreeMap<String, Source>,
prop_indexes: BTreeMap<(String, String), Source>,
name_indexes: BTreeMap<(String, String), Arc<dyn NameIndex>>,
kinds_indexes: BTreeMap<String, Source>,
kind_labels: BTreeMap<String, (String, u64)>,
parents: BTreeMap<String, String>,
aliases: BTreeMap<String, String>,
blocks: BTreeMap<String, (u64, u64)>,
refused: BTreeMap<(String, String), String>,
refused_edges: BTreeMap<(String, String), String>,
tables: BTreeMap<String, (u64, u64)>,
bases: BTreeMap<String, u64>,
ends: BTreeMap<String, (String, String)>,
edge_rows: BTreeMap<String, Source>,
edge_row_props: BTreeMap<(String, String), (Source, Type)>,
lists: BTreeMap<(String, String), (Source, Type)>,
edge_lists: BTreeMap<(String, String), (Source, Type)>,
edge_row_lists: BTreeMap<(String, String), (Source, Type)>,
}
impl Catalog {
/// An empty catalog.
pub fn new() -> Self {
Catalog::default()
}
/// Node label `name`: the ids in `source` (one column).
pub fn label(&mut self, name: &str, source: Source) -> &mut Self {
self.labels.insert(name.into(), source);
self
}
/// Edge label `name`: the edges in `source` (two columns, from and to; a graph is best:
/// a walk over it needs no copy).
pub fn edge(&mut self, name: &str, source: Source) -> &mut Self {
self.edges.insert(name.into(), source);
self
}
/// The parallel edges of edge label `name`: `source` holds (source, destination,
/// number of edges) for every pair of [`Catalog::edge`]'s (a pair with no row matches
/// nothing where the counts are read). With it each of a pair's edges is a match of its
/// own; without, each pair is one edge.
pub fn edge_counts(&mut self, name: &str, source: Source) -> &mut Self {
self.edge_counts.insert(name.into(), source);
self
}
/// The parallel-edge counts of edge label `name` ([`Catalog::edge_counts`]).
pub fn edge_count_source(&self, name: &str) -> Option<&Source> {
self.edge_counts.get(name)
}
/// Property `key` of the nodes labelled `label`: `source` maps node id to value (two
/// columns). A node with no row has no value, and a comparison or a returned value
/// that needs it leaves the node out (there are no nulls); so has a row whose value is
/// null (an unsigned value has none: the row is left out where the source is read).
pub fn property(&mut self, label: &str, key: &str, source: Source) -> &mut Self {
self.props.insert((label.into(), key.into()), source);
self.types.remove(&(label.to_string(), key.to_string()));
self
}
/// Property `key` of the nodes labelled `label` is one the catalog cannot read, `why`
/// (such as its column's type): a query that reads it is refused with `why`, by name;
/// a query that does not runs.
pub fn refused_property(&mut self, label: &str, key: &str, why: &str) -> &mut Self {
self.refused.insert((label.into(), key.into()), why.into());
self
}
/// [`Catalog::refused_property`] for property `key` of the edges labelled `label`.
pub fn refused_edge_property(&mut self, label: &str, key: &str, why: &str) -> &mut Self {
self.refused_edges
.insert((label.into(), key.into()), why.into());
self
}
/// Property `key` of the edges labelled `label`: `source` holds (from, to, value)
/// rows (three columns). Edges are pairs of nodes here, so two edges of a label between
/// the same nodes are one edge with each of their values.
pub fn edge_property(&mut self, label: &str, key: &str, source: Source) -> &mut Self {
self.edge_props.insert((label.into(), key.into()), source);
self.edge_types
.remove(&(label.to_string(), key.to_string()));
self
}
/// [`Catalog::edge_property`] with values of type `ty` (the third column a signed
/// integer, float, boolean or string column; a null value is null).
pub fn typed_edge_property(
&mut self,
label: &str,
key: &str,
source: Source,
ty: Type,
) -> &mut Self {
self.edge_property(label, key, source);
self.edge_types.insert((label.into(), key.into()), ty);
self
}
/// The type of property `key` of the edges labelled `label` (unsigned unless given by
/// [`Catalog::typed_edge_property`]): how a reader of [`Catalog::edge_property`]'s
/// source (a procedure's weights) decodes its third column.
pub fn edge_property_type(&self, label: &str, key: &str) -> Type {
self.edge_types
.get(&(label.to_string(), key.to_string()))
.copied()
.unwrap_or_default()
}
/// A reach index of edge label `label`: `source` holds (a, b) when a path of zero or
/// more `label` edges leads from `a` to `b`, answered with both bound (an external
/// relation, such as kleene's `ReachRel` on kleene-index's 2-hop labels). A quantified
/// edge `*` or `+` of that label between two nodes pinned to one id each (an equality
/// with a constant, or an index lookup of one value) is answered by it instead of a
/// search.
pub fn reach_index(&mut self, label: &str, source: Source) -> &mut Self {
self.reach_indexes.insert(label.into(), source);
self
}
/// An index of property `key` of the nodes labelled `label`: `source` holds (lo, hi,
/// node) for each node whose value lies in `lo..=hi`, answered with `lo` and `hi` bound
/// (an external relation, such as kleene's `RangeRel`). A node of that one label with
/// `n.key = c`, `<`, `<=`, `>` or `>=` constants is found by one lookup of the range
/// instead of a scan of the label.
pub fn property_index(&mut self, label: &str, key: &str, source: Source) -> &mut Self {
self.prop_indexes.insert((label.into(), key.into()), source);
self
}
/// A name index of string property `key` of the nodes labelled `label`: a node of that
/// one label with `n.key = "text"` (or `IN` a list of strings, or a property map
/// `{key: "text"}`) is found by the index's lookup of each string instead of a scan of
/// the label and a compare of every value. The property must be a [`Type::Str`]
/// [`Catalog::typed_property`].
pub fn name_index(&mut self, label: &str, key: &str, index: Arc<dyn NameIndex>) -> &mut Self {
self.name_indexes.insert((label.into(), key.into()), index);
self
}
/// A kinds index named `name`: `source` holds (kind, node) rows, answered with `kind`
/// bound (an external relation, such as kleene's `KindsRel` on kleene-index's bitmap
/// per kind).
pub fn kinds_index(&mut self, name: &str, source: Source) -> &mut Self {
self.kinds_indexes.insert(name.into(), source);
self
}
/// Node label `label` as the nodes of kind `kind` in kinds index `index`. The label is
/// also given with [`Catalog::label`]; a node whose labels (or label alternatives
/// `A|B`) are all kinds of one index is found by a lookup of each kind (a union of the
/// bitmaps) instead of reading the label's source.
pub fn kind_label(&mut self, label: &str, index: &str, kind: u64) -> &mut Self {
self.kind_labels.insert(label.into(), (index.into(), kind));
self
}
/// Node label `label`'s nodes are exactly the ids `base..base + count` (in a catalog of
/// one id space: a vertex type of a set, kleene-gar's `IdSpace`): a node of such labels
/// (or of any label, when every label of no other's is one) with bounds on its `id(n)`
/// is listed from the numbers ([`crate::IdRanges`]), no label read.
pub fn id_block(&mut self, label: &str, base: u64, count: u64) -> &mut Self {
self.blocks.insert(label.into(), (base, count));
self
}
/// The ids of label `label`, when they are a block.
pub fn block(&self, label: &str) -> Option<(u64, u64)> {
self.blocks.get(label).copied()
}
/// Edge label `name` is another name of edge label `of` (both given with
/// [`Catalog::edge`]: the same edges): a union of labels naming both (or of all labels,
/// `-->`) reads them once, under `name`.
pub fn edge_alias(&mut self, name: &str, of: &str) -> &mut Self {
self.aliases.insert(name.into(), of.into());
self
}
/// The edge label `name` is another name of.
pub fn alias_of(&self, name: &str) -> Option<&str> {
self.aliases.get(name).map(String::as_str)
}
/// Node label `label` holds some of label `of`'s nodes (a kind label of a vertex type):
/// its nodes' properties are `of`'s, `labels(n)` of a node found by `of` lists it where
/// it holds the node, and a node with no label is found through `of` alone.
pub fn sub_label(&mut self, label: &str, of: &str) -> &mut Self {
self.parents.insert(label.into(), of.into());
self
}
/// Node label `label` is a vertex table: its nodes are its rows `0..count` (its
/// source lists exactly those), and `id(n)` of row `r` is `base + r`. With vertex tables
/// in a catalog, node ids are row numbers within a table (tables share them), `id(n)`
/// tells nodes of two tables apart, and a node with no label and no edge (`MATCH (n)`)
/// is any row of any vertex table, bound by its `id(n)`. A catalog with none has one id
/// space: `id(n)` is the node's id itself, and `MATCH (n)` any node of any label.
pub fn vertex_table(&mut self, label: &str, base: u64, count: u64) -> &mut Self {
self.tables.insert(label.into(), (base, count));
self
}
/// Node label `label` holds rows of a vertex table numbered from `base` (a label of
/// some of a table's rows, such as a kind label): `id(n)` of row `r` is `base + r`.
pub fn id_base(&mut self, label: &str, base: u64) -> &mut Self {
self.bases.insert(label.into(), base);
self
}
/// Edge label `label` goes from nodes of vertex table `from` to nodes of vertex table
/// `to`: a node with no label at one of its ends is a row of that table (for its
/// `id(n)` and its whole value in `RETURN`).
pub fn edge_ends(&mut self, label: &str, from: &str, to: &str) -> &mut Self {
self.ends.insert(label.into(), (from.into(), to.into()));
self
}
/// Whether the catalog has vertex tables ([`Catalog::vertex_table`]).
pub fn numbered(&self) -> bool {
!self.tables.is_empty()
}
/// The vertex tables: (label, base, count), by label.
pub fn tables(&self) -> impl Iterator<Item = (&str, u64, u64)> {
self.tables.iter().map(|(l, &(b, c))| (l.as_str(), b, c))
}
/// The (base, count) of vertex table `label`.
pub fn table(&self, label: &str) -> Option<(u64, u64)> {
self.tables.get(label).copied()
}
/// The id base of label `label`: of its vertex table, or given by [`Catalog::id_base`].
pub fn base(&self, label: &str) -> Option<u64> {
self.tables
.get(label)
.map(|t| t.0)
.or_else(|| self.bases.get(label).copied())
}
/// The vertex tables at the ends of edge label `label`.
pub fn ends(&self, label: &str) -> Option<&(String, String)> {
self.ends.get(label)
}
/// The vertex table of a node label: the label itself, or the table at its id base (a
/// label of some of a table's rows, such as a kind).
pub fn table_named(&self, label: &str) -> Option<String> {
if self.tables.contains_key(label) {
return Some(label.to_string());
}
let base = self.base(label)?;
self.tables
.iter()
.find(|(_, t)| t.0 == base && t.1 > 0)
.map(|(l, _)| l.clone())
}
/// The properties of label `label`: (key, source, type), by key.
pub fn label_props(&self, label: &str) -> Vec<(String, Source, Type)> {
self.props
.iter()
.filter(|((l, _), _)| l == label)
.map(|((_, k), s)| (k.clone(), s.clone(), self.prop_type(label, k)))
.collect()
}
/// The properties of edge label `label`: (key, source, type), by key.
pub fn edge_label_props(&self, label: &str) -> Vec<(String, Source, Type)> {
self.edge_props
.iter()
.filter(|((l, _), _)| l == label)
.map(|((_, k), s)| (k.clone(), s.clone(), self.edge_property_type(label, k)))
.collect()
}
/// Every node label.
pub fn node_labels(&self) -> impl Iterator<Item = &str> {
self.labels.keys().map(String::as_str)
}
/// The name index of string property `key` of label `label` ([`Catalog::name_index`]).
pub fn name_idx(&self, label: &str, key: &str) -> Option<&Arc<dyn NameIndex>> {
self.name_indexes.get(&(label.to_string(), key.to_string()))
}
/// Kinds index `name` ([`Catalog::kinds_index`]).
pub fn kinds_idx(&self, name: &str) -> Option<&Source> {
self.kinds_indexes.get(name)
}
/// The kinds index and kind of kind label `label` ([`Catalog::kind_label`]).
pub fn kind_of(&self, label: &str) -> Option<&(String, u64)> {
self.kind_labels.get(label)
}
/// The reach index of edge label `label` ([`Catalog::reach_index`]).
pub fn reach_idx(&self, label: &str) -> Option<&Source> {
self.reach_indexes.get(label)
}
/// The range index of property `key` of label `label` ([`Catalog::property_index`]).
pub fn prop_idx(&self, label: &str, key: &str) -> Option<&Source> {
self.prop_indexes.get(&(label.to_string(), key.to_string()))
}
/// Every edge label.
pub fn edge_labels(&self) -> impl Iterator<Item = &str> {
self.edges.keys().map(String::as_str)
}
/// The (from, to, value) source of property `key` of edge label `label`.
pub fn edge_prop(&self, label: &str, key: &str) -> Option<&Source> {
self.edge_props.get(&(label.to_string(), key.to_string()))
}
/// Why property `key` of label `label` is refused (a node label; an edge label with
/// `edge`); with no label, of the first label that refuses it and has no such property.
pub fn refused_prop(&self, label: Option<&str>, key: &str, edge: bool) -> Option<String> {
let (map, props) = if edge {
(&self.refused_edges, &self.edge_props)
} else {
(&self.refused, &self.props)
};
match label {
Some(l) => {
let of = |l: &str| {
map.get(&(l.to_string(), key.to_string()))
.map(|why| format!("property `{key}` of `{l}`: {why}"))
};
of(l).or_else(|| {
self.parents
.get(l)
.filter(|_| !props.contains_key(&(l.to_string(), key.to_string())))
.and_then(|p| of(p))
})
}
None => map
.iter()
.filter(|((_, k), _)| k == key)
.find(|_| !props.keys().any(|(_, k)| k == key))
.map(|((l, _), why)| format!("property `{key}` of `{l}`: {why}")),
}
}
/// The label whose property `key` a node of `label` has: `label`'s own, else (a label
/// of some of another's nodes, [`Catalog::sub_label`]) that one's.
pub fn prop_owner<'a>(&'a self, label: &'a str, key: &str) -> Option<&'a str> {
let has = |l: &str| self.props.contains_key(&(l.to_string(), key.to_string()));
if has(label) {
return Some(label);
}
self.parents
.get(label)
.map(String::as_str)
.filter(|p| has(p))
}
/// The source of property `key` of label `label`'s nodes (its own, or the label's it
/// holds some nodes of).
pub fn label_prop(&self, label: &str, key: &str) -> Option<&Source> {
let owner = self.prop_owner(label, key)?;
self.props.get(&(owner.to_string(), key.to_string()))
}
/// The labels of no other label's nodes ([`Catalog::sub_label`]): a node of any label
/// is a node of one of them.
pub fn top_labels(&self) -> impl Iterator<Item = &str> {
self.node_labels()
.filter(|l| !self.parents.contains_key(*l))
}
/// The labels of some of `label`'s nodes.
pub fn sub_labels<'a>(&'a self, label: &'a str) -> impl Iterator<Item = &'a str> {
self.parents
.iter()
.filter(move |(_, p)| *p == label)
.map(|(l, _)| l.as_str())
}
/// The labels of no other label's nodes that have property `key`: a node with no label
/// has a value of it only as a node of one of them.
pub fn holders(&self, key: &str) -> Vec<String> {
self.top_labels()
.filter(|l| self.props.contains_key(&(l.to_string(), key.to_string())))
.map(String::from)
.collect()
}
/// [`Catalog::property`] with values of type `ty` (a string, signed integer, float or
/// boolean column; a null value is null, as is a node with no row).
pub fn typed_property(
&mut self,
label: &str,
key: &str,
source: Source,
ty: Type,
) -> &mut Self {
self.property(label, key, source);
self.types.insert((label.into(), key.into()), ty);
self
}
/// The type of property `key` of label `label` (unsigned unless given).
pub fn prop_type(&self, label: &str, key: &str) -> Type {
let owner = self.prop_owner(label, key).unwrap_or(label);
self.types
.get(&(owner.to_string(), key.to_string()))
.copied()
.unwrap_or_default()
}
/// The source of node label `name`.
pub fn node_label(&self, name: &str) -> Option<&Source> {
self.labels.get(name)
}
/// The source of edge label `name`.
pub fn edge_label(&self, name: &str) -> Option<&Source> {
self.edges.get(name)
}
}
impl Catalog {
/// The source and column types of `name`, a relation of the catalog: node label `L`
/// (`[U64]`, its ids), edge label `E` (`[U64, U64]`, from and to), property `L.k` of a
/// node label (`[U64, t]`, id and value) or `E.k` of an edge label (`[U64, U64, t]`),
/// `t` the property's type; an edge label by its rows, `E@row` (`[U64, U64, U64]`: row,
/// from, to) and `E@row.k` (`[U64, t]`: row, value; [`Catalog::edge_rows`]); a list
/// property `L.k` (`[U64, U64, t]`, id, position and value: [`Catalog::list_property`])
/// or `E.k` (`[U64, U64, U64, t]`; by rows `E@row.k`, `[U64, U64, t]`: row, position,
/// value). Refused: a name the catalog does not have, a property a
/// reader refused (with why), a name that is both a node and an edge label (or names a
/// property of both). `L@id` is node label `L`'s rows and ids ([`Catalog::row_ids`]);
/// `L@(k1, k2, ..)` its properties side by side ([`Catalog::columns`]).
///
/// A property read another way, by a form after `@`:
///
/// | Name | Relation |
/// |---|---|
/// | `L.k@u64`, `E.k@u64` | a signed integer property read as unsigned: every column `u64`, a row whose value is negative or null left out (an `Int32` or `Int64` column with neither read in place); an unsigned property as it is |
/// | `L.k@hex`, `E.k@hex` | a string or bytes property as the lowercase hex of each value's bytes (a `str` column, every row, a null null): bytes that are not text, such as hashes; hex compares as the bytes do |
///
/// (`L.k` itself of a bytes column, `Binary`, `LargeBinary` or `BinaryView`, is its text: a
/// value that is not UTF-8 has none, null; of a `FixedSizeBinary` column, never text, the
/// same as `L.k@hex`.)
pub fn relation(&self, name: &str) -> Result<(Source, Vec<Type>)> {
match parse_name(name) {
Name::Columns { label, keys } => self.columns(label, &keys),
Name::RowIds { label } => self.row_id_relation(label),
Name::EdgeRows { label, key } => self.row_relation(name, label, key),
Name::Form { of, form } => self.read_as(name, of, form),
Name::Plain { .. } => self.plain_relation(name),
}
}
/// [`Catalog::relation`] of a plain name: `L`, `E`, `L.k`, `E.k` (a list column too).
fn plain_relation(&self, name: &str) -> Result<(Source, Vec<Type>)> {
let mut found: Vec<(Source, Vec<Type>)> = Vec::new();
if let Some(s) = self.labels.get(name) {
found.push((s.clone(), vec![Type::U64]));
}
if let Some(s) = self.edges.get(name) {
found.push((s.clone(), vec![Type::U64, Type::U64]));
}
if let Some((label, key)) = name.split_once('.') {
if let Some(s) = self.label_prop(label, key) {
found.push((s.clone(), vec![Type::U64, self.prop_type(label, key)]));
}
if let Some(s) = self.edge_prop(label, key) {
let t = self.edge_property_type(label, key);
found.push((s.clone(), vec![Type::U64, Type::U64, t]));
}
self.list_relations(label, key, &mut found);
if found.is_empty() {
let why = self
.refused_prop(Some(label), key, false)
.or_else(|| self.refused_prop(Some(label), key, true));
if let Some(why) = why {
return Err(PlanError::Input(why));
}
}
}
match found.len() {
1 => Ok(found.pop().expect("one")),
0 => Err(PlanError::Input(format!(
"the catalog has no relation `{name}`"
))),
_ => Err(PlanError::Input(format!(
"`{name}` names both a node and an edge relation of the catalog"
))),
}
}
}
impl Catalog {
/// Relation `name`: property `of` read by `form` ([`Catalog::relation`]'s table).
fn read_as(&self, name: &str, of: &str, form: &str) -> Result<(Source, Vec<Type>)> {
let refuse = |why: String| Err(PlanError::Input(format!("`{name}`: {why}")));
let (source, types) = self.relation(of)?;
if !of.contains('.') || types.len() < 2 {
return refuse(format!(
"`@{form}` reads a property (`L.k` or `E.k`); `{of}` is a label"
));
}
let value = *types.last().expect("a property has a value column");
match form {
"u64" => match value {
Type::U64 => Ok((source, types)),
Type::I64 => Ok((unsigned_rows(name, &source)?, vec![Type::U64; types.len()])),
t => refuse(format!(
"`@u64` reads an integer property; `{of}` is of type {t}"
)),
},
"hex" => match value {
Type::Str => Ok((hex_rows(name, &source)?, types)),
t => refuse(format!(
"`@hex` reads a string or bytes property; `{of}` is of type {t}"
)),
},
_ => refuse(format!("no form `@{form}` (the forms: `@u64`, `@hex`)")),
}
}
/// `(row, id)` of node label `label`: `id = base + row`, by arithmetic
/// ([`crate::IdShift`]), for a vertex table or an id block (rows `0..count`) or a label
/// with an id base ([`Catalog::id_base`]: any row). `None` for a label with no base (a
/// catalog of one id space whose label is no block) or no such label. The relation
/// `L@id` of [`Catalog::relation`], and `id(n)` of a node of a vertex table in GQL.
pub fn row_ids(&self, label: &str) -> Option<crate::IdShift> {
if let Some(&(base, count)) = self.tables.get(label).or_else(|| self.blocks.get(label)) {
return Some(crate::IdShift::new(base, Some(count)));
}
self.bases
.get(label)
.map(|&base| crate::IdShift::new(base, None))
}
/// Properties `keys` of node label `label` as one relation, `(id, k1, .., kn)` (the
/// relation `L@(k1, k2, ..)` of [`Catalog::relation`]), of types `[U64, t1, .., tn]`: the
/// properties' columns side by side, when each is [`Source::Columns`] over one and the
/// same id column (kleene-gar's vertex columns are). One scan of it reads what `n`
/// relations of one column each give by `n - 1` joins on the id. Refused by name: no
/// key, a key given twice, a label the catalog lacks, a property it lacks or refuses,
/// properties not stored side by side.
pub fn columns(&self, label: &str, keys: &[&str]) -> Result<(Source, Vec<Type>)> {
let name = format!("{label}@({})", keys.join(", "));
let no = |why: String| Err(PlanError::Input(format!("`{name}`: {why}")));
if keys.iter().all(|k| k.is_empty()) {
return no("no column named".into());
}
if !self.labels.contains_key(label) && !self.tables.contains_key(label) {
return no(format!("the catalog has no node label `{label}`"));
}
let mut ids: Option<arrow_array::ArrayRef> = None;
let mut columns = Vec::with_capacity(keys.len() + 1);
let mut types = vec![Type::U64];
for (i, key) in keys.iter().enumerate() {
if key.is_empty() || keys[..i].contains(key) {
return no(format!("column `{key}` named twice or empty"));
}
let Some(source) = self.label_prop(label, key) else {
return no(match self.refused_prop(Some(label), key, false) {
Some(why) => why,
None => format!("label `{label}` has no property `{key}`"),
});
};
let pair = match source {
Source::Columns(c) if c.len() == 2 => c,
_ => return no(format!("property `{key}` is not stored side by side")),
};
match &ids {
None => {
ids = Some(pair[0].clone());
columns.push(pair[0].clone());
}
Some(first) if Arc::ptr_eq(first, &pair[0]) => {}
Some(_) => {
return no(format!(
"property `{key}` is not stored side by side with `{}` (its ids are \
another column)",
keys[0]
));
}
}
columns.push(pair[1].clone());
types.push(self.prop_type(label, key));
}
Ok((Source::Columns(columns), types))
}
/// `L@id` as a relation: `(row, id)` of node label `label`, two unsigned columns.
fn row_id_relation(&self, label: &str) -> Result<(Source, Vec<Type>)> {
match self.row_ids(label) {
Some(shift) => Ok((
Source::External(Arc::new(shift)),
vec![Type::U64, Type::U64],
)),
None if self.labels.contains_key(label) || self.tables.contains_key(label) => {
Err(PlanError::Input(format!(
"`{label}@id`: node label `{label}` has no row numbers (no vertex table, id \
block or id base)"
)))
}
None => Err(PlanError::Input(format!(
"`{label}@id`: the catalog has no node label `{label}`"
))),
}
}
}
impl Catalog {
/// Whether the catalog lacks `name` altogether, for every name form
/// [`Catalog::relation`] reads (both read one parse of the name): its label is missing
/// (no node label `L` for `L`, `L.k`, `L@id`, `L@(k1, ..)`; no edge label `E` for `E`,
/// `E.k`, `E@row`, `E@row.k`), or a column it names is (no property, refused property or
/// list column `k` of the label); `X@form` lacks what `X` lacks. A name whose label and
/// columns are there but that the catalog cannot give in its form (a refused column, a
/// label with no row numbers, an unknown form) is not lacking: [`Catalog::relation`]
/// refuses it by name.
pub fn lacks(&self, name: &str) -> bool {
let node = |l: &str| self.labels.contains_key(l) || self.tables.contains_key(l);
let edge = |l: &str| self.edges.contains_key(l);
match parse_name(name) {
Name::Columns { label, keys } => {
!node(label)
|| keys
.iter()
.any(|k| !k.is_empty() && !self.node_column(label, k))
}
Name::RowIds { label } => !node(label),
Name::EdgeRows { label, key } => {
(!edge(label) && !node(label)) || key.is_some_and(|k| !self.edge_column(label, k))
}
Name::Form { of, .. } => self.lacks(of),
Name::Plain { name, key } => {
!self.labels.contains_key(name)
&& !edge(name)
&& key.is_none_or(|(l, k)| !self.node_column(l, k) && !self.edge_column(l, k))
}
}
}
/// Whether node label `label` has column `key`: a property, a refused one or a list.
fn node_column(&self, label: &str, key: &str) -> bool {
self.label_prop(label, key).is_some()
|| self.refused_prop(Some(label), key, false).is_some()
|| self.list_prop(label, key).is_some()
}
/// Whether edge label `label` has column `key`: a property (by its ends or by the
/// edges' rows), a refused one or a list.
fn edge_column(&self, label: &str, key: &str) -> bool {
self.edge_prop(label, key).is_some()
|| self.refused_prop(Some(label), key, true).is_some()
|| self.list_edge_prop(label, key).is_some()
|| self.edge_row_prop(label, key).is_some()
|| self.list_edge_row_prop(label, key).is_some()
}
/// The schema's rows: every node label; every edge label (by table name, and by bare
/// edge name where one type alone has it); every property read (label, key, type
/// name), of nodes and of edges, a list column's type `list` and its element type's
/// name (`list u64`); every property refused (label, key, why), list columns not.
pub fn schema_rows(&self) -> [Vec<Vec<crate::Datum>>; 4] {
use crate::Datum;
let s = |x: &str| Datum::Str(x.to_string());
let labels = self.labels.keys().map(|l| vec![s(l)]).collect();
let edges = self.edges.keys().map(|e| vec![s(e)]).collect();
let mut columns: Vec<Vec<Datum>> = self
.props
.keys()
.map(|(l, k)| vec![s(l), s(k), s(self.prop_type(l, k).name())])
.collect();
columns.extend(
self.edge_props
.keys()
.map(|(l, k)| vec![s(l), s(k), s(self.edge_property_type(l, k).name())]),
);
let list = |t: &Type| s(&format!("list {}", t.name()));
columns.extend(
self.lists
.iter()
.chain(&self.edge_lists)
.map(|((l, k), (_, t))| vec![s(l), s(k), list(t)]),
);
// a list column is read (as rows), not refused
let refused = self
.refused
.iter()
.filter(|(lk, _)| !self.lists.contains_key(*lk))
.chain(
self.refused_edges
.iter()
.filter(|(lk, _)| !self.edge_lists.contains_key(*lk)),
)
.map(|((l, k), why)| vec![s(l), s(k), s(why)])
.collect();
[labels, edges, columns, refused]
}
}
/// The relations of a catalog's schema ([`Plan::schema`]), each of string columns, bound
/// by [`Inputs::bind`] from the catalog it is given.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Schema {
/// `(label)`: every node label (one with no nodes too).
pub label: RelId,
/// `(edge)`: every edge label, by table name (`src_edge_dst`) and by bare edge name
/// where one edge type alone has it.
pub edge: RelId,
/// `(label, column, type)`: every property the catalog reads, of a node or an edge
/// label, its type's name (`u64`, `i64`, `f64`, `bool`, `str`; a list column `list `
/// and its element type's, `list u64`).
pub column: RelId,
/// `(label, column, why)`: every property the catalog refuses, with why.
pub refused: RelId,
}
impl Plan {
/// An input named `name` of `types`, empty where `catalog` lacks the name
/// ([`Catalog::lacks`]): [`Inputs::bind`] binds it empty then, else as
/// [`Plan::input_from`] (whose types must be `types`). Refused: a name the catalog has
/// of other types, a property it refuses (by name, with why), a name of both a node and
/// an edge relation.
///
/// ```
/// use kleene_plan::{Catalog, Plan, Type};
/// let c = Catalog::new();
/// let mut p = Plan::new();
/// let inst = p.input_or_empty(&c, "inst", &[Type::U64]).unwrap();
/// assert!(p.is_optional(inst));
/// ```
pub fn input_or_empty(
&mut self,
catalog: &Catalog,
name: &str,
types: &[Type],
) -> Result<RelId> {
if !catalog.lacks(name) {
let (_, have) = catalog.relation(name)?;
if have != types {
return Err(PlanError::Input(format!(
"input `{name}` is declared {types:?}; the catalog's are {have:?}"
)));
}
}
let rel = if types.iter().all(|&t| t == Type::U64) {
self.input(name, types.len())
} else {
self.input_typed(name, types)
};
self.optional.push(rel);
Ok(rel)
}
/// Whether `rel` is an input that is empty where the catalog lacks its name
/// ([`Plan::input_or_empty`]).
pub fn is_optional(&self, rel: RelId) -> bool {
self.optional.contains(&rel)
}
/// The catalog's schema as four input relations of strings ([`Schema`]: `schema.label`,
/// `schema.edge`, `schema.column`, `schema.refused`), which [`Inputs::bind`] fills from
/// the catalog it is given, so a rule decides what the set has
/// (`no_inst(S) :- site(S), !label(inst)` with `inst` a string constant). Made once:
/// a second call gives the same relations. Refused: a catalog that has a relation of
/// one of those names itself.
pub fn schema(&mut self, catalog: &Catalog) -> Result<Schema> {
let names = [
"schema.label",
"schema.edge",
"schema.column",
"schema.refused",
];
if let Some(n) = names.iter().find(|n| !catalog.lacks(n)) {
return Err(PlanError::Input(format!(
"the catalog has a relation `{n}` of its own: the schema's relations cannot take that name"
)));
}
if let Some(s) = self.schema {
return Ok(s);
}
let s = Schema {
label: self.input_typed(names[0], &[Type::Str]),
edge: self.input_typed(names[1], &[Type::Str]),
column: self.input_typed(names[2], &[Type::Str; 3]),
refused: self.input_typed(names[3], &[Type::Str; 3]),
};
self.schema = Some(s);
Ok(s)
}
/// The schema's relations, when [`Plan::schema`] made them.
pub fn schema_rels(&self) -> Option<Schema> {
self.schema
}
}
/// A relation's name as the catalog reads it, parsed once: [`Catalog::relation`] reads
/// it and [`Catalog::lacks`] answers from it, so a name form has both answers.
enum Name<'a> {
/// `L@(k1, k2, ..)`: properties of a node label side by side.
Columns { label: &'a str, keys: Vec<&'a str> },
/// `L@id`: a node label's (row, id).
RowIds { label: &'a str },
/// `E@row`, `E@row.k`: an edge label's rows, or a property by them.
EdgeRows {
label: &'a str,
key: Option<&'a str>,
},
/// `X@form`: relation `X` read by a form (`T.c@hex`, `T.c@u64`).
Form { of: &'a str, form: &'a str },
/// `L`, `E`, `L.k`, `E.k` (a list column too): `key` the (label, key) of a dotted name.
Plain {
name: &'a str,
key: Option<(&'a str, &'a str)>,
},
}
/// `name` parsed into its form ([`Name`]), the forms tried in this order.
fn parse_name(name: &str) -> Name<'_> {
if let Some((label, keys)) = name.strip_suffix(')').and_then(|n| n.split_once("@(")) {
let keys = keys.split(',').map(str::trim).collect();
return Name::Columns { label, keys };
}
if let Some(label) = name.strip_suffix("@id") {
return Name::RowIds { label };
}
if let Some((label, rest)) = name.split_once(ROW) {
if rest.is_empty() {
return Name::EdgeRows { label, key: None };
}
if let Some(key) = rest.strip_prefix('.') {
return Name::EdgeRows {
label,
key: Some(key),
};
}
}
if let Some((of, form)) = name.rsplit_once('@') {
return Name::Form { of, form };
}
Name::Plain {
name,
key: name.split_once('.'),
}
}
/// The mark of an edge label's rows in a relation's name: `E@row`, `E@row.k`.
const ROW: &str = "@row";
impl Catalog {
/// Edge label `label` by its rows: `source` holds (row, from, to), one row per edge
/// (three columns), the row a number of the label's own (an X.gar edge type's place of
/// the edge in its by-source order), not a node id. Two edges of the label between the
/// same nodes are two rows; read by name as `label@row` ([`Catalog::relation`]).
pub fn edge_rows(&mut self, label: &str, source: Source) -> &mut Self {
self.edge_rows.insert(label.into(), source);
self
}
/// Property `key` of the edges labelled `label` by their rows: `source` holds (row,
/// value), the row of [`Catalog::edge_rows`], the value of type `ty`; read by name as
/// `label@row.key`, so a rule joins one edge's values on its row.
pub fn edge_row_property(
&mut self,
label: &str,
key: &str,
source: Source,
ty: Type,
) -> &mut Self {
self.edge_row_props
.insert((label.into(), key.into()), (source, ty));
self
}
/// The (row, from, to) source of edge label `label` ([`Catalog::edge_rows`]).
pub fn edge_row_source(&self, label: &str) -> Option<&Source> {
self.edge_rows.get(label)
}
/// The (row, value) source and type of property `key` of edge label `label`
/// ([`Catalog::edge_row_property`]).
pub fn edge_row_prop(&self, label: &str, key: &str) -> Option<&(Source, Type)> {
self.edge_row_props
.get(&(label.to_string(), key.to_string()))
}
/// [`Catalog::relation`] of a name of edge rows: `E@row` (`[U64, U64, U64]`: row, from,
/// to) or `E@row.k` (`[U64, t]`: row, value). A property the reader refused as `E.k` is
/// refused here with the same why.
fn row_relation(
&self,
name: &str,
label: &str,
key: Option<&str>,
) -> Result<(Source, Vec<Type>)> {
let Some(key) = key else {
return match self.edge_rows.get(label) {
Some(s) => Ok((s.clone(), vec![Type::U64; 3])),
None => Err(PlanError::Input(format!(
"the catalog has no rows of edge label `{label}` (`{name}`)"
))),
};
};
if let Some((s, t)) = self.list_edge_row_prop(label, key) {
return Ok((s.clone(), vec![Type::U64, Type::U64, t]));
}
match self.edge_row_prop(label, key) {
Some((s, t)) => Ok((s.clone(), vec![Type::U64, *t])),
None => Err(PlanError::Input(
self.refused_prop(Some(label), key, true)
.unwrap_or_else(|| format!("the catalog has no relation `{name}`")),
)),
}
}
}
/// `source`, the columns of a string or bytes property (its value the last column), with
/// the value column as its hex ([`crate::typed::hex_column`]).
fn hex_rows(name: &str, source: &Source) -> Result<Source> {
let hex = |columns: &[arrow_array::ArrayRef]| -> Result<Vec<arrow_array::ArrayRef>> {
let (last, rest) = columns
.split_last()
.ok_or_else(|| PlanError::Input(format!("`{name}`: no columns")))?;
let mut out = rest.to_vec();
out.push(crate::typed::hex_column(last)?);
Ok(out)
};
match source {
Source::Columns(columns) => Ok(Source::Columns(hex(columns)?)),
Source::ColumnsAt { columns, bases } => Ok(Source::ColumnsAt {
columns: hex(columns)?,
bases: bases.clone(),
}),
_ => Err(PlanError::Input(format!(
"`{name}`: `@hex` reads a property given as Arrow columns"
))),
}
}
/// `source`, the columns of a signed integer property (its value the last column), as the
/// rows whose value is neither null nor negative, the value unsigned: the same columns when
/// every row is kept and the value column is `Int32` or `Int64` (read in place), else the
/// kept rows of each column and the values as `UInt64`.
fn unsigned_rows(name: &str, source: &Source) -> Result<Source> {
use arrow_array::cast::AsArray;
use arrow_array::types::{Int8Type, Int16Type, Int32Type, Int64Type};
use arrow_array::{Array, ArrayRef, BooleanArray, UInt64Array};
use arrow_schema::DataType;
let columns = match source {
Source::Columns(columns) => columns,
Source::ColumnsAt { columns, .. } => columns,
_ => {
return Err(PlanError::Input(format!(
"`{name}`: `@u64` reads a property given as Arrow columns"
)));
}
};
let Some((last, rest)) = columns.split_last() else {
return Err(PlanError::Input(format!("`{name}`: no columns")));
};
let values: Vec<Option<i64>> = match last.data_type() {
DataType::Int8 => last
.as_primitive::<Int8Type>()
.iter()
.map(|x| x.map(i64::from))
.collect(),
DataType::Int16 => last
.as_primitive::<Int16Type>()
.iter()
.map(|x| x.map(i64::from))
.collect(),
DataType::Int32 => last
.as_primitive::<Int32Type>()
.iter()
.map(|x| x.map(i64::from))
.collect(),
DataType::Int64 => last.as_primitive::<Int64Type>().iter().collect(),
d => {
return Err(PlanError::Input(format!(
"`{name}`: `@u64` reads a signed integer column, not {d}"
)));
}
};
let keep: Vec<bool> = values.iter().map(|x| x.is_some_and(|x| x >= 0)).collect();
if keep.iter().all(|&k| k) && matches!(last.data_type(), DataType::Int32 | DataType::Int64) {
return Ok(source.clone());
}
let mask = BooleanArray::from(keep);
let mut out: Vec<ArrayRef> = rest
.iter()
.map(|c| datafusion::arrow::compute::filter(c.as_ref(), &mask))
.collect::<std::result::Result<_, _>>()?;
let kept: UInt64Array = values
.iter()
.filter_map(|x| x.filter(|&x| x >= 0).map(|x| x as u64))
.collect();
out.push(std::sync::Arc::new(kept));
debug_assert!(out.iter().all(|c| c.len() == out[0].len()));
Ok(match source {
Source::ColumnsAt { bases, .. } => Source::ColumnsAt {
columns: out,
bases: bases.clone(),
},
_ => Source::Columns(out),
})
}
/// Why a list property is refused where one value per node or edge is read.
const LIST_WHY: &str =
"a list: read by its name as rows (id, position, value), in GQL by `UNWIND n.key AS x`";
impl Catalog {
/// List property `key` of the nodes labelled `label`: `source` holds (id, position,
/// value) rows (three columns), one per element of a node's list, the position from 0,
/// the value of type `ty` (a null element null). A node whose list is empty or null has
/// no row. Read by name as relation `label.key` ([`Catalog::relation`]); a read of one
/// value per node (a GQL `n.key`) is refused by name.
pub fn list_property(&mut self, label: &str, key: &str, source: Source, ty: Type) -> &mut Self {
self.lists.insert((label.into(), key.into()), (source, ty));
self.refused_property(label, key, LIST_WHY)
}
/// [`Catalog::list_property`] of the edges labelled `label`: `source` holds (from, to,
/// position, value) rows (four columns), one per element of an edge's list.
pub fn list_edge_property(
&mut self,
label: &str,
key: &str,
source: Source,
ty: Type,
) -> &mut Self {
self.edge_lists
.insert((label.into(), key.into()), (source, ty));
self.refused_edge_property(label, key, LIST_WHY)
}
/// The (id, position, value) source of list property `key` of label `label`'s nodes
/// (its own, or the label's it holds some nodes of), and the elements' type.
pub fn list_prop(&self, label: &str, key: &str) -> Option<(&Source, Type)> {
let at = |l: &str| self.lists.get(&(l.to_string(), key.to_string()));
at(label)
.or_else(|| self.parents.get(label).and_then(|p| at(p)))
.map(|(s, t)| (s, *t))
}
/// The (from, to, position, value) source of list property `key` of edge label
/// `label`, and the elements' type.
pub fn list_edge_prop(&self, label: &str, key: &str) -> Option<(&Source, Type)> {
self.edge_lists
.get(&(label.to_string(), key.to_string()))
.map(|(s, t)| (s, *t))
}
/// [`Catalog::list_edge_property`] by the edges' rows: `source` holds (row, position,
/// value), the row of [`Catalog::edge_rows`], one per element of an edge's list (two
/// edges between the same nodes told apart); read by name as `label@row.key`.
pub fn list_edge_row_property(
&mut self,
label: &str,
key: &str,
source: Source,
ty: Type,
) -> &mut Self {
self.edge_row_lists
.insert((label.into(), key.into()), (source, ty));
self
}
/// The (row, position, value) source of list property `key` of edge label `label`
/// ([`Catalog::list_edge_row_property`]), and the elements' type.
pub fn list_edge_row_prop(&self, label: &str, key: &str) -> Option<(&Source, Type)> {
self.edge_row_lists
.get(&(label.to_string(), key.to_string()))
.map(|(s, t)| (s, *t))
}
/// The list relations named `label.key` ([`Catalog::relation`]), pushed onto `found`.
fn list_relations(&self, label: &str, key: &str, found: &mut Vec<(Source, Vec<Type>)>) {
if let Some((s, t)) = self.list_prop(label, key) {
found.push((s.clone(), vec![Type::U64, Type::U64, t]));
}
if let Some((s, t)) = self.list_edge_prop(label, key) {
found.push((s.clone(), vec![Type::U64, Type::U64, Type::U64, t]));
}
}
}
impl Plan {
/// An input relation named `name`, of the width and column types the catalog gives
/// that name ([`Catalog::relation`]); [`Inputs::bind`] gives it its source.
pub fn input_from(&mut self, catalog: &Catalog, name: &str) -> Result<RelId> {
let (_, types) = catalog.relation(name)?;
Ok(if types.iter().all(|&t| t == Type::U64) {
self.input(name, types.len())
} else {
self.input_typed(name, &types)
})
}
}
impl Inputs {
/// Give the relations of [`Plan::schema`] that have no source yet `catalog`'s schema
/// ([`Catalog::schema_rows`]); [`Inputs::bind`] does this first. A client that binds
/// its other inputs by hand (GQL) binds the schema's with this alone.
pub fn bind_schema(&mut self, plan: &Plan, catalog: &Catalog) -> Result<&mut Self> {
let Some(sc) = plan.schema_rels() else {
return Ok(self);
};
let rows = catalog.schema_rows();
for (rel, rows) in [sc.label, sc.edge, sc.column, sc.refused]
.into_iter()
.zip(rows)
{
if self.source(rel).is_none() {
let types = plan.types(rel);
self.datums(rel, &types, &rows, false)?;
}
}
Ok(self)
}
/// Give every input relation of `plan` that has no source yet and whose name `catalog`
/// has ([`Catalog::relation`]) that source, and the index the catalog has of it
/// ([`Inputs::index`]: a label's id block, a property's name or range index, the found
/// ids within the property's label); the relation's column types must be the
/// catalog's. An input of [`Plan::input_or_empty`] the catalog lacks is bound empty;
/// the relations of [`Plan::schema`] get the catalog's schema
/// ([`Catalog::schema_rows`]). Inputs the catalog does not name are left as they are
/// (given by hand).
pub fn bind(&mut self, plan: &Plan, catalog: &Catalog) -> Result<&mut Self> {
self.bind_schema(plan, catalog)?;
for (i, r) in plan.relations().iter().enumerate() {
let rel = RelId(i as u32);
if r.kind != RelKind::Input || self.source(rel).is_some() || plan.is_counted(rel) {
continue;
}
let found = if plan.is_optional(rel) {
if catalog.lacks(&r.name) {
let types = plan.types(rel);
self.datums(rel, &types, &[], false)?;
continue;
}
// a column the catalog refuses stays an error, by name, with why
Some(catalog.relation(&r.name)?)
} else {
catalog.relation(&r.name).ok()
};
let Some((source, types)) = found else {
continue;
};
let have = plan.types(rel);
if have != types {
return Err(PlanError::Input(format!(
"input `{}` has columns {have:?}, the catalog's are {types:?}",
r.name
)));
}
self.set(rel, source);
// and its index, for the index choice
if let Some(b) = catalog.block(&r.name) {
self.index(rel, crate::Index::Blocks(vec![b]));
} else if let Some((label, key)) = r.name.split_once('.') {
let within = Some(label.to_string());
if let Some(index) = catalog.name_idx(label, key) {
let index = index.clone();
self.index(rel, crate::Index::Names { index, within });
} else if let Some(lookup) = catalog.prop_idx(label, key) {
let lookup = lookup.clone();
self.index(rel, crate::Index::Range { lookup, within });
}
}
}
Ok(self)
}
}