use std::collections::BTreeMap;
use relate_core::{Result, Value};
use relate_model::{ConstraintClassification, ConstraintType, EntityKind};
use relate_parser::{ConstraintEntityFilter, ConstraintKindFilter};
use crate::ctx::QueryCtx;
use crate::overlay::ExecGraph;
use crate::row::Row;
use super::entity_variable;
use crate::exec::catalog::{catalog_row, constraint_binding, optional_string_cell, string_list};
fn show_constraint_type_name(kind: ConstraintType, entity: EntityKind) -> &'static str {
match kind {
ConstraintType::Unique => match entity {
EntityKind::Node => "NODE_PROPERTY_UNIQUENESS",
EntityKind::Relationship => "RELATIONSHIP_PROPERTY_UNIQUENESS",
},
ConstraintType::Key => match entity {
EntityKind::Node => "NODE_KEY",
EntityKind::Relationship => "RELATIONSHIP_KEY",
},
ConstraintType::Exists => match entity {
EntityKind::Node => "NODE_PROPERTY_EXISTENCE",
EntityKind::Relationship => "RELATIONSHIP_PROPERTY_EXISTENCE",
},
ConstraintType::PropertyType => match entity {
EntityKind::Node => "NODE_PROPERTY_TYPE",
EntityKind::Relationship => "RELATIONSHIP_PROPERTY_TYPE",
},
ConstraintType::LabelExistence | ConstraintType::NodeLabelExistence => {
"NODE_LABEL_EXISTENCE"
}
ConstraintType::SourceLabel => "RELATIONSHIP_SOURCE_LABEL",
ConstraintType::SourceLabelExistence => "RELATIONSHIP_SOURCE_LABEL_EXISTENCE",
ConstraintType::TargetLabel => "RELATIONSHIP_TARGET_LABEL",
ConstraintType::TargetLabelExistence => "RELATIONSHIP_TARGET_LABEL_EXISTENCE",
}
}
fn constraint_filter_types(wanted: ConstraintKindFilter) -> &'static [ConstraintType] {
match wanted {
ConstraintKindFilter::Unique => &[ConstraintType::Unique],
ConstraintKindFilter::Key => &[ConstraintType::Key],
ConstraintKindFilter::PropertyType => &[ConstraintType::PropertyType],
ConstraintKindFilter::PropertyExistence => &[ConstraintType::Exists],
ConstraintKindFilter::Existence => &[
ConstraintType::Exists,
ConstraintType::LabelExistence,
ConstraintType::NodeLabelExistence,
ConstraintType::SourceLabelExistence,
ConstraintType::TargetLabelExistence,
],
}
}
fn constraint_create_statement(
def: &relate_catalog::ConstraintDef,
kind: Option<ConstraintType>,
entity: EntityKind,
classification: ConstraintClassification,
cypher5: bool,
) -> Option<String> {
if classification == ConstraintClassification::Dependent {
return None;
}
let kind = kind?;
if cypher5 && kind == ConstraintType::PropertyType {
return None;
}
let verb = crate::graph_type::standalone_verb(kind, def.property_type.as_deref())?;
let variable = entity_variable(entity);
let pattern = match entity {
EntityKind::Node => format!("({variable}:`{}`)", def.label),
EntityKind::Relationship => format!("()-[{variable}:`{}`]-()", def.label),
};
let properties = def
.properties
.iter()
.map(|property| format!("{variable}.`{property}`"))
.collect::<Vec<_>>()
.join(", ");
Some(format!(
"CREATE CONSTRAINT `{}` FOR {pattern} REQUIRE ({properties}) {verb}",
def.name
))
}
fn constraint_statement_binding(
def: &relate_catalog::ConstraintDef,
kind: Option<ConstraintType>,
entity: EntityKind,
current: &relate_parser::GraphTypeBody,
detail: Option<&relate_model::Constraint>,
cypher5: bool,
) -> (ConstraintClassification, Option<String>) {
let classification = detail
.map(|constraint| crate::graph_type::classify_constraint(current, constraint))
.unwrap_or_else(|| {
crate::graph_type::classify_constraint_parts(current, kind, entity, &def.label)
});
let statement = constraint_create_statement(def, kind, entity, classification, cypher5);
(classification, statement)
}
pub(super) fn constraint_ddl_statement(
def: &relate_catalog::ConstraintDef,
current: &relate_parser::GraphTypeBody,
derived: &BTreeMap<String, relate_model::Constraint>,
) -> Option<String> {
constraint_statement_for(def, current, derived, false)
}
pub(super) fn constraint_statement_for(
def: &relate_catalog::ConstraintDef,
current: &relate_parser::GraphTypeBody,
derived: &BTreeMap<String, relate_model::Constraint>,
cypher5: bool,
) -> Option<String> {
let binding = constraint_binding(def, derived);
let (kind, entity, detail) = (binding.kind, binding.entity, binding.detail);
constraint_statement_binding(def, kind, entity, current, detail, cypher5).1
}
struct ConstraintRowContext<'a> {
kind: Option<ConstraintType>,
entity: EntityKind,
detail: Option<&'a relate_model::Constraint>,
current: &'a relate_parser::GraphTypeBody,
cypher5: bool,
committed: bool,
}
fn constraint_row(def: relate_catalog::ConstraintDef, ctx: ConstraintRowContext<'_>) -> Row {
let ConstraintRowContext {
kind,
entity,
detail,
current,
cypher5,
committed,
} = ctx;
let index_backed = kind.is_some_and(|kind| kind.is_index_backed());
let display_type = kind.map_or("UNKNOWN", |kind| show_constraint_type_name(kind, entity));
let (classification, create_statement) =
constraint_statement_binding(&def, kind, entity, current, detail, cypher5);
let create_statement = optional_string_cell(create_statement.as_deref());
catalog_row([
("id", crate::exec::catalog::schema_id_cell(committed)),
("name", Value::String(def.name.as_str().into())),
("type", Value::String(display_type.into())),
("entityType", Value::String(entity.display_name().into())),
("labelsOrTypes", string_list([def.label])),
(
"properties",
if def.properties.is_empty() {
Value::Null
} else {
string_list(def.properties)
},
),
(
"ownedIndex",
optional_string_cell(index_backed.then_some(def.name.as_str())),
),
(
"propertyType",
optional_string_cell(def.property_type.as_deref()),
),
(
"enforcedLabel",
optional_string_cell(
detail.and_then(|constraint| constraint.enforced_label.as_deref()),
),
),
(
"classification",
Value::String(classification.as_str().into()),
),
(
"options",
if index_backed {
crate::exec::catalog::options_cell(&BTreeMap::new())
} else {
Value::Null
},
),
("createStatement", create_statement),
])
}
pub(crate) fn show_constraints_rows(
graph: &ExecGraph<'_>,
c: &relate_parser::ShowConstraintsClause,
qctx: QueryCtx<'_>,
) -> Result<Vec<Row>> {
let show = graph.show_schema()?;
let derived = &show.data.derived_constraints;
let current = show.data.current_graph_type.to_body();
let wanted_entity = match c.type_filter.entity {
ConstraintEntityFilter::Any => None,
ConstraintEntityFilter::Node => Some(EntityKind::Node),
ConstraintEntityFilter::Relationship => Some(EntityKind::Relationship),
};
let wanted_kind = c.type_filter.kind;
Ok(graph
.named_constraints()
.into_iter()
.filter_map(|def| {
let binding = constraint_binding(&def, derived);
let (kind, entity, detail) = (binding.kind, binding.entity, binding.detail);
let entity_matches = wanted_entity.is_none_or(|wanted| wanted == entity);
let kind_matches = wanted_kind.is_none_or(|wanted| {
kind.is_some_and(|k| constraint_filter_types(wanted).contains(&k))
});
(entity_matches && kind_matches).then_some((def, kind, entity, detail))
})
.map(|(def, kind, entity, detail)| {
let committed = graph.base().has_constraint(&def.name);
constraint_row(
def,
ConstraintRowContext {
kind,
entity,
detail,
current: ¤t,
cypher5: qctx.is_cypher5(),
committed,
},
)
})
.collect())
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use crate::exec::test_support::{assert_row_keys_match, column, exec_autocommit, exec_cypher};
use crate::graph::Graph;
#[test]
fn constraint_row_keys_match_front_column_tables() {
assert_row_keys_match(
Some("CREATE CONSTRAINT person_email FOR (n:Person) REQUIRE n.email IS NOT NULL"),
"SHOW CONSTRAINTS YIELD *",
&relate_front::show_columns::full_constraint_columns(),
);
}
#[test]
fn constraint_options_follow_the_index_backed_rule() {
let g = Graph::default();
exec_autocommit(
&g,
"CREATE CONSTRAINT k1 FOR (n:P) REQUIRE (n.id) IS UNIQUE",
)
.unwrap();
exec_autocommit(
&g,
"CREATE CONSTRAINT e1 FOR (n:P) REQUIRE (n.name) IS NOT NULL",
)
.unwrap();
let options = column(
&exec_cypher(&g, "SHOW CONSTRAINTS YIELD options"),
"options",
|value| Some(value.clone()),
);
let empty_config = relate_core::Value::Map(
[(
crate::exec::ddl_options::KEY_INDEX_CONFIG.to_string(),
relate_core::Value::Map(Default::default()),
)]
.into_iter()
.collect::<BTreeMap<_, _>>()
.into(),
);
assert_eq!(options, vec![relate_core::Value::Null, empty_config]);
}
}