Skip to main content

relate_executor/exec/catalog_show/
mod.rs

1//! `SHOW ...` catalog command row producers (extracted `execute_catalog` arms).
2
3use 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
25/// The pattern variable Neo4j CE's rendered statements use — the single
26/// place the `n`-for-nodes / `r`-for-relationships decision lives; both
27/// the `SHOW INDEXES` and the `SHOW CONSTRAINTS` createStatement
28/// renderings read it.
29fn entity_variable(entity: EntityKind) -> &'static str {
30    match entity {
31        EntityKind::Node => "n",
32        EntityKind::Relationship => "r",
33    }
34}
35
36/// The `FOR` pattern for a label/type-token index, quoting and
37/// `|`-joining the labels itself: `(n:`A`|`B`)` / `()-[r:`T`]-()`.
38pub(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
51/// The store's whole-catalog DDL statements (ADR-0481 §3): one `CREATE
52/// INDEX` / `CREATE CONSTRAINT` statement per named catalog entry, in the
53/// order the checkpoint manifest persists the catalog
54/// ([`Graph::named_indexes`] then [`Graph::named_constraints`] — the
55/// name-keyed catalog's order; the catalog keeps no creation sequence).
56/// Every statement is the `SHOW INDEXES` / `SHOW CONSTRAINTS`
57/// `createStatement` rendering — the dialect's full form, since a schema
58/// mirror must recreate, not hide.
59/// An entry whose renderer returns `None` — exactly the rows where the
60/// SHOW column is NULL (a legacy detail-less index row, a
61/// graph-type-managed dependent constraint, a kind with no standalone
62/// CREATE form) — is absent: its schema is already carried by the graph
63/// type's canonical text or the manifest, never a fabricated statement.
64pub 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        // A backing index's entry is absent because `index_ddl_statement`
72        // suppresses it (the constraint's own statement recreates it).
73        .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            // The schema mirror's constraint statement (ADR-0481 §3) is
83            // the SHOW row's own binding — a mirror must recreate, not
84            // hide: `constraint_statement_for` classifies and renders
85            // exactly as the `SHOW CONSTRAINTS` row does, and `None` (a
86            // graph-type-managed dependent constraint, a kind with no
87            // standalone CREATE form) omits the entry rather than
88            // fabricate a statement, its schema already carried by the
89            // graph type's canonical text.
90            constraints::constraint_statement_for(def, &current, &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        // The stored graph-type table is String-keyed (persisted names);
129        // the query's name reads through the text bridge.
130        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            // The one def→model crossing, through the one binding: a stored
164            // kind tag that does not parse is a corrupt catalog row, not a
165            // row to drop.
166            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    /// Runs a SHOW DATABASES statement through the real catalog path
224    /// (the shared [`show_catalog_rows`](crate::exec::test_support)
225    /// harness) against a theater opted into the `ontology` preview
226    /// feature, so it carries all three fixed namespaces.
227    fn show_databases(query: &str) -> Vec<Row> {
228        // ADR-0593: the pinned three-row shape is the `ontology`-on
229        // listing — the fixture's graph opts in exactly the way the
230        // show-catalog fixtures do. The flag-off two-row listing (CE's
231        // own) is pinned by the test below and the engine's preview-gate
232        // suite.
233        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    /// Pins the ADR-0142 Browser/Desktop-compat values *and* types
245    /// on every row: strings for access/address/role/requestedStatus/
246    /// currentStatus/statusMessage, booleans for writer/default/home.
247    /// `access` is the one namespace-dependent value (ADR-0116 §4:
248    /// `system_ontologies` is read-only).
249    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    /// The `ontology`-on listing carries exactly the three fixed
286    /// namespaces (ADR-0116 §1): `neo4j` (default/home), `system` and
287    /// `system_ontologies` (read-only, visible under the opt-in,
288    /// ADR-0593); every row must carry the Browser-compat values.
289    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        // Front validation must still accept a YIELD of these columns
304        // (values changed, not the column set).
305        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    /// ADR-0593: the flag-off listing is CE's exact two rows — the
323    /// `system_ontologies` row returns with the opt-in (the fixture
324    /// above).
325    #[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    /// Pins the load-bearing YIELD-* invariant: `show_databases_rows`
342    /// inserts keys in exactly
343    /// `relate_front::show_columns::full_database_columns()` order —
344    /// the front crate's own composition of its DEFAULT ++ NON_DEFAULT
345    /// tables; the shared key-order pin (`assert_row_keys_match`, no
346    /// setup needed here) carries the invariant.
347    #[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    /// ADR-0481 §3: the whole-catalog DDL statements are exactly the SHOW
357    /// `createStatement` column's renderings of the same committed state —
358    /// one renderer, two callers, byte-identical output — and the pinned
359    /// renderings are the exact text the `schema.cypher` mirror carries.
360    #[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        // The SHOW columns, read through the SHOW row producers. Catalog
377        // order is the name-keyed maps' order and the SHOW rows come from
378        // the same maps, so the two orders agree without sorting. The two
379        // default lookup rows are synthesized, not catalog entries, so the
380        // mirror omits them and so does this comparison (every catalog row
381        // is non-LOOKUP).
382        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        // The pinned renderings, in the catalog's name order.
394        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}