use std::collections::{BTreeMap, BTreeSet};
use relate_core::{Error, Result, Value};
use crate::exec::catalog::principal_cell;
use crate::graph::Procedure;
use crate::overlay::ExecGraph;
use crate::procedure_registry::ProcSignature;
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};
const RELATE_VERSION: &str = env!("CARGO_PKG_VERSION");
const NEO4J_KERNEL_VERSION: &str = "2026.10-relate";
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_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 => db_info_rows(graph),
Self::DbmsInfo => dbms_info_rows(),
Self::DbmsShowCurrentUser => dbms_show_current_user_rows(principal),
Self::DbmsConfig => dbms_config_rows(),
Self::DbmsLicenseAgreementDetails => dbms_license_agreement_rows(),
Self::DbmsListCapabilities => 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 dbms_list_capabilities_rows(graph: &ExecGraph<'_>) -> Vec<BTreeMap<String, Value>> {
fn row(name: &str, description: &str, value: Value) -> BTreeMap<String, Value> {
BTreeMap::from([
("name".to_string(), Value::String(name.into())),
("description".to_string(), Value::String(description.into())),
("value".to_string(), value),
])
}
vec![
row(
"cypher.version",
"The Cypher dialect version this engine implements.",
Value::String("25".into()),
),
row(
"fulltext.index",
"Whether fulltext indexes and their query procedures are available.",
Value::Bool(true),
),
row(
"vector.index",
"Whether vector indexes and their query procedures are available.",
Value::Bool(true),
),
row(
"pattern.engine",
"The pattern-matching engine in force for this database.",
Value::String(graph.base().pattern_engine().as_str().into()),
),
]
}
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")
}
fn db_info_rows(graph: &ExecGraph<'_>) -> Vec<BTreeMap<String, Value>> {
let namespace = graph.namespace().as_str();
vec![BTreeMap::from([
("id".into(), Value::String(namespace.into())),
("name".into(), Value::String(namespace.into())),
("creationDate".into(), Value::Null),
])]
}
fn dbms_info_rows() -> Vec<BTreeMap<String, Value>> {
vec![BTreeMap::from([
("id".into(), Value::String("relate".into())),
("name".into(), Value::String("system".into())),
(
"creationDate".into(),
Value::String("1970-01-01T00:00:00Z".into()),
),
])]
}
fn dbms_show_current_user_rows(principal: Option<&str>) -> Vec<BTreeMap<String, Value>> {
vec![BTreeMap::from([
("username".into(), principal_cell(principal, "relate")),
(
"roles".into(),
Value::List(vec![Value::String("admin".into())].into()),
),
("flags".into(), Value::List(Vec::new().into())),
])]
}
fn dbms_license_agreement_rows() -> Vec<BTreeMap<String, Value>> {
vec![BTreeMap::from([
("status".into(), Value::String("yes".into())),
("daysLeftOnTrial".into(), Value::Null),
("totalTrialDays".into(), Value::Null),
])]
}
fn dbms_components_rows() -> Vec<BTreeMap<String, Value>> {
const COMPONENTS: &[(&str, &[&str])] = &[
("Neo4j Kernel", &[NEO4J_KERNEL_VERSION]),
("Cypher", &["5", "25"]),
("Relate", &[RELATE_VERSION]),
];
COMPONENTS
.iter()
.map(|(name, versions)| {
BTreeMap::from([
("name".into(), Value::String((*name).into())),
(
"versions".into(),
Value::List(
versions
.iter()
.map(|version| Value::String((*version).into()))
.collect::<Vec<_>>()
.into(),
),
),
("edition".into(), Value::String("community".into())),
])
})
.collect()
}
fn dbms_config_rows() -> Vec<BTreeMap<String, Value>> {
const CONFIG: &[(&str, &str, &str)] = &[
(
"browser.allow_outgoing_connections",
"true",
"Whether the Browser may open outgoing connections to other servers.",
),
(
"browser.credential_timeout",
"0",
"Seconds before the Browser discards retained credentials (0 = never).",
),
(
"browser.post_connect_cmd",
"",
"Command the Browser runs after connecting.",
),
(
"browser.remote_content_hostname_whitelist",
"*",
"Hostnames the Browser may load remote content from.",
),
(
"browser.retain_connection_credentials",
"false",
"Whether the Browser retains connection credentials.",
),
(
"browser.retain_editor_history",
"true",
"Whether the Browser retains editor history.",
),
(
"client.allow_telemetry",
"false",
"Whether client telemetry collection is allowed.",
),
(
"dbms.security.auth_enabled",
"true",
"Whether the server requires authentication.",
),
(
"server.metrics.prefix",
"relate",
"Prefix for reported metrics names.",
),
];
CONFIG
.iter()
.map(|(name, value, description)| {
BTreeMap::from([
("name".into(), Value::String((*name).into())),
("description".into(), Value::String((*description).into())),
("value".into(), Value::String((*value).into())),
("dynamic".into(), Value::Bool(false)),
("defaultValue".into(), Value::String((*value).into())),
("startupValue".into(), Value::String((*value).into())),
("explicitlySet".into(), Value::Bool(false)),
("validValues".into(), Value::String("".into())),
])
})
.collect()
}
#[cfg(test)]
mod tests {
use super::test_helpers::{rows, rows_with_principal, string};
use super::*;
use crate::graph::Graph;
#[test]
fn dbms_list_capabilities_reports_the_engines_own_facts() {
let graph = Graph::default();
let rows = rows(&graph, "dbms.listCapabilities");
let names: Vec<&str> = rows
.iter()
.map(|r| {
r["name"]
.as_string()
.expect("every capability row names itself")
})
.collect();
assert_eq!(
names,
[
"cypher.version",
"fulltext.index",
"vector.index",
"pattern.engine"
]
);
assert_eq!(rows[0]["value"], Value::String("25".into()));
assert_eq!(rows[1]["value"], Value::Bool(true));
assert_eq!(rows[2]["value"], Value::Bool(true));
assert_eq!(rows[3]["value"], Value::String("auto".into()));
for row in &rows {
assert!(!row["description"]
.as_string()
.expect("every capability row carries a description")
.is_empty());
}
}
#[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 dbms_components_returns_kernel_cypher_relate_rows_with_edition() {
let graph = Graph::default();
let rows = rows(&graph, "dbms.components");
assert_eq!(rows.len(), 3);
assert_eq!(rows[0]["name"], string("Neo4j Kernel"));
assert_eq!(
rows[0]["versions"],
Value::List(vec![string(NEO4J_KERNEL_VERSION)].into())
);
assert_eq!(rows[0]["edition"], string("community"));
assert_eq!(rows[1]["name"], string("Cypher"));
assert_eq!(
rows[1]["versions"],
Value::List(vec![string("5"), string("25")].into())
);
assert_eq!(rows[1]["edition"], string("community"));
assert_eq!(rows[2]["name"], string("Relate"));
assert_eq!(
rows[2]["versions"],
Value::List(vec![string(RELATE_VERSION)].into())
);
assert_eq!(rows[2]["edition"], string("community"));
}
#[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")]]);
}
#[test]
fn db_info_reports_the_graphs_namespace() {
let graph = Graph::default();
let neo4j_rows = rows(&graph, "db.info");
assert_eq!(neo4j_rows.len(), 1);
assert_eq!(neo4j_rows[0]["id"], string("neo4j"));
assert_eq!(neo4j_rows[0]["name"], string("neo4j"));
let mut ontologies = Graph::default();
ontologies.set_namespace(relate_core::Namespace::SystemOntologies);
let ontologies_rows = rows(&ontologies, "db.info");
assert_eq!(ontologies_rows.len(), 1);
assert_eq!(ontologies_rows[0]["id"], string("system_ontologies"));
assert_eq!(ontologies_rows[0]["name"], string("system_ontologies"));
}
#[test]
fn dbms_info_returns_the_desktop_compat_row() {
let graph = Graph::default();
let rows = rows(&graph, "dbms.info");
assert_eq!(rows.len(), 1);
assert_eq!(rows[0]["id"], string("relate"));
assert_eq!(rows[0]["name"], string("system"));
assert_eq!(rows[0]["creationDate"], string("1970-01-01T00:00:00Z"));
}
#[test]
fn dbms_info_signature_declares_id_name_creation_date_outputs() {
let signature = crate::procedure_registry::builtin_procedure_signature("dbms.info")
.expect("dbms.info is registered");
assert!(signature.executable);
let outputs: Vec<&str> = signature.returns.iter().map(|ret| ret.name).collect();
assert_eq!(outputs, ["id", "name", "creationDate"]);
}
#[test]
fn dbms_components_signature_declares_edition_output() {
let signature = crate::procedure_registry::builtin_procedure_signature("dbms.components")
.expect("dbms.components is registered");
let outputs: Vec<&str> = signature.returns.iter().map(|ret| ret.name).collect();
assert_eq!(outputs, ["name", "versions", "edition"]);
}
#[test]
fn dbms_show_current_user_returns_the_placeholder_row_without_a_principal() {
let graph = Graph::default();
let rows = rows(&graph, "dbms.showCurrentUser");
assert_eq!(rows.len(), 1);
assert_eq!(rows[0]["username"], string("relate"));
assert_eq!(rows[0]["roles"], Value::List(vec![string("admin")].into()));
assert_eq!(rows[0]["flags"], Value::List(Vec::new().into()));
}
#[test]
fn dbms_show_current_user_reports_the_connection_principal() {
let graph = Graph::default();
let rows = rows_with_principal(&graph, "dbms.showCurrentUser", Some("alice"));
assert_eq!(rows.len(), 1);
assert_eq!(rows[0]["username"], string("alice"));
assert_eq!(rows[0]["roles"], Value::List(vec![string("admin")].into()));
assert_eq!(rows[0]["flags"], Value::List(Vec::new().into()));
}
#[test]
fn dbms_config_rows_match_the_adr0143_allowlist() {
let graph = Graph::default();
let client_rows = rows(&graph, "dbms.clientConfig");
let list_rows = rows(&graph, "dbms.listConfig");
assert_eq!(client_rows, list_rows);
assert_eq!(client_rows.len(), 9);
let expected: &[(&str, &str)] = &[
("browser.allow_outgoing_connections", "true"),
("browser.credential_timeout", "0"),
("browser.post_connect_cmd", ""),
("browser.remote_content_hostname_whitelist", "*"),
("browser.retain_connection_credentials", "false"),
("browser.retain_editor_history", "true"),
("client.allow_telemetry", "false"),
("dbms.security.auth_enabled", "true"),
("server.metrics.prefix", "relate"),
];
for (row, (name, value)) in client_rows.iter().zip(expected) {
assert_eq!(row["name"], string(name));
assert_eq!(row["value"], string(value));
assert_eq!(row["dynamic"], Value::Bool(false));
assert_eq!(row["defaultValue"], string(value));
assert_eq!(row["startupValue"], string(value));
assert_eq!(row["explicitlySet"], Value::Bool(false));
assert_eq!(row["validValues"], string(""));
assert!(matches!(&row["description"], Value::String(d) if !d.is_empty()));
}
}
#[test]
fn dbms_license_agreement_details_returns_the_honest_row() {
let graph = Graph::default();
let rows = rows(&graph, "dbms.licenseAgreementDetails");
assert_eq!(rows.len(), 1);
assert_eq!(rows[0]["status"], string("yes"));
assert_eq!(rows[0]["daysLeftOnTrial"], Value::Null);
assert_eq!(rows[0]["totalTrialDays"], Value::Null);
}
}