1use 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]) -> Option<String> {
39 if labels.is_empty() {
41 return None;
42 }
43 let variable = entity_variable(entity);
44 let tokens = labels
45 .iter()
46 .map(|label| backtick(label))
47 .collect::<Vec<_>>()
48 .join("|");
49 Some(match entity {
50 EntityKind::Node => format!("({variable}:{tokens})"),
51 EntityKind::Relationship => format!("()-[{variable}:{tokens}]-()"),
52 })
53}
54
55pub fn catalog_create_statements(graph: &Graph) -> Vec<String> {
69 let snapshot = graph.schema_snapshot();
70 let data = &snapshot.show.data;
71 let current = data.current_graph_type.to_body();
72 snapshot
73 .indexes
74 .iter()
75 .filter_map(|idx| {
78 indexes::index_ddl_statement(
79 idx,
80 &data.index_details,
81 &data.index_options,
82 &snapshot.constraints,
83 )
84 })
85 .chain(snapshot.constraints.iter().filter_map(|def| {
86 constraints::constraint_statement_for(def, ¤t, &data.derived_constraints)
95 }))
96 .collect()
97}
98
99pub(crate) fn show_roles_rows(c: &relate_parser::ShowRolesClause) -> Vec<Row> {
100 let roles = [
101 ("admin", Some("neo4j")),
102 ("architect", None),
103 ("publisher", None),
104 ("editor", None),
105 ("reader", None),
106 ("PUBLIC", None),
107 ];
108 roles
109 .into_iter()
110 .filter(|(_, member)| !matches!(c.modifier, RoleModifier::Populated) || member.is_some())
111 .map(|(role, member)| {
112 let mut row = catalog_row([("role", Value::String(role.into()))]);
113 if c.with_users {
114 row.insert(
115 "member".into(),
116 member
117 .map(|m| Value::String(m.into()))
118 .unwrap_or(Value::Null),
119 );
120 }
121 row
122 })
123 .collect()
124}
125
126pub(crate) fn show_graph_type_rows(
127 graph: &ExecGraph<'_>,
128 c: &relate_parser::ShowGraphTypeClause,
129) -> Result<Vec<Row>> {
130 Ok({
131 let state = graph.show_schema()?;
132 let body = c
135 .name
136 .with_str(|text| state.data.graph_types.get(text))
137 .ok_or_else(|| Error::semantic("GraphTypeNotFound"))?;
138 vec![catalog_row([
139 ("name", Value::String(c.name.to_string().into())),
140 (
141 "body",
142 Value::String(
143 crate::graph_type::canonicalize_graph_type_body(&body.to_body())
144 .map_err(crate::graph_type::persisted_derive_error)?
145 .into(),
146 ),
147 ),
148 ])]
149 })
150}
151
152pub(crate) fn show_current_graph_type_rows(
153 graph: &ExecGraph<'_>,
154 c: &relate_parser::ShowCurrentGraphTypeClause,
155) -> Result<Vec<Row>> {
156 let state = graph.show_schema()?;
157 let extras = graph
158 .named_constraints()
159 .into_iter()
160 .filter(|constraint| {
161 !state
162 .data
163 .derived_constraints
164 .contains_key(constraint.name.as_str())
165 })
166 .map(|constraint| {
167 let binding = constraint_binding(&constraint, &state.data.derived_constraints);
171 let kind = binding.kind.ok_or_else(|| {
172 Error::internal(format!(
173 "constraint `{}` carries the unrecognized kind tag `{}`",
174 constraint.name, constraint.kind
175 ))
176 })?;
177 Ok(constraint.to_model(kind))
178 })
179 .collect::<Result<Vec<_>>>()?;
180 let stored_body = state.data.current_graph_type.to_body();
183 let (body, extras) = match c.variant {
184 Some(variant) => crate::graph_type::apply_show_variant(variant, &stored_body, &extras)?,
185 None => (stored_body, extras),
186 };
187 Ok(if let Some(as_graph) = c.as_graph {
188 let (nodes, rels) =
189 crate::graph_type_visualize::render_graph_type_as_graph(&body, &extras, as_graph)?;
190 vec![catalog_row([
191 (
192 "nodes",
193 Value::List(
194 nodes
195 .iter()
196 .map(relate_core::cypher_to_value)
197 .collect::<Vec<_>>()
198 .into(),
199 ),
200 ),
201 (
202 "relationships",
203 Value::List(
204 rels.iter()
205 .map(relate_core::cypher_to_value)
206 .collect::<Vec<_>>()
207 .into(),
208 ),
209 ),
210 ])]
211 } else {
212 vec![catalog_row([(
213 "specification",
214 Value::String(
215 crate::graph_type::current_graph_type_specification(&body, &extras)
216 .map_err(crate::graph_type::persisted_derive_error)?
217 .into(),
218 ),
219 )])]
220 })
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226 use crate::graph::Graph;
227
228 fn show_databases(query: &str) -> Vec<Row> {
233 let mut graph = Graph::default();
239 graph.configure_preview(relate_core::PreviewFeatures::parse("ontology").unwrap());
240 crate::exec::test_support::show_catalog_rows(&graph, query)
241 }
242
243 fn row_named<'a>(rows: &'a [Row], name: &str) -> &'a Row {
244 rows.iter()
245 .find(|row| row.get("name") == Some(&Value::String(name.into())))
246 .unwrap_or_else(|| panic!("no row for {name}"))
247 }
248
249 fn assert_browser_compat_row(row: &Row, is_default: bool, expected_access: &str) {
255 assert!(
256 matches!(row.get("access"), Some(Value::String(s)) if &**s == expected_access),
257 "access: {:?}",
258 row.get("access")
259 );
260 assert!(
261 matches!(row.get("address"), Some(Value::String(s)) if &**s == "localhost:7687"),
262 "address: {:?}",
263 row.get("address")
264 );
265 assert!(
266 matches!(row.get("role"), Some(Value::String(s)) if &**s == "primary"),
267 "role: {:?}",
268 row.get("role")
269 );
270 assert!(
271 matches!(row.get("requestedStatus"), Some(Value::String(s)) if &**s == "online"),
272 "requestedStatus: {:?}",
273 row.get("requestedStatus")
274 );
275 assert!(
276 matches!(row.get("currentStatus"), Some(Value::String(s)) if &**s == "online"),
277 "currentStatus: {:?}",
278 row.get("currentStatus")
279 );
280 assert!(
281 matches!(row.get("statusMessage"), Some(Value::String(s)) if s.is_empty()),
282 "statusMessage: {:?}",
283 row.get("statusMessage")
284 );
285 assert_eq!(row.get("writer"), Some(&Value::Bool(true)));
286 assert_eq!(row.get("default"), Some(&Value::Bool(is_default)));
287 assert_eq!(row.get("home"), Some(&Value::Bool(is_default)));
288 }
289
290 fn assert_fixed_namespace_rows(rows: &[Row]) {
295 assert_eq!(rows.len(), 3);
296 assert_browser_compat_row(row_named(rows, "neo4j"), true, "read-write");
297 assert_browser_compat_row(row_named(rows, "system"), false, "read-write");
298 assert_browser_compat_row(row_named(rows, "system_ontologies"), false, "read-only");
299 }
300
301 #[test]
302 fn bare_show_databases_rows_carry_browser_compat_values() {
303 assert_fixed_namespace_rows(&show_databases("SHOW DATABASES"));
304 }
305
306 #[test]
307 fn show_databases_yield_exposes_browser_compat_values() {
308 relate_front::parse_and_lower(
311 "SHOW DATABASES YIELD name, access, address, role, writer, \
312 requestedStatus, currentStatus, statusMessage, default, home \
313 RETURN name",
314 )
315 .expect("front validates the YIELD list");
316 assert_fixed_namespace_rows(&show_databases(
317 "SHOW DATABASES YIELD name, access, address, role, writer, \
318 requestedStatus, currentStatus, statusMessage, default, home",
319 ));
320 }
321
322 #[test]
323 fn show_databases_yield_star_exposes_browser_compat_values() {
324 assert_fixed_namespace_rows(&show_databases("SHOW DATABASES YIELD *"));
325 }
326
327 #[test]
331 fn show_databases_without_the_opt_in_lists_the_two_ce_rows() {
332 let graph = Graph::default();
333 let rows = crate::exec::test_support::show_catalog_rows(&graph, "SHOW DATABASES");
334 assert_eq!(rows.len(), 2);
335 assert_browser_compat_row(row_named(&rows, "neo4j"), true, "read-write");
336 assert_browser_compat_row(row_named(&rows, "system"), false, "read-write");
337 }
338
339 #[test]
340 fn show_default_database_row_marks_neo4j_default_and_home() {
341 let rows = show_databases("SHOW DEFAULT DATABASE");
342 assert_eq!(rows.len(), 1);
343 assert_browser_compat_row(row_named(&rows, "neo4j"), true, "read-write");
344 }
345
346 #[test]
353 fn show_databases_row_key_order_matches_front_column_tables() {
354 crate::exec::test_support::assert_row_keys_match(
355 None,
356 "SHOW DATABASES YIELD *",
357 &relate_front::show_columns::full_database_columns(),
358 );
359 }
360
361 #[test]
366 fn catalog_create_statements_are_the_show_create_statement_renders() {
367 use crate::exec::test_support::{column, exec_autocommit, exec_cypher, string_cell};
368
369 let g = Graph::default();
370 exec_autocommit(&g, "CREATE INDEX person_name FOR (n:Person) ON (n.name)").unwrap();
371 exec_autocommit(&g, "CREATE TEXT INDEX book_title FOR (n:Book) ON (n.title)").unwrap();
372 exec_autocommit(
373 &g,
374 "CREATE CONSTRAINT person_email FOR (n:Person) REQUIRE n.email IS NOT NULL",
375 )
376 .unwrap();
377
378 let ddl = super::catalog_create_statements(&g);
379 assert_eq!(ddl.len(), 3, "{ddl:?}");
380
381 let show_indexes = exec_cypher(
388 &g,
389 "SHOW INDEXES YIELD name, type, createStatement \
390 WHERE type <> 'LOOKUP' RETURN createStatement",
391 );
392 let index_statements = column(&show_indexes, "createStatement", string_cell);
393 let show_constraints = exec_cypher(&g, "SHOW CONSTRAINTS YIELD createStatement");
394 let constraint_statements = column(&show_constraints, "createStatement", string_cell);
395 assert_eq!(&ddl[..index_statements.len()], &index_statements[..]);
396 assert_eq!(&ddl[index_statements.len()..], &constraint_statements[..]);
397
398 assert_eq!(
400 ddl,
401 vec![
402 "CREATE TEXT INDEX `book_title` FOR (n:`Book`) ON (n.`title`)",
403 "CREATE RANGE INDEX `person_name` FOR (n:`Person`) ON (n.`name`)",
404 "CREATE CONSTRAINT `person_email` FOR (n:`Person`) REQUIRE (n.`email`) IS NOT NULL",
405 ]
406 );
407 }
408}