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/entities.rs

//! Whole values read for a few ids: every property of some nodes and edges, and which labels
//! hold them, by one small plan over the ids asked alone ([`Engine::read_entities`]). A
//! query that returns whole nodes or edges (GQL's `RETURN n`) asks this after its own
//! ORDER BY / LIMIT cut the rows, so `RETURN n LIMIT 1` reads one node.

use std::collections::{BTreeSet, HashMap, HashSet};

use kleene_graph::GraphBackend;

use crate::rules::{Atom, Literal, Plan, RelId, Term, Var};
use crate::{Datum, Engine, Facts, Inputs, Result, Source, Type, Value};

/// The nodes of one label asked: their ids (as the label's source holds them), whether to
/// test that the label holds them, and its properties to read.
#[derive(Clone, Debug)]
pub struct NodeAsk {
    /// The label's name (for the plan's relation names).
    pub name: String,
    /// The label's nodes (one column); `None`: not tested, only properties read.
    pub members: Option<Source>,
    /// Its properties: (key, `(node, value)` source, value type).
    pub props: Vec<(String, Source, Type)>,
    /// The ids asked.
    pub ids: BTreeSet<Value>,
}

/// The edges of one label asked: the (from, to) pairs, its edges and its properties.
#[derive(Clone, Debug)]
pub struct EdgeAsk {
    /// The label's name.
    pub name: String,
    /// Its edges (two columns, or a graph).
    pub source: Source,
    /// Its properties: (key, `(from, to, value)` source, value type).
    pub props: Vec<(String, Source, Type)>,
    /// The pairs asked.
    pub pairs: BTreeSet<(Value, Value)>,
}

/// What [`Engine::read_entities`] found, by the asks' indices.
#[derive(Clone, Debug, Default)]
pub struct Entities {
    /// (node ask, id) where the label (with `members`) holds the id.
    pub member: HashSet<(usize, Value)>,
    /// (node ask, property index, id) to its value, where it has one.
    pub values: HashMap<(usize, usize, Value), Datum>,
    /// (edge ask, from, to) where the label has that edge.
    pub on: HashSet<(usize, Value, Value)>,
    /// (edge ask, property index, from, to) to its value; of several edges between one pair,
    /// the least (by the type's order, a null last).
    pub edge_values: HashMap<(usize, usize, Value, Value), Datum>,
}

impl Entities {
    /// The value of node ask `ask`'s property `prop` at `id`, null where none.
    pub fn value(&self, ask: usize, prop: usize, id: Value) -> Datum {
        self.values
            .get(&(ask, prop, id))
            .cloned()
            .unwrap_or(Datum::Null)
    }

    /// The value of edge ask `ask`'s property `prop` on (`from`, `to`), null where none.
    pub fn edge_value(&self, ask: usize, prop: usize, from: Value, to: Value) -> Datum {
        self.edge_values
            .get(&(ask, prop, from, to))
            .cloned()
            .unwrap_or(Datum::Null)
    }
}

/// An input relation of `source`: an external one answers lookups by the values the
/// `want` atom binds.
fn declare(
    plan: &mut Plan,
    inputs: &mut Inputs,
    name: &str,
    types: &[Type],
    source: &Source,
) -> RelId {
    let r = match source {
        Source::External(_) => plan.external_typed(name, types),
        _ => plan.input_typed(name, types),
    };
    inputs.set(r, source.clone());
    r
}

fn pos(rel: RelId, vars: &[Var]) -> Literal {
    Literal::Pos(head(rel, vars))
}

fn head(rel: RelId, vars: &[Var]) -> Atom {
    Atom {
        rel,
        terms: vars.iter().map(|&v| Term::Var(v)).collect(),
    }
}

