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]) -> Option<String> {
39    // An empty token list would render `(n:)`: no faithful pattern exists.
40    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
55/// The store's whole-catalog DDL statements (ADR-0481 §3): one `CREATE
56/// INDEX` / `CREATE CONSTRAINT` statement per named catalog entry, in the
57/// order the checkpoint manifest persists the catalog
58/// ([`Graph::named_indexes`] then [`Graph::named_constraints`] — the
59/// name-keyed catalog's order; the catalog keeps no creation sequence).
60/// Every statement is the `SHOW INDEXES` / `SHOW CONSTRAINTS`
61/// `createStatement` rendering — the dialect's full form, since a schema
62/// mirror must recreate, not hide.
63/// An entry whose renderer returns `None` — exactly the rows where the
64/// SHOW column is NULL (a legacy detail-less index row, a
65/// graph-type-managed dependent constraint, a kind with no standalone
66/// CREATE form) — is absent: its schema is already carried by the graph
67/// type's canonical text or the manifest, never a fabricated statement.
68pub 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        // A backing index's entry is absent because `index_ddl_statement`
76        // suppresses it (the constraint's own statement recreates it).
77        .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            // The schema mirror's constraint statement (ADR-0481 §3) is
87            // the SHOW row's own binding — a mirror must recreate, not
88            // hide: `constraint_statement_for` classifies and renders
89            // exactly as the `SHOW CONSTRAINTS` row does, and `None` (a
90            // graph-type-managed dependent constraint, a kind with no
91            // standalone CREATE form) omits the entry rather than
92            // fabricate a statement, its schema already carried by the
93            // graph type's canonical text.
94            constraints::constraint_statement_for(def, &current, &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        // The stored graph-type table is String-keyed (persisted names);
133        // the query's name reads through the text bridge.
134        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            // The one def→model crossing, through the one binding: a stored
168            // kind tag that does not parse is a corrupt catalog row, not a
169            // row to drop.
170            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    // CIP-275: a display variant transforms the stored body and extras
181    // before either renderer runs; nothing is written back.
182    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    /// Runs a SHOW DATABASES statement through the real catalog path
229    /// (the shared [`show_catalog_rows`](crate::exec::test_support)
230    /// harness) against a theater opted into the `ontology` preview
231    /// feature, so it carries all three fixed namespaces.
232    fn show_databases(query: &str) -> Vec<Row> {
233        // ADR-0593: the pinned three-row shape is the `ontology`-on
234        // listing — the fixture's graph opts in exactly the way the
235        // show-catalog fixtures do. The flag-off two-row listing (CE's
236        // own) is pinned by the test below and the engine's preview-gate
237        // suite.
238        let mut graph = Graph::default();
239        graph.configure_preview(relate_core::PreviewSources {
240            env: relate_core::PreviewFeatures::parse("ontology").unwrap(),
241            ..relate_core::PreviewSources::default()
242        });
243        crate::exec::test_support::show_catalog_rows(&graph, query)
244    }
245
246    fn row_named<'a>(rows: &'a [Row], name: &str) -> &'a Row {
247        rows.iter()
248            .find(|row| row.get("name") == Some(&Value::String(name.into())))
249            .unwrap_or_else(|| panic!("no row for {name}"))
250    }
251
252    /// Pins the ADR-0142 Browser/Desktop-compat values *and* types
253    /// on every row of an embedded store: strings for access/role/requestedStatus/
254    /// currentStatus/statusMessage, a null `address` (no surface serves the
255    /// store, ADR-0729), booleans for writer/default/home.
256    /// `access` is the one namespace-dependent value (ADR-0116 §4:
257    /// `system_ontologies` is read-only).
258    fn assert_browser_compat_row(row: &Row, is_default: bool, expected_access: &str) {
259        assert!(
260            matches!(row.get("access"), Some(Value::String(s)) if &**s == expected_access),
261            "access: {:?}",
262            row.get("access")
263        );
264        assert_eq!(
265            row.get("address"),
266            Some(&Value::Null),
267            "an embedded store advertises no address (ADR-0729)"
268        );
269        assert!(
270            matches!(row.get("role"), Some(Value::String(s)) if &**s == "primary"),
271            "role: {:?}",
272            row.get("role")
273        );
274        assert!(
275            matches!(row.get("requestedStatus"), Some(Value::String(s)) if &**s == "online"),
276            "requestedStatus: {:?}",
277            row.get("requestedStatus")
278        );
279        assert!(
280            matches!(row.get("currentStatus"), Some(Value::String(s)) if &**s == "online"),
281            "currentStatus: {:?}",
282            row.get("currentStatus")
283        );
284        assert!(
285            matches!(row.get("statusMessage"), Some(Value::String(s)) if s.is_empty()),
286            "statusMessage: {:?}",
287            row.get("statusMessage")
288        );
289        assert_eq!(row.get("writer"), Some(&Value::Bool(true)));
290        assert_eq!(row.get("default"), Some(&Value::Bool(is_default)));
291        assert_eq!(row.get("home"), Some(&Value::Bool(is_default)));
292    }
293
294    /// The `ontology`-on listing carries exactly the three fixed
295    /// namespaces (ADR-0116 §1): `neo4j` (default/home), `system` and
296    /// `system_ontologies` (read-only, visible under the opt-in,
297    /// ADR-0593); every row must carry the Browser-compat values.
298    fn assert_fixed_namespace_rows(rows: &[Row]) {
299        assert_eq!(rows.len(), 3);
300        assert_browser_compat_row(row_named(rows, "neo4j"), true, "read-write");
301        assert_browser_compat_row(row_named(rows, "system"), false, "read-write");
302        assert_browser_compat_row(row_named(rows, "system_ontologies"), false, "read-only");
303    }
304
305    #[test]
306    fn bare_show_databases_rows_carry_browser_compat_values() {
307        assert_fixed_namespace_rows(&show_databases("SHOW DATABASES"));
308    }
309
310    #[test]
311    fn show_databases_yield_exposes_browser_compat_values() {
312        // Front validation must still accept a YIELD of these columns
313        // (values changed, not the column set).
314        relate_front::parse_and_lower(
315            "SHOW DATABASES YIELD name, access, address, role, writer, \
316             requestedStatus, currentStatus, statusMessage, default, home \
317             RETURN name",
318        )
319        .expect("front validates the YIELD list");
320        assert_fixed_namespace_rows(&show_databases(
321            "SHOW DATABASES YIELD name, access, address, role, writer, \
322             requestedStatus, currentStatus, statusMessage, default, home",
323        ));
324    }
325
326    #[test]
327    fn show_databases_yield_star_exposes_browser_compat_values() {
328        assert_fixed_namespace_rows(&show_databases("SHOW DATABASES YIELD *"));
329    }
330
331    /// ADR-0593: the flag-off listing is CE's exact two rows — the
332    /// `system_ontologies` row returns with the opt-in (the fixture
333    /// above).
334    #[test]
335    fn show_databases_without_the_opt_in_lists_the_two_ce_rows() {
336        let graph = Graph::default();
337        let rows = crate::exec::test_support::show_catalog_rows(&graph, "SHOW DATABASES");
338        assert_eq!(rows.len(), 2);
339        assert_browser_compat_row(row_named(&rows, "neo4j"), true, "read-write");
340        assert_browser_compat_row(row_named(&rows, "system"), false, "read-write");
341    }
342
343    #[test]
344    fn show_default_database_row_marks_neo4j_default_and_home() {
345        let rows = show_databases("SHOW DEFAULT DATABASE");
346        assert_eq!(rows.len(), 1);
347        assert_browser_compat_row(row_named(&rows, "neo4j"), true, "read-write");
348    }
349
350    /// Pins the load-bearing YIELD-* invariant: `show_databases_rows`
351    /// inserts keys in exactly
352    /// `relate_front::show_columns::full_database_columns()` order —
353    /// the front crate's own composition of its DEFAULT ++ NON_DEFAULT
354    /// tables; the shared key-order pin (`assert_row_keys_match`, no
355    /// setup needed here) carries the invariant.
356    #[test]
357    fn show_databases_row_key_order_matches_front_column_tables() {
358        crate::exec::test_support::assert_row_keys_match(
359            None,
360            "SHOW DATABASES YIELD *",
361            &relate_front::show_columns::full_database_columns(),
362        );
363    }
364
365    /// ADR-0481 §3: the whole-catalog DDL statements are exactly the SHOW
366    /// `createStatement` column's renderings of the same committed state —
367    /// one renderer, two callers, byte-identical output — and the pinned
368    /// renderings are the exact text the `schema.cypher` mirror carries.
369    #[test]
370    fn catalog_create_statements_are_the_show_create_statement_renders() {
371        use crate::exec::test_support::{column, exec_autocommit, exec_cypher, string_cell};
372
373        let g = Graph::default();
374        exec_autocommit(&g, "CREATE INDEX person_name FOR (n:Person) ON (n.name)").unwrap();
375        exec_autocommit(&g, "CREATE TEXT INDEX book_title FOR (n:Book) ON (n.title)").unwrap();
376        exec_autocommit(
377            &g,
378            "CREATE CONSTRAINT person_email FOR (n:Person) REQUIRE n.email IS NOT NULL",
379        )
380        .unwrap();
381
382        let ddl = super::catalog_create_statements(&g);
383        assert_eq!(ddl.len(), 3, "{ddl:?}");
384
385        // The SHOW columns, read through the SHOW row producers. Catalog
386        // order is the name-keyed maps' order and the SHOW rows come from
387        // the same maps, so the two orders agree without sorting. The two
388        // default lookup rows are synthesized, not catalog entries, so the
389        // mirror omits them and so does this comparison (every catalog row
390        // is non-LOOKUP).
391        let show_indexes = exec_cypher(
392            &g,
393            "SHOW INDEXES YIELD name, type, createStatement \
394             WHERE type <> 'LOOKUP' RETURN createStatement",
395        );
396        let index_statements = column(&show_indexes, "createStatement", string_cell);
397        let show_constraints = exec_cypher(&g, "SHOW CONSTRAINTS YIELD createStatement");
398        let constraint_statements = column(&show_constraints, "createStatement", string_cell);
399        assert_eq!(&ddl[..index_statements.len()], &index_statements[..]);
400        assert_eq!(&ddl[index_statements.len()..], &constraint_statements[..]);
401
402        // The pinned renderings, in the catalog's name order.
403        assert_eq!(
404            ddl,
405            vec![
406                "CREATE TEXT INDEX `book_title` FOR (n:`Book`) ON (n.`title`)",
407                "CREATE RANGE INDEX `person_name` FOR (n:`Person`) ON (n.`name`)",
408                "CREATE CONSTRAINT `person_email` FOR (n:`Person`) REQUIRE (n.`email`) IS NOT NULL",
409            ]
410        );
411    }
412}