Skip to main content

relate_executor/exec/
ddl_notifications.rs

1//! Schema-DDL query notifications: Neo4j's `00NA0`-`00NA2` family.
2//!
3//! The notifications ride the plan tree's statement-scoped list (ADR-0363
4//! decision 3), so a plain DDL execution still reports none; `EXPLAIN`
5//! derives them from the parsed clause and the catalog state. Nothing is
6//! executed here — each detector consumes the verdict of the execution gate
7//! it describes (the index create gate and the constraint create gate both
8//! hand the rule that made the statement a no-op out), so an `EXPLAIN` of a
9//! no-op `IF NOT EXISTS` statement reports exactly the note its execution
10//! would, and a statement the gate rejects raises none.
11//!
12//! The descriptions are Neo4j's own GQLSTATUS text. They are advisory (the
13//! spec harness enforces the code), so the renderers below spell the
14//! notification form — variable `e`, unquoted simple names — rather than
15//! reusing the SHOW `createStatement` renderer, whose backticked, `n`/`r`
16//! form is a different contract.
17//!
18//! The one detector that needs a catalog snapshot (the `IF NOT EXISTS`
19//! `CREATE INDEX` note) takes it once, and only when it will use it: a
20//! failed read is the statement's own error, never a silent "the rule does
21//! not exist". The constraint note reads no snapshot of its own — it
22//! consumes the execution gate's verdict.
23
24use std::collections::BTreeMap;
25use std::str::FromStr;
26
27use relate_catalog::ConstraintDef;
28use relate_core::{Result, Value};
29use relate_model::wire::{Notification, NotificationKind};
30use relate_model::{ConstraintType, EntityKind};
31use relate_names::SmallName;
32use relate_parser::{OptionsForm, SchemaName};
33
34use crate::exec::catalog_schema::{constraint_create_gate, constraint_def};
35use crate::exec::ddl::{
36    default_index_name, drop_target_exists, index_conflict_gate, ExistingRule, Gate, IndexFacts,
37    SchemaTarget,
38};
39use crate::graph_type::standalone_verb;
40use crate::overlay::ExecGraph;
41use crate::redo::{IndexDetailSpec, IndexFacts as IndexRowFacts, IndexKindSpec};
42
43use super::catalog::schema_name_value;
44
45/// The schema-DDL notifications one IR clause raises at `EXPLAIN` time: the
46/// catalog passthrough's parsed clause and the IR's own compact legacy
47/// `CreateIndex`/`DropIndex` shapes all dispatch here, so the statement
48/// walker never re-assembles a clause shape across the crate boundary. A
49/// non-DDL clause raises none.
50pub fn ddl_notifications(
51    graph: &ExecGraph<'_>,
52    clause: &relate_ir::Clause,
53    params: &BTreeMap<String, Value>,
54) -> Result<Vec<Notification>> {
55    match clause {
56        relate_ir::Clause::Catalog(command) => catalog_clause_notifications(graph, command, params),
57        relate_ir::Clause::CreateIndex {
58            name,
59            if_not_exists,
60            label,
61            property,
62        } => {
63            // Text renders: the notification layer owns String text.
64            let name_text = name.as_ref().map(|n| n.to_string());
65            legacy_create_index_notifications(
66                graph,
67                name_text.as_deref(),
68                *if_not_exists,
69                label,
70                property,
71            )
72        }
73        relate_ir::Clause::DropIndex { if_exists, target } => {
74            Ok(legacy_drop_index_notifications(graph, *if_exists, target))
75        }
76        _ => Ok(Vec::new()),
77    }
78}
79
80/// One parsed catalog clause's notes. A non-DDL catalog clause (a `SHOW`, an
81/// `ALTER DATABASE`) raises none.
82fn catalog_clause_notifications(
83    graph: &ExecGraph<'_>,
84    clause: &relate_parser::Clause,
85    params: &BTreeMap<String, Value>,
86) -> Result<Vec<Notification>> {
87    match clause {
88        relate_parser::Clause::CreateIndex(c) => match clause_name(c.name.as_ref(), params) {
89            ClauseName::Unresolvable => Ok(Vec::new()),
90            ClauseName::Unnamed => create_index_notifications(graph, c, None),
91            ClauseName::Named(name) => create_index_notifications(graph, c, Some(&name)),
92        },
93        relate_parser::Clause::CreateConstraint(c) => match clause_name(c.name.as_ref(), params) {
94            ClauseName::Unresolvable => Ok(Vec::new()),
95            ClauseName::Unnamed => create_constraint_notifications(graph, c, None, params),
96            ClauseName::Named(name) => {
97                create_constraint_notifications(graph, c, Some(&name), params)
98            }
99        },
100        relate_parser::Clause::DropIndex(c) => match clause_name(Some(&c.name), params) {
101            ClauseName::Named(name) => Ok(drop_notifications(
102                graph,
103                DropNoun::Index,
104                &name,
105                c.if_exists,
106            )),
107            // `DROP` always names its target, so `Unnamed` cannot occur; the
108            // unresolvable-parameter policy is no notes.
109            ClauseName::Unnamed | ClauseName::Unresolvable => Ok(Vec::new()),
110        },
111        relate_parser::Clause::DropConstraint(c) => match clause_name(Some(&c.name), params) {
112            ClauseName::Named(name) => Ok(drop_notifications(
113                graph,
114                DropNoun::Constraint,
115                &name,
116                c.if_exists,
117            )),
118            ClauseName::Unnamed | ClauseName::Unresolvable => Ok(Vec::new()),
119        },
120        _ => Ok(Vec::new()),
121    }
122}
123
124/// A schema clause's declared name, resolved once for every detector. The
125/// `Unresolvable` state's one policy is **no notes**: the note is advisory,
126/// and the statement itself fails with `ParameterMissing` at execution — an
127/// `EXPLAIN` must never describe a command that cannot run.
128enum ClauseName {
129    /// The clause names none; the engine generates one (`CREATE` only).
130    Unnamed,
131    /// The declared name, from a literal or a resolved parameter.
132    Named(String),
133    /// A parameter name did not resolve.
134    Unresolvable,
135}
136
137fn clause_name(name: Option<&SchemaName>, params: &BTreeMap<String, Value>) -> ClauseName {
138    match name {
139        None => ClauseName::Unnamed,
140        Some(name) => match schema_name_value(name, params) {
141            Ok(resolved) => ClauseName::Named(resolved),
142            Err(_) => ClauseName::Unresolvable,
143        },
144    }
145}
146
147/// The IR's compact `CreateIndex` clause (the single-label, single-property,
148/// option-less RANGE shape the front-end keeps in the IR): the same `00NA0`
149/// note as the catalog passthrough's rich form, through the one shared tail.
150fn legacy_create_index_notifications(
151    graph: &ExecGraph<'_>,
152    name: Option<&str>,
153    if_not_exists: bool,
154    label: &SmallName,
155    property: &SmallName,
156) -> Result<Vec<Notification>> {
157    if !if_not_exists {
158        return Ok(Vec::new());
159    }
160    // Text renders: the notification layer owns String text.
161    let resolved = name
162        .map(str::to_string)
163        .unwrap_or_else(|| default_index_name(&label.to_string(), &property.to_string()));
164    let facts = IndexFacts::legacy_range(
165        resolved,
166        label.to_string(),
167        property.to_string(),
168        if_not_exists,
169    );
170    already_exists_index_note(graph, &facts, name, None)
171}
172
173/// The legacy IR `DropIndex` clause: the `00NA1` note when the target is
174/// missing under `IF EXISTS`, through the one DROP-target existence rule.
175fn legacy_drop_index_notifications(
176    graph: &ExecGraph<'_>,
177    if_exists: bool,
178    target: &relate_ir::DropIndexTarget,
179) -> Vec<Notification> {
180    if !if_exists {
181        return Vec::new();
182    }
183    let (exists, command, name) = match target {
184        relate_ir::DropIndexTarget::Name(name) => (
185            drop_target_exists(graph, SchemaTarget::IndexName(name)).is_some(),
186            format!("DROP INDEX {name} IF EXISTS"),
187            Some(name.as_str()),
188        ),
189        relate_ir::DropIndexTarget::Schema { label, property } => {
190            // Text renders: the stored-index lookup and the notification
191            // text both speak String.
192            let label = label.to_string();
193            let property = property.to_string();
194            (
195                drop_target_exists(
196                    graph,
197                    SchemaTarget::IndexSchema {
198                        label: &label,
199                        property: &property,
200                    },
201                )
202                .is_some(),
203                format!("DROP INDEX ON :{label}({property}) IF EXISTS"),
204                None,
205            )
206        }
207    };
208    if exists {
209        return Vec::new();
210    }
211    vec![does_not_exist_note(&command, name)]
212}
213
214/// The noun a `DROP … IF EXISTS` note names: both kinds share the note text.
215#[derive(Clone, Copy)]
216enum DropNoun {
217    Index,
218    Constraint,
219}
220
221impl DropNoun {
222    fn noun(self) -> &'static str {
223        match self {
224            DropNoun::Index => "INDEX",
225            DropNoun::Constraint => "CONSTRAINT",
226        }
227    }
228}
229
230/// `DROP INDEX/CONSTRAINT … IF EXISTS` on a missing name is a no-op with a
231/// `00NA1` note. A parameter name resolves from the statement's parameters
232/// exactly as the execution gate resolves it.
233fn drop_notifications(
234    graph: &ExecGraph<'_>,
235    noun: DropNoun,
236    name: &str,
237    if_exists: bool,
238) -> Vec<Notification> {
239    if !if_exists {
240        return Vec::new();
241    }
242    let target = match noun {
243        DropNoun::Index => SchemaTarget::IndexName(name),
244        DropNoun::Constraint => SchemaTarget::ConstraintName(name),
245    };
246    if drop_target_exists(graph, target).is_some() {
247        return Vec::new();
248    }
249    vec![does_not_exist_note(
250        &format!("DROP {} {name} IF EXISTS", noun.noun()),
251        Some(name),
252    )]
253}
254
255/// The `CREATE INDEX` notes: the `IF NOT EXISTS` no-op (`00NA0`) and the
256/// missing-dimensions note (`00NA2`, which fires whether or not the index
257/// already exists).
258fn create_index_notifications(
259    graph: &ExecGraph<'_>,
260    c: &relate_parser::CreateIndexClause,
261    name: Option<&str>,
262) -> Result<Vec<Notification>> {
263    let mut notifications = Vec::new();
264    if c.kind == relate_parser::IndexKind::Vector && !vector_dimensions_given(c) {
265        notifications.push(Notification::new(
266            NotificationKind::SchemaVectorIndexDimensionsNotSpecified,
267            "note: successful completion - vector index dimensions not specified. \
268             When creating a vector index, `vector.dimensions` should be specified. \
269             Omitting it is allowed, but specifying dimensions ensures that only \
270             vectors of that size are indexed and makes dimension mismatches fail \
271             clearly at query time. For example, set `OPTIONS { indexConfig: { \
272             `vector.dimensions`: 1536 } }` when creating the index.",
273        ));
274    }
275    if !c.if_not_exists {
276        return Ok(notifications);
277    }
278    let facts = IndexFacts::from_clause(
279        c,
280        name.map(str::to_string)
281            .unwrap_or_else(|| IndexFacts::generated_name(c)),
282    );
283    notifications.extend(already_exists_index_note(
284        graph,
285        &facts,
286        name,
287        literal_options_text(c.options.literal()),
288    )?);
289    Ok(notifications)
290}
291
292/// The `00NA0` note for an `IF NOT EXISTS` create the gate made a no-op —
293/// the one tail both the rich catalog clause and the IR's compact legacy
294/// clause share. The note reads the create gate's own evidence (the same
295/// rule that made the statement a no-op names it), so the two cannot
296/// disagree, and the effective name resolves inside the gate.
297fn already_exists_index_note(
298    graph: &ExecGraph<'_>,
299    facts: &IndexFacts,
300    declared_name: Option<&str>,
301    options: Option<String>,
302) -> Result<Vec<Notification>> {
303    // The gate's error is the statement's own (a failed catalog read, a
304    // rejected name collision): `EXPLAIN` fails with it rather than
305    // reporting a note for a statement that cannot run. Only a skip carries
306    // evidence for a note.
307    let gate = index_conflict_gate(graph, facts)?;
308    let Gate::Skip(ExistingRule::Index(rule)) = gate else {
309        return Ok(Vec::new());
310    };
311    let Some(descriptor) = index_descriptor_text(&rule.index, rule.detail.as_ref()) else {
312        return Ok(Vec::new());
313    };
314    let Some(tail) = index_descriptor_tail(
315        IndexKindSpec::from(facts.kind),
316        EntityKind::from_relationship_flag(facts.relationship),
317        &facts.labels,
318        &facts.properties,
319        &facts.with_properties,
320    ) else {
321        return Ok(Vec::new());
322    };
323    let command = create_index_command(
324        IndexKindSpec::from(facts.kind),
325        declared_name,
326        facts.if_not_exists,
327        &tail,
328        options,
329    );
330    Ok(vec![already_exists_note(&command, &descriptor)])
331}
332
333/// Whether the clause's literal `OPTIONS` carries `vector.dimensions`. An
334/// `OPTIONS $param` map is unknown at plan time, so it counts as given
335/// (no note) — the executed statement still records the real config.
336fn vector_dimensions_given(c: &relate_parser::CreateIndexClause) -> bool {
337    match &c.options {
338        OptionsForm::Absent => false,
339        // Unknown at plan time; the executed statement records the real
340        // config, so it counts as given (no note).
341        OptionsForm::Parameter(_) => true,
342        OptionsForm::Literal(entries) => entries
343            .iter()
344            .filter(|(key, _)| key == super::ddl_options::KEY_INDEX_CONFIG)
345            .any(|(_, value)| {
346                let relate_parser::Expr::Map(pairs) = value else {
347                    return false;
348                };
349                pairs.iter().any(|pair| pair.key == "vector.dimensions")
350            }),
351    }
352}
353
354/// One existing index's descriptor in the notification's own spelling,
355/// resolved through the one [`IndexFacts`] precedence — so a detail-less row
356/// is classified exactly like its SHOW row. `None` when the index's shape
357/// has no faithful rendering (a property-less non-LOOKUP index fails closed
358/// rather than fabricate a LOOKUP statement).
359fn index_descriptor_text(
360    index: &relate_catalog::IndexDef,
361    detail: Option<&IndexDetailSpec>,
362) -> Option<String> {
363    let facts = IndexRowFacts::resolve(index, detail, None);
364    let tail = index_descriptor_tail(
365        facts.kind,
366        EntityKind::from_relationship_flag(facts.relationship),
367        &facts.labels,
368        &facts.properties,
369        &facts.with_properties,
370    )?;
371    Some(format!(
372        "{} INDEX {} {tail}",
373        facts.kind.display_name(),
374        index.name
375    ))
376}
377
378/// The `FOR …` tail shared by a `CREATE … INDEX` command and an existing
379/// index's descriptor. `kind` and `entity` are the typed facts (a LOOKUP
380/// index is `is_lookup`, never "property list empty"; the entity kind picks
381/// the node/relationship pattern), and a property-less non-LOOKUP index
382/// returns `None`: it has no faithful `ON` clause.
383fn index_descriptor_tail(
384    kind: IndexKindSpec,
385    entity: EntityKind,
386    labels: &[String],
387    properties: &[String],
388    with_properties: &[String],
389) -> Option<String> {
390    if kind.is_lookup() {
391        let (pattern, each) = match entity {
392            EntityKind::Node => ("(e)", "labels(e)"),
393            EntityKind::Relationship => ("()-[e]-()", "type(e)"),
394        };
395        return Some(format!("FOR {pattern} ON EACH {each}"));
396    }
397    if properties.is_empty() {
398        return None;
399    }
400    let tokens = labels.join("|");
401    let pattern = match entity {
402        EntityKind::Node if tokens.is_empty() => "(e)".to_string(),
403        EntityKind::Node => format!("(e:{tokens})"),
404        EntityKind::Relationship if tokens.is_empty() => "()-[e]-()".to_string(),
405        EntityKind::Relationship => format!("()-[e:{tokens}]-()"),
406    };
407    let refs = properties
408        .iter()
409        .map(|property| format!("e.{property}"))
410        .collect::<Vec<_>>();
411    let mut text = format!("FOR {pattern} ON ({})", refs.join(", "));
412    if !with_properties.is_empty() {
413        let with = with_properties
414            .iter()
415            .map(|property| format!("e.{property}"))
416            .collect::<Vec<_>>();
417        text.push_str(&format!(" WITH [{}]", with.join(", ")));
418    }
419    Some(text)
420}
421
422/// The `CREATE … INDEX …` command text the note quotes: the kind and name,
423/// the `IF NOT EXISTS` marker exactly where the source statement writes it,
424/// the shared `FOR …` tail, and any literal `OPTIONS` suffix.
425fn create_index_command(
426    kind: IndexKindSpec,
427    name: Option<&str>,
428    if_not_exists: bool,
429    tail: &str,
430    options: Option<String>,
431) -> String {
432    let mut command = format!("CREATE {} INDEX ", kind.display_name());
433    if let Some(name) = name {
434        command.push_str(name);
435        command.push(' ');
436    }
437    if if_not_exists {
438        command.push_str("IF NOT EXISTS ");
439    }
440    command.push_str(tail);
441    if let Some(options) = options {
442        command.push_str(&options);
443    }
444    command
445}
446
447/// The literal `OPTIONS {…}` suffix in the statement's own spelling. `None`
448/// for a parameter map (unknown at plan time) or an empty map.
449fn literal_options_text(options: Option<&[(String, relate_parser::Expr)]>) -> Option<String> {
450    let options = options?;
451    if options.is_empty() {
452        return None;
453    }
454    let mut entries = Vec::with_capacity(options.len());
455    for (key, value) in options {
456        let relate_parser::Expr::Map(pairs) = value else {
457            return None;
458        };
459        let inner = pairs
460            .iter()
461            .map(|pair| {
462                simple_expr_text(&pair.value).map(|text| format!("`{}`: {}", pair.key, text))
463            })
464            .collect::<Option<Vec<_>>>()?;
465        entries.push(format!("`{key}`: {{{}}}", inner.join(", ")));
466    }
467    Some(format!(" OPTIONS {{{}}}", entries.join(", ")))
468}
469
470/// A scalar expression's literal text; `None` for anything that is not a
471/// literal at plan time.
472fn simple_expr_text(expr: &relate_parser::Expr) -> Option<String> {
473    match expr {
474        relate_parser::Expr::Literal(relate_parser::LiteralValue::Integer(value)) => {
475            Some(value.to_string())
476        }
477        relate_parser::Expr::Literal(relate_parser::LiteralValue::Float(value)) => {
478            // The one float spelling (`Value::to_cypher_literal` → core's
479            // canonical `float_literal`), never a second `format!`.
480            Some(relate_core::Value::Float(*value).to_cypher_literal())
481        }
482        relate_parser::Expr::Literal(relate_parser::LiteralValue::Bool(value)) => {
483            Some(value.to_string())
484        }
485        // The one scalar spelling (`Value::to_cypher_literal`): a string's
486        // quotes are escaped, so the quoted command text stays valid Cypher
487        // whatever the user's OPTIONS literal holds.
488        relate_parser::Expr::Literal(relate_parser::LiteralValue::String(value)) => {
489            Some(relate_core::Value::String(value.as_str().into()).to_cypher_literal())
490        }
491        _ => None,
492    }
493}
494
495/// The `CREATE CONSTRAINT` note: an `IF NOT EXISTS` create whose name or
496/// schema already exists (`00NA0`). The note reads the execution gate's own
497/// verdict, so it follows the gate's precedence exactly — including the
498/// rejections that make the statement unrunnable (a graph-type-managed
499/// label, a conflict), which `EXPLAIN` reports as the statement's own error
500/// instead of describing a command that cannot run.
501fn create_constraint_notifications(
502    graph: &ExecGraph<'_>,
503    c: &relate_parser::CreateConstraintClause,
504    name: Option<&str>,
505    params: &BTreeMap<String, Value>,
506) -> Result<Vec<Notification>> {
507    if !c.if_not_exists {
508        return Ok(Vec::new());
509    }
510    // The same definition the execution handler builds (kind tag, property
511    // type, name), so the gate sees one shape.
512    let (def, constraint_type) = constraint_def(c, name.map(str::to_string))?;
513    // The EXPLAIN layer carries no dialect version; the gate's OPTIONS
514    // validation can only turn the statement into an error (the statement's
515    // own, which propagates), so the version cannot change the skip
516    // evidence. Only a skip carries evidence for a note.
517    let gate = constraint_create_gate(graph, c, &def, constraint_type, params)?;
518    let Gate::Skip(rule) = gate else {
519        return Ok(Vec::new());
520    };
521    let ExistingRule::Constraint(existing) = rule else {
522        // A serving-pair index has no constraint descriptor to name.
523        return Ok(Vec::new());
524    };
525    let Some(descriptor) = constraint_descriptor_text(&existing) else {
526        return Ok(Vec::new());
527    };
528    let Some(command) = constraint_command_text(&def, constraint_type, name) else {
529        return Ok(Vec::new());
530    };
531    Ok(vec![already_exists_note(&command, &descriptor)])
532}
533
534/// The `FOR <pattern> REQUIRE (<properties>)` tail shared by a
535/// `CREATE CONSTRAINT` command and an existing constraint's descriptor — the
536/// constraint counterpart of [`index_descriptor_tail`], so the two renderings
537/// cannot drift.
538fn constraint_tail(entity: EntityKind, label: &str, properties: &[String]) -> String {
539    let pattern = match entity {
540        EntityKind::Node => format!("(e:{label})"),
541        EntityKind::Relationship => format!("()-[e:{label}]-()"),
542    };
543    if properties.is_empty() {
544        return format!("FOR {pattern}");
545    }
546    let refs = properties
547        .iter()
548        .map(|property| format!("e.{property}"))
549        .collect::<Vec<_>>()
550        .join(", ");
551    format!("FOR {pattern} REQUIRE ({refs})")
552}
553
554/// The `CREATE CONSTRAINT …` command text the note quotes, from the same
555/// definition the gate saw.
556fn constraint_command_text(
557    def: &ConstraintDef,
558    kind: ConstraintType,
559    name: Option<&str>,
560) -> Option<String> {
561    let verb = standalone_verb(kind, def.property_type.as_deref())?;
562    let entity = EntityKind::from_relationship_flag(def.relationship);
563    let mut command = String::from("CREATE CONSTRAINT ");
564    if let Some(name) = name {
565        command.push_str(name);
566        command.push(' ');
567    }
568    command.push_str("IF NOT EXISTS ");
569    command.push_str(&constraint_tail(entity, &def.label, &def.properties));
570    command.push(' ');
571    command.push_str(&verb);
572    Some(command)
573}
574
575/// An existing constraint's descriptor text (the command text without
576/// `CREATE`/`IF NOT EXISTS`), or `None` when the stored kind tag does not
577/// parse or has no standalone verb — the caller skips the note rather than
578/// emit `REQUIRE ` with nothing after it.
579fn constraint_descriptor_text(def: &relate_catalog::ConstraintDef) -> Option<String> {
580    let kind = ConstraintType::from_str(&def.kind).ok()?;
581    let verb = standalone_verb(kind, def.property_type.as_deref())?;
582    let entity = EntityKind::from_relationship_flag(def.relationship);
583    Some(format!(
584        "CONSTRAINT {} {} {verb}",
585        def.name,
586        constraint_tail(entity, &def.label, &def.properties)
587    ))
588}
589
590/// The `00NA0` note: the command and the existing rule's descriptor. One
591/// spelling of Neo4j's asserted text, shared by the index and constraint
592/// notes.
593fn already_exists_note(command: &str, descriptor: &str) -> Notification {
594    Notification::new(
595        NotificationKind::SchemaIndexOrConstraintAlreadyExists,
596        format!(
597            "note: successful completion - index or constraint already exists. \
598             The command '{command}' has no effect. The index or constraint specified by \
599             '{descriptor}' already exists."
600        ),
601    )
602}
603
604/// The `00NA1` note: the command and, when the statement named one, the
605/// missing catalog name.
606fn does_not_exist_note(command: &str, name: Option<&str>) -> Notification {
607    let subject = match name {
608        Some(name) => format!("`{name}` "),
609        None => String::new(),
610    };
611    Notification::new(
612        NotificationKind::SchemaIndexOrConstraintDoesNotExist,
613        format!(
614            "note: successful completion - index or constraint does not exist. \
615             The command '{command}' has no effect. The specified index or constraint \
616             {subject}does not exist."
617        ),
618    )
619}
620
621#[cfg(test)]
622mod tests {
623    use super::*;
624    use crate::exec::test_support::exec_autocommit;
625    use crate::graph::Graph;
626
627    fn notes(graph: &Graph, query: &str) -> Vec<Notification> {
628        let text = query.strip_prefix("EXPLAIN ").unwrap_or(query);
629        let statement = relate_parser::parse(text).expect("parses");
630        let view = ExecGraph::read(graph);
631        statement
632            .clauses
633            .iter()
634            .flat_map(|clause| {
635                catalog_clause_notifications(&view, clause, &BTreeMap::new())
636                    .expect("notification facts read")
637            })
638            .collect()
639    }
640
641    fn assert_single_note(
642        graph: &Graph,
643        query: &str,
644        kind: NotificationKind,
645        code: &str,
646    ) -> Notification {
647        let found = notes(graph, query);
648        assert_eq!(found.len(), 1, "expected one note for `{query}`: {found:?}");
649        assert_eq!(found[0].kind(), kind);
650        assert_eq!(found[0].gql_status(), code);
651        found.into_iter().next().expect("checked non-empty")
652    }
653
654    #[test]
655    fn duplicate_if_not_exists_index_raises_the_already_exists_note() {
656        let g = Graph::default();
657        exec_autocommit(&g, "CREATE INDEX i1 FOR (n:L) ON (n.p)").unwrap();
658        assert_single_note(
659            &g,
660            "EXPLAIN CREATE INDEX i1 IF NOT EXISTS FOR (n:L) ON (n.p)",
661            NotificationKind::SchemaIndexOrConstraintAlreadyExists,
662            "00NA0",
663        );
664    }
665
666    #[test]
667    fn equivalent_schema_notifications_name_the_existing_rule() {
668        let g = Graph::default();
669        exec_autocommit(&g, "CREATE INDEX i1 FOR (n:L) ON (n.p)").unwrap();
670        let note = assert_single_note(
671            &g,
672            "EXPLAIN CREATE INDEX i2 IF NOT EXISTS FOR (n:L) ON (n.p)",
673            NotificationKind::SchemaIndexOrConstraintAlreadyExists,
674            "00NA0",
675        );
676        assert!(note.description().contains("RANGE INDEX i1"));
677
678        exec_autocommit(&g, "CREATE CONSTRAINT c1 FOR (n:M) REQUIRE (n.p) IS UNIQUE").unwrap();
679        let note = assert_single_note(
680            &g,
681            "EXPLAIN CREATE CONSTRAINT c2 IF NOT EXISTS FOR (n:M) REQUIRE (n.p) IS UNIQUE",
682            NotificationKind::SchemaIndexOrConstraintAlreadyExists,
683            "00NA0",
684        );
685        assert!(note.description().contains("CONSTRAINT c1"));
686    }
687
688    #[test]
689    fn vector_without_dimensions_raises_the_dimensions_note() {
690        let g = Graph::default();
691        assert_single_note(
692            &g,
693            "EXPLAIN CREATE VECTOR INDEX v1 FOR (n:L) ON (n.p)",
694            NotificationKind::SchemaVectorIndexDimensionsNotSpecified,
695            "00NA2",
696        );
697    }
698
699    #[test]
700    fn drop_if_exists_missing_raises_the_does_not_exist_note() {
701        let g = Graph::default();
702        assert_single_note(
703            &g,
704            "EXPLAIN DROP INDEX missing IF EXISTS",
705            NotificationKind::SchemaIndexOrConstraintDoesNotExist,
706            "00NA1",
707        );
708    }
709
710    #[test]
711    fn plain_create_raises_no_note() {
712        let g = Graph::default();
713        assert!(notes(&g, "EXPLAIN CREATE INDEX i1 FOR (n:L) ON (n.p)").is_empty());
714    }
715
716    /// A parameter-supplied name resolves from the statement's parameters,
717    /// exactly as the execution gate resolves it.
718    #[test]
719    fn parameter_names_resolve_for_the_note() {
720        let g = Graph::default();
721        exec_autocommit(&g, "CREATE INDEX i1 FOR (n:L) ON (n.p)").unwrap();
722        let statement = relate_parser::parse("CREATE INDEX $name IF NOT EXISTS FOR (n:L) ON (n.p)")
723            .expect("parses");
724        let view = ExecGraph::read(&g);
725        let params = BTreeMap::from([("name".to_string(), Value::String("i1".into()))]);
726        let found = statement
727            .clauses
728            .iter()
729            .flat_map(|clause| {
730                catalog_clause_notifications(&view, clause, &params)
731                    .expect("notification facts read")
732            })
733            .collect::<Vec<_>>();
734        assert_eq!(found[0].gql_status(), "00NA0");
735        assert!(
736            found[0]
737                .description()
738                .contains("CREATE RANGE INDEX i1 IF NOT EXISTS"),
739            "{}",
740            found[0].description()
741        );
742    }
743
744    /// An unresolvable parameter name yields no notes at all — the one policy
745    /// for every schema-DDL site. Before, the schema-equivalence probe still
746    /// fired and the command text fabricated a `$parameter` placeholder.
747    #[test]
748    fn unresolvable_parameter_name_raises_no_note() {
749        let g = Graph::default();
750        exec_autocommit(&g, "CREATE INDEX i1 FOR (n:L) ON (n.p)").unwrap();
751        assert!(notes(
752            &g,
753            "EXPLAIN CREATE INDEX $missing IF NOT EXISTS FOR (n:L) ON (n.p)"
754        )
755        .is_empty());
756    }
757
758    /// The create gate's skip and the note's rule are the same evidence: a
759    /// name that exists with a *different* schema still names that index.
760    #[test]
761    fn name_collision_note_names_the_occupied_index() {
762        let g = Graph::default();
763        exec_autocommit(&g, "CREATE INDEX i1 FOR (n:L) ON (n.p)").unwrap();
764        let note = assert_single_note(
765            &g,
766            "EXPLAIN CREATE INDEX i1 IF NOT EXISTS FOR (n:Other) ON (n.q)",
767            NotificationKind::SchemaIndexOrConstraintAlreadyExists,
768            "00NA0",
769        );
770        assert!(
771            note.description().contains("RANGE INDEX i1"),
772            "{}",
773            note.description()
774        );
775        assert!(
776            note.description()
777                .contains("CREATE RANGE INDEX i1 IF NOT EXISTS FOR (e:Other) ON (e.q)"),
778            "{}",
779            note.description()
780        );
781    }
782
783    /// A constraint kind with no standalone `REQUIRE` verb (label existence)
784    /// skips the note instead of emitting `REQUIRE ` with an empty verb.
785    #[test]
786    fn constraint_without_a_standalone_verb_skips_the_note() {
787        let g = Graph::default();
788        exec_autocommit(&g, "CREATE CONSTRAINT q FOR (n:P) REQUIRE n:Q").unwrap();
789        assert!(notes(
790            &g,
791            "EXPLAIN CREATE CONSTRAINT q2 IF NOT EXISTS FOR (n:P) REQUIRE n:Q"
792        )
793        .is_empty());
794    }
795
796    /// RB2: an unnamed `CREATE INDEX … IF NOT EXISTS` resolves the same
797    /// generated name the execution gate does, so an occupied generated name
798    /// is reported by the note (before, the name probe was skipped and the
799    /// note was silently absent while execution was a no-op).
800    #[test]
801    fn unnamed_if_not_exists_index_probes_the_generated_name() {
802        let g = Graph::default();
803        // Create the unnamed index for real, then read the name the engine
804        // generated — the EXPLAIN probe must derive the same one.
805        exec_autocommit(&g, "CREATE INDEX FOR (n:L) ON (n.p)").unwrap();
806        let name = g
807            .named_indexes()
808            .into_iter()
809            .next()
810            .expect("the unnamed create landed")
811            .name;
812        let note = assert_single_note(
813            &g,
814            "EXPLAIN CREATE INDEX IF NOT EXISTS FOR (n:L) ON (n.p)",
815            NotificationKind::SchemaIndexOrConstraintAlreadyExists,
816            "00NA0",
817        );
818        assert!(
819            note.description().contains(&format!("RANGE INDEX {name}")),
820            "{}",
821            note.description()
822        );
823        // The executed statement is the same no-op.
824        exec_autocommit(&g, "CREATE INDEX IF NOT EXISTS FOR (n:L) ON (n.p)").unwrap();
825        assert_eq!(g.named_indexes().len(), 1);
826    }
827
828    /// RB1: a graph-type-managed label makes the `CREATE CONSTRAINT` gate
829    /// reject a *different* dependency-managed schema, so `EXPLAIN` fails
830    /// with that same error instead of describing a command that cannot run.
831    /// An `IF NOT EXISTS` create whose schema the graph type already derives
832    /// is by contrast a no-op (Neo4j's live corpus).
833    #[test]
834    fn graph_type_managed_constraint_explain_propagates_the_gate_error() {
835        let g = Graph::default();
836        exec_autocommit(&g, "ALTER CURRENT GRAPH TYPE SET { (:L => {p :: STRING}) }").unwrap();
837        exec_autocommit(
838            &g,
839            "CREATE CONSTRAINT x IF NOT EXISTS FOR (n:L) REQUIRE n.p IS :: STRING",
840        )
841        .expect("an equivalent derived constraint satisfies IF NOT EXISTS");
842        let error = match exec_autocommit(
843            &g,
844            "CREATE CONSTRAINT x IF NOT EXISTS FOR (n:L) REQUIRE n.q IS :: STRING",
845        ) {
846            Ok(_) => panic!("the gate must reject a dependency-managed constraint"),
847            Err(error) => error,
848        };
849        assert!(
850            error
851                .to_string()
852                .contains("IncompatibleGraphTypeDependence"),
853            "{error}"
854        );
855        let statement = relate_parser::parse(
856            "CREATE CONSTRAINT x IF NOT EXISTS FOR (n:L) REQUIRE n.q IS :: STRING",
857        )
858        .expect("parses");
859        let clause = statement.clauses.first().expect("one clause");
860        let view = ExecGraph::read(&g);
861        let error = catalog_clause_notifications(&view, clause, &BTreeMap::new())
862            .expect_err("the gate's rejection propagates out of the note derivation");
863        assert!(
864            error
865                .to_string()
866                .contains("IncompatibleGraphTypeDependence"),
867            "{error}"
868        );
869    }
870
871    /// B3: a property-less non-LOOKUP index has no faithful `ON` clause, so
872    /// the tail fails closed instead of fabricating a LOOKUP statement.
873    #[test]
874    fn property_less_non_lookup_index_has_no_descriptor() {
875        assert_eq!(
876            index_descriptor_tail(IndexKindSpec::Point, EntityKind::Node, &[], &[], &[]),
877            None
878        );
879        assert_eq!(
880            index_descriptor_tail(IndexKindSpec::Lookup, EntityKind::Node, &[], &[], &[]),
881            Some("FOR (e) ON EACH labels(e)".to_string())
882        );
883    }
884}