use std::cell::{Cell, RefCell};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::thread::LocalKey;
use relate_core::tokens::{workspace_meter, LedgerGuard, TokenLedger};
use relate_core::{Result, Value};
use relate_front::parse_and_lower;
use relate_ir::Query;
use relate_planner::{plan, plan_with_tokens, LogicalPlan, NoPatternStats};
use crate::graph::Graph;
use crate::metrics::{ClauseMetricsRecord, PlanMetricsSink, StatementMemoRecord};
use crate::overlay::ExecGraph;
use crate::pattern_engine::PatternEngine;
use crate::test_support::PeakPoolDouble;
use super::super::{execute, execute_read_at, ExecRequest, QueryResult, ReadAdmission};
pub(crate) fn clauses_of(cypher: &str) -> Vec<relate_ir::Clause> {
let q = parse_and_lower(cypher).unwrap();
q.parts.into_iter().flat_map(|p| p.clauses).collect()
}
pub(crate) fn exec_lowered(g: &Graph, q: Query, cypher: &str) -> QueryResult {
try_exec_lowered(g, q, cypher, &BTreeMap::new()).unwrap()
}
fn try_exec_lowered(
g: &Graph,
q: Query,
cypher: &str,
params: &BTreeMap<String, Value>,
) -> Result<QueryResult> {
run_planned(g, &plan(q, &mut |_| false)?, cypher, params, None)
}
pub(crate) fn run_planned(
g: &Graph,
p: &LogicalPlan,
cypher: &str,
params: &BTreeMap<String, Value>,
plan_metrics: Option<&dyn PlanMetricsSink>,
) -> Result<QueryResult> {
let pin = g.pin_now()?;
let schema = g.schema_snapshot();
let mut request = ExecRequest::new(p, params, cypher);
request.plan_metrics = plan_metrics;
execute_read_at(&ReadAdmission {
graph: g,
snapshot_ts: pin.ts(),
schema: &schema,
request,
cancel: None,
ontology_document: None,
})
}
pub(crate) fn exec_cypher(g: &Graph, cypher: &str) -> QueryResult {
exec_lowered(g, parse_and_lower(cypher).unwrap(), cypher)
}
pub(crate) fn exec_cypher_resolved(g: &Graph, cypher: &str) -> QueryResult {
let planned = plan_with_tokens(
parse_and_lower(cypher).unwrap(),
&mut |_| false,
&NoPatternStats,
g,
)
.unwrap();
run_planned(g, &planned, cypher, &BTreeMap::new(), None).unwrap()
}
pub(crate) fn try_exec_cypher(g: &Graph, cypher: &str) -> Result<QueryResult> {
try_exec_cypher_params(g, cypher, &BTreeMap::new())
}
pub(crate) fn try_exec_cypher_params(
g: &Graph,
cypher: &str,
params: &BTreeMap<String, Value>,
) -> Result<QueryResult> {
try_exec_lowered(g, parse_and_lower(cypher)?, cypher, params)
}
pub(crate) fn error_of(result: Result<QueryResult>) -> String {
match result {
Err(err) => err.to_string(),
Ok(done) => panic!(
"the query errors, but it returned a result: {:?}",
done.rows
),
}
}
pub(crate) fn with_flag_disabled<R>(
flag: &'static LocalKey<Cell<bool>>,
f: impl FnOnce() -> R,
) -> R {
struct Restore {
flag: &'static LocalKey<Cell<bool>>,
}
impl Drop for Restore {
fn drop(&mut self) {
self.flag.with(|cell| cell.set(false));
}
}
flag.with(|cell| cell.set(true));
let _restore = Restore { flag };
f()
}
fn run_cypher_with(
g: &Graph,
cypher: &str,
params: &BTreeMap<String, Value>,
sink: Option<&dyn PlanMetricsSink>,
) -> QueryResult {
let planned = plan(parse_and_lower(cypher).unwrap(), &mut |_| false).unwrap();
run_planned(g, &planned, cypher, params, sink).unwrap()
}
pub(crate) fn profiled(g: &Graph, cypher: &str) -> Vec<ClauseMetricsRecord> {
profiled_params(g, cypher, &BTreeMap::new())
}
pub(crate) fn profiled_params(
g: &Graph,
cypher: &str,
params: &BTreeMap<String, Value>,
) -> Vec<ClauseMetricsRecord> {
let recorder = super::ClauseRecords(RefCell::new(Vec::new()));
run_cypher_with(g, cypher, params, Some(&recorder));
recorder.0.take()
}
struct MemoSink {
clauses: RefCell<Vec<ClauseMetricsRecord>>,
statement: Cell<StatementMemoRecord>,
}
impl PlanMetricsSink for MemoSink {
fn record_clause(&self, record: ClauseMetricsRecord) {
self.clauses.borrow_mut().push(record);
}
fn record_statement_memos(&self, record: StatementMemoRecord) {
self.statement.set(record);
}
}
pub(crate) fn profiled_memos(
g: &Graph,
cypher: &str,
) -> (
Vec<Vec<Value>>,
Vec<ClauseMetricsRecord>,
StatementMemoRecord,
) {
let sink = MemoSink {
clauses: RefCell::new(Vec::new()),
statement: Cell::new(StatementMemoRecord::default()),
};
let result = run_cypher_with(g, cypher, &BTreeMap::new(), Some(&sink));
(result.rows, sink.clauses.take(), sink.statement.get())
}
fn run_metered_with(
g: &Graph,
cypher: &str,
sink: Option<&dyn PlanMetricsSink>,
) -> (QueryResult, u64) {
let pool = Arc::new(PeakPoolDouble::new(u64::MAX / 4));
assert!(relate_core::tokens::PeakPool::try_grow(pool.as_ref(), 1));
let mut ledger = TokenLedger::new(u64::MAX / 4, 1, pool);
let _guard = LedgerGuard::install(&mut ledger);
let result = run_cypher_with(g, cypher, &BTreeMap::new(), sink);
let (_, peak, _) = workspace_meter().expect("ledger installed");
(result, peak)
}
pub(crate) fn profiled_metered(g: &Graph, cypher: &str) -> (Vec<Vec<Value>>, u64) {
let recorder = super::ClauseRecords(RefCell::new(Vec::new()));
let (result, peak) = run_metered_with(g, cypher, Some(&recorder));
(result.rows, peak)
}
pub(crate) fn exec_cypher_on(graph: &ExecGraph<'_>, cypher: &str) -> QueryResult {
try_exec_cypher_on(graph, cypher).unwrap()
}
pub(crate) fn try_exec_cypher_on(graph: &ExecGraph<'_>, cypher: &str) -> Result<QueryResult> {
let p = plan(parse_and_lower(cypher)?, &mut |_| false)?;
execute(graph, &ExecRequest::new(&p, &BTreeMap::new(), cypher))
}
pub(crate) fn sort_rows(rows: &mut [Vec<Value>]) {
rows.sort_by_cached_key(|row| format!("{row:?}"));
}
pub(crate) fn with_n_stage(cypher: &str) -> String {
let scan = cypher.replacen(") RETURN", ") WITH n RETURN", 1);
assert_ne!(scan, cypher, "the oracle rewrite must apply: {cypher}");
scan
}
pub(crate) fn same_rows(a: &QueryResult, b: &QueryResult) -> bool {
if a.columns != b.columns {
return false;
}
let mut a = a.rows.clone();
let mut b = b.rows.clone();
sort_rows(&mut a);
sort_rows(&mut b);
a == b
}
pub(crate) fn written(matched: &str, rest: &str) -> String {
format!("{matched} {rest}")
}
pub(crate) fn written_and_held(matched: &str, rest: &str) -> (String, String) {
(written(matched, rest), format!("{matched} WITH * {rest}"))
}
pub(crate) fn walk_only(mut graph: Graph) -> Graph {
graph.configure_pattern_engine(PatternEngine::Walk);
graph
}
pub(crate) fn assert_written_agrees_with_held(
fixture: impl Fn() -> Graph,
side: &str,
written: &str,
expected: &str,
) -> QueryResult {
let auto = fixture();
let walk = walk_only(fixture());
let oracle = exec_cypher(&auto, expected);
let got = exec_cypher(&auto, written);
assert!(same_rows(&got, &oracle), "{written}: {side} vs expected");
let walked = exec_cypher(&walk, written);
assert!(same_rows(&walked, &oracle), "{written}: walk vs expected");
oracle
}
pub(crate) fn assert_agrees_with_held(
fixture: impl Fn() -> Graph,
side: &str,
written: &str,
expected: &str,
) {
let oracle = assert_written_agrees_with_held(fixture, side, written, expected);
assert!(!oracle.rows.is_empty(), "{written}: the fixture matches");
}
pub(crate) fn run_metered(g: &Graph, cypher: &str) -> (Vec<Vec<Value>>, u64) {
let (result, peak) = run_metered_with(g, cypher, None);
(result.rows, peak)
}
pub(crate) fn record_for(records: &[ClauseMetricsRecord], clause: usize) -> &ClauseMetricsRecord {
records
.iter()
.find(|record| record.clause == clause)
.unwrap_or_else(|| panic!("a record for clause {clause} of {}", records.len()))
}
pub(crate) fn served(records: &[ClauseMetricsRecord]) -> &ClauseMetricsRecord {
records
.iter()
.find(|record| record.kernel.is_some())
.unwrap_or_else(|| panic!("a rung served the MATCH clause ({} records)", records.len()))
}