use std::collections::{BTreeMap, BTreeSet};
use relate_core::{Error, Result, Value};
use crate::graph::Procedure;
use crate::overlay::ExecGraph;
use crate::procedure_registry::ProcSignature;
mod dbms;
mod graph_counts;
mod schema;
mod stats;
#[cfg(test)]
mod test_helpers;
use schema::{schema_node_type_rows, schema_rel_type_rows, schema_visualization_rows};
pub(crate) fn executable_signature(name: &str) -> Option<&'static ProcSignature> {
crate::procedure_registry::builtin_procedure_signature(name)
.filter(|signature| signature.executable)
}
pub(crate) fn procedure_metadata(signature: &ProcSignature) -> Procedure {
Procedure {
name: signature.name.into(),
arg_names: signature
.args
.iter()
.map(|arg| arg.name.to_string())
.collect(),
arg_types: signature
.args
.iter()
.map(|arg| arg.type_str.to_string())
.collect(),
yield_names: signature
.returns
.iter()
.map(|ret| ret.name.to_string())
.collect(),
rows: Vec::new(),
}
}
pub(crate) fn compat_rewrite_bypassed(name: &str) -> Error {
Error::internal(format!(
"compat procedure '{name}' is re-implemented as a Cypher body and is \
rewritten by the query front-end; a call reaching the executor means \
the front-end injection was bypassed"
))
}
pub(crate) fn builtin_procedure_rows(
graph: &ExecGraph<'_>,
signature: &'static ProcSignature,
principal: Option<&str>,
args: &BTreeMap<String, Value>,
) -> Result<Vec<BTreeMap<String, Value>>> {
if relate_front::compat_callables::is_compat_callable(signature.name) {
return Err(compat_rewrite_bypassed(signature.name));
}
if signature.is_void() {
return Ok(Vec::new());
}
let producer = signature.rows.ok_or_else(|| {
Error::internal(format!(
"builtin procedure '{}' declares return columns but has no row producer",
signature.name
))
})?;
producer.produce(graph, principal, args)
}
impl crate::procedure_registry::RowProducer {
fn produce(
self,
graph: &ExecGraph<'_>,
principal: Option<&str>,
args: &BTreeMap<String, Value>,
) -> Result<Vec<BTreeMap<String, Value>>> {
let rows = match self {
Self::TxGetMetaData => tx_get_metadata_rows(),
Self::DbmsComponents => dbms::dbms_components_rows(),
Self::DbPing => ping_rows(),
Self::DbLabels => label_rows(graph),
Self::DbRelationshipTypes => relationship_type_rows(graph),
Self::DbPropertyKeys => property_key_rows(graph),
Self::DbInfo => dbms::db_info_rows(graph),
Self::DbmsInfo => dbms::dbms_info_rows(),
Self::DbmsShowCurrentUser => dbms::dbms_show_current_user_rows(principal),
Self::DbmsConfig => dbms::dbms_config_rows(),
Self::DbmsLicenseAgreementDetails => dbms::dbms_license_agreement_rows(),
Self::DbmsListCapabilities => dbms::dbms_list_capabilities_rows(graph),
Self::FulltextAnalyzers => fulltext_analyzer_rows(),
Self::DbStatsRetrieve => stats::stats_retrieve_rows(
graph,
args.get("section")
.expect("db.stats.retrieve binds its required section before its rows")
.as_string(),
)?,
Self::SchemaNodeTypeProperties => schema_node_type_rows(graph),
Self::SchemaRelTypeProperties => schema_rel_type_rows(graph),
Self::SchemaVisualization => schema_visualization_rows(graph, args.get("options")),
};
Ok(rows)
}
}
fn tx_get_metadata_rows() -> Vec<BTreeMap<String, Value>> {
vec![BTreeMap::from([(
"metadata".into(),
Value::Map(BTreeMap::from([("source".into(), Value::String("cip230".into()))]).into()),
)])]
}
fn distinct_string_rows(
values: impl IntoIterator<Item = String>,
column: &str,
) -> Vec<BTreeMap<String, Value>> {
values
.into_iter()
.collect::<BTreeSet<_>>()
.into_iter()
.map(|value| BTreeMap::from([(column.into(), Value::String(value.into()))]))
.collect()
}
fn ping_rows() -> Vec<BTreeMap<String, Value>> {
vec![BTreeMap::from([("success".into(), Value::Bool(true))])]
}
fn fulltext_analyzer_rows() -> Vec<BTreeMap<String, Value>> {
crate::exec::fulltext::analyzer_catalog()
.map(|entry| {
BTreeMap::from([
("analyzer".to_string(), Value::String(entry.name.into())),
(
"description".to_string(),
Value::String(entry.description.into()),
),
(
"stopwords".to_string(),
crate::exec::catalog::string_list(
entry.stopwords.iter().map(|word| word.to_string()),
),
),
])
})
.collect()
}
fn label_rows(graph: &ExecGraph<'_>) -> Vec<BTreeMap<String, Value>> {
if let Some(names) = graph
.base()
.windowed_label_names(|| graph.sees_exact_base_stats())
{
return distinct_string_rows(names, "label");
}
let labels = graph
.all_node_ids()
.into_iter()
.flat_map(|id| graph.node_labels(id).unwrap_or_default());
distinct_string_rows(labels, "label")
}
fn relationship_type_rows(graph: &ExecGraph<'_>) -> Vec<BTreeMap<String, Value>> {
if let Some(names) = graph
.base()
.windowed_rel_type_names(|| graph.sees_exact_base_stats())
{
return distinct_string_rows(names, "relationshipType");
}
let types = graph
.all_rel_ids()
.into_iter()
.filter_map(|id| graph.rel_type(id));
distinct_string_rows(types, "relationshipType")
}
fn property_key_rows(graph: &ExecGraph<'_>) -> Vec<BTreeMap<String, Value>> {
let node_keys = graph
.all_node_ids()
.into_iter()
.flat_map(|id| graph.node_prop_keys(id));
let rel_keys = graph
.all_rel_ids()
.into_iter()
.flat_map(|id| graph.rel_prop_keys(id));
distinct_string_rows(node_keys.chain(rel_keys), "propertyKey")
}
#[cfg(test)]
mod tests {
use super::test_helpers::{rows, string};
use super::*;
use crate::graph::Graph;
#[test]
fn a_void_call_type_checks_its_arguments() {
let graph = Graph::default();
for query in [
"CALL db.awaitIndexes('not-an-int')",
"CALL tx.setMetaData(1)",
] {
let error = crate::exec::test_support::error_of(
crate::exec::test_support::try_exec_cypher(&graph, query),
);
assert!(error.contains("InvalidArgumentType"), "{query}: {error}");
}
}
#[test]
fn a_null_stats_section_is_a_typed_rejection() {
let graph = Graph::default();
let error = crate::exec::test_support::error_of(
crate::exec::test_support::try_exec_cypher(&graph, "CALL db.stats.retrieve(null)"),
);
assert!(
error.contains("InvalidArgumentValue: db.stats.retrieve") && error.contains("NULL"),
"{error}"
);
}
#[test]
fn removed_catalog_procedures_are_unknown() {
let graph = Graph::default();
for name in ["db.indexes", "db.constraints"] {
let error = crate::exec::test_support::error_of(
crate::exec::test_support::try_exec_cypher(&graph, &format!("CALL {name}()")),
);
assert!(error.contains("ProcedureNotFound: "), "{name}: {error}");
}
}
#[test]
fn metadata_comes_from_the_signature_without_running_a_producer() {
fn metadata(name: &str) -> Procedure {
procedure_metadata(executable_signature(name).expect("a registered builtin"))
}
let graph = Graph::default();
crate::exec::test_support::exec_autocommit(&graph, "CREATE (:User {name: 'a'})")
.expect("the fixture's CREATE succeeds");
let labels = metadata("db.labels");
assert_eq!(labels.yield_names, ["label"]);
assert!(labels.rows.is_empty());
assert_eq!(rows(&graph, "db.labels").len(), 1);
let retrieve = metadata("db.stats.retrieve");
assert_eq!(retrieve.arg_names, ["section"]);
assert_eq!(retrieve.arg_types, ["STRING"]);
assert_eq!(retrieve.yield_names, ["section", "data"]);
assert!(retrieve.rows.is_empty());
let await_indexes = metadata("db.awaitIndexes");
assert!(await_indexes.yield_names.is_empty() && await_indexes.rows.is_empty());
let catalog_only =
crate::procedure_registry::builtin_procedure_signature("db.clearQueryCaches")
.expect("the catalog-only row is registered");
assert!(catalog_only.listed && !catalog_only.executable);
assert!(executable_signature("db.clearQueryCaches").is_none());
}
#[test]
fn a_diverted_row_declaring_signature_is_an_internal_error_on_the_generic_path() {
let graph = Graph::default();
let view = ExecGraph::read(&graph);
let signature = executable_signature("db.index.vector.queryNodes")
.expect("db.index.vector.queryNodes is registered");
let error = builtin_procedure_rows(&view, signature, None, &BTreeMap::new())
.expect_err("a diverted procedure has no generic row producer");
let message = error.to_string();
assert!(
message.contains("dedicated executor") || message.contains("no row producer"),
"{message}"
);
}
#[test]
fn a_terminal_void_builtin_call_answers_no_rows() {
let graph = Graph::default();
let void = crate::exec::test_support::exec_cypher(&graph, "CALL db.awaitIndexes()");
assert!(void.rows.is_empty());
let rows_afield = crate::exec::test_support::exec_cypher(&graph, "CALL db.ping()");
assert_eq!(rows_afield.rows.len(), 1);
}
#[test]
fn db_ping_reports_success() {
let rows = rows(&Graph::default(), "db.ping");
assert_eq!(rows.len(), 1);
assert_eq!(rows[0]["success"], Value::Bool(true));
let signature = crate::procedure_registry::builtin_procedure_signature("db.ping")
.expect("db.ping is registered");
assert_eq!(signature.returns[0].name, "success");
assert_eq!(signature.returns[0].type_str, "BOOLEAN");
assert!(signature.works_on_system);
}
#[test]
fn fulltext_list_available_analyzers_answers_the_analyzer_table() {
let graph = Graph::default();
let signature = crate::procedure_registry::builtin_procedure_signature(
"db.index.fulltext.listAvailableAnalyzers",
)
.expect("registered");
assert!(signature.executable && signature.works_on_system);
let rows = rows(&graph, "db.index.fulltext.listAvailableAnalyzers");
assert_eq!(rows.len(), 45);
let swedish = rows
.iter()
.find(|row| row["analyzer"] == string("swedish"))
.expect("swedish is listed");
assert_eq!(
swedish["description"],
string("Swedish analyzer with stemming and stop word filtering.")
);
let english = rows
.iter()
.find(|row| row["analyzer"] == string("english"))
.expect("english is listed");
assert!(matches!(
&english["stopwords"],
Value::List(words) if !words.is_empty()
));
let french = rows
.iter()
.find(|row| row["analyzer"] == string("french"))
.expect("french is listed");
assert_eq!(french["stopwords"], Value::List(Vec::new().into()));
let result = crate::exec::test_support::exec_cypher(
&graph,
"CALL db.index.fulltext.listAvailableAnalyzers() YIELD analyzer \
WHERE analyzer = 'swedish' RETURN analyzer",
);
assert_eq!(result.rows, vec![vec![string("swedish")]]);
}
}