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, NoPatternStats};
use crate::graph::Graph;
use crate::metrics::{ClauseMetricsRecord, PlanMetricsSink};
use crate::overlay::ExecGraph;
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> {
try_exec_lowered_with_metrics(g, q, cypher, params, None, false)
}
fn try_exec_lowered_with_metrics(
g: &Graph,
q: Query,
cypher: &str,
params: &BTreeMap<String, Value>,
plan_metrics: Option<&dyn PlanMetricsSink>,
resolve_tokens: bool,
) -> Result<QueryResult> {
let p = if resolve_tokens {
plan_with_tokens(q, &mut |_| false, &NoPatternStats, g)?
} else {
plan(q, &mut |_| false)?
};
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 {
try_exec_lowered_with_metrics(
g,
parse_and_lower(cypher).unwrap(),
cypher,
&BTreeMap::new(),
None,
true,
)
.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()
}
pub(crate) fn profiled(g: &Graph, cypher: &str) -> Vec<ClauseMetricsRecord> {
struct Recorder(RefCell<Vec<ClauseMetricsRecord>>);
impl PlanMetricsSink for Recorder {
fn record_clause(&self, record: ClauseMetricsRecord) {
self.0.borrow_mut().push(record);
}
}
let recorder = Recorder(RefCell::new(Vec::new()));
try_exec_lowered_with_metrics(
g,
parse_and_lower(cypher).unwrap(),
cypher,
&BTreeMap::new(),
Some(&recorder),
false,
)
.unwrap();
recorder.0.take()
}
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 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 run_metered(g: &Graph, cypher: &str) -> (Vec<Vec<Value>>, 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 rows = exec_cypher(g, cypher).rows;
let (_, peak, _) = workspace_meter().expect("ledger installed");
(rows, peak)
}
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()))
}