#![allow(dead_code)]
use std::collections::{BTreeMap, BTreeSet};
use chrono::{SecondsFormat, TimeZone, Utc};
use sha2::{Digest, Sha256};
use uuid::Uuid;
use crate::error::{Error, Result};
use crate::storage_interface::{
SchemaConstraintDescriptor, SchemaEntityType, StorageInterface, WritableStorage,
};
use crate::value::{NodeValue, Properties, RelationshipValue, Value};
pub(crate) type ProcedureRow = BTreeMap<String, Value>;
pub(crate) type ProcedureRows = Box<dyn Iterator<Item = Result<ProcedureRow>>>;
pub(crate) type ReadProcedureHandler = fn(&dyn StorageInterface, &[Value]) -> Result<ProcedureRows>;
pub(crate) type WriteProcedureHandler = fn(&mut dyn WritableStorage, &[Value]) -> Result<()>;
#[derive(Clone, Copy)]
pub(crate) enum ProcedureHandler {
Read(ReadProcedureHandler),
Write(WriteProcedureHandler),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ProcedureMode {
Read,
Write,
Schema,
Dbms,
}
impl std::fmt::Display for ProcedureMode {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self {
Self::Read => "READ",
Self::Write => "WRITE",
Self::Schema => "SCHEMA",
Self::Dbms => "DBMS",
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ProcedureValueType {
Any,
Boolean,
Integer,
Float,
String,
List,
Map,
}
impl ProcedureValueType {
pub(crate) fn accepts(self, value: &Value) -> bool {
matches!(self, Self::Any)
|| matches!(
(self, value),
(Self::Boolean, Value::Boolean(_))
| (Self::Integer, Value::Integer(_))
| (Self::Float, Value::Float(_))
| (Self::String, Value::String(_))
| (Self::List, Value::List(_))
| (Self::Map, Value::Map(_))
)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum ProcedureDefault {
Null,
Boolean(bool),
Integer(i64),
Float(f64),
String(&'static str),
}
impl ProcedureDefault {
pub(crate) fn value(self) -> Value {
match self {
Self::Null => Value::Null,
Self::Boolean(value) => Value::Boolean(value),
Self::Integer(value) => Value::Integer(value),
Self::Float(value) => Value::Float(value),
Self::String(value) => Value::String(value.to_owned()),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ProcedureArgument {
pub name: &'static str,
pub value_type: ProcedureValueType,
pub nullable: bool,
pub default: Option<ProcedureDefault>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ProcedureOutput {
pub name: &'static str,
pub value_type: ProcedureValueType,
pub nullable: bool,
}
#[derive(Clone, Copy)]
pub(crate) struct ProcedureSignature {
pub name: &'static str,
pub mode: ProcedureMode,
pub arguments: &'static [ProcedureArgument],
pub outputs: &'static [ProcedureOutput],
pub description: &'static str,
pub deprecated_by: Option<&'static str>,
pub handler: ProcedureHandler,
}
const PING_OUTPUTS: &[ProcedureOutput] = &[ProcedureOutput {
name: "success",
value_type: ProcedureValueType::Boolean,
nullable: false,
}];
const DATABASE_INFO_OUTPUTS: &[ProcedureOutput] = &[
ProcedureOutput {
name: "id",
value_type: ProcedureValueType::String,
nullable: false,
},
ProcedureOutput {
name: "name",
value_type: ProcedureValueType::String,
nullable: false,
},
ProcedureOutput {
name: "creationDate",
value_type: ProcedureValueType::String,
nullable: false,
},
];
const LABEL_NAME_ARGUMENT: &[ProcedureArgument] = &[ProcedureArgument {
name: "newLabel",
value_type: ProcedureValueType::String,
nullable: false,
default: None,
}];
const RELATIONSHIP_TYPE_NAME_ARGUMENT: &[ProcedureArgument] = &[ProcedureArgument {
name: "newRelationshipType",
value_type: ProcedureValueType::String,
nullable: false,
default: None,
}];
const PROPERTY_NAME_ARGUMENT: &[ProcedureArgument] = &[ProcedureArgument {
name: "newProperty",
value_type: ProcedureValueType::String,
nullable: false,
default: None,
}];
const LABEL_OUTPUTS: &[ProcedureOutput] = &[ProcedureOutput {
name: "label",
value_type: ProcedureValueType::String,
nullable: false,
}];
const RELATIONSHIP_TYPE_OUTPUTS: &[ProcedureOutput] = &[ProcedureOutput {
name: "relationshipType",
value_type: ProcedureValueType::String,
nullable: false,
}];
const PROPERTY_KEY_OUTPUTS: &[ProcedureOutput] = &[ProcedureOutput {
name: "propertyKey",
value_type: ProcedureValueType::String,
nullable: false,
}];
const NODE_TYPE_PROPERTY_OUTPUTS: &[ProcedureOutput] = &[
ProcedureOutput {
name: "nodeType",
value_type: ProcedureValueType::String,
nullable: false,
},
ProcedureOutput {
name: "nodeLabels",
value_type: ProcedureValueType::List,
nullable: false,
},
ProcedureOutput {
name: "propertyName",
value_type: ProcedureValueType::String,
nullable: true,
},
ProcedureOutput {
name: "propertyTypes",
value_type: ProcedureValueType::List,
nullable: true,
},
ProcedureOutput {
name: "mandatory",
value_type: ProcedureValueType::Boolean,
nullable: false,
},
];
const REL_TYPE_PROPERTY_OUTPUTS: &[ProcedureOutput] = &[
ProcedureOutput {
name: "relType",
value_type: ProcedureValueType::String,
nullable: false,
},
ProcedureOutput {
name: "propertyName",
value_type: ProcedureValueType::String,
nullable: true,
},
ProcedureOutput {
name: "propertyTypes",
value_type: ProcedureValueType::List,
nullable: true,
},
ProcedureOutput {
name: "mandatory",
value_type: ProcedureValueType::Boolean,
nullable: false,
},
];
const SCHEMA_VISUALIZATION_OUTPUTS: &[ProcedureOutput] = &[
ProcedureOutput {
name: "nodes",
value_type: ProcedureValueType::List,
nullable: false,
},
ProcedureOutput {
name: "relationships",
value_type: ProcedureValueType::List,
nullable: false,
},
];
const PROCEDURES: &[ProcedureSignature] = &[
ProcedureSignature {
name: "db.createLabel",
mode: ProcedureMode::Write,
arguments: LABEL_NAME_ARGUMENT,
outputs: &[],
description: "Create a label token.",
deprecated_by: None,
handler: ProcedureHandler::Write(create_label),
},
ProcedureSignature {
name: "db.createRelationshipType",
mode: ProcedureMode::Write,
arguments: RELATIONSHIP_TYPE_NAME_ARGUMENT,
outputs: &[],
description: "Create a relationship-type token.",
deprecated_by: None,
handler: ProcedureHandler::Write(create_relationship_type),
},
ProcedureSignature {
name: "db.createProperty",
mode: ProcedureMode::Write,
arguments: PROPERTY_NAME_ARGUMENT,
outputs: &[],
description: "Create a property-key token.",
deprecated_by: None,
handler: ProcedureHandler::Write(create_property),
},
ProcedureSignature {
name: "db.info",
mode: ProcedureMode::Read,
arguments: &[],
outputs: DATABASE_INFO_OUTPUTS,
description: "Provide persistent database identity information.",
deprecated_by: None,
handler: ProcedureHandler::Read(database_info),
},
ProcedureSignature {
name: "db.ping",
mode: ProcedureMode::Read,
arguments: &[],
outputs: PING_OUTPUTS,
description: "Test whether the database connection is available.",
deprecated_by: None,
handler: ProcedureHandler::Read(ping),
},
ProcedureSignature {
name: "db.labels",
mode: ProcedureMode::Read,
arguments: &[],
outputs: LABEL_OUTPUTS,
description: "List labels attached to visible nodes.",
deprecated_by: None,
handler: ProcedureHandler::Read(labels),
},
ProcedureSignature {
name: "db.relationshipTypes",
mode: ProcedureMode::Read,
arguments: &[],
outputs: RELATIONSHIP_TYPE_OUTPUTS,
description: "List relationship types attached to visible relationships.",
deprecated_by: None,
handler: ProcedureHandler::Read(relationship_types),
},
ProcedureSignature {
name: "db.propertyKeys",
mode: ProcedureMode::Read,
arguments: &[],
outputs: PROPERTY_KEY_OUTPUTS,
description: "List all public property-key tokens in the database.",
deprecated_by: None,
handler: ProcedureHandler::Read(property_keys),
},
ProcedureSignature {
name: "db.schema.nodeTypeProperties",
mode: ProcedureMode::Read,
arguments: &[],
outputs: NODE_TYPE_PROPERTY_OUTPUTS,
description: "Show the derived property schema of nodes.",
deprecated_by: None,
handler: ProcedureHandler::Read(node_type_properties),
},
ProcedureSignature {
name: "db.schema.relTypeProperties",
mode: ProcedureMode::Read,
arguments: &[],
outputs: REL_TYPE_PROPERTY_OUTPUTS,
description: "Show the derived property schema of relationships.",
deprecated_by: None,
handler: ProcedureHandler::Read(rel_type_properties),
},
ProcedureSignature {
name: "db.schema.visualization",
mode: ProcedureMode::Read,
arguments: &[],
outputs: SCHEMA_VISUALIZATION_OUTPUTS,
description: "Visualize the data-derived graph schema.",
deprecated_by: None,
handler: ProcedureHandler::Read(schema_visualization),
},
];
fn token_name<'a>(procedure: &str, arguments: &'a [Value]) -> Result<&'a str> {
match arguments {
[Value::String(name)] => Ok(name),
_ => Err(Error::InvalidProcedureCall {
name: procedure.to_owned(),
message: "expected one non-null string argument".to_owned(),
}),
}
}
fn create_label(storage: &mut dyn WritableStorage, arguments: &[Value]) -> Result<()> {
storage.ensure_label_token(token_name("db.createLabel", arguments)?)
}
fn create_relationship_type(storage: &mut dyn WritableStorage, arguments: &[Value]) -> Result<()> {
storage.ensure_relationship_type_token(token_name("db.createRelationshipType", arguments)?)
}
fn create_property(storage: &mut dyn WritableStorage, arguments: &[Value]) -> Result<()> {
storage.ensure_property_key_token(token_name("db.createProperty", arguments)?)
}
const DEFERRED: &[(&str, &str)] = &[
("db.awaitIndex", "online index population is not available"),
(
"db.awaitIndexes",
"online index population is not available",
),
("db.resampleIndex", "index sampling is not available"),
(
"db.resampleOutdatedIndexes",
"index sampling is not available",
),
(
"db.prepareForReplanning",
"query plan cache and index sampling are not available",
),
(
"db.index.fulltext.listAvailableAnalyzers",
"the full-text index provider is not available",
),
(
"db.index.fulltext.awaitEventuallyConsistentIndexRefresh",
"the full-text index provider is not available",
),
(
"db.index.fulltext.queryNodes",
"the full-text index provider is not available",
),
(
"db.index.fulltext.queryRelationships",
"the full-text index provider is not available",
),
(
"db.index.vector.createNodeIndex",
"vector index schema maintenance is not available",
),
(
"db.index.vector.queryNodes",
"the vector index provider is not available",
),
(
"db.index.vector.queryRelationships",
"the vector index provider is not available",
),
(
"db.create.setNodeVectorProperty",
"Neo4j vector property encoding is not available",
),
(
"db.create.setVectorProperty",
"Neo4j vector property encoding is not available",
),
(
"db.create.setRelationshipVectorProperty",
"Neo4j vector property encoding is not available",
),
(
"dbms.info",
"an embedded database has no Neo4j DBMS system database",
),
(
"dbms.listConfig",
"Neo4j DBMS configuration is not available",
),
(
"dbms.clientConfig",
"Neo4j DBMS client configuration is not available",
),
(
"tx.setMetaData",
"transaction metadata has no public littlegraph contract",
),
(
"tx.getMetaData",
"transaction metadata has no public littlegraph contract",
),
(
"db.clearQueryCaches",
"littlegraph has no persistent query plan cache",
),
(
"dbms.upgradeStatus",
"an embedded database has no Neo4j system graph upgrade service",
),
(
"dbms.upgrade",
"an embedded database has no Neo4j system graph upgrade service",
),
(
"dbms.listConnections",
"an embedded database has no network connection service",
),
(
"dbms.killConnection",
"an embedded database has no network connection service",
),
(
"dbms.killConnections",
"an embedded database has no network connection service",
),
(
"dbms.listAllCapabilities",
"Neo4j DBMS capabilities are not available",
),
(
"dbms.listCapabilities",
"Neo4j DBMS capabilities are not available",
),
(
"internal.db.system.info",
"Neo4j system metrics are not available",
),
];
pub(crate) fn resolve(name: &str) -> Result<&'static ProcedureSignature> {
if let Some(signature) = PROCEDURES.iter().find(|signature| signature.name == name) {
return Ok(signature);
}
if let Some((_, reason)) = DEFERRED.iter().find(|(candidate, _)| *candidate == name) {
return Err(Error::DeferredProcedure {
name: name.to_owned(),
reason: (*reason).to_owned(),
});
}
Err(Error::UnknownProcedure {
name: name.to_owned(),
})
}
fn ping(_storage: &dyn StorageInterface, _arguments: &[Value]) -> Result<ProcedureRows> {
Ok(Box::new(std::iter::once(Ok(BTreeMap::from([(
"success".to_owned(),
Value::Boolean(true),
)])))))
}
fn database_info(storage: &dyn StorageInterface, _arguments: &[Value]) -> Result<ProcedureRows> {
storage.check_query_control()?;
let metadata = storage.database_metadata().ok_or_else(|| {
Error::Execution("database metadata is unavailable for db.info()".to_owned())
})?;
let external_id = Uuid::from_bytes(metadata.external_store_id).to_string();
let id = format!("{:X}", Sha256::digest(external_id.as_bytes()));
let creation_date = Utc
.timestamp_millis_opt(metadata.creation_time_millis)
.single()
.ok_or_else(|| Error::Execution("database creation time is out of range".to_owned()))?
.to_rfc3339_opts(SecondsFormat::AutoSi, true);
Ok(Box::new(std::iter::once(Ok(BTreeMap::from([
("id".to_owned(), Value::String(id)),
("name".to_owned(), Value::String(metadata.name.clone())),
("creationDate".to_owned(), Value::String(creation_date)),
])))))
}
fn labels(storage: &dyn StorageInterface, _arguments: &[Value]) -> Result<ProcedureRows> {
let mut in_use = BTreeSet::new();
for node_id in storage.node_ids() {
storage.check_query_control()?;
if let Some(node) = storage.node(node_id) {
in_use.extend(node.labels.iter().cloned());
}
}
extend_schema_entity_tokens(storage, SchemaEntityType::Node, &mut in_use)?;
Ok(named_string_rows(
"label",
storage
.label_tokens()
.into_iter()
.filter(move |label| in_use.contains(label)),
))
}
fn relationship_types(
storage: &dyn StorageInterface,
_arguments: &[Value],
) -> Result<ProcedureRows> {
let mut in_use = BTreeSet::new();
for relationship_id in storage.relationship_ids() {
storage.check_query_control()?;
if let Some(relationship) = storage.relationship(relationship_id) {
in_use.insert(relationship.r#type.clone());
}
}
extend_schema_entity_tokens(storage, SchemaEntityType::Relationship, &mut in_use)?;
Ok(named_string_rows(
"relationshipType",
storage
.relationship_type_tokens()
.into_iter()
.filter(move |relationship_type| in_use.contains(relationship_type)),
))
}
fn extend_schema_entity_tokens(
storage: &dyn StorageInterface,
entity_type: SchemaEntityType,
in_use: &mut BTreeSet<String>,
) -> Result<()> {
let Some(metadata) = storage.schema_metadata() else {
return Ok(());
};
for schema in metadata.indexes.iter().map(|index| &index.schema).chain(
metadata
.constraints
.iter()
.map(|constraint| &constraint.schema),
) {
storage.check_query_control()?;
if schema.entity_type == entity_type {
in_use.extend(schema.entity_tokens.iter().cloned());
}
}
Ok(())
}
fn property_keys(storage: &dyn StorageInterface, _arguments: &[Value]) -> Result<ProcedureRows> {
storage.check_query_control()?;
Ok(named_string_rows(
"propertyKey",
storage.property_key_tokens().into_iter(),
))
}
fn named_string_rows(
field: &'static str,
values: impl Iterator<Item = String> + 'static,
) -> ProcedureRows {
Box::new(
values.map(move |value| Ok(BTreeMap::from([(field.to_owned(), Value::String(value))]))),
)
}
#[derive(Default)]
struct PropertyGroup {
entities: usize,
properties: BTreeMap<String, PropertySummary>,
}
#[derive(Default)]
struct PropertySummary {
present: usize,
types: BTreeSet<String>,
}
fn node_type_properties(
storage: &dyn StorageInterface,
_arguments: &[Value],
) -> Result<ProcedureRows> {
let mut groups = BTreeMap::<Vec<String>, PropertyGroup>::new();
for node_id in storage.node_ids() {
storage.check_query_control()?;
let Some(node) = storage.node(node_id) else {
continue;
};
let mut labels = node.labels.clone();
labels.sort();
labels.dedup();
update_property_group(
groups.entry(labels).or_default(),
&node.properties,
|property_name, value| {
storage
.node_property_type(node_id, property_name)
.unwrap_or_else(|| neo4j_value_type_name(value))
},
);
}
charge_property_groups(storage, &groups, |labels| {
labels.iter().try_fold(
labels.len().checked_mul(std::mem::size_of::<String>())?,
|bytes, label| bytes.checked_add(label.len()),
)
})?;
let mut rows = Vec::new();
for (labels, group) in groups {
storage.check_query_control()?;
let node_type = labels
.iter()
.map(|label| format!(":`{label}`"))
.collect::<String>();
let node_labels = Value::List(labels.into_iter().map(Value::String).collect());
if group.properties.is_empty() {
let row = BTreeMap::from([
("nodeType".to_owned(), Value::String(node_type)),
("nodeLabels".to_owned(), node_labels),
("propertyName".to_owned(), Value::Null),
("propertyTypes".to_owned(), Value::Null),
("mandatory".to_owned(), Value::Boolean(false)),
]);
charge_materialized_row(storage, &row)?;
rows.push(Ok(row));
continue;
}
for (property_name, property) in group.properties {
let row = BTreeMap::from([
("nodeType".to_owned(), Value::String(node_type.clone())),
("nodeLabels".to_owned(), node_labels.clone()),
("propertyName".to_owned(), Value::String(property_name)),
(
"propertyTypes".to_owned(),
property_types_value(property.types),
),
(
"mandatory".to_owned(),
Value::Boolean(property.present == group.entities),
),
]);
charge_materialized_row(storage, &row)?;
rows.push(Ok(row));
}
}
Ok(Box::new(rows.into_iter()))
}
fn rel_type_properties(
storage: &dyn StorageInterface,
_arguments: &[Value],
) -> Result<ProcedureRows> {
let mut groups = BTreeMap::<String, PropertyGroup>::new();
for relationship_id in storage.relationship_ids() {
storage.check_query_control()?;
let Some(relationship) = storage.relationship(relationship_id) else {
continue;
};
update_property_group(
groups.entry(relationship.r#type.clone()).or_default(),
&relationship.properties,
|property_name, value| {
storage
.relationship_property_type(relationship_id, property_name)
.unwrap_or_else(|| neo4j_value_type_name(value))
},
);
}
charge_property_groups(storage, &groups, |relationship_type| {
Some(relationship_type.len())
})?;
let mut rows = Vec::new();
for (relationship_type, group) in groups {
storage.check_query_control()?;
let rel_type = format!(":`{relationship_type}`");
if group.properties.is_empty() {
let row = BTreeMap::from([
("relType".to_owned(), Value::String(rel_type)),
("propertyName".to_owned(), Value::Null),
("propertyTypes".to_owned(), Value::Null),
("mandatory".to_owned(), Value::Boolean(false)),
]);
charge_materialized_row(storage, &row)?;
rows.push(Ok(row));
continue;
}
for (property_name, property) in group.properties {
let row = BTreeMap::from([
("relType".to_owned(), Value::String(rel_type.clone())),
("propertyName".to_owned(), Value::String(property_name)),
(
"propertyTypes".to_owned(),
property_types_value(property.types),
),
(
"mandatory".to_owned(),
Value::Boolean(property.present == group.entities),
),
]);
charge_materialized_row(storage, &row)?;
rows.push(Ok(row));
}
}
Ok(Box::new(rows.into_iter()))
}
fn update_property_group(
group: &mut PropertyGroup,
properties: &BTreeMap<String, Value>,
mut type_name: impl FnMut(&str, &Value) -> String,
) {
group.entities += 1;
for (name, value) in properties {
if matches!(value, Value::Null) {
continue;
}
let summary = group.properties.entry(name.clone()).or_default();
summary.present += 1;
summary.types.insert(type_name(name, value));
}
}
fn charge_property_groups<K>(
storage: &dyn StorageInterface,
groups: &BTreeMap<K, PropertyGroup>,
key_heap_bytes: impl Fn(&K) -> Option<usize>,
) -> Result<()> {
let mut bytes = 0_usize;
for (key, group) in groups {
bytes = bytes
.checked_add(std::mem::size_of::<(K, PropertyGroup)>())
.and_then(|bytes| bytes.checked_add(key_heap_bytes(key)?))
.ok_or(Error::Transaction(
crate::error::TransactionErrorKind::ResourceLimit,
))?;
for (property_name, summary) in &group.properties {
bytes = bytes
.checked_add(std::mem::size_of::<(String, PropertySummary)>())
.and_then(|bytes| bytes.checked_add(property_name.len()))
.ok_or(Error::Transaction(
crate::error::TransactionErrorKind::ResourceLimit,
))?;
for property_type in &summary.types {
bytes = bytes
.checked_add(std::mem::size_of::<String>())
.and_then(|bytes| bytes.checked_add(property_type.len()))
.ok_or(Error::Transaction(
crate::error::TransactionErrorKind::ResourceLimit,
))?;
}
}
}
storage.charge_query_memory(bytes)
}
fn property_types_value(types: BTreeSet<String>) -> Value {
Value::List(types.into_iter().map(Value::String).collect())
}
fn charge_materialized_row(
storage: &dyn StorageInterface,
row: &BTreeMap<String, Value>,
) -> Result<()> {
let mut bytes = std::mem::size_of::<BTreeMap<String, Value>>();
for (name, value) in row {
bytes = bytes
.checked_add(std::mem::size_of::<(String, Value)>())
.and_then(|bytes| bytes.checked_add(name.capacity()))
.and_then(|bytes| bytes.checked_add(value.estimated_heap_bytes()?))
.ok_or(Error::Transaction(
crate::error::TransactionErrorKind::ResourceLimit,
))?;
}
storage.charge_query_memory(bytes)
}
fn neo4j_value_type_name(value: &Value) -> String {
match value {
Value::Null => "Null".to_owned(),
Value::Boolean(_) => "Boolean".to_owned(),
Value::Integer(_) => "Long".to_owned(),
Value::Float(_) => "Double".to_owned(),
Value::String(_) => "String".to_owned(),
Value::List(values) => list_type_name(values),
Value::Map(_) => "Map".to_owned(),
Value::Node(_) => "Node".to_owned(),
Value::Relationship(_) => "Relationship".to_owned(),
Value::Path(_) => "Path".to_owned(),
}
}
fn list_type_name(values: &[Value]) -> String {
let Some(first) = values.first() else {
return "Array".to_owned();
};
let first_type = neo4j_value_type_name(first);
if values
.iter()
.all(|value| neo4j_value_type_name(value) == first_type)
{
format!("{first_type}Array")
} else {
"Array".to_owned()
}
}
fn schema_visualization(
storage: &dyn StorageInterface,
_arguments: &[Value],
) -> Result<ProcedureRows> {
let mut labels_in_use = BTreeSet::new();
for node_id in storage.node_ids() {
storage.check_query_control()?;
if let Some(node) = storage.node(node_id) {
labels_in_use.extend(node.labels.iter().cloned());
}
}
let mut ordered_labels = storage
.label_tokens()
.into_iter()
.filter(|label| labels_in_use.remove(label))
.collect::<Vec<_>>();
ordered_labels.extend(labels_in_use);
let mut virtual_nodes = BTreeMap::<String, NodeValue>::new();
for (offset, label) in ordered_labels.into_iter().enumerate() {
storage.check_query_control()?;
let id = format!("-{}", 100 + offset);
let (indexes, constraints) = schema_visualization_metadata(storage, &label);
let properties = Properties::from([
("name".to_owned(), Value::String(label.clone())),
(
"indexes".to_owned(),
Value::List(indexes.into_iter().map(Value::String).collect()),
),
(
"constraints".to_owned(),
Value::List(constraints.into_iter().map(Value::String).collect()),
),
]);
virtual_nodes.insert(label.clone(), NodeValue::new(id, vec![label], properties));
}
let mut endpoints = BTreeMap::<String, (BTreeSet<String>, BTreeSet<String>)>::new();
for relationship_id in storage.relationship_ids() {
storage.check_query_control()?;
let Some(relationship) = storage.relationship(relationship_id) else {
continue;
};
let Some(start) = storage.node(relationship.start) else {
continue;
};
let Some(end) = storage.node(relationship.end) else {
continue;
};
let endpoint_labels = endpoints.entry(relationship.r#type.clone()).or_default();
endpoint_labels.0.extend(start.labels.iter().cloned());
endpoint_labels.1.extend(end.labels.iter().cloned());
}
let mut ordered_relationship_types = storage
.relationship_type_tokens()
.into_iter()
.filter(|relationship_type| endpoints.contains_key(relationship_type))
.collect::<Vec<_>>();
ordered_relationship_types.extend(
endpoints
.keys()
.filter(|relationship_type| !ordered_relationship_types.contains(relationship_type))
.cloned()
.collect::<Vec<_>>(),
);
let mut relationships = Vec::new();
let mut relationship_offset = 0_usize;
for relationship_type in ordered_relationship_types {
let Some((start_labels, end_labels)) = endpoints.get(&relationship_type) else {
continue;
};
for start_label in start_labels {
for end_label in end_labels {
storage.check_query_control()?;
let (Some(start), Some(end)) =
(virtual_nodes.get(start_label), virtual_nodes.get(end_label))
else {
continue;
};
let id = format!("-{}", 100 + relationship_offset);
relationship_offset += 1;
relationships.push(Value::Relationship(RelationshipValue::new(
id,
start.id.clone(),
end.id.clone(),
relationship_type.clone(),
Properties::from([(
"name".to_owned(),
Value::String(relationship_type.clone()),
)]),
)));
}
}
}
let nodes = virtual_nodes.into_values().map(Value::Node).collect();
let row = BTreeMap::from([
("nodes".to_owned(), Value::List(nodes)),
("relationships".to_owned(), Value::List(relationships)),
]);
charge_materialized_row(storage, &row)?;
Ok(Box::new(std::iter::once(Ok(row))))
}
fn schema_visualization_metadata(
storage: &dyn StorageInterface,
label: &str,
) -> (Vec<String>, Vec<String>) {
let Some(metadata) = storage.schema_metadata() else {
return (Vec::new(), Vec::new());
};
let indexes = metadata
.indexes
.iter()
.filter(|index| {
!index.unique
&& index.schema.entity_type == SchemaEntityType::Node
&& index
.schema
.entity_tokens
.iter()
.any(|token| token == label)
})
.map(|index| index.schema.property_keys.join(","))
.collect();
let constraints = metadata
.constraints
.iter()
.filter(|constraint| {
constraint.schema.entity_type == SchemaEntityType::Node
&& constraint
.schema
.entity_tokens
.iter()
.any(|token| token == label)
})
.map(constraint_user_description)
.collect();
(indexes, constraints)
}
fn constraint_user_description(constraint: &SchemaConstraintDescriptor) -> String {
let entity = match constraint.schema.entity_type {
SchemaEntityType::Node => "NODE",
SchemaEntityType::Relationship => "RELATIONSHIP",
};
let constraint_type = match constraint.constraint_type.as_str() {
"UNIQUE" => format!("{entity} PROPERTY UNIQUENESS"),
"EXISTS" => format!("{entity} PROPERTY EXISTENCE"),
"UNIQUE_EXISTS" => format!("{entity} KEY"),
"PROPERTY_TYPE" => format!("{entity} PROPERTY TYPE"),
"RELATIONSHIP_ENDPOINT_LABEL" => format!(
"RELATIONSHIP {} LABEL",
if constraint.endpoint_type.as_deref() == Some("START") {
"SOURCE"
} else {
"TARGET"
}
),
"NODE_LABEL_EXISTENCE" => "NODE LABEL EXISTENCE".to_owned(),
value => value.to_owned(),
};
let mut fields = vec![
format!("id={}", constraint.id),
format!("name='{}'", constraint.name),
format!("type='{constraint_type}'"),
format!("schema={}", schema_user_description(&constraint.schema)),
];
if let Some(owned_index) = constraint.owned_index {
fields.push(format!("ownedIndex={owned_index}"));
}
if !constraint.property_types.is_empty() {
fields.push(format!(
"propertyType={}",
constraint.property_types.join(" | ")
));
}
if let Some(label) = constraint
.required_label
.as_ref()
.or(constraint.endpoint_label.as_ref())
{
fields.push(format!("enforcedLabel={label}"));
}
format!("Constraint( {} )", fields.join(", "))
}
fn schema_user_description(schema: &crate::storage_interface::SchemaDescriptor) -> String {
fn token(name: &str) -> String {
if name.contains(':') {
format!("`{name}`")
} else {
name.to_owned()
}
}
let tokens = schema
.entity_tokens
.iter()
.map(|name| token(name))
.collect::<Vec<_>>()
.join("|");
let properties = schema
.property_keys
.iter()
.map(|name| token(name))
.collect::<Vec<_>>()
.join(", ");
match schema.entity_type {
SchemaEntityType::Node => format!("(:{tokens} {{{properties}}})"),
SchemaEntityType::Relationship => format!("()-[:{tokens} {{{properties}}}]-()"),
}
}
#[cfg(test)]
mod tests {
use std::collections::{BTreeMap, BTreeSet};
use super::{resolve, ProcedureHandler, ProcedureMode, ProcedureRow};
use crate::error::Error;
use crate::graph_model::{Node, NodeId, Relationship, RelationshipId};
use crate::storage_interface::{
DatabaseMetadata, SchemaConstraintDescriptor, SchemaDescriptor, SchemaEntityType,
SchemaIndexDescriptor, SchemaMetadata, StorageInterface,
};
use crate::value::{Properties, Value};
struct CatalogStorage {
nodes: Vec<Node>,
relationships: Vec<Relationship>,
labels: Vec<String>,
relationship_types: Vec<String>,
property_keys: Vec<String>,
metadata: Option<DatabaseMetadata>,
schema: Option<SchemaMetadata>,
}
impl StorageInterface for CatalogStorage {
fn database_metadata(&self) -> Option<&DatabaseMetadata> {
self.metadata.as_ref()
}
fn schema_metadata(&self) -> Option<&SchemaMetadata> {
self.schema.as_ref()
}
fn node_ids(&self) -> Vec<NodeId> {
(0..self.nodes.len()).collect()
}
fn relationship_ids(&self) -> Vec<RelationshipId> {
(0..self.relationships.len()).collect()
}
fn node(&self, id: NodeId) -> Option<&Node> {
self.nodes.get(id)
}
fn relationship(&self, id: RelationshipId) -> Option<&Relationship> {
self.relationships.get(id)
}
fn outgoing_relationships(&self, _id: NodeId) -> &[RelationshipId] {
&[]
}
fn incoming_relationships(&self, _id: NodeId) -> &[RelationshipId] {
&[]
}
fn nodes_with_label(&self, _label: &str) -> &[NodeId] {
&[]
}
fn node_by_external_id(&self, _external_id: &str) -> Option<NodeId> {
None
}
fn relationship_by_external_id(&self, _external_id: &str) -> Option<RelationshipId> {
None
}
fn label_tokens(&self) -> Vec<String> {
self.labels.clone()
}
fn relationship_type_tokens(&self) -> Vec<String> {
self.relationship_types.clone()
}
fn property_key_tokens(&self) -> Vec<String> {
self.property_keys.clone()
}
}
fn call(name: &str, storage: &dyn StorageInterface) -> Vec<ProcedureRow> {
let signature = resolve(name).expect("resolve procedure");
let ProcedureHandler::Read(handler) = signature.handler else {
panic!("expected READ procedure")
};
handler(storage, &[])
.expect("invoke procedure")
.collect::<crate::Result<Vec<_>>>()
.expect("consume procedure rows")
}
#[test]
fn resolves_ping_with_neo4j_signature() {
let signature = resolve("db.ping").expect("resolve db.ping");
assert_eq!(signature.mode, ProcedureMode::Read);
assert!(signature.arguments.is_empty());
assert_eq!(signature.outputs[0].name, "success");
}
#[test]
fn resolves_token_creation_with_neo4j_write_signatures() {
for (name, argument) in [
("db.createLabel", "newLabel"),
("db.createRelationshipType", "newRelationshipType"),
("db.createProperty", "newProperty"),
] {
let signature = resolve(name).expect("resolve token procedure");
assert_eq!(signature.mode, ProcedureMode::Write);
assert_eq!(signature.arguments.len(), 1);
assert_eq!(signature.arguments[0].name, argument);
assert_eq!(
signature.arguments[0].value_type,
super::ProcedureValueType::String
);
assert!(!signature.arguments[0].nullable);
assert!(signature.outputs.is_empty());
assert!(matches!(signature.handler, ProcedureHandler::Write(_)));
}
}
#[test]
fn database_info_uses_neo4j_identity_and_utc_time_formatting() {
let storage = CatalogStorage {
nodes: Vec::new(),
relationships: Vec::new(),
labels: Vec::new(),
relationship_types: Vec::new(),
property_keys: Vec::new(),
metadata: Some(DatabaseMetadata {
name: "movies".to_owned(),
external_store_id: [
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
0xdd, 0xee, 0xff,
],
creation_time_millis: 1_704_164_645_006,
}),
schema: None,
};
assert_eq!(
call("db.info", &storage),
[BTreeMap::from([
(
"id".to_owned(),
Value::String(
"E34F7B59834D35A6DCB646F99B7D856DF3FFBC955CECE7C90714D13705703680"
.to_owned()
)
),
("name".to_owned(), Value::String("movies".to_owned())),
(
"creationDate".to_owned(),
Value::String("2024-01-02T03:04:05.006Z".to_owned())
),
])]
);
}
#[test]
fn distinguishes_deferred_and_unknown_procedures() {
assert!(matches!(
resolve("db.awaitIndex"),
Err(Error::DeferredProcedure { .. })
));
assert!(matches!(
resolve("db.notReal"),
Err(Error::UnknownProcedure { .. })
));
}
#[test]
fn classifies_every_reassessed_builtin_as_deferred() {
let mut names = BTreeSet::new();
for (name, reason) in super::DEFERRED {
assert!(names.insert(*name), "duplicate deferred procedure `{name}`");
assert!(!reason.is_empty());
assert!(matches!(
resolve(name),
Err(Error::DeferredProcedure {
name: deferred_name,
reason: deferred_reason,
}) if deferred_name == *name && deferred_reason == *reason
));
}
assert!(names.contains("db.index.fulltext.queryNodes"));
assert!(names.contains("db.index.vector.queryRelationships"));
assert!(names.contains("db.create.setRelationshipVectorProperty"));
assert!(names.contains("tx.setMetaData"));
assert!(names.contains("dbms.killConnections"));
assert!(names.contains("internal.db.system.info"));
}
#[test]
fn procedure_names_are_case_sensitive() {
assert!(matches!(
resolve("DB.PING"),
Err(Error::UnknownProcedure { .. })
));
}
#[test]
fn token_readers_distinguish_in_use_and_all_tokens() {
let storage = CatalogStorage {
nodes: vec![Node {
id: 0,
external_id: "4:node:0".to_owned(),
labels: vec!["Used".to_owned()],
properties: Properties::new(),
}],
relationships: vec![Relationship {
id: 0,
external_id: "5:rel:0".to_owned(),
start: 0,
end: 0,
r#type: "ACTIVE".to_owned(),
properties: Properties::new(),
}],
labels: vec![
"Unused".to_owned(),
"SchemaOnly".to_owned(),
"Used".to_owned(),
],
relationship_types: vec![
"INACTIVE".to_owned(),
"SCHEMA_ONLY".to_owned(),
"ACTIVE".to_owned(),
],
property_keys: vec!["unusedKey".to_owned(), "usedKey".to_owned()],
metadata: None,
schema: Some(SchemaMetadata {
indexes: vec![SchemaIndexDescriptor {
id: 1,
name: "schema_only_node".to_owned(),
schema: SchemaDescriptor {
entity_type: SchemaEntityType::Node,
entity_tokens: vec!["SchemaOnly".to_owned()],
property_keys: vec!["unusedKey".to_owned()],
matching_type: "COMPLETE_ALL_TOKENS".to_owned(),
},
index_type: "RANGE".to_owned(),
provider: "range-1.0".to_owned(),
unique: false,
owning_constraint: None,
}],
constraints: vec![SchemaConstraintDescriptor {
id: 2,
name: "schema_only_relationship".to_owned(),
schema: SchemaDescriptor {
entity_type: SchemaEntityType::Relationship,
entity_tokens: vec!["SCHEMA_ONLY".to_owned()],
property_keys: vec!["usedKey".to_owned()],
matching_type: "COMPLETE_ALL_TOKENS".to_owned(),
},
constraint_type: "EXISTS".to_owned(),
graph_type_dependence: "UNDESIGNATED".to_owned(),
index_type: None,
owned_index: None,
property_types: Vec::new(),
endpoint_type: None,
endpoint_label: None,
required_label: None,
}],
}),
};
assert_eq!(
call("db.labels", &storage),
[
BTreeMap::from([("label".to_owned(), Value::String("SchemaOnly".to_owned()))]),
BTreeMap::from([("label".to_owned(), Value::String("Used".to_owned()))]),
]
);
assert_eq!(
call("db.relationshipTypes", &storage),
[
BTreeMap::from([(
"relationshipType".to_owned(),
Value::String("SCHEMA_ONLY".to_owned())
)]),
BTreeMap::from([(
"relationshipType".to_owned(),
Value::String("ACTIVE".to_owned())
)]),
]
);
assert_eq!(call("db.propertyKeys", &storage).len(), 2);
}
#[test]
fn schema_readers_group_entities_and_compute_types_and_mandatory() {
let properties = |entries: &[(&str, Value)]| {
entries
.iter()
.map(|(key, value)| ((*key).to_owned(), value.clone()))
.collect()
};
let storage = CatalogStorage {
nodes: vec![
Node {
id: 0,
external_id: "4:node:0".to_owned(),
labels: vec!["Person".to_owned(), "Employee".to_owned()],
properties: properties(&[
("name", Value::String("Alice".to_owned())),
("score", Value::Integer(1)),
]),
},
Node {
id: 1,
external_id: "4:node:1".to_owned(),
labels: vec!["Employee".to_owned(), "Person".to_owned()],
properties: properties(&[
("name", Value::String("Bob".to_owned())),
("score", Value::Float(2.5)),
]),
},
Node {
id: 2,
external_id: "4:node:2".to_owned(),
labels: vec!["Person".to_owned()],
properties: Properties::new(),
},
Node {
id: 3,
external_id: "4:node:3".to_owned(),
labels: vec!["Person".to_owned()],
properties: properties(&[("name", Value::String("Carol".to_owned()))]),
},
],
relationships: vec![
Relationship {
id: 0,
external_id: "5:rel:0".to_owned(),
start: 0,
end: 1,
r#type: "KNOWS".to_owned(),
properties: properties(&[("since", Value::Integer(2020))]),
},
Relationship {
id: 1,
external_id: "5:rel:1".to_owned(),
start: 1,
end: 0,
r#type: "KNOWS".to_owned(),
properties: Properties::new(),
},
Relationship {
id: 2,
external_id: "5:rel:2".to_owned(),
start: 0,
end: 0,
r#type: "EMPTY".to_owned(),
properties: Properties::new(),
},
],
labels: vec!["Person".to_owned(), "Employee".to_owned()],
relationship_types: vec!["KNOWS".to_owned(), "EMPTY".to_owned()],
property_keys: vec!["name".to_owned(), "score".to_owned(), "since".to_owned()],
metadata: None,
schema: None,
};
let node_rows = call("db.schema.nodeTypeProperties", &storage);
let score = node_rows
.iter()
.find(|row| row.get("propertyName") == Some(&Value::String("score".to_owned())))
.expect("score schema row");
assert_eq!(
score["nodeType"],
Value::String(":`Employee`:`Person`".to_owned())
);
assert_eq!(
score["propertyTypes"],
Value::List(vec![
Value::String("Double".to_owned()),
Value::String("Long".to_owned())
])
);
assert_eq!(score["mandatory"], Value::Boolean(true));
let person_name = node_rows
.iter()
.find(|row| {
row.get("nodeType") == Some(&Value::String(":`Person`".to_owned()))
&& row.get("propertyName") == Some(&Value::String("name".to_owned()))
})
.expect("person name schema row");
assert_eq!(person_name["mandatory"], Value::Boolean(false));
let relationship_rows = call("db.schema.relTypeProperties", &storage);
let since = relationship_rows
.iter()
.find(|row| row.get("propertyName") == Some(&Value::String("since".to_owned())))
.expect("relationship property schema row");
assert_eq!(since["relType"], Value::String(":`KNOWS`".to_owned()));
assert_eq!(since["mandatory"], Value::Boolean(false));
assert!(relationship_rows.iter().any(|row| {
row.get("relType") == Some(&Value::String(":`EMPTY`".to_owned()))
&& row.get("propertyName") == Some(&Value::Null)
&& row.get("mandatory") == Some(&Value::Boolean(false))
}));
}
#[test]
fn schema_visualization_builds_virtual_cartesian_relationships() {
let storage = CatalogStorage {
nodes: vec![
Node {
id: 0,
external_id: "4:node:0".to_owned(),
labels: vec!["Alpha".to_owned()],
properties: Properties::new(),
},
Node {
id: 1,
external_id: "4:node:1".to_owned(),
labels: vec!["Beta".to_owned(), "Gamma".to_owned()],
properties: Properties::new(),
},
Node {
id: 2,
external_id: "4:node:2".to_owned(),
labels: vec!["Isolated".to_owned()],
properties: Properties::new(),
},
],
relationships: vec![Relationship {
id: 0,
external_id: "5:rel:0".to_owned(),
start: 0,
end: 1,
r#type: "LINKS".to_owned(),
properties: Properties::new(),
}],
labels: vec![
"Alpha".to_owned(),
"Beta".to_owned(),
"Gamma".to_owned(),
"Isolated".to_owned(),
],
relationship_types: vec!["LINKS".to_owned()],
property_keys: Vec::new(),
metadata: None,
schema: Some(SchemaMetadata {
indexes: vec![
SchemaIndexDescriptor {
id: 1,
name: "alpha_name".to_owned(),
schema: SchemaDescriptor {
entity_type: SchemaEntityType::Node,
entity_tokens: vec!["Alpha".to_owned()],
property_keys: vec!["name".to_owned(), "code".to_owned()],
matching_type: "COMPLETE_ALL_TOKENS".to_owned(),
},
index_type: "RANGE".to_owned(),
provider: "range-1.0".to_owned(),
unique: false,
owning_constraint: None,
},
SchemaIndexDescriptor {
id: 2,
name: "alpha_unique".to_owned(),
schema: SchemaDescriptor {
entity_type: SchemaEntityType::Node,
entity_tokens: vec!["Alpha".to_owned()],
property_keys: vec!["id".to_owned()],
matching_type: "COMPLETE_ALL_TOKENS".to_owned(),
},
index_type: "RANGE".to_owned(),
provider: "range-1.0".to_owned(),
unique: true,
owning_constraint: Some(3),
},
],
constraints: vec![SchemaConstraintDescriptor {
id: 3,
name: "alpha_id".to_owned(),
schema: SchemaDescriptor {
entity_type: SchemaEntityType::Node,
entity_tokens: vec!["Alpha".to_owned()],
property_keys: vec!["id".to_owned()],
matching_type: "COMPLETE_ALL_TOKENS".to_owned(),
},
constraint_type: "UNIQUE".to_owned(),
graph_type_dependence: "UNDESIGNATED".to_owned(),
index_type: Some("RANGE".to_owned()),
owned_index: Some(2),
property_types: Vec::new(),
endpoint_type: None,
endpoint_label: None,
required_label: None,
}],
}),
};
let rows = call("db.schema.visualization", &storage);
assert_eq!(rows.len(), 1);
let Value::List(nodes) = &rows[0]["nodes"] else {
panic!("expected virtual nodes")
};
let Value::List(relationships) = &rows[0]["relationships"] else {
panic!("expected virtual relationships")
};
assert_eq!(nodes.len(), 4);
assert_eq!(relationships.len(), 2);
let node_ids = nodes
.iter()
.map(|node| match node {
Value::Node(node) => {
assert!(node.id.starts_with('-'));
if node.properties["name"] == Value::String("Alpha".to_owned()) {
assert_eq!(
node.properties["indexes"],
Value::List(vec![Value::String("name,code".to_owned())])
);
assert_eq!(
node.properties["constraints"],
Value::List(vec![Value::String(
"Constraint( id=3, name='alpha_id', type='NODE PROPERTY UNIQUENESS', schema=(:Alpha {id}), ownedIndex=2 )"
.to_owned()
)])
);
} else {
assert_eq!(node.properties["indexes"], Value::List(Vec::new()));
assert_eq!(node.properties["constraints"], Value::List(Vec::new()));
}
node.id.clone()
}
value => panic!("expected node, got {value:?}"),
})
.collect::<BTreeSet<_>>();
for relationship in relationships {
let Value::Relationship(relationship) = relationship else {
panic!("expected relationship")
};
assert!(relationship.id.starts_with('-'));
assert!(node_ids.contains(&relationship.start));
assert!(node_ids.contains(&relationship.end));
assert_eq!(relationship.r#type, "LINKS");
assert_eq!(
relationship.properties["name"],
Value::String("LINKS".to_owned())
);
}
let empty = CatalogStorage {
nodes: Vec::new(),
relationships: Vec::new(),
labels: Vec::new(),
relationship_types: Vec::new(),
property_keys: Vec::new(),
metadata: None,
schema: None,
};
let empty_rows = call("db.schema.visualization", &empty);
assert_eq!(empty_rows[0]["nodes"], Value::List(Vec::new()));
assert_eq!(empty_rows[0]["relationships"], Value::List(Vec::new()));
}
#[test]
fn formats_every_decoded_constraint_kind_like_neo4j() {
fn constraint(
id: u64,
name: &str,
entity_type: SchemaEntityType,
entity_token: &str,
property_keys: &[&str],
constraint_type: &str,
) -> SchemaConstraintDescriptor {
SchemaConstraintDescriptor {
id,
name: name.to_owned(),
schema: SchemaDescriptor {
entity_type,
entity_tokens: vec![entity_token.to_owned()],
property_keys: property_keys
.iter()
.map(|property| (*property).to_owned())
.collect(),
matching_type: "COMPLETE_ALL_TOKENS".to_owned(),
},
constraint_type: constraint_type.to_owned(),
graph_type_dependence: "UNDESIGNATED".to_owned(),
index_type: None,
owned_index: None,
property_types: Vec::new(),
endpoint_type: None,
endpoint_label: None,
required_label: None,
}
}
let mut unique = constraint(
1,
"unique",
SchemaEntityType::Node,
"Label:One",
&["prop:one", "prop2"],
"UNIQUE",
);
unique.owned_index = Some(7);
assert_eq!(
super::constraint_user_description(&unique),
"Constraint( id=1, name='unique', type='NODE PROPERTY UNIQUENESS', schema=(:`Label:One` {`prop:one`, prop2}), ownedIndex=7 )"
);
let exists = constraint(
2,
"exists",
SchemaEntityType::Node,
"Label",
&["prop"],
"EXISTS",
);
assert_eq!(
super::constraint_user_description(&exists),
"Constraint( id=2, name='exists', type='NODE PROPERTY EXISTENCE', schema=(:Label {prop}) )"
);
let mut node_key = constraint(
3,
"node_key",
SchemaEntityType::Node,
"Label",
&["first", "second"],
"UNIQUE_EXISTS",
);
node_key.owned_index = Some(8);
assert_eq!(
super::constraint_user_description(&node_key),
"Constraint( id=3, name='node_key', type='NODE KEY', schema=(:Label {first, second}), ownedIndex=8 )"
);
let mut property_type = constraint(
4,
"property_type",
SchemaEntityType::Node,
"Label",
&["prop"],
"PROPERTY_TYPE",
);
property_type.property_types = vec!["BOOLEAN".to_owned(), "INTEGER".to_owned()];
assert_eq!(
super::constraint_user_description(&property_type),
"Constraint( id=4, name='property_type', type='NODE PROPERTY TYPE', schema=(:Label {prop}), propertyType=BOOLEAN | INTEGER )"
);
let mut endpoint = constraint(
5,
"endpoint",
SchemaEntityType::Relationship,
"LINKS",
&[],
"RELATIONSHIP_ENDPOINT_LABEL",
);
endpoint.endpoint_type = Some("START".to_owned());
endpoint.endpoint_label = Some("Source".to_owned());
assert_eq!(
super::constraint_user_description(&endpoint),
"Constraint( id=5, name='endpoint', type='RELATIONSHIP SOURCE LABEL', schema=()-[:LINKS {}]-(), enforcedLabel=Source )"
);
let mut required_label = constraint(
6,
"required_label",
SchemaEntityType::Node,
"Label",
&[],
"NODE_LABEL_EXISTENCE",
);
required_label.required_label = Some("Required".to_owned());
assert_eq!(
super::constraint_user_description(&required_label),
"Constraint( id=6, name='required_label', type='NODE LABEL EXISTENCE', schema=(:Label {}), enforcedLabel=Required )"
);
}
}