relate_executor/exec/catalog_show/
mod.rs1use relate_core::{Error, Result, Value};
4use relate_model::EntityKind;
5use relate_parser::RoleModifier;
6
7use crate::graph::Graph;
8use crate::overlay::ExecGraph;
9use crate::row::Row;
10
11use super::catalog::{backtick, catalog_row, constraint_binding};
12
13pub(crate) mod constraints;
14mod databases;
15pub(crate) mod indexes;
16mod settings;
17mod transactions;
18
19pub(crate) use constraints::show_constraints_rows;
20pub(crate) use databases::show_databases_rows;
21pub(crate) use indexes::{show_indexes_result, show_indexes_rows};
22pub(crate) use settings::show_settings_rows;
23pub(crate) use transactions::{show_transactions_rows, terminate_transactions_rows};
24
25fn entity_variable(entity: EntityKind) -> &'static str {
30 match entity {
31 EntityKind::Node => "n",
32 EntityKind::Relationship => "r",
33 }
34}
35
36pub(super) fn entity_pattern(entity: EntityKind, labels: &[String]) -> String {
39 let variable = entity_variable(entity);
40 let tokens = labels
41 .iter()
42 .map(|label| backtick(label))
43 .collect::<Vec<_>>()
44 .join("|");
45 match entity {
46 EntityKind::Node => format!("({variable}:{tokens})"),
47 EntityKind::Relationship => format!("()-[{variable}:{tokens}]-()"),
48 }
49}
50
51pub fn catalog_create_statements(graph: &Graph) -> Vec<String> {
65 let snapshot = graph.schema_snapshot();
66 let data = &snapshot.show.data;
67 let current = data.current_graph_type.to_body();
68 snapshot
69 .indexes
70 .iter()
71 .filter_map(|idx| {
74 indexes::index_ddl_statement(
75 idx,
76 &data.index_details,
77 &data.index_options,
78 &snapshot.constraints,
79 )
80 })
81 .chain(snapshot.constraints.iter().filter_map(|def| {
82 constraints::constraint_statement_for(def, ¤t, &data.derived_constraints)
91 }))
92 .collect()
93}
94
95pub(crate) fn show_roles_rows(c: &relate_parser::ShowRolesClause) -> Vec<Row> {
96 let roles = [
97 ("admin", Some("neo4j")),
98 ("architect", None),
99 ("publisher", None),
100 ("editor", None),
101 ("reader", None),
102 ("PUBLIC", None),
103 ];
104 roles
105 .into_iter()
106 .filter(|(_, member)| !matches!(c.modifier, RoleModifier::Populated) || member.is_some())
107 .map(|(role, member)| {
108 let mut row = catalog_row([("role", Value::String(role.into()))]);
109 if c.with_users {
110 row.insert(
111 "member".into(),
112 member
113 .map(|m| Value::String(m.into()))
114 .unwrap_or(Value::Null),
115 );
116 }
117 row
118 })
119 .collect()
120}
121
122pub(crate) fn show_graph_type_rows(
123 graph: &ExecGraph<'_>,
124 c: &relate_parser::ShowGraphTypeClause,
125) -> Result<Vec<Row>> {
126 Ok({
127 let state = graph.show_schema()?;
128 let body = c
131 .name
132 .with_str(|text| state.data.graph_types.get(text))
133 .ok_or_else(|| Error::semantic("GraphTypeNotFound"))?;
134 vec![catalog_row([
135 ("name", Value::String(c.name.to_string().into())),
136 (
137 "body",
138 Value::String(
139 crate::graph_type::canonicalize_graph_type_body(&body.to_body())
140 .map_err(crate::graph_type::persisted_derive_error)?
141 .into(),
142 ),
143 ),
144 ])]
145 })
146}
147
148pub(crate) fn show_current_graph_type_rows(
149 graph: &ExecGraph<'_>,
150 c: &relate_parser::ShowCurrentGraphTypeClause,
151) -> Result<Vec<Row>> {
152 let state = graph.show_schema()?;
153 let extras = graph
154 .named_constraints()
155 .into_iter()
156 .filter(|constraint| {
157 !state
158 .data
159 .derived_constraints
160 .contains_key(constraint.name.as_str())
161 })
162 .map(|constraint| {
163 let binding = constraint_binding(&constraint, &state.data.derived_constraints);
167 let kind = binding.kind.ok_or_else(|| {
168 Error::internal(format!(
169 "constraint `{}` carries the unrecognized kind tag `{}`",
170 constraint.name, constraint.kind
171 ))
172 })?;
173 Ok(constraint.to_model(kind))
174 })
175 .collect::<Result<Vec<_>>>()?;
176 Ok(if let Some(as_graph) = c.as_graph {
177 let (nodes, rels) = crate::graph_type_visualize::render_graph_type_as_graph(
178 &state.data.current_graph_type.to_body(),
179 &extras,
180 as_graph,
181 )?;
182 vec![catalog_row([
183 (
184 "nodes",
185 Value::List(
186 nodes
187 .iter()
188 .map(relate_core::cypher_to_value)
189 .collect::<Vec<_>>()
190 .into(),
191 ),
192 ),
193 (
194 "relationships",
195 Value::List(
196 rels.iter()
197 .map(relate_core::cypher_to_value)
198 .collect::<Vec<_>>()
199 .into(),
200 ),
201 ),
202 ])]
203 } else {
204 vec![catalog_row([(
205 "specification",
206 Value::String(
207 crate::graph_type::current_graph_type_specification(
208 &state.data.current_graph_type.to_body(),
209 &extras,
210 )
211 .map_err(crate::graph_type::persisted_derive_error)?
212 .into(),
213 ),
214 )])]
215 })
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221 use crate::graph::Graph;
222
223 fn show_databases(query: &str) -> Vec<Row> {
228 let mut graph = Graph::default();
234 graph.configure_preview(relate_core::PreviewFeatures::parse("ontology").unwrap());
235 crate::exec::test_support::show_catalog_rows(&graph, query)
236 }
237
238 fn row_named<'a>(rows: &'a [Row], name: &str) -> &'a Row {
239 rows.iter()
240 .find(|row| row.get("name") == Some(&Value::String(name.into())))
241 .unwrap_or_else(|| panic!("no row for {name}"))
242 }
243
244 fn assert_browser_compat_row(row: &Row, is_default: bool, expected_access: &str) {
250 assert!(
251 matches!(row.get("access"), Some(Value::String(s)) if &**s == expected_access),
252 "access: {:?}",
253 row.get("access")
254 );
255 assert!(
256 matches!(row.get("address"), Some(Value::String(s)) if &**s == "localhost:7687"),
257 "address: {:?}",
258 row.get("address")
259 );
260 assert!(
261 matches!(row.get("role"), Some(Value::String(s)) if &**s == "primary"),
262 "role: {:?}",
263 row.get("role")
264 );
265 assert!(
266 matches!(row.get("requestedStatus"), Some(Value::String(s)) if &**s == "online"),
267 "requestedStatus: {:?}",
268 row.get("requestedStatus")
269 );
270 assert!(
271 matches!(row.get("currentStatus"), Some(Value::String(s)) if &**s == "online"),
272 "currentStatus: {:?}",
273 row.get("currentStatus")
274 );
275 assert!(
276 matches!(row.get("statusMessage"), Some(Value::String(s)) if s.is_empty()),
277 "statusMessage: {:?}",
278 row.get("statusMessage")
279 );
280 assert_eq!(row.get("writer"), Some(&Value::Bool(true)));
281 assert_eq!(row.get("default"), Some(&Value::Bool(is_default)));
282 assert_eq!(row.get("home"), Some(&Value::Bool(is_default)));
283 }
284
285 fn assert_fixed_namespace_rows(rows: &[Row]) {
290 assert_eq!(rows.len(), 3);
291 assert_browser_compat_row(row_named(rows, "neo4j"), true, "read-write");
292 assert_browser_compat_row(row_named(rows, "system"), false, "read-write");
293 assert_browser_compat_row(row_named(rows, "system_ontologies"), false, "read-only");
294 }
295
296 #[test]
297 fn bare_show_databases_rows_carry_browser_compat_values() {
298 assert_fixed_namespace_rows(&show_databases("SHOW DATABASES"));
299 }
300
301 #[test]
302 fn show_databases_yield_exposes_browser_compat_values() {
303 relate_front::parse_and_lower(
306 "SHOW DATABASES YIELD name, access, address, role, writer, \
307 requestedStatus, currentStatus, statusMessage, default, home \
308 RETURN name",
309 )
310 .expect("front validates the YIELD list");
311 assert_fixed_namespace_rows(&show_databases(
312 "SHOW DATABASES YIELD name, access, address, role, writer, \
313 requestedStatus, currentStatus, statusMessage, default, home",
314 ));
315 }
316
317 #[test]
318 fn show_databases_yield_star_exposes_browser_compat_values() {
319 assert_fixed_namespace_rows(&show_databases("SHOW DATABASES YIELD *"));
320 }
321
322 #[test]
326 fn show_databases_without_the_opt_in_lists_the_two_ce_rows() {
327 let graph = Graph::default();
328 let rows = crate::exec::test_support::show_catalog_rows(&graph, "SHOW DATABASES");
329 assert_eq!(rows.len(), 2);
330 assert_browser_compat_row(row_named(&rows, "neo4j"), true, "read-write");
331 assert_browser_compat_row(row_named(&rows, "system"), false, "read-write");
332 }
333
334 #[test]
335 fn show_default_database_row_marks_neo4j_default_and_home() {
336 let rows = show_databases("SHOW DEFAULT DATABASE");
337 assert_eq!(rows.len(), 1);
338 assert_browser_compat_row(row_named(&rows, "neo4j"), true, "read-write");
339 }
340
341 #[test]
348 fn show_databases_row_key_order_matches_front_column_tables() {
349 crate::exec::test_support::assert_row_keys_match(
350 None,
351 "SHOW DATABASES YIELD *",
352 &relate_front::show_columns::full_database_columns(),
353 );
354 }
355
356 #[test]
361 fn catalog_create_statements_are_the_show_create_statement_renders() {
362 use crate::exec::test_support::{column, exec_autocommit, exec_cypher, string_cell};
363
364 let g = Graph::default();
365 exec_autocommit(&g, "CREATE INDEX person_name FOR (n:Person) ON (n.name)").unwrap();
366 exec_autocommit(&g, "CREATE TEXT INDEX book_title FOR (n:Book) ON (n.title)").unwrap();
367 exec_autocommit(
368 &g,
369 "CREATE CONSTRAINT person_email FOR (n:Person) REQUIRE n.email IS NOT NULL",
370 )
371 .unwrap();
372
373 let ddl = super::catalog_create_statements(&g);
374 assert_eq!(ddl.len(), 3, "{ddl:?}");
375
376 let show_indexes = exec_cypher(
383 &g,
384 "SHOW INDEXES YIELD name, type, createStatement \
385 WHERE type <> 'LOOKUP' RETURN createStatement",
386 );
387 let index_statements = column(&show_indexes, "createStatement", string_cell);
388 let show_constraints = exec_cypher(&g, "SHOW CONSTRAINTS YIELD createStatement");
389 let constraint_statements = column(&show_constraints, "createStatement", string_cell);
390 assert_eq!(&ddl[..index_statements.len()], &index_statements[..]);
391 assert_eq!(&ddl[index_statements.len()..], &constraint_statements[..]);
392
393 assert_eq!(
395 ddl,
396 vec![
397 "CREATE TEXT INDEX `book_title` FOR (n:`Book`) ON (n.`title`)",
398 "CREATE RANGE INDEX `person_name` FOR (n:`Person`) ON (n.`name`)",
399 "CREATE CONSTRAINT `person_email` FOR (n:`Person`) REQUIRE (n.`email`) IS NOT NULL",
400 ]
401 );
402 }
403}