use relate_model::{CypherValue, IndexMap, VectorCoordKind};
use crate::convert::temporal_to_cypher;
use crate::value::{next_depth, Node, Relationship, Value};
use crate::Error;
pub const MAX_PLAN_WIRE_DEPTH: u32 = 1_000;
#[derive(Clone, Copy)]
pub(crate) enum DepthPolicy {
Data,
Plan,
}
enum Level {
Deeper,
Saturates,
OverBudget(u32),
}
impl DepthPolicy {
fn admit(self, enclosing: u32) -> Level {
match self {
DepthPolicy::Data => match next_depth(enclosing) {
Some(_) => Level::Deeper,
None => Level::Saturates,
},
DepthPolicy::Plan => {
if enclosing < MAX_PLAN_WIRE_DEPTH {
Level::Deeper
} else {
Level::OverBudget(enclosing + 1)
}
}
}
}
}
fn plan_budget_exceeded(at: u32) -> Error {
Error::capacity_plan_wire(u64::from(at), u64::from(MAX_PLAN_WIRE_DEPTH))
}
enum Input<'a> {
Value(&'a Value),
Node(&'a Node),
Rel(&'a Relationship),
}
enum PathElement {
Node,
Rel,
}
enum Frame<'a> {
List {
items: std::slice::Iter<'a, Value>,
child_depth: u32,
out: Vec<CypherValue>,
},
Map {
entries: std::collections::btree_map::Iter<'a, String, Value>,
pending: Option<String>,
child_depth: u32,
out: IndexMap<String, CypherValue>,
},
Vector {
coord: VectorCoordKind,
values: std::slice::Iter<'a, Value>,
child_depth: u32,
out: Vec<CypherValue>,
},
Node {
node: &'a Node,
entries: std::slice::Iter<'a, (String, Value)>,
pending: Option<String>,
child_depth: u32,
out: IndexMap<String, CypherValue>,
},
Rel {
rel: &'a Relationship,
entries: std::slice::Iter<'a, (String, Value)>,
pending: Option<String>,
child_depth: u32,
out: IndexMap<String, CypherValue>,
},
Path {
nodes: std::slice::Iter<'a, Node>,
rels: std::slice::Iter<'a, Relationship>,
pending: Option<PathElement>,
child_depth: u32,
nodes_out: Vec<CypherValue>,
rels_out: Vec<CypherValue>,
},
}
impl<'a> Frame<'a> {
fn child_depth(&self) -> u32 {
match self {
Frame::List { child_depth, .. }
| Frame::Map { child_depth, .. }
| Frame::Vector { child_depth, .. }
| Frame::Node { child_depth, .. }
| Frame::Rel { child_depth, .. }
| Frame::Path { child_depth, .. } => *child_depth,
}
}
fn next_child(&mut self) -> Option<Input<'a>> {
match self {
Frame::List { items, .. } => items.next().map(Input::Value),
Frame::Vector { values, .. } => values.next().map(Input::Value),
Frame::Map {
entries, pending, ..
} => {
let (key, value) = entries.next()?;
*pending = Some(key.clone());
Some(Input::Value(value))
}
Frame::Node {
entries, pending, ..
}
| Frame::Rel {
entries, pending, ..
} => {
let (key, value) = entries.next()?;
*pending = Some(key.clone());
Some(Input::Value(value))
}
Frame::Path {
nodes,
rels,
pending,
..
} => {
if let Some(node) = nodes.next() {
*pending = Some(PathElement::Node);
Some(Input::Node(node))
} else if let Some(rel) = rels.next() {
*pending = Some(PathElement::Rel);
Some(Input::Rel(rel))
} else {
None
}
}
}
}
fn place(&mut self, done: CypherValue) {
match self {
Frame::List { out, .. } | Frame::Vector { out, .. } => out.push(done),
Frame::Map { pending, out, .. }
| Frame::Node { pending, out, .. }
| Frame::Rel { pending, out, .. } => {
let key = pending
.take()
.expect("a placed value follows the child its key was stashed for");
out.insert(key, done);
}
Frame::Path {
pending,
nodes_out,
rels_out,
..
} => match pending
.take()
.expect("a placed value follows the element its kind was stashed for")
{
PathElement::Node => nodes_out.push(done),
PathElement::Rel => rels_out.push(done),
},
}
}
fn close(self) -> CypherValue {
match self {
Frame::List { out, .. } => CypherValue::List(out),
Frame::Map { out, .. } => CypherValue::Map(out),
Frame::Vector { coord, out, .. } => CypherValue::Vector {
coord,
dim: out.len(),
values: out,
},
Frame::Node { node, out, .. } => CypherValue::Node {
id: node.id,
labels: (*node.labels).clone(),
properties: out,
},
Frame::Rel { rel, out, .. } => CypherValue::Relationship {
id: rel.id,
start_id: rel.start,
end_id: rel.end,
rel_type: rel.rel_type.clone(),
properties: out,
},
Frame::Path {
nodes_out,
rels_out,
..
} => CypherValue::Path {
nodes: nodes_out,
relationships: rels_out,
},
}
}
}
pub(crate) fn value_to_cypher_walk(
root: &Value,
policy: DepthPolicy,
) -> crate::Result<CypherValue> {
fn deliver(stack: &mut Vec<Frame<'_>>, done: CypherValue) -> Option<CypherValue> {
match stack.last_mut() {
Some(parent) => {
parent.place(done);
None
}
None => Some(done),
}
}
fn admit_or<'a>(
stack: &mut Vec<Frame<'a>>,
policy: DepthPolicy,
enclosing: u32,
open: impl FnOnce() -> Frame<'a>,
) -> crate::Result<()> {
match policy.admit(enclosing) {
Level::Deeper => stack.push(open()),
Level::Saturates => stack
.last_mut()
.expect("a refused container always has a parent frame")
.place(CypherValue::Null),
Level::OverBudget(at) => return Err(plan_budget_exceeded(at)),
}
Ok(())
}
let mut stack: Vec<Frame<'_>> = Vec::new();
let mut current: Option<Input<'_>> = Some(Input::Value(root));
loop {
let input = current
.take()
.or_else(|| stack.last_mut().and_then(Frame::next_child));
let Some(input) = input else {
let frame = stack
.pop()
.expect("the walk always has an input or an open frame");
let closed = frame.close();
if let Some(finished) = deliver(&mut stack, closed) {
return Ok(finished);
}
continue;
};
let enclosing = stack.last().map_or(0, Frame::child_depth);
let done: Option<CypherValue> = match input {
Input::Value(Value::Null) => Some(CypherValue::Null),
Input::Value(Value::Bool(b)) => Some(CypherValue::Bool(*b)),
Input::Value(Value::Int(i)) => Some(CypherValue::Int(*i)),
Input::Value(Value::Float(f)) => Some(CypherValue::Float(*f)),
Input::Value(Value::String(s)) => Some(CypherValue::Str(String::from(&**s))),
Input::Value(Value::Uuid(u)) => {
Some(CypherValue::Str(crate::value::uuid_hyphenated(*u)))
}
Input::Value(Value::Bytes(b)) => Some(CypherValue::List(
b.iter().map(|&x| CypherValue::Int(x.into())).collect(),
)),
Input::Value(Value::Point(p)) => Some(CypherValue::Point(p.clone())),
Input::Value(Value::Temporal(t)) => Some(temporal_to_cypher(t)),
Input::Value(Value::List(xs)) => {
admit_or(&mut stack, policy, enclosing, || Frame::List {
items: xs.iter(),
child_depth: enclosing + 1,
out: Vec::with_capacity(xs.len()),
})?;
None
}
Input::Value(Value::Map(m)) => {
admit_or(&mut stack, policy, enclosing, || Frame::Map {
entries: m.iter(),
pending: None,
child_depth: enclosing + 1,
out: IndexMap::with_capacity(m.len()),
})?;
None
}
Input::Value(Value::Vector { coord, values }) => {
admit_or(&mut stack, policy, enclosing, || Frame::Vector {
coord: *coord,
values: values.iter(),
child_depth: enclosing + 1,
out: Vec::with_capacity(values.len()),
})?;
None
}
Input::Value(Value::Node(n)) => {
admit_or(&mut stack, policy, enclosing, || Frame::Node {
node: n,
entries: n.properties.entries().iter(),
pending: None,
child_depth: enclosing + 1,
out: IndexMap::with_capacity(n.properties.entries().len()),
})?;
None
}
Input::Value(Value::Relationship(r)) => {
admit_or(&mut stack, policy, enclosing, || Frame::Rel {
rel: r,
entries: r.properties.entries().iter(),
pending: None,
child_depth: enclosing + 1,
out: IndexMap::with_capacity(r.properties.entries().len()),
})?;
None
}
Input::Value(Value::Path(p)) => {
admit_or(&mut stack, policy, enclosing, || Frame::Path {
nodes: p.nodes.iter(),
rels: p.rels.iter(),
pending: None,
child_depth: enclosing,
nodes_out: Vec::new(),
rels_out: Vec::new(),
})?;
None
}
Input::Node(n) => {
admit_or(&mut stack, policy, enclosing, || Frame::Node {
node: n,
entries: n.properties.entries().iter(),
pending: None,
child_depth: enclosing + 1,
out: IndexMap::with_capacity(n.properties.entries().len()),
})?;
None
}
Input::Rel(r) => {
admit_or(&mut stack, policy, enclosing, || Frame::Rel {
rel: r,
entries: r.properties.entries().iter(),
pending: None,
child_depth: enclosing + 1,
out: IndexMap::with_capacity(r.properties.entries().len()),
})?;
None
}
};
if let Some(done) = done {
if let Some(finished) = deliver(&mut stack, done) {
return Ok(finished);
}
}
}
}