use std::cell::RefCell;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use relate_core::Result;
use relate_front::parse_and_lower;
use relate_planner::{plan, plan_with_tokens, NoPatternStats};
use crate::graph::Graph;
use crate::overlay::{ExecGraph, WriteScratch};
use crate::redo::RedoOp;
use super::super::{execute, execute_unvalidated, ExecRequest, QueryResult};
pub(crate) fn write_scratch_at(g: &Graph, ts: u64) -> RefCell<WriteScratch> {
RefCell::new(WriteScratch::new(
ts,
Arc::new(AtomicU64::new(g.next_node_id() as u64)),
Arc::new(AtomicU64::new(g.next_rel_id() as u64)),
))
}
pub(crate) fn write_scratch(g: &Graph) -> RefCell<WriteScratch> {
write_scratch_at(g, g.commit_ts())
}
pub(crate) fn exec_write(
g: &Graph,
scratch: &RefCell<WriteScratch>,
cypher: &str,
) -> Result<QueryResult> {
run_write(g, scratch, cypher, execute)
}
pub(crate) fn exec_write_batched(
g: &Graph,
scratch: &RefCell<WriteScratch>,
cypher: &str,
sink: &dyn crate::ctx::BatchCommit,
) -> Result<QueryResult> {
let q = parse_and_lower(cypher)?;
let p = plan_with_tokens(q, &mut |_| false, &NoPatternStats, g)?;
let params = BTreeMap::new();
let mut request = ExecRequest::new(&p, ¶ms, cypher);
request.batch_commit = Some(sink);
execute(&ExecGraph::write(g, scratch), &request)
}
pub(crate) fn exec_write_unvalidated(
g: &Graph,
scratch: &RefCell<WriteScratch>,
cypher: &str,
) -> Result<QueryResult> {
run_write(g, scratch, cypher, execute_unvalidated)
}
pub(crate) fn exec_autocommit(g: &Graph, cypher: &str) -> Result<QueryResult> {
let scratch = write_scratch(g);
let result = exec_write(g, &scratch, cypher)?;
commit_scratch(g, scratch);
Ok(result)
}
pub(crate) fn exec_write_uncommitted(g: &Graph, cypher: &str) -> QueryResult {
exec_write(g, &write_scratch(g), cypher).unwrap()
}
fn run_write(
g: &Graph,
scratch: &RefCell<WriteScratch>,
cypher: &str,
run: fn(&ExecGraph<'_>, &ExecRequest<'_>) -> Result<QueryResult>,
) -> Result<QueryResult> {
let p = plan(parse_and_lower(cypher)?, &mut |_| false)?;
run(
&ExecGraph::write(g, scratch),
&ExecRequest::new(&p, &BTreeMap::new(), cypher),
)
}
pub(crate) fn commit_scratch(g: &Graph, scratch: RefCell<WriteScratch>) {
let ops = scratch.into_inner().take_redo();
if !ops.is_empty() {
g.apply_redo(ops, g.commit_ts() + 1).unwrap();
}
}
pub(crate) struct ApplySink<'a> {
pub(crate) graph: &'a Graph,
pub(crate) calls: AtomicUsize,
}
impl crate::ctx::BatchCommit for ApplySink<'_> {
fn commit_batch(&self, ops: Vec<RedoOp>, _snapshot_ts: u64) -> Result<u64> {
self.calls.fetch_add(1, Ordering::Relaxed);
let commit_ts = self.graph.commit_ts() + 1;
self.graph.apply_redo(ops, commit_ts)?;
Ok(commit_ts)
}
}