impl<B: GraphBackend> Engine<B> {
    /// Read the whole values asked: per node ask, its membership (where tested) and
    /// properties of the ids asked; per edge ask, which pairs are edges and their
    /// properties. One plan of a `want` relation per ask joined with each source, so only
    /// the ids asked are read (an external source is asked by them).
    pub async fn read_entities(&self, nodes: &[NodeAsk], edges: &[EdgeAsk]) -> Result<Entities> {
        let mut plan = Plan::new();
        let mut inputs = Inputs::new();
        let (n, a, b, v) = (plan.var("N"), plan.var("A"), plan.var("B"), plan.var("V"));
        let mut has_rel: Vec<(usize, RelId)> = Vec::new();
        let mut prop_rel: Vec<(usize, usize, Type, RelId)> = Vec::new();
        for (i, ask) in nodes.iter().enumerate().filter(|x| !x.1.ids.is_empty()) {
            let want = plan.input(&format!("want node {}", ask.name), 1);
            inputs.facts(want, Facts::from_rows(1, ask.ids.iter().map(|&x| [x]))?);
            if let Some(members) = &ask.members {
                let name = format!("node {}", ask.name);
                let src = declare(&mut plan, &mut inputs, &name, &[Type::U64], members);
                let has = plan.derived(&format!("has {}", ask.name), 1);
                plan.rule(head(has, &[n]), [pos(want, &[n]), pos(src, &[n])])?;
                has_rel.push((i, has));
            }
            for (k, (key, source, ty)) in ask.props.iter().enumerate() {
                let name = format!("node {}.{key}", ask.name);
                let src = declare(&mut plan, &mut inputs, &name, &[Type::U64, *ty], source);
                let p = plan.derived_typed(&format!("whole {name}"), &[Type::U64, *ty]);
                plan.rule(head(p, &[n, v]), [pos(want, &[n]), pos(src, &[n, v])])?;
                prop_rel.push((i, k, *ty, p));
            }
        }
        let mut pair_rel: Vec<(usize, RelId)> = Vec::new();
        let mut eprop_rel: Vec<(usize, usize, Type, RelId)> = Vec::new();
        for (i, ask) in edges.iter().enumerate().filter(|x| !x.1.pairs.is_empty()) {
            let want = plan.input(&format!("want edge {}", ask.name), 2);
            inputs.facts(
                want,
                Facts::from_rows(2, ask.pairs.iter().map(|&(x, y)| [x, y]))?,
            );
            let name = format!("edge {}", ask.name);
            let src = declare(&mut plan, &mut inputs, &name, &[Type::U64; 2], &ask.source);
            let has = plan.derived(&format!("has {}", ask.name), 2);
            plan.rule(head(has, &[a, b]), [pos(want, &[a, b]), pos(src, &[a, b])])?;
            pair_rel.push((i, has));
            for (k, (key, source, ty)) in ask.props.iter().enumerate() {
                let name = format!("edge {}.{key}", ask.name);
                let types = [Type::U64, Type::U64, *ty];
                let src = declare(&mut plan, &mut inputs, &name, &types, source);
                let p = plan.derived_typed(&format!("whole {name}"), &types);
                plan.rule(
                    head(p, &[a, b, v]),
                    [pos(want, &[a, b]), pos(src, &[a, b, v])],
                )?;
                eprop_rel.push((i, k, *ty, p));
            }
        }
        let mut got = Entities::default();
        if has_rel.is_empty() && prop_rel.is_empty() && pair_rel.is_empty() {
            return Ok(got);
        }
        let out = self.run(&plan, &inputs).await?;
        let rows_of = |rel: RelId| -> Vec<Vec<Value>> {
            out.get(rel)
                .map(|f| f.rows().map(|r| r.to_vec()).collect())
                .unwrap_or_default()
        };
        for (i, rel) in has_rel {
            got.member
                .extend(rows_of(rel).into_iter().map(|r| (i, r[0])));
        }
        for (i, k, ty, rel) in prop_rel {
            for r in rows_of(rel) {
                got.values
                    .entry((i, k, r[0]))
                    .or_insert_with(|| ty.decode(r[1], out.dict()));
            }
        }
        for (i, rel) in pair_rel {
            got.on
                .extend(rows_of(rel).into_iter().map(|r| (i, r[0], r[1])));
        }
        // the least code of several edges between one pair (codes keep the order; the null
        // code is the largest)
        let mut least: HashMap<(usize, usize, Value, Value), (Value, Type)> = HashMap::new();
        for (i, k, ty, rel) in eprop_rel {
            for r in rows_of(rel) {
                let x = least.entry((i, k, r[0], r[1])).or_insert((r[2], ty));
                x.0 = x.0.min(r[2]);
            }
        }
        got.edge_values = least
            .into_iter()
            .map(|(key, (code, ty))| (key, ty.decode(code, out.dict())))
            .collect();
        Ok(got)
    }
}