use std::collections::BTreeMap;
use std::str::FromStr;
use relate_core::{Error, Result, Value};
use relate_model::identifier::quote_identifier_always;
use relate_model::EntityKind;
use crate::eval::filter_rows_where;
use crate::graph::QueryStats;
use crate::overlay::ExecGraph;
use crate::row::Row;
use super::ddl_options::KEY_INDEX_CONFIG;
use super::scope::visible_keys;
use super::{catalog_schema, catalog_show, graph_type_schema, QueryResult};
use crate::ctx::QueryCtx;
const CURRENT_USER: &str = "neo4j";
fn executable_by_user(executable: Option<&relate_parser::ExecutableBy>) -> bool {
use relate_parser::ExecutableBy;
match executable {
None | Some(ExecutableBy::Current) => true,
Some(ExecutableBy::User(user)) => user == CURRENT_USER,
}
}
pub(crate) fn constraint_binding<'a>(
def: &relate_catalog::ConstraintDef,
derived: &'a BTreeMap<String, relate_model::Constraint>,
) -> ConstraintBinding<'a> {
ConstraintBinding {
kind: relate_model::ConstraintType::from_str(&def.kind).ok(),
entity: EntityKind::from_relationship_flag(def.relationship),
detail: derived.get(&def.name),
}
}
pub(crate) struct ConstraintBinding<'a> {
pub kind: Option<relate_model::ConstraintType>,
pub entity: EntityKind,
pub detail: Option<&'a relate_model::Constraint>,
}
pub(crate) struct SpaceConstraintNames {
pub visualization: &'static str,
pub graph_counts: &'static str,
}
pub(crate) fn space_constraint_names(kind: relate_model::ConstraintType) -> SpaceConstraintNames {
use relate_model::ConstraintType;
match kind {
ConstraintType::Unique => SpaceConstraintNames {
visualization: "NODE PROPERTY UNIQUENESS",
graph_counts: "Uniqueness constraint",
},
ConstraintType::Key => SpaceConstraintNames {
visualization: "NODE KEY",
graph_counts: "Node Key",
},
ConstraintType::Exists => SpaceConstraintNames {
visualization: "NODE PROPERTY EXISTENCE",
graph_counts: "Existence constraint",
},
ConstraintType::PropertyType => SpaceConstraintNames {
visualization: "NODE PROPERTY TYPE",
graph_counts: "Property type constraint",
},
ConstraintType::LabelExistence | ConstraintType::NodeLabelExistence => {
SpaceConstraintNames {
visualization: "NODE LABEL EXISTENCE",
graph_counts: "Node label existence constraint",
}
}
ConstraintType::SourceLabel => SpaceConstraintNames {
visualization: "RELATIONSHIP SOURCE LABEL",
graph_counts: "Relationship endpoint label constraint",
},
ConstraintType::SourceLabelExistence => SpaceConstraintNames {
visualization: "RELATIONSHIP SOURCE LABEL EXISTENCE",
graph_counts: "Relationship endpoint label constraint",
},
ConstraintType::TargetLabel => SpaceConstraintNames {
visualization: "RELATIONSHIP TARGET LABEL",
graph_counts: "Relationship endpoint label constraint",
},
ConstraintType::TargetLabelExistence => SpaceConstraintNames {
visualization: "RELATIONSHIP TARGET LABEL EXISTENCE",
graph_counts: "Relationship endpoint label constraint",
},
}
}
pub(crate) fn imported_catalog(
rows: Vec<indexmap::IndexMap<String, relate_model::CypherValue>>,
) -> Vec<Row> {
rows.into_iter()
.map(|r| {
r.into_iter()
.map(|(k, v)| (k, relate_core::cypher_to_value(&v)))
.collect()
})
.collect()
}
fn visible_catalog(
visible: bool,
rows: impl FnOnce() -> Vec<indexmap::IndexMap<String, relate_model::CypherValue>>,
) -> Vec<Row> {
if visible {
imported_catalog(rows())
} else {
Vec::new()
}
}
fn require_catalog_info(
clause: &relate_parser::Clause,
) -> Result<relate_front::show_columns::CatalogInfo<'_>> {
relate_front::show_columns::catalog_info(clause)
.ok_or_else(|| Error::internal("catalog projection called for a non-catalog clause"))
}
const SOURCE_CELLS: &str = "\u{0}show.sources";
const SOURCE_PREVIOUS: &str = "\u{0}show.previous";
fn compose_catalog_rows(
info: &relate_front::show_columns::CatalogInfo<'_>,
input: impl IntoIterator<Item = Row>,
mut catalog: Vec<Row>,
) -> Vec<Row> {
if info.prefill {
for row in &mut catalog {
for column in &info.full_columns {
row.entry(column.clone()).or_insert(Value::Null);
}
}
}
let projection = info.projection();
let fill: Option<&[(String, String)]> = match &projection {
relate_front::show_columns::CatalogProjection::Star => None,
relate_front::show_columns::CatalogProjection::Columns(pairs) => Some(pairs),
};
let mut output = Vec::new();
for outer in input {
for raw in &catalog {
let mut row = outer.clone();
match fill {
None => {
for (k, v) in raw {
row.entry(k.clone()).or_insert_with(|| v.clone());
}
}
Some(pairs) => {
let outputs: std::collections::HashSet<&str> =
pairs.iter().map(|(out, _)| out.as_str()).collect();
let mut sources = BTreeMap::new();
for (out, src) in pairs {
let value = raw.get(src).cloned().unwrap_or(Value::Null);
if src != out && !outputs.contains(src.as_str()) {
sources.insert(src.clone(), value.clone());
}
row.insert(out.clone(), value);
}
if !sources.is_empty() {
let mut previous = BTreeMap::new();
for (key, value) in &sources {
if let Some(old) = row.get(key) {
previous.insert(key.clone(), old.clone());
}
row.insert(key.clone(), value.clone());
}
row.insert(SOURCE_CELLS.into(), Value::Map(sources.into()));
row.insert(SOURCE_PREVIOUS.into(), Value::Map(previous.into()));
}
}
}
output.push(row);
}
}
output
}
fn restore_source_names(row: &mut Row) -> Result<()> {
let marker_invariant_broken = |marker: &str, found: Option<&Value>| {
Error::internal(format!(
"SHOW source-name restore: {marker} did not hold the map the write \
site inserts (found {found:?}); {SOURCE_CELLS} and {SOURCE_PREVIOUS} \
are always written together"
))
};
let sources = match row.shift_remove(SOURCE_CELLS) {
None => return Ok(()),
Some(Value::Map(sources)) => sources,
Some(other) => return Err(marker_invariant_broken(SOURCE_CELLS, Some(&other))),
};
let previous = match row.shift_remove(SOURCE_PREVIOUS) {
Some(Value::Map(previous)) => previous,
other => return Err(marker_invariant_broken(SOURCE_PREVIOUS, other.as_ref())),
};
for key in sources.keys() {
match previous.get(key) {
Some(value) => {
row.insert(key.clone(), value.clone());
}
None => {
row.shift_remove(key);
}
}
}
Ok(())
}
fn finish_catalog_rows(
graph: &ExecGraph<'_>,
info: &relate_front::show_columns::CatalogInfo<'_>,
params: &BTreeMap<String, Value>,
mut output: Vec<Row>,
) -> Result<Vec<Row>> {
let predicate = info.where_expr.map(relate_front::lower_expr).transpose()?;
super::order::apply_yield_page_stages(graph, params, info.stages, &mut output)?;
if let Some(predicate) = predicate.as_ref() {
output = filter_rows_where(graph, params, predicate, output)?;
}
for row in &mut output {
restore_source_names(row)?;
}
Ok(output)
}
pub(crate) fn project_catalog(
graph: &ExecGraph<'_>,
input: Vec<Row>,
catalog: Vec<Row>,
clause: &relate_parser::Clause,
params: &BTreeMap<String, Value>,
) -> Result<Vec<Row>> {
let info = require_catalog_info(clause)?;
let output = compose_catalog_rows(&info, input, catalog);
finish_catalog_rows(graph, &info, params, output)
}
pub(crate) fn project_catalog_by_row<F>(
graph: &ExecGraph<'_>,
input: Vec<Row>,
clause: &relate_parser::Clause,
params: &BTreeMap<String, Value>,
mut select: F,
) -> Result<Vec<Row>>
where
F: FnMut(&Row) -> Result<Vec<Row>>,
{
let info = require_catalog_info(clause)?;
let mut output = Vec::new();
for row in input {
let catalog = select(&row)?;
output.extend(compose_catalog_rows(&info, std::iter::once(row), catalog));
}
finish_catalog_rows(graph, &info, params, output)
}
pub(crate) fn catalog_result(rows: &[Row], clause: &relate_parser::Clause) -> Option<QueryResult> {
let info = relate_front::show_columns::catalog_info(clause)?;
let columns = match info.projection() {
relate_front::show_columns::CatalogProjection::Star => rows
.first()
.map(visible_keys)
.unwrap_or_else(|| info.full_columns.clone()),
relate_front::show_columns::CatalogProjection::Columns(pairs) => {
pairs.into_iter().map(|(output, _)| output).collect()
}
};
let data = rows
.iter()
.map(|row| {
super::read_declared_columns(row, &columns, super::Missing::Null)
.expect("padding a missing result column with null is infallible")
})
.collect();
Some(QueryResult::intermediate(
columns,
data,
QueryStats::default(),
))
}
pub(crate) fn catalog_row(pairs: impl IntoIterator<Item = (&'static str, Value)>) -> Row {
pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()
}
pub(crate) fn principal_cell(principal: Option<&str>, placeholder: &str) -> Value {
Value::String(principal.unwrap_or(placeholder).into())
}
pub(crate) fn string_list(values: impl IntoIterator<Item = String>) -> Value {
Value::List(
values
.into_iter()
.map(|s| Value::String(s.into()))
.collect::<Vec<_>>()
.into(),
)
}
pub(crate) fn optional_string_cell(value: Option<&str>) -> Value {
value
.map(|s| Value::String(s.into()))
.unwrap_or(Value::Null)
}
pub(crate) fn options_cell(options: &BTreeMap<String, Value>) -> Value {
let mut cell = options.clone();
cell.entry(KEY_INDEX_CONFIG.to_string())
.or_insert_with(|| Value::Map(BTreeMap::new().into()));
Value::Map(cell.into())
}
pub(crate) fn schema_id_cell(committed: bool) -> Value {
if committed {
Value::Int(0)
} else {
Value::Null
}
}
pub(crate) fn backtick(identifier: &str) -> String {
quote_identifier_always(identifier)
}
pub(crate) fn schema_name_value(
name: &relate_parser::SchemaName,
params: &BTreeMap<String, Value>,
) -> Result<String> {
match name {
relate_parser::SchemaName::Literal(name) => Ok(name.clone()),
relate_parser::SchemaName::Parameter(name) => match params.get(name) {
Some(Value::String(value)) => Ok(String::from(&**value)),
None => Err(Error::parameters_missing([name.as_str()])),
Some(_) => Err(Error::type_error("schema name must be STRING")),
},
}
}
enum CatalogArm {
CrossJoin(Vec<Row>),
Finished(Vec<Row>),
}
pub(crate) fn execute_catalog(
graph: &ExecGraph<'_>,
clause: &relate_parser::Clause,
rows: Vec<Row>,
params: &BTreeMap<String, Value>,
qctx: QueryCtx<'_>,
) -> Result<Vec<Row>> {
use relate_parser::{Clause as C, FunctionScope};
let mut rows = rows;
let arm = match clause {
C::ShowFunctions(c) => CatalogArm::CrossJoin(visible_catalog(
!matches!(c.scope, FunctionScope::UserDefined)
&& executable_by_user(c.executable.as_ref()),
|| crate::show_catalog::function_catalog_rows(graph.preview()),
)),
C::ShowProcedures(c) => CatalogArm::CrossJoin(visible_catalog(
executable_by_user(c.executable.as_ref()),
|| crate::show_catalog::procedure_catalog_rows(graph.preview()),
)),
C::ShowRoles(c) => CatalogArm::CrossJoin(catalog_show::show_roles_rows(c)),
C::ShowServers(_) => CatalogArm::CrossJoin(vec![catalog_row([(
"name",
Value::String("relate-server-1".into()),
)])]),
C::ShowUsers(_) => CatalogArm::CrossJoin(vec![catalog_row([(
"user",
Value::String(CURRENT_USER.into()),
)])]),
C::ShowSettings(c) => CatalogArm::Finished(catalog_show::show_settings_rows(
graph,
c,
std::mem::take(&mut rows),
clause,
params,
)?),
C::ShowTransactions(c) => CatalogArm::CrossJoin(catalog_show::show_transactions_rows(
graph, c, &rows, params, qctx,
)?),
C::TerminateTransactions(c) => {
CatalogArm::Finished(catalog_show::terminate_transactions_rows(
graph,
c,
std::mem::take(&mut rows),
clause,
params,
)?)
}
C::ShowDatabases(c) => {
CatalogArm::CrossJoin(catalog_show::show_databases_rows(graph, c, params)?)
}
C::ShowIndexes(c) => CatalogArm::CrossJoin(catalog_show::show_indexes_rows(graph, c)?),
C::ShowConstraints(c) => {
CatalogArm::CrossJoin(catalog_show::show_constraints_rows(graph, c)?)
}
C::ShowGraphType(c) => CatalogArm::CrossJoin(catalog_show::show_graph_type_rows(graph, c)?),
C::ShowCurrentGraphType(c) => {
CatalogArm::CrossJoin(catalog_show::show_current_graph_type_rows(graph, c)?)
}
C::CreateIndex(c) => CatalogArm::Finished(catalog_schema::catalog_create_index(
graph,
c,
std::mem::take(&mut rows),
params,
)?),
C::DropIndex(c) => CatalogArm::Finished(catalog_schema::catalog_drop_index(
graph,
c,
std::mem::take(&mut rows),
params,
)?),
C::CreateConstraint(c) => CatalogArm::Finished(catalog_schema::catalog_create_constraint(
graph,
c,
std::mem::take(&mut rows),
params,
)?),
C::DropConstraint(c) => CatalogArm::Finished(catalog_schema::catalog_drop_constraint(
graph,
c,
std::mem::take(&mut rows),
params,
)?),
C::AlterDatabase(c) => CatalogArm::Finished(catalog_schema::catalog_alter_database(
graph,
c,
std::mem::take(&mut rows),
params,
)?),
C::CreateGraphType(c) => {
CatalogArm::Finished(graph_type_schema::catalog_create_graph_type(
graph,
c,
std::mem::take(&mut rows),
params,
)?)
}
C::AlterCurrentGraphType(c) => {
CatalogArm::Finished(graph_type_schema::alter_current_graph_type(
graph,
c,
std::mem::take(&mut rows),
params,
)?)
}
_ => return Err(Error::semantic("unsupported catalog command")),
};
match arm {
CatalogArm::Finished(rows) => Ok(rows),
CatalogArm::CrossJoin(catalog) => project_catalog(graph, rows, catalog, clause, params),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn imported_catalog_preserves_temporal_and_map_list_values() {
let date = chrono::NaiveDate::from_ymd_opt(2024, 2, 29).unwrap();
let mut attrs = indexmap::IndexMap::new();
attrs.insert("nested".to_string(), relate_model::CypherValue::Int(7));
let mut row = indexmap::IndexMap::new();
row.insert("created".to_string(), relate_model::CypherValue::Date(date));
row.insert("attrs".to_string(), relate_model::CypherValue::Map(attrs));
row.insert(
"tags".to_string(),
relate_model::CypherValue::List(vec![
relate_model::CypherValue::Str("a".to_string()),
relate_model::CypherValue::Int(2),
]),
);
let rows = imported_catalog(vec![row]);
assert_eq!(rows.len(), 1);
let row = &rows[0];
assert!(matches!(
row.get("created"),
Some(Value::Temporal(relate_core::temporal::Temporal::Date(d))) if *d == date
));
assert!(
matches!(row.get("attrs"), Some(Value::Map(m)) if m.get("nested") == Some(&Value::Int(7)))
);
match row.get("tags") {
Some(Value::List(items)) => {
assert_eq!(items[0], Value::String("a".into()));
assert_eq!(items[1], Value::Int(2));
}
other => panic!("expected list, got {other:?}"),
}
}
}