Skip to main content

relate_engine_api/redo/
index.rs

1//! The index-DDL payload family: the typed index kind, the serving-pair
2//! predicates, the legacy property encoding, and the detail spec its
3//! `CatalogIndexDetail` op carries. A private sibling re-exported at the
4//! `redo` root (the one-public-path pattern), so callers keep using
5//! `crate::redo::…`.
6
7use std::collections::BTreeMap;
8
9use relate_catalog::{ConstraintDef, IndexDef};
10use relate_core::Value;
11use relate_model::EntityKind;
12use serde::{Deserialize, Serialize};
13
14use super::RedoOp;
15
16/// The DDL index kind carried by [`IndexDetailSpec`]: a
17/// serde-serializable mirror of `relate_parser::IndexKind`.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19pub enum IndexKindSpec {
20    Range,
21    Point,
22    Text,
23    Fulltext,
24    Lookup,
25    Vector,
26}
27
28impl IndexKindSpec {
29    /// Every variant; derived inverses (and their tests) iterate this so
30    /// the variant list is maintained in exactly one place.
31    pub const ALL: [IndexKindSpec; 6] = [
32        IndexKindSpec::Range,
33        IndexKindSpec::Point,
34        IndexKindSpec::Text,
35        IndexKindSpec::Fulltext,
36        IndexKindSpec::Lookup,
37        IndexKindSpec::Vector,
38    ];
39
40    /// The upper-case display name Neo4j's `SHOW INDEXES` `type` column
41    /// uses (same strings as `relate_parser::IndexKind::display_name`).
42    /// The `SHOW INDEXES` `type` column spelling — the parser's own display
43    /// name, so the six names live once in the crate that owns the dialect.
44    pub fn display_name(&self) -> &'static str {
45        relate_parser::IndexKind::from(*self).display_name()
46    }
47
48    /// Parse the display name back into the kind — the inverse of
49    /// [`IndexKindSpec::display_name`], used to recover the kind of
50    /// legacy catalog rows that predate `CatalogIndexDetail` from their
51    /// `{props}#{KIND}#{name}` property encoding. Derived from the one
52    /// string table in `display_name` so the two directions cannot drift.
53    pub fn from_display_name(name: &str) -> Option<Self> {
54        Self::ALL
55            .into_iter()
56            .find(|kind| kind.display_name() == name)
57    }
58
59    /// The Neo4j `SHOW INDEXES` `indexProvider` column value for this
60    /// kind. Exhaustive on purpose: a new index kind fails to compile
61    /// here instead of silently falling back to `range-1.0`.
62    pub fn provider_name(&self) -> &'static str {
63        match self {
64            IndexKindSpec::Range => "range-1.0",
65            IndexKindSpec::Point => "point-1.0",
66            IndexKindSpec::Text => "text-3.0",
67            IndexKindSpec::Fulltext => "fulltext-2.0",
68            IndexKindSpec::Lookup => "token-lookup-1.0",
69            IndexKindSpec::Vector => "vector-2026.08",
70        }
71    }
72
73    /// The DDL default `indexConfig` this kind records when the statement
74    /// names none — the one mutator the DDL layer applies. `None` for the
75    /// kinds whose default config is the empty map: RANGE, TEXT and LOOKUP
76    /// record none, and VECTOR's metric-dependent defaults are applied by
77    /// `vector_config::apply_defaults` through the vector OPTIONS pipeline
78    /// (`catalog_schema::create_config`), which is why this table omits it.
79    /// The table lives beside [`IndexKindSpec::display_name`] and
80    /// [`IndexKindSpec::provider_name`] so a new kind states its default
81    /// here, never in a `_`-glued match one layer above.
82    pub fn default_config(&self) -> Option<fn(&mut BTreeMap<String, Value>)> {
83        match self {
84            IndexKindSpec::Point => Some(apply_point_defaults),
85            IndexKindSpec::Fulltext => Some(apply_fulltext_defaults),
86            IndexKindSpec::Range
87            | IndexKindSpec::Text
88            | IndexKindSpec::Lookup
89            | IndexKindSpec::Vector => None,
90        }
91    }
92
93    /// The one LOOKUP discrimination: a LOOKUP index carries no
94    /// label/property tokens. Every LOOKUP reader — the row's null-ed
95    /// `labelsOrTypes`/`properties` cells, the createStatement's EACH form,
96    /// the notification descriptor's tail — asks this, never its own
97    /// `matches!`.
98    pub fn is_lookup(&self) -> bool {
99        matches!(self, IndexKindSpec::Lookup)
100    }
101
102    /// The kind of one index row, resolved once — the detail's kind when the
103    /// detail join hits, else the legacy `{props}#{KIND}#{name}` encoding's
104    /// kind for a detail-less legacy WAL/checkpoint row (`catalog_create_index`
105    /// writes both redo ops in one statement today), else RANGE. The one
106    /// resolution every kind reader consults — the kind filter, the row's
107    /// type/provider columns and LOOKUP nulling, the createStatement's own
108    /// `detail.kind`, and the planner-IR diagnostic table's `type` cell.
109    /// The RANGE default covers exactly the encoding's two no-kind shapes:
110    /// the bare pre-encoding form (`name`, written before kinds existed —
111    /// RANGE by history, the only kind that era stored) and an unparseable
112    /// kind segment (`name#NOTAKIND#idx`, pinned to no kind by the redo
113    /// decoder's own tests). The second cannot occur in a store this engine
114    /// wrote — [`legacy_property_encoding`] only ever embeds a valid
115    /// [`IndexKindSpec`] — so the default never fabricates a kind over a
116    /// reachable row.
117    pub fn resolve(detail: Option<&IndexDetailSpec>, legacy_property: &str) -> Self {
118        detail
119            .map(|detail| detail.kind)
120            .or_else(|| split_legacy_property_encoding(legacy_property).1)
121            .unwrap_or(IndexKindSpec::Range)
122    }
123}
124
125/// The spatial bounds Neo4j records for a `POINT` index that names none:
126/// one key per coordinate reference system, each a `[min…]`/`[max…]` list.
127fn apply_point_defaults(config: &mut BTreeMap<String, Value>) {
128    const DEFAULTS: &[(&str, &[f64])] = &[
129        ("spatial.cartesian.min", &[-1000000.0, -1000000.0]),
130        ("spatial.cartesian.max", &[1000000.0, 1000000.0]),
131        (
132            "spatial.cartesian-3d.min",
133            &[-1000000.0, -1000000.0, -1000000.0],
134        ),
135        (
136            "spatial.cartesian-3d.max",
137            &[1000000.0, 1000000.0, 1000000.0],
138        ),
139        ("spatial.wgs-84.min", &[-180.0, -90.0]),
140        ("spatial.wgs-84.max", &[180.0, 90.0]),
141        ("spatial.wgs-84-3d.min", &[-180.0, -90.0, -1000000.0]),
142        ("spatial.wgs-84-3d.max", &[180.0, 90.0, 1000000.0]),
143    ];
144    for (key, values) in DEFAULTS {
145        let coordinates = values
146            .iter()
147            .map(|value| Value::Float(*value))
148            .collect::<Vec<_>>();
149        config
150            .entry((*key).to_string())
151            .or_insert_with(|| Value::List(coordinates.into()));
152    }
153}
154
155/// The fulltext config Neo4j records when the statement names none.
156fn apply_fulltext_defaults(config: &mut BTreeMap<String, Value>) {
157    config
158        .entry("fulltext.analyzer".to_string())
159        .or_insert_with(|| Value::String("standard-no-stop-words".into()));
160    config
161        .entry("fulltext.eventually_consistent".to_string())
162        .or_insert(Value::Bool(false));
163}
164
165impl From<IndexKindSpec> for relate_parser::IndexKind {
166    fn from(kind: IndexKindSpec) -> Self {
167        match kind {
168            IndexKindSpec::Range => relate_parser::IndexKind::Range,
169            IndexKindSpec::Point => relate_parser::IndexKind::Point,
170            IndexKindSpec::Text => relate_parser::IndexKind::Text,
171            IndexKindSpec::Fulltext => relate_parser::IndexKind::Fulltext,
172            IndexKindSpec::Lookup => relate_parser::IndexKind::Lookup,
173            IndexKindSpec::Vector => relate_parser::IndexKind::Vector,
174        }
175    }
176}
177
178impl From<relate_parser::IndexKind> for IndexKindSpec {
179    fn from(kind: relate_parser::IndexKind) -> Self {
180        match kind {
181            relate_parser::IndexKind::Range => IndexKindSpec::Range,
182            relate_parser::IndexKind::Point => IndexKindSpec::Point,
183            relate_parser::IndexKind::Text => IndexKindSpec::Text,
184            relate_parser::IndexKind::Fulltext => IndexKindSpec::Fulltext,
185            relate_parser::IndexKind::Lookup => IndexKindSpec::Lookup,
186            relate_parser::IndexKind::Vector => IndexKindSpec::Vector,
187        }
188    }
189}
190
191/// The index side of an ADR-0372 serving-pair check: the rule's kind,
192/// entity kind, labels, and properties, as the creating statement spells
193/// them (or as the materialized `index_details` record them).
194#[derive(Clone, Copy)]
195pub struct ServingPairIndex<'a> {
196    pub kind: IndexKindSpec,
197    pub relationship: bool,
198    pub labels: &'a [String],
199    pub properties: &'a [String],
200}
201
202/// The constraint side of an ADR-0372 serving-pair check.
203#[derive(Clone, Copy)]
204pub struct ServingPairConstraint<'a> {
205    pub backed: bool,
206    pub relationship: bool,
207    pub label: &'a str,
208    pub properties: &'a [String],
209}
210
211/// ADR-0372's serving-pair conflict, the one canonical form, owning the
212/// whole match: the pair's typed fields in, the verdict out. A schema rule
213/// pair conflicts only when the index kind is RANGE — the only kind that
214/// can serve a constraint's backing (ADR-0339) — and the constraint is
215/// index-backed (uniqueness/key), on the same label and properties.
216/// Property-type/existence constraints and FULLTEXT/VECTOR/POINT indexes
217/// coexist with everything. All three creation directions consult this; a
218/// change to the rule lands here once.
219pub fn serving_pair_conflicts(
220    index: ServingPairIndex<'_>,
221    constraint: ServingPairConstraint<'_>,
222) -> bool {
223    index.kind == IndexKindSpec::Range
224        && index.relationship == constraint.relationship
225        && index.labels.len() == 1
226        && constraint.label == index.labels[0]
227        && constraint.properties == index.properties
228        && constraint.backed
229}
230
231/// Decode a legacy `IndexDef.property` string: split the value `catalog_create_index`
232/// (and the constraint-backed index
233/// path) into its props head and index kind. A bare property name (no
234/// `#`) is its own head with no kind. The single decoder for this
235/// format — every reader of `IndexDef.property` goes through here.
236pub fn split_legacy_property_encoding(property: &str) -> (&str, Option<IndexKindSpec>) {
237    match property.split_once('#') {
238        None => (property, None),
239        Some((head, rest)) => (
240            head,
241            rest.split('#')
242                .next()
243                .and_then(IndexKindSpec::from_display_name),
244        ),
245    }
246}
247
248/// Encode an `IndexDef.property` in the legacy `{property}#{KIND}#{name}`
249/// format — the encoder half of [`split_legacy_property_encoding`], which
250/// decodes the result back to `(property, Some(kind))`.
251pub fn legacy_property_encoding(property: &str, kind: IndexKindSpec, name: &str) -> String {
252    format!("{property}#{}#{name}", kind.display_name())
253}
254
255/// The backing pair an index-backed constraint owns under its own name:
256/// the catalog index row (the legacy-encoded first property, so a
257/// constraint's backing index and a user index on the same pair coexist
258/// as distinct rows) and the theater detail that materializes the row's
259/// seek postings. `None` for every kind that owns no backing index. The
260/// pair's one construction — the `CREATE CONSTRAINT` path and the
261/// derived-migration install both build it here, so the backing rule
262/// lives beside its encoding. The composite detail carries the
263/// constraint's full property list (CIP-11/46/62), so an equality seek
264/// on any constrained property is served; only the legacy row stays
265/// first-property-only.
266///
267/// # Errors
268///
269/// [`relate_core::Error::storage`] for an index-backed definition whose
270/// property list is empty — a malformed backing row no encoder can
271/// spell, never a silent default.
272pub fn constraint_backing_pair(
273    def: &relate_catalog::ConstraintDef,
274) -> relate_core::Result<Option<(relate_catalog::IndexDef, IndexDetailSpec)>> {
275    if !def.is_index_backed() {
276        return Ok(None);
277    }
278    let property = def.properties.first().ok_or_else(|| {
279        relate_core::Error::storage("index-backed constraint has no property for its backing index")
280    })?;
281    Ok(Some((
282        relate_catalog::IndexDef {
283            name: def.name.clone(),
284            label: def.label.clone(),
285            property: legacy_property_encoding(property, IndexKindSpec::Range, &def.name),
286        },
287        IndexDetailSpec {
288            kind: IndexKindSpec::Range,
289            relationship: def.relationship,
290            labels: vec![def.label.clone()],
291            properties: def.properties.clone(),
292            with_properties: Vec::new(),
293        },
294    )))
295}
296
297/// Decode a legacy `IndexDef.property` string into its property-name
298/// list: the comma-join head of [`split_legacy_property_encoding`]
299/// split back into names (a bare single property name is its own
300/// one-element list). The list half of the format's decoder pair —
301/// every reader that wants the names (not the raw head) decodes through
302/// here, never an inline comma split one layer above the canonical
303/// decoder.
304pub fn legacy_property_names(property: &str) -> Vec<String> {
305    split_legacy_property_encoding(property)
306        .0
307        .split(',')
308        .map(str::to_string)
309        .collect()
310}
311
312/// The (label, property) pair a catalog row holds, judged through the
313/// legacy encoding's one decoder — the one spelling of "this row
314/// indexes that pair", consulted by the by-schema probe, the DDL
315/// conflict gate's legacy-duplicate arm, and the committed schema's
316/// held-row retirement.
317pub fn holds_index_pair(row: &IndexDef, label: &str, property: &str) -> bool {
318    row.label == label && split_legacy_property_encoding(&row.property).0 == property
319}
320
321/// One index's typed facts as every reader resolves them, through the fixed
322/// precedence the `SHOW INDEXES` row and the `00NA0` note share: the index's
323/// [`IndexDetailSpec`], then the owning constraint (a constraint-backed
324/// index), then the legacy [`IndexDef`] encoding. No reader re-spells the
325/// chain, so a new detail field lands in every rendering at once.
326#[derive(Clone, Debug, PartialEq, Eq)]
327pub struct IndexFacts {
328    pub kind: IndexKindSpec,
329    pub relationship: bool,
330    pub labels: Vec<String>,
331    pub properties: Vec<String>,
332    /// `WITH [...]` single-stage-filtering properties (VECTOR).
333    pub with_properties: Vec<String>,
334}
335
336impl IndexFacts {
337    /// Resolve one index's facts. `backing` is the index's index-backed
338    /// constraint of the same name, when the caller has already joined it
339    /// (the SHOW row); `None` elsewhere. A detail-less, constraint-less row
340    /// is the legacy encoding: a node index, its label from the
341    /// [`IndexDef`] and its properties from the encoding's head.
342    pub fn resolve(
343        index: &IndexDef,
344        detail: Option<&IndexDetailSpec>,
345        backing: Option<&ConstraintDef>,
346    ) -> Self {
347        let kind = IndexKindSpec::resolve(detail, &index.property);
348        let relationship = detail.is_some_and(|detail| detail.relationship)
349            || backing.is_some_and(|constraint| constraint.relationship);
350        if let Some(detail) = detail {
351            return Self {
352                kind,
353                relationship,
354                labels: detail.labels.clone(),
355                properties: detail.properties.clone(),
356                with_properties: detail.with_properties.clone(),
357            };
358        }
359        if let Some(constraint) = backing {
360            return Self {
361                kind,
362                relationship,
363                labels: vec![constraint.label.clone()],
364                properties: constraint.properties.clone(),
365                with_properties: Vec::new(),
366            };
367        }
368        Self {
369            kind,
370            relationship,
371            labels: vec![index.label.clone()],
372            properties: legacy_property_names(&index.property),
373            with_properties: Vec::new(),
374        }
375    }
376}
377
378/// Resolve every named index's [`IndexFacts`] with the detail and
379/// backing-constraint joins done once, in the caller's order, for the
380/// statement-scoped index readers; the SHOW row resolves its own rows
381/// through the same [`backing_constraint_by_name`] join this shares.
382#[doc(hidden)]
383pub fn resolve_index_facts(
384    indexes: &[relate_catalog::IndexDef],
385    details: &std::collections::BTreeMap<String, IndexDetailSpec>,
386    constraints: &[relate_catalog::ConstraintDef],
387) -> Vec<IndexFacts> {
388    indexes
389        .iter()
390        .map(|index| {
391            let detail = details.get(&index.name);
392            let backing = backing_constraint_by_name(&index.name, constraints);
393            IndexFacts::resolve(index, detail, backing)
394        })
395        .collect()
396}
397
398/// The index-backed constraint of the given name, when one exists — the
399/// one owner-constraint join every index reader resolves through (moved
400/// from `exec::catalog` beside `IndexFacts`, its every consumer: the
401/// SHOW row, the graph-counts row, and [`resolve_index_facts`]).
402#[doc(hidden)]
403pub fn backing_constraint_by_name<'a>(
404    name: &str,
405    constraints: &'a [relate_catalog::ConstraintDef],
406) -> Option<&'a relate_catalog::ConstraintDef> {
407    constraints
408        .iter()
409        .find(|def| def.name == name && def.is_index_backed())
410}
411
412/// Typed payload of [`RedoOp::CatalogIndexDetail`]: the catalog facts of
413/// a `CREATE INDEX`, captured once at DDL-execution time from the parsed
414/// clause. `apply_redo` stores it verbatim -- it never formats a CREATE
415/// INDEX string and re-parses it.
416#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
417pub struct IndexDetailSpec {
418    pub kind: IndexKindSpec,
419    /// True for a relationship (`FOR ()-[r:T]-()`) index.
420    pub relationship: bool,
421    /// Node labels, or (for a relationship index) relationship types;
422    /// more than one entry only for the `A|B` disjunctive form, empty for
423    /// a LOOKUP index.
424    #[serde(default)]
425    pub labels: Vec<String>,
426    #[serde(default)]
427    pub properties: Vec<String>,
428    /// `WITH [...]` single-stage-filtering properties (VECTOR).
429    #[serde(default)]
430    pub with_properties: Vec<String>,
431}
432
433impl IndexDetailSpec {
434    /// The entity kind this index covers — the one derivation of the
435    /// `relationship` flag, consulted by every scan, filter preparation,
436    /// and procedure classification that needs it; no caller re-spells
437    /// the flag's decoding beside it.
438    pub fn entity_kind(&self) -> EntityKind {
439        EntityKind::from_relationship_flag(self.relationship)
440    }
441
442    /// Node `(label, property)` pairs this detail materializes and charges.
443    /// Relationship indexes, multi-label indexes, and kinds other than
444    /// single-property TEXT or POINT, or RANGE, contribute nothing.
445    pub fn covered_pairs(&self) -> Vec<(&str, &str, IndexKindSpec)> {
446        if self.relationship || self.labels.len() != 1 || self.properties.is_empty() {
447            return Vec::new();
448        }
449        let label = self.labels[0].as_str();
450        match self.kind {
451            IndexKindSpec::Text | IndexKindSpec::Point if self.properties.len() == 1 => {
452                vec![(label, self.properties[0].as_str(), self.kind)]
453            }
454            IndexKindSpec::Range => self
455                .properties
456                .iter()
457                .map(|property| (label, property.as_str(), IndexKindSpec::Range))
458                .collect(),
459            _ => Vec::new(),
460        }
461    }
462
463    /// The node `(label, property)` pairs this index serves an equality seek
464    /// on. Derived from [`Self::covered_pairs`] so the entity, label-count
465    /// and kind gates live once: only a single-label node RANGE index
466    /// contributes, and it contributes **every** covered property — the
467    /// executor materializes and seeks each component of a composite index,
468    /// so leading-only coverage would under-report it. A relationship index
469    /// never yields a node pair, and a property name is never split on a
470    /// comma.
471    pub fn range_seek_pairs(&self) -> Vec<(&str, &str)> {
472        self.covered_pairs()
473            .into_iter()
474            .filter_map(|(label, property, kind)| {
475                (kind == IndexKindSpec::Range).then_some((label, property))
476            })
477            .collect()
478    }
479}
480
481/// Apply the catalog index ops in `ops` to `details`. This is the speculative
482/// projection `estimate_redo_delta` uses; committed replay in `apply_redo`
483/// stores the same two ops.
484pub fn project_index_details(details: &mut BTreeMap<String, IndexDetailSpec>, ops: &[RedoOp]) {
485    for op in ops {
486        match op {
487            RedoOp::CatalogIndexDetail { name, detail, .. } => {
488                details.insert(name.clone(), detail.clone());
489            }
490            RedoOp::DropIndex { name } => {
491                details.remove(name);
492            }
493            _ => {}
494        }
495    }
496}