Skip to main content

relate_executor/exec/
ddl_options.rs

1//! The schema-DDL `OPTIONS` module — the one owner of every option rule a
2//! `CREATE INDEX`/`CREATE CONSTRAINT` carries: the outer map's key/class
3//! policy and its literal-vs-parameter resolution (ADR-0489), the
4//! `CREATE INDEX` target shape, and the per-kind `indexConfig` vocabulary.
5//!
6//! Every rejection here is either the statement *shape* rule (Neo4j's
7//! front-end `SemanticError.*` constructions, surfaced as `SyntaxError`) or
8//! the run-time argument validator's (`ArgumentError`). For the
9//! `indexConfig` *value* path it is always the latter: live Neo4j reports
10//! `Neo.ClientError.General.InvalidArguments` for a non-map or foreign
11//! config and `Neo.ClientError.Statement.ArgumentError` for an unknown
12//! setting or analyzer name — both the openCypher `ArgumentError` class
13//! (live-verified 2026-11-02/03 on neo4j:2026.09-enterprise).
14
15use std::collections::{BTreeMap, HashSet};
16use std::hash::Hash;
17
18use relate_core::{Error, Result, Value};
19use relate_parser::{IndexKind, OptionsForm};
20
21use crate::eval::eval;
22use crate::exec::fulltext::Analyzer;
23use crate::overlay::ExecGraph;
24use crate::row::Row;
25
26// ---------------------------------------------------------------------
27// The shared `indexConfig` vocabulary (ADR-0489)
28// ---------------------------------------------------------------------
29
30/// The one outer `OPTIONS` key every index kind admits and records; the
31/// inner per-kind schema lives in [`create_config`] and the vector
32/// feature module, the stored read in `exec::vector::stored_config`.
33pub(crate) const KEY_INDEX_CONFIG: &str = "indexConfig";
34
35/// The one non-MAP `indexConfig` rejection: every index kind's config slot
36/// rejects a non-map the same way, so the sentence is shared rather than
37/// re-authored per kind (live Neo4j reports
38/// `Neo.ClientError.General.InvalidArguments` for all of them, ADR-0489).
39pub(crate) const INDEX_CONFIG_NOT_A_MAP: &str = "Invalid input for 'indexConfig'. Expected a MAP.";
40
41/// One navigation of the `indexConfig` option — Map or absent, anything
42/// else is rejected at this boundary, never silently dropped. A borrow: the
43/// one mutating consumer (the vector CREATE defaults) clones at its point of
44/// mutation.
45pub(crate) fn index_config(
46    options: &BTreeMap<String, Value>,
47) -> Result<Option<&BTreeMap<String, Value>>> {
48    Ok(index_config_or(options, &|_| {
49        // ADR-0489: a rejected `indexConfig` value is the DDL argument
50        // validator's failure (Neo4j `Neo.ClientError.General.
51        // InvalidArguments`), not a statement-shape syntax error.
52        Error::argument_error(INDEX_CONFIG_NOT_A_MAP)
53    })?
54    .map(|(_, map)| map))
55}
56
57/// [`index_config`] with the caller's own non-map rejection: a surface whose
58/// authored text names the offending value builds it here rather than
59/// navigating the key a second time. The found value rides with the map, so
60/// a rejection naming the whole `indexConfig` value needs no re-rendering.
61pub(crate) fn index_config_or<'a>(
62    options: &'a BTreeMap<String, Value>,
63    rejected: &dyn Fn(&Value) -> Error,
64) -> Result<Option<(&'a Value, &'a BTreeMap<String, Value>)>> {
65    match options.get(KEY_INDEX_CONFIG) {
66        None => Ok(None),
67        Some(value @ Value::Map(map)) => Ok(Some((value, map.as_ref()))),
68        Some(value) => Err(rejected(value)),
69    }
70}
71
72// ---------------------------------------------------------------------
73// Outer OPTIONS key policy and resolution (ADR-0489)
74// ---------------------------------------------------------------------
75
76/// The outer `OPTIONS` allowlist every schema DDL command admits, in both
77/// spellings. Cypher 25 removed `indexProvider`, so `indexConfig` is the
78/// only key. A literal spelling is the front end's syntax-class rejection
79/// before its value expression is lowered (an absent parameter in the value
80/// slot must not change the class); a whole-map parameter carrying a foreign
81/// key is the argument validator's rejection after resolution — the same
82/// allowlist, the class differing by provenance.
83pub(crate) const ADMITTED_OPTION_KEYS: &[&str] = &[KEY_INDEX_CONFIG];
84
85/// Live's rejection text for a non-admitted `OPTIONS` key: name the key and
86/// the admitted spelling(s), rendered from [`ADMITTED_OPTION_KEYS`] so the
87/// text and the allowlist cannot drift. `indexProvider` was deprecated and
88/// then removed upstream, so the schema DDL resolvers read the same text
89/// for every non-admitted key. The *class* stays by provenance — a literal
90/// key is the front end's `SyntaxError`, a whole-map parameter's is the
91/// argument validator's `ArgumentError` — matching live 2026.10.1's driver
92/// codes; the GQL status (22N04) rides inside live's message, which is why
93/// this text names no code of its own.
94pub(crate) fn rejected_option_key_message(key: &str) -> String {
95    let expected = ADMITTED_OPTION_KEYS
96        .iter()
97        .map(|admitted| format!("'{admitted}'"))
98        .collect::<Vec<_>>()
99        .join(", ");
100    format!("Invalid input '{key}' for 'OPTIONS'. Expected {expected}.")
101}
102
103/// The literal-spelling rejection the schema DDL resolvers share: the front
104/// end's syntax class carrying the pinned text.
105fn literal_option_key(key: &str) -> Error {
106    Error::syntax(rejected_option_key_message(key))
107}
108
109/// The parameter-spelling twin: the argument validator's class, its message
110/// key lowercased as live does.
111fn parameter_option_key(key: &str) -> Error {
112    Error::argument_error(rejected_option_key_message(&key.to_lowercase()))
113}
114
115/// The schema DDL resolvers' one key policy (the index and constraint
116/// twins): the shared allowlist, the syntax class for a literal foreign
117/// key, the argument class for a whole-map parameter's.
118fn ddl_option_key_policy() -> OptionKeyPolicy<'static> {
119    OptionKeyPolicy {
120        admitted: ADMITTED_OPTION_KEYS,
121        literal: &literal_option_key,
122        parameter: &parameter_option_key,
123    }
124}
125
126/// The one whole-map `OPTIONS $param` → map invariant: an absent parameter
127/// is `ParameterMissing` (ADR-0308), a non-MAP is the run-time argument
128/// validator's `ArgumentError` carrying the caller's text (ADR-0489). The
129/// schema DDL resolvers and the graph-type resolver share it, so no caller
130/// re-spells the two rejections.
131pub(crate) fn parameter_map<'a>(
132    params: &'a BTreeMap<String, Value>,
133    parameter: &str,
134    not_a_map: &str,
135) -> Result<&'a BTreeMap<String, Value>> {
136    match params.get(parameter) {
137        Some(Value::Map(map)) => Ok(map),
138        None => Err(Error::parameters_missing([parameter])),
139        Some(_) => Err(Error::argument_error(not_a_map)),
140    }
141}
142
143/// The outer-map key policy [`resolve_options`] applies: the admitted keys
144/// and the rejection each spelling raises for a foreign key. The class and
145/// wording differ by surface -- the statement's own front end rejects a
146/// literal foreign key as a syntax error, a whole-map parameter's foreign
147/// key is the argument validator's, and the graph-type body reports its
148/// kinds' own messages in both spellings -- so the caller supplies them.
149pub(crate) struct OptionKeyPolicy<'a> {
150    /// The keys the calling command admits.
151    pub(crate) admitted: &'a [&'a str],
152    /// The literal-spelling rejection for a foreign key.
153    pub(crate) literal: &'a dyn Fn(&str) -> Error,
154    /// The resolved-parameter-spelling rejection for a foreign key.
155    pub(crate) parameter: &'a dyn Fn(&str) -> Error,
156}
157
158/// The one `OPTIONS` resolution sequence (ADR-0489), shared by
159/// `CREATE CONSTRAINT`, `CREATE INDEX` and the graph-type body, one arm per
160/// form:
161///
162/// - `Absent` yields no options;
163/// - `Literal` checks every key against the policy *before* any value
164///   expression is lowered (so a shape rejection wins over an absent
165///   parameter in a value slot), then lowers and evaluates the values;
166/// - `Parameter` resolves the whole map (absent → `ParameterMissing`,
167///   non-MAP → `ArgumentError`), then checks its keys against the policy.
168pub(crate) fn resolve_options(
169    graph: &ExecGraph<'_>,
170    form: &OptionsForm,
171    params: &BTreeMap<String, Value>,
172    policy: &OptionKeyPolicy<'_>,
173    not_a_map: &'static str,
174) -> Result<BTreeMap<String, Value>> {
175    let mut options = BTreeMap::new();
176    match form {
177        OptionsForm::Absent => {}
178        OptionsForm::Literal(entries) => {
179            if let Some((key, _)) = entries
180                .iter()
181                .find(|(key, _)| !policy.admitted.contains(&key.as_str()))
182            {
183                return Err((policy.literal)(key));
184            }
185            for (key, expression) in entries {
186                options.insert(
187                    key.clone(),
188                    eval(
189                        graph,
190                        &Row::new(),
191                        &relate_front::lower_expr(expression)?,
192                        params,
193                    )?,
194                );
195            }
196        }
197        OptionsForm::Parameter(parameter) => {
198            options = parameter_map(params, parameter, not_a_map)?.clone();
199            // The resolved map has no value expressions, so its keys are
200            // checked after resolution; that provenance is the argument
201            // validator's class.
202            if let Some(key) = options
203                .keys()
204                .find(|key| !policy.admitted.contains(&key.as_str()))
205            {
206                return Err((policy.parameter)(key));
207            }
208        }
209    }
210    Ok(options)
211}
212
213/// The `CREATE CONSTRAINT` options shape (ADR-0489): an
214/// index-backed constraint admits only `indexConfig`, and any other literal
215/// key is the front end's syntax error, rejected before the value
216/// expression is lowered and before the schema-conflict checks run. A
217/// rejected `indexConfig` *value*, and every rejection reached through a
218/// whole-map `OPTIONS $param` (including a non-map parameter), is the
219/// argument validator's `ArgumentError`. EXISTENCE and PROPERTY TYPE
220/// constraints admit no options at all: any entry is rejected, whether
221/// written literally or supplied by the parameter (live-verified 2026-11-02
222/// on neo4j:2026.09-enterprise). Running before the conflict gate makes the
223/// shape class win over an equivalent rule, matching Neo4j's compile-time
224/// ordering.
225pub(crate) fn validate_constraint_options(
226    graph: &ExecGraph<'_>,
227    c: &relate_parser::CreateConstraintClause,
228    constraint_type: relate_model::ConstraintType,
229    params: &BTreeMap<String, Value>,
230) -> Result<()> {
231    let options = resolve_options(
232        graph,
233        &c.options,
234        params,
235        &ddl_option_key_policy(),
236        "Could not create constraint with options: expected a map value.",
237    )?;
238    // EXISTENCE and PROPERTY TYPE constraints admit no options at all
239    // (Neo4j 22N81): an empty map is accepted, any entry is not.
240    if matches!(
241        constraint_type,
242        relate_model::ConstraintType::Exists | relate_model::ConstraintType::PropertyType
243    ) {
244        return if options.is_empty() {
245            Ok(())
246        } else {
247            Err(Error::argument_error(
248                "InvalidOptionsMap: this constraint has no valid options values",
249            ))
250        };
251    }
252    // The one admitted value shape: an empty `indexConfig` map, navigated
253    // through the module's one accessor.
254    if index_config(&options)?.is_some_and(|config| !config.is_empty()) {
255        return Err(Error::argument_error("InvalidOptionsMap"));
256    }
257    Ok(())
258}
259
260// ---------------------------------------------------------------------
261// CREATE INDEX target shape
262// ---------------------------------------------------------------------
263
264/// The kinds that take exactly one property, with the rejection each raises
265/// when the count differs (Neo4j's two messages, live-verified): POINT/TEXT
266/// report the property-count rule in the front end, VECTOR reports its own
267/// unsupported-shape error. One table, consulted once.
268fn single_property_rejection(kind: IndexKind) -> Option<&'static str> {
269    match kind {
270        IndexKind::Point | IndexKind::Text => {
271            Some("InvalidArguments: this index type requires one property")
272        }
273        IndexKind::Vector => Some("UnsupportedIndexOrConstraint"),
274        IndexKind::Range | IndexKind::Fulltext | IndexKind::Lookup => None,
275    }
276}
277
278/// The duplicated-token policy: no token repeats within its vocabulary.
279fn has_duplicates<'a, T: Hash + Eq + 'a>(mut items: impl Iterator<Item = &'a T>) -> bool {
280    let mut seen = HashSet::new();
281    items.any(|item| !seen.insert(item))
282}
283
284/// The label text the catalog records for a `CREATE INDEX` clause — the
285/// one place the label-less rule lives. A LOOKUP index is the one
286/// label-less form (the legacy catalog encoding stores it with an empty
287/// label); every other kind must name a label or relationship type, a
288/// statement-shape `SyntaxError` — never a fabricated empty label.
289pub(crate) fn index_label(c: &relate_parser::CreateIndexClause) -> Result<String> {
290    match c.labels.first() {
291        Some(label) => Ok(label.to_string()),
292        None if c.kind == IndexKind::Lookup => Ok(String::new()),
293        None => Err(Error::syntax(
294            "a non-LOOKUP index must name a label or relationship type",
295        )),
296    }
297}
298
299/// The `CREATE INDEX` target-shape policy: the single-property kinds'
300/// property count and the duplicated-token rule (22N76 — the label and the
301/// property vocabularies are separate sets, each without duplicates, for
302/// every index kind), and the label-less rule (LOOKUP only). Runs before the OPTIONS shape so a target rejection
303/// wins over a config one.
304fn validate_index_target(c: &relate_parser::CreateIndexClause) -> Result<()> {
305    if let Some(detail) = single_property_rejection(c.kind) {
306        if c.properties.len() != 1 {
307            return Err(Error::syntax(detail));
308        }
309    }
310    // Raised before the conflict gate so `IF NOT EXISTS` can never mask it.
311    index_label(c)?;
312    if has_duplicates(c.labels.iter())
313        || has_duplicates(c.properties.iter().chain(&c.with_properties))
314    {
315        return Err(Error::semantic("IndexContainsDuplicatedTokens"));
316    }
317    Ok(())
318}
319
320/// The committed-schema path's per-kind index options resolution
321/// (ADR-0649 §6): the same per-kind `ConfigPolicy` a `CREATE INDEX`
322/// runs, over the flat option payload a committed ontology envelope
323/// carries. Nests the payload under `indexConfig` (the one key the
324/// engine's stored readers navigate), validates the kind's vocabulary
325/// and values — refusing what a CREATE would reject — and completes
326/// the kind's defaults, returning the resolved options map the
327/// catalog detail records. Public for the facade's open-tail
328/// application (`relate::committed`), the one external consumer: the
329/// committed file is untrusted input, and its option payloads get the
330/// DDL path's own validation rather than a parallel one.
331pub fn resolve_committed_index_options(
332    kind: crate::redo::IndexKindSpec,
333    flat: BTreeMap<String, Value>,
334) -> Result<BTreeMap<String, Value>> {
335    let mut options = BTreeMap::new();
336    options.insert(KEY_INDEX_CONFIG.to_string(), Value::Map(flat.into()));
337    ConfigPolicy::for_kind(kind.into()).validate(&mut options)?;
338    Ok(options)
339}
340
341/// One committed index as the facade's open tail hands it to the DDL
342/// home (ADR-0649 §6): the catalog row's identity, its typed detail,
343/// and its evaluated options — borrowed from the codec's carrier, so
344/// no second owned spelling of the carrier exists.
345pub struct CommittedIndexFact<'a> {
346    pub name: &'a str,
347    pub detail: &'a crate::redo::IndexDetailSpec,
348    pub options: &'a BTreeMap<String, Value>,
349}
350
351/// The committed schema's catalog redo group (ADR-0649 §6) — the DDL
352/// home's own construction, so the catalog policy (the op order, the
353/// detail shape, the option resolution, the held-row retirement) has
354/// one compiler-linked home with `CREATE INDEX`: a new index kind,
355/// WITH-property rule, or op order added to DDL reaches the store's
356/// open path through this function, never through a parallel
357/// assembly. Each committed index first retires every catalog row held
358/// under its name or its indexed pair (the committed file is the
359/// source and wins, ADR-0649 decision 2 — a file edit that retargets
360/// or renames an index overrides the machine's stale row the way any
361/// later commit would, instead of failing the open on the catalog's
362/// duplicate rules), then records the row and its typed detail in the
363/// DDL path's own order; the group ends at the current graph type.
364pub fn committed_catalog_ops(
365    held: &[relate_catalog::IndexDef],
366    indexes: &[CommittedIndexFact<'_>],
367    graph_type: &relate_engine_api::graph_type::GraphTypeSpec,
368) -> Result<Vec<crate::redo::RedoOp>> {
369    use crate::redo::RedoOp;
370    let mut ops = Vec::with_capacity(indexes.len() * 3 + 1);
371    for index in indexes {
372        // The carrier's stated contract (relate-storage's
373        // `CommittedIndex`): every producer refuses label-less and
374        // non-single-property entries — the typed refusal here is the
375        // boundary's own check, so a future producer that misses it
376        // fails the open, never panics it.
377        let [label] = index.detail.labels.as_slice() else {
378            return Err(Error::storage(format!(
379                "the committed schema's index '{}' declares no or multiple labels",
380                index.name
381            )));
382        };
383        let [property] = index.detail.properties.as_slice() else {
384            return Err(Error::storage(format!(
385                "the committed schema's index '{}' declares no or multiple properties",
386                index.name
387            )));
388        };
389        // The pair half is the one pair predicate
390        // (`holds_index_pair`: the legacy encoding's own decoder), so
391        // a row any producer wrote retires — a raw string equality
392        // would only ever match this function's own previous rows.
393        for stale in held.iter().filter(|held| {
394            held.name == index.name || crate::redo::holds_index_pair(held, label, property)
395        }) {
396            ops.push(RedoOp::DropIndex {
397                name: stale.name.clone(),
398            });
399        }
400        // The row records the same legacy-encoded property the DDL
401        // create side records (`legacy_property_encoding`), so a
402        // committed index and the equivalent `CREATE INDEX` install
403        // byte-identical catalog rows and the catalog's own
404        // pair-keyed comparisons see them as the same pair.
405        ops.push(RedoOp::CreateIndex {
406            name: index.name.to_string(),
407            label: label.clone(),
408            property: crate::redo::legacy_property_encoding(
409                property,
410                index.detail.kind,
411                index.name,
412            ),
413        });
414        // The option payloads get the per-kind resolution a CREATE
415        // INDEX runs — the committed file is untrusted input, and an
416        // option a CREATE would reject refuses here.
417        let options = resolve_committed_index_options(index.detail.kind, index.options.clone())?;
418        ops.push(crate::exec::ddl::index_detail_op(
419            index.name,
420            index.detail.clone(),
421            &options,
422        ));
423    }
424    ops.push(RedoOp::SetCurrentGraphType {
425        body: graph_type.clone(),
426    });
427    Ok(ops)
428}
429
430/// The `CREATE INDEX` options shape (ADR-0489), the `CREATE CONSTRAINT`
431/// twin's counterpart: the target shape, the shared `OPTIONS` resolution
432/// (whose allowlist excludes `indexProvider` in both spellings), and the
433/// per-kind `indexConfig` policy. Returns the resolved options map the
434/// catalog detail records. Runs before the conflict gate so an `IF NOT
435/// EXISTS`/equivalent-rule skip can never mask a shape rejection.
436pub(crate) fn resolve_index_options(
437    graph: &ExecGraph<'_>,
438    c: &relate_parser::CreateIndexClause,
439    params: &BTreeMap<String, Value>,
440) -> Result<BTreeMap<String, Value>> {
441    validate_index_target(c)?;
442    let mut options = resolve_options(
443        graph,
444        &c.options,
445        params,
446        &ddl_option_key_policy(),
447        "InvalidInputValue: OPTIONS parameter must be a MAP",
448    )?;
449    // Validation and the kind's defaults are the one policy's two halves.
450    ConfigPolicy::for_kind(c.kind).validate(&mut options)?;
451    Ok(options)
452}
453
454// ---------------------------------------------------------------------
455// Per-kind indexConfig vocabulary
456// ---------------------------------------------------------------------
457
458/// One value shape an `indexConfig` setting admits.
459#[derive(Clone, Copy)]
460enum ValueShape {
461    /// A list of numbers (a POINT index's spatial bound).
462    NumericList,
463    /// One of the fulltext analyzer names.
464    Analyzer,
465    /// A boolean.
466    Boolean,
467}
468
469impl ValueShape {
470    fn check(self, key: &str, value: &Value) -> Result<()> {
471        match self {
472            Self::NumericList => {
473                if matches!(
474                    value,
475                    Value::List(items)
476                        if items.iter().all(|item| matches!(item, Value::Float(_) | Value::Int(_)))
477                ) {
478                    Ok(())
479                } else {
480                    Err(Error::argument_error(
481                        "Invalid input for 'indexConfig'. Expected to be MAP<STRING, LIST<FLOAT>>.",
482                    ))
483                }
484            }
485            Self::Analyzer => match value {
486                Value::String(name) if Analyzer::from_name(name).is_some() => Ok(()),
487                _ => Err(Error::argument_error(format!(
488                    "Invalid input for analyzer name: {value:?}"
489                ))),
490            },
491            Self::Boolean => {
492                if matches!(value, Value::Bool(_)) {
493                    Ok(())
494                } else {
495                    Err(Error::argument_error(format!(
496                        "Invalid input for '{key}'. Expected a boolean."
497                    )))
498                }
499            }
500        }
501    }
502}
503
504/// One index kind's `indexConfig` family: the settings it admits and the
505/// prefixes of the families other kinds own. The shared loop in
506/// [`validate_config_family`] is the only control flow.
507struct ConfigFamily {
508    keys: &'static [(&'static str, ValueShape)],
509    /// Key prefixes that name another index kind's config — rejected as a
510    /// foreign family, never as an unknown setting.
511    foreign_prefixes: &'static [&'static str],
512    /// Completes "Expected {…}." in the foreign-family rejection.
513    foreign_expected: &'static str,
514}
515
516/// The point index's `indexConfig` keys: two-dimensional and 3D bounds in
517/// the cartesian and WGS-84 coordinate systems (Neo4j's live allowlist,
518/// 2026.09).
519const POINT_FAMILY: ConfigFamily = ConfigFamily {
520    keys: &[
521        ("spatial.cartesian.min", ValueShape::NumericList),
522        ("spatial.cartesian.max", ValueShape::NumericList),
523        ("spatial.cartesian-3d.min", ValueShape::NumericList),
524        ("spatial.cartesian-3d.max", ValueShape::NumericList),
525        ("spatial.wgs-84.min", ValueShape::NumericList),
526        ("spatial.wgs-84.max", ValueShape::NumericList),
527        ("spatial.wgs-84-3d.min", ValueShape::NumericList),
528        ("spatial.wgs-84-3d.max", ValueShape::NumericList),
529    ],
530    foreign_prefixes: &["fulltext.", "vector."],
531    foreign_expected: "a spatial bound",
532};
533
534/// The `indexConfig` key naming a fulltext index's analyzer.
535pub(crate) const KEY_FULLTEXT_ANALYZER: &str = "fulltext.analyzer";
536
537/// The one stored-setting reader every typed read-side reader is a single
538/// call of: navigate the outer `indexConfig` (the one [`index_config`]
539/// boundary, its non-map rejection mapped to the shared drift error),
540/// find the stored setting by key, then narrow — absent answers the
541/// caller's default, a value the caller's typed reading fails to narrow
542/// is the drift rejection. The create-time validation would have
543/// rejected a stored shape this reader cannot narrow, so the rejection
544/// is catalog drift, never a silently unconfigured index.
545fn stored_setting<T>(
546    options: &BTreeMap<String, Value>,
547    index_name: &str,
548    key: &str,
549    default: T,
550    narrow: impl Fn(&Value) -> Option<T>,
551) -> Result<T> {
552    let drift = || {
553        Error::execution(format!(
554            "InvalidIndexDefinition: fulltext index {index_name} has an invalid indexConfig option"
555        ))
556    };
557    let config = index_config(options).map_err(|_| drift())?;
558    match config.and_then(|config| config.get(key)) {
559        None => Ok(default),
560        Some(value) => narrow(value).ok_or_else(drift),
561    }
562}
563
564/// The analyzer a stored fulltext index was created with: its
565/// [`KEY_FULLTEXT_ANALYZER`] setting, the standard analyzer when absent.
566pub(crate) fn index_analyzer(
567    options: &BTreeMap<String, Value>,
568    index_name: &str,
569) -> Result<Analyzer> {
570    stored_setting(
571        options,
572        index_name,
573        KEY_FULLTEXT_ANALYZER,
574        Analyzer::Standard,
575        |value| match value {
576            Value::String(name) => Analyzer::from_name(name),
577            _ => None,
578        },
579    )
580}
581
582/// The `indexConfig` key naming a fulltext index's eventual consistency.
583pub(crate) const KEY_FULLTEXT_EVENTUALLY_CONSISTENT: &str = "fulltext.eventually_consistent";
584
585/// Whether a stored fulltext index was created eventually consistent: its
586/// [`KEY_FULLTEXT_EVENTUALLY_CONSISTENT`] setting, `false` when absent.
587/// The SEARCH clause rejects such an index (ADR-0680); the
588/// `db.index.fulltext.query*` procedures are its supported surface.
589pub(crate) fn index_eventually_consistent(
590    options: &BTreeMap<String, Value>,
591    index_name: &str,
592) -> Result<bool> {
593    stored_setting(
594        options,
595        index_name,
596        KEY_FULLTEXT_EVENTUALLY_CONSISTENT,
597        false,
598        |value| match value {
599            Value::Bool(eventually_consistent) => Some(*eventually_consistent),
600            _ => None,
601        },
602    )
603}
604
605/// The fulltext index's two `indexConfig` settings.
606const FULLTEXT_FAMILY: ConfigFamily = ConfigFamily {
607    // The key vocabulary is the read side's (these constants); the create
608    // side owns only the value shapes.
609    keys: &[
610        (KEY_FULLTEXT_ANALYZER, ValueShape::Analyzer),
611        (KEY_FULLTEXT_EVENTUALLY_CONSISTENT, ValueShape::Boolean),
612    ],
613    foreign_prefixes: &["spatial.", "vector."],
614    foreign_expected: "'fulltext.analyzer' or 'fulltext.eventually_consistent'",
615};
616
617/// The create side of the vector option schema, the read side's mirror
618/// (`exec::vector::stored_config`): one adjacent pipeline — navigate the
619/// outer `indexConfig` (Map or absent, anything else is rejected at the
620/// [`index_config`] boundary), parse (the typed DDL errors), apply the
621/// DDL defaults, and return the canonical `indexConfig` value to store
622/// under [`KEY_INDEX_CONFIG`]. The parse and the defaults are the root
623/// schema's ([`crate::vector_config`]) — a root module this exec file
624/// imports downward, never the reverse (LABS-845).
625fn create_config(options: &BTreeMap<String, Value>) -> Result<Value> {
626    let mut config = index_config(options)?.cloned().unwrap_or_default();
627    let parsed = crate::vector_config::parse_config(&config)?;
628    crate::vector_config::apply_defaults(&mut config, &parsed);
629    Ok(Value::Map(config.into()))
630}
631
632/// The per-kind `indexConfig` value policy: one variant per validation
633/// strategy, so every kind — VECTOR included — has exactly one policy.
634enum ConfigPolicy {
635    /// The kind consumes no config: absent or empty is fine, anything else
636    /// is rejected.
637    Nothing { non_empty: &'static str },
638    /// A key/value family, validated by the shared loop, then completed
639    /// with the kind's default config so SHOW INDEXES' `options` and
640    /// `createStatement` carry Neo4j's shape; a caller-supplied entry wins.
641    /// The per-kind table is `IndexKindSpec::default_config`, not a match
642    /// here.
643    Family {
644        family: &'static ConfigFamily,
645        kind: crate::redo::IndexKindSpec,
646    },
647    /// VECTOR: the typed parse and the DDL defaults are
648    /// [`create_config`]'s navigate-and-default pipeline.
649    Vector,
650}
651
652impl ConfigPolicy {
653    /// The kind's value policy — one variant per kind, no absent mode.
654    fn for_kind(kind: IndexKind) -> Self {
655        match kind {
656            IndexKind::Lookup => Self::Nothing {
657                non_empty: "Invalid input for index config. Expected nothing.",
658            },
659            IndexKind::Range | IndexKind::Text => Self::Nothing {
660                non_empty: "InvalidIndexConfig",
661            },
662            IndexKind::Point => Self::Family {
663                family: &POINT_FAMILY,
664                kind: crate::redo::IndexKindSpec::from(kind),
665            },
666            IndexKind::Fulltext => Self::Family {
667                family: &FULLTEXT_FAMILY,
668                kind: crate::redo::IndexKindSpec::from(kind),
669            },
670            IndexKind::Vector => Self::Vector,
671        }
672    }
673
674    /// Validate the resolved options map's `indexConfig` entry (absent = no
675    /// config), navigating the one [`index_config`] boundary itself so every
676    /// variant — the mutating VECTOR one included — shares the same entry
677    /// point.
678    fn validate(&self, options: &mut BTreeMap<String, Value>) -> Result<()> {
679        match self {
680            Self::Nothing { non_empty } => match index_config(options)? {
681                None => Ok(()),
682                Some(map) if map.is_empty() => Ok(()),
683                Some(_) => Err(Error::argument_error(*non_empty)),
684            },
685            Self::Family { family, kind } => {
686                // One navigation: validate the working map, then complete
687                // it with the kind's defaults.
688                let mut config = index_config(options)?.cloned().unwrap_or_default();
689                validate_config_family(&config, family)?;
690                if let Some(defaults) = kind.default_config() {
691                    defaults(&mut config);
692                    options.insert(KEY_INDEX_CONFIG.into(), Value::Map(config.into()));
693                }
694                Ok(())
695            }
696            Self::Vector => {
697                let config = create_config(options)?;
698                options.insert(KEY_INDEX_CONFIG.into(), config);
699                Ok(())
700            }
701        }
702    }
703}
704
705/// The shared per-key loop of a config family: lowercase, the foreign-family
706/// prefix rejection, the table lookup, and the value shape.
707fn validate_config_family(map: &BTreeMap<String, Value>, family: &ConfigFamily) -> Result<()> {
708    for (key, value) in map.iter() {
709        let lowered = key.to_ascii_lowercase();
710        if family
711            .foreign_prefixes
712            .iter()
713            .any(|prefix| lowered.starts_with(prefix))
714        {
715            return Err(Error::argument_error(format!(
716                "Invalid input '{key}' for index config. Expected {}.",
717                family.foreign_expected
718            )));
719        }
720        let Some((_, shape)) = family.keys.iter().find(|(name, _)| *name == lowered) else {
721            let expected: Vec<&str> = family.keys.iter().map(|(name, _)| *name).collect();
722            return Err(Error::argument_error(format!(
723                "Invalid input '{key}' for index setting. Expected one of {}.",
724                expected.join(", ")
725            )));
726        };
727        shape.check(key, value)?;
728    }
729    Ok(())
730}
731
732#[cfg(test)]
733mod tests {
734    use super::*;
735    use relate_parser::SchemaEntityType;
736
737    fn clause(
738        kind: IndexKind,
739        labels: Vec<relate_names::SmallName>,
740    ) -> relate_parser::CreateIndexClause {
741        relate_parser::CreateIndexClause {
742            name: None,
743            entity_type: SchemaEntityType::Node,
744            labels,
745            properties: Vec::new(),
746            if_not_exists: true,
747            kind,
748            on_each: false,
749            with_properties: Vec::new(),
750            options: OptionsForm::Absent,
751        }
752    }
753
754    /// The label-less rejection is a statement-shape `SyntaxError`, raised by
755    /// the target-shape policy that runs ahead of the conflict gate (even
756    /// under `IF NOT EXISTS`); LOOKUP stays the one label-less form.
757    #[test]
758    fn a_label_less_non_lookup_index_is_a_syntax_error_before_the_gate() {
759        let err = validate_index_target(&clause(IndexKind::Range, Vec::new()))
760            .expect_err("label-less RANGE must be rejected");
761        assert!(matches!(err, Error::Syntax(_)), "{err:?}");
762        validate_index_target(&clause(IndexKind::Lookup, Vec::new())).unwrap();
763    }
764}