lora-database 0.10.1

LoraDB — embeddable in-memory graph database with Cypher query support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//! Schema-command execution: routes `CREATE INDEX` and `SHOW INDEXES`
//! straight to the catalog instead of going through the read/write
//! query pipeline.
//!
//! DDL bypasses the analyzer/compiler entirely. `CREATE INDEX` mutates
//! the in-memory catalog, emits a catalog mutation event for WAL/archive
//! replay, and populates the backing RANGE/TEXT/POINT structures as a
//! side effect; `SHOW INDEXES` is a pure read.
//!
//! ## Why not a physical operator?
//!
//! Index DDL is a catalog mutation, not a row-producing op. Threading
//! it through the full plan tree would force every executor cursor to
//! understand catalog-only side effects. Routing here keeps the
//! existing pipeline focused on row-producing work.

use std::any::Any;
use std::collections::BTreeMap;
use std::time::Instant;

use anyhow::{anyhow, Result};
use lora_ast::{
    ConstraintKind as AstConstraintKind, ConstraintNameSpec, CreateConstraint, CreateIndex,
    DropConstraint, DropIndex, Expr, IndexEntityKind as AstIndexEntityKind,
    IndexKind as AstIndexKind, IndexKindFilter, IndexNameSpec, IndexOptions,
    PropertyTypeExpr as AstPropertyTypeExpr, PropertyTypeTerm as AstPropertyTypeTerm,
    ScalarType as AstScalarType, SchemaCommand, ShowConstraints, ShowIndexes,
    VectorCoordType as AstVectorCoordType,
};
use lora_executor::{LoraValue, Row};
use lora_store::{
    ConstraintDefinition, ConstraintRequest, CreateConstraintError, CreateIndexError,
    CreateIndexOutcome, DropConstraintError, DropIndexError, GraphStorage, GraphStorageMut,
    IndexConfigValue, IndexDefinition, IndexRequest, StoredConstraintKind, StoredIndexEntity,
    StoredIndexKind, StoredPropertyType, StoredPropertyTypeTerm, StoredScalarType,
    StoredVectorCoordType,
};

use crate::database::{
    row_projection::{row_from_columns, NamedColumn},
    Database,
};

impl<S> Database<S>
where
    S: GraphStorage + GraphStorageMut + Any + Clone + Send + Sync + 'static,
{
    /// Cheap textual prefix check that lets us route DDL before invoking
    /// the parser-cache + analyzer + compiler pipeline. Kept independent
    /// of the full grammar: false negatives only delay routing (DDL falls
    /// into the regular parser, which then fails); false positives are
    /// impossible because the actual parser accepts these prefixes only
    /// for schema commands.
    pub(crate) fn is_schema_command_text(query: &str) -> bool {
        let mut words = query.split_whitespace();
        let Some(first) = words.next() else {
            return false;
        };
        let Some(second) = words.next() else {
            return false;
        };

        if first.eq_ignore_ascii_case("SHOW") {
            return is_index_keyword(second)
                || is_constraint_keyword(second)
                || (is_show_index_filter(second) && words.next().is_some_and(is_index_keyword));
        }

        if first.eq_ignore_ascii_case("CREATE") {
            return second.eq_ignore_ascii_case("CONSTRAINT")
                || second.eq_ignore_ascii_case("INDEX")
                || (is_create_index_kind(second)
                    && words
                        .next()
                        .is_some_and(|word| word.eq_ignore_ascii_case("INDEX")));
        }

        first.eq_ignore_ascii_case("DROP")
            && (second.eq_ignore_ascii_case("INDEX") || second.eq_ignore_ascii_case("CONSTRAINT"))
    }

    pub(crate) fn execute_schema_command(
        &self,
        command: &SchemaCommand,
        params: BTreeMap<String, LoraValue>,
        deadline: Option<Instant>,
    ) -> Result<Vec<Row>> {
        match command {
            SchemaCommand::CreateIndex(cmd) => self.execute_create_index(cmd, params, deadline),
            SchemaCommand::DropIndex(cmd) => self.execute_drop_index(cmd, params),
            SchemaCommand::ShowIndexes(cmd) => self.execute_show_indexes(cmd, &params),
            SchemaCommand::CreateConstraint(cmd) => {
                self.execute_create_constraint(cmd, params, deadline)
            }
            SchemaCommand::DropConstraint(cmd) => self.execute_drop_constraint(cmd, params),
            SchemaCommand::ShowConstraints(cmd) => self.execute_show_constraints(cmd, &params),
        }
    }

    fn execute_create_index(
        &self,
        cmd: &CreateIndex,
        params: BTreeMap<String, LoraValue>,
        _deadline: Option<Instant>,
    ) -> Result<Vec<Row>> {
        let request = build_index_request(cmd, &params)?;
        let if_not_exists = cmd.if_not_exists;

        // Catalog mutation goes through the canonical write path so the
        // writer lock is held for the duration and the store can emit
        // the durable catalog mutation event used by WAL/archive replay.
        let outcome = self.with_logged_store_mut(|store| {
            store
                .create_index(request, if_not_exists)
                .map_err(map_create_index_error)
        })?;

        match outcome {
            CreateIndexOutcome::Created(_def) => Ok(Vec::new()),
            CreateIndexOutcome::NoOpExists(_def) => {
                // The Cypher reference returns *no rows* and a notification
                // for IF NOT EXISTS no-ops. Notifications are not a
                // first-class result kind in lora yet; surface this via
                // the absence of a row, mirroring the row count.
                Ok(Vec::new())
            }
        }
    }

    fn execute_show_indexes(
        &self,
        cmd: &ShowIndexes,
        params: &BTreeMap<String, LoraValue>,
    ) -> Result<Vec<Row>> {
        let snapshot = self.read_store();
        let indexes = snapshot.list_indexes();
        let rows: Vec<Row> = indexes
            .into_iter()
            .filter(|def| index_matches_filter(def, cmd.filter))
            .map(definition_to_row)
            .collect();
        match &cmd.pipeline {
            Some(pipeline) => super::show_pipeline::apply_pipeline(rows, pipeline, params),
            None => Ok(rows),
        }
    }

    fn execute_drop_index(
        &self,
        cmd: &DropIndex,
        params: BTreeMap<String, LoraValue>,
    ) -> Result<Vec<Row>> {
        let name = match &cmd.name {
            IndexNameSpec::Literal(n) => n.clone(),
            IndexNameSpec::Parameter(p) => resolve_string_param(p, &params)?,
        };
        let if_exists = cmd.if_exists;
        let _outcome = self.with_logged_store_mut(|store| {
            store
                .drop_index(&name, if_exists)
                .map_err(map_drop_index_error)
        })?;
        Ok(Vec::new())
    }

    fn execute_create_constraint(
        &self,
        cmd: &CreateConstraint,
        params: BTreeMap<String, LoraValue>,
        _deadline: Option<Instant>,
    ) -> Result<Vec<Row>> {
        let request = build_constraint_request(cmd, &params)?;
        let if_not_exists = cmd.if_not_exists;
        let _outcome = self.with_logged_store_mut(|store| {
            store
                .create_constraint(request, if_not_exists)
                .map_err(map_create_constraint_error)
        })?;
        Ok(Vec::new())
    }

    fn execute_drop_constraint(
        &self,
        cmd: &DropConstraint,
        params: BTreeMap<String, LoraValue>,
    ) -> Result<Vec<Row>> {
        let name = match &cmd.name {
            ConstraintNameSpec::Literal(n) => n.clone(),
            ConstraintNameSpec::Parameter(p) => resolve_string_param(p, &params)?,
        };
        let if_exists = cmd.if_exists;
        let _outcome = self.with_logged_store_mut(|store| {
            store
                .drop_constraint(&name, if_exists)
                .map_err(map_drop_constraint_error)
        })?;
        Ok(Vec::new())
    }

    fn execute_show_constraints(
        &self,
        cmd: &ShowConstraints,
        params: &BTreeMap<String, LoraValue>,
    ) -> Result<Vec<Row>> {
        let snapshot = self.read_store();
        let constraints = snapshot.list_constraints();
        let rows: Vec<Row> = constraints.into_iter().map(constraint_to_row).collect();
        match &cmd.pipeline {
            Some(pipeline) => super::show_pipeline::apply_pipeline(rows, pipeline, params),
            None => Ok(rows),
        }
    }
}

fn is_index_keyword(word: &str) -> bool {
    word.eq_ignore_ascii_case("INDEXES") || word.eq_ignore_ascii_case("INDEX")
}

fn is_constraint_keyword(word: &str) -> bool {
    word.eq_ignore_ascii_case("CONSTRAINTS") || word.eq_ignore_ascii_case("CONSTRAINT")
}

fn is_show_index_filter(word: &str) -> bool {
    word.eq_ignore_ascii_case("ALL")
        || word.eq_ignore_ascii_case("RANGE")
        || word.eq_ignore_ascii_case("TEXT")
        || word.eq_ignore_ascii_case("POINT")
        || word.eq_ignore_ascii_case("LOOKUP")
        || word.eq_ignore_ascii_case("FULLTEXT")
        || word.eq_ignore_ascii_case("VECTOR")
}

fn is_create_index_kind(word: &str) -> bool {
    word.eq_ignore_ascii_case("RANGE")
        || word.eq_ignore_ascii_case("TEXT")
        || word.eq_ignore_ascii_case("POINT")
        || word.eq_ignore_ascii_case("LOOKUP")
        || word.eq_ignore_ascii_case("FULLTEXT")
        || word.eq_ignore_ascii_case("VECTOR")
}

fn index_matches_filter(def: &IndexDefinition, filter: Option<IndexKindFilter>) -> bool {
    let Some(filter) = filter else { return true };
    match filter {
        IndexKindFilter::All => true,
        IndexKindFilter::Range => matches!(def.kind, StoredIndexKind::Range),
        IndexKindFilter::Text => matches!(def.kind, StoredIndexKind::Text),
        IndexKindFilter::Point => matches!(def.kind, StoredIndexKind::Point),
        IndexKindFilter::Lookup => matches!(def.kind, StoredIndexKind::Lookup),
        IndexKindFilter::Fulltext => matches!(def.kind, StoredIndexKind::Fulltext),
        IndexKindFilter::Vector => matches!(def.kind, StoredIndexKind::Vector),
    }
}

fn build_index_request(
    cmd: &CreateIndex,
    params: &BTreeMap<String, LoraValue>,
) -> Result<IndexRequest> {
    let explicit_name = match &cmd.name {
        Some(IndexNameSpec::Literal(name)) => Some(name.clone()),
        Some(IndexNameSpec::Parameter(param)) => Some(resolve_string_param(param, params)?),
        None => None,
    };

    let kind = match cmd.kind {
        AstIndexKind::Range => StoredIndexKind::Range,
        AstIndexKind::Text => StoredIndexKind::Text,
        AstIndexKind::Point => StoredIndexKind::Point,
        AstIndexKind::Lookup => StoredIndexKind::Lookup,
        AstIndexKind::Vector => StoredIndexKind::Vector,
        AstIndexKind::Fulltext => StoredIndexKind::Fulltext,
    };

    let entity = match cmd.entity {
        AstIndexEntityKind::Node => StoredIndexEntity::Node,
        AstIndexEntityKind::Relationship => StoredIndexEntity::Relationship,
    };

    let options = match cmd.options.as_ref() {
        Some(opts) => evaluate_options(opts)?,
        None => BTreeMap::new(),
    };

    if kind == StoredIndexKind::Vector {
        if cmd.properties.len() != 1 {
            return Err(anyhow!(
                "VECTOR indexes are single-property; got {} properties",
                cmd.properties.len()
            ));
        }
        validate_vector_options(&options)?;
    }

    if kind == StoredIndexKind::Fulltext {
        validate_fulltext_options(&options)?;
    }

    Ok(IndexRequest {
        explicit_name,
        kind,
        entity,
        label: cmd.label.clone(),
        additional_labels: cmd.additional_labels.clone(),
        properties: cmd.properties.clone(),
        options,
    })
}

fn resolve_string_param(name: &str, params: &BTreeMap<String, LoraValue>) -> Result<String> {
    match params.get(name) {
        Some(LoraValue::String(s)) => Ok(s.clone()),
        Some(other) => Err(anyhow!(
            "parameter `${name}` for an index name must be a string, got {:?}",
            other
        )),
        None => Err(anyhow!(
            "parameter `${name}` was not supplied for index name"
        )),
    }
}

fn evaluate_options(opts: &IndexOptions) -> Result<BTreeMap<String, IndexConfigValue>> {
    let mut out = BTreeMap::new();
    for (key, expr) in &opts.config {
        out.insert(key.clone(), evaluate_literal_expr(expr)?);
    }
    Ok(out)
}

/// Validate the OPTIONS map for `CREATE FULLTEXT INDEX`. Today the
/// engine only ships a single "standard" analyzer (lowercase +
/// non-alphanumeric tokenisation), so we accept that name and reject
/// anything else with a clear error. `fulltext.eventually_consistent`
/// parses but is currently a no-op — we apply maintenance synchronously.
fn validate_fulltext_options(opts: &BTreeMap<String, IndexConfigValue>) -> Result<()> {
    if let Some(analyzer) = opts.get("fulltext.analyzer") {
        let name = match analyzer {
            IndexConfigValue::String(s) => s.as_str(),
            other => {
                return Err(anyhow!(
                    "`fulltext.analyzer` must be a string, got {other:?}"
                ))
            }
        };
        if !(name.eq_ignore_ascii_case("standard") || name.eq_ignore_ascii_case("simple")) {
            return Err(anyhow!(
                "fulltext analyzer `{name}` is not supported; only `standard` and `simple` are currently available"
            ));
        }
    }
    if let Some(ec) = opts.get("fulltext.eventually_consistent") {
        match ec {
            IndexConfigValue::Bool(_) => {}
            other => {
                return Err(anyhow!(
                    "`fulltext.eventually_consistent` must be a boolean, got {other:?}"
                ))
            }
        }
    }
    Ok(())
}

/// Validate the OPTIONS map for `CREATE VECTOR INDEX`. The parser
/// hoists the inner `indexConfig: { ... }` map up so `options` is the
/// keys directly: `vector.dimensions` and `vector.similarity_function`.
fn validate_vector_options(opts: &BTreeMap<String, IndexConfigValue>) -> Result<()> {
    let dim = opts
        .get("vector.dimensions")
        .ok_or_else(|| anyhow!(
            "CREATE VECTOR INDEX requires OPTIONS {{ indexConfig: {{ `vector.dimensions`: N, `vector.similarity_function`: '...' }} }}"
        ))?;
    let dim = match dim {
        IndexConfigValue::Integer(n) => *n,
        other => {
            return Err(anyhow!(
                "`vector.dimensions` must be a positive integer, got {other:?}"
            ))
        }
    };
    if !(1..=4096).contains(&dim) {
        return Err(anyhow!(
            "`vector.dimensions` must be in 1..=4096, got {dim}"
        ));
    }
    let sim = opts
        .get("vector.similarity_function")
        .ok_or_else(|| anyhow!("`vector.similarity_function` is required"))?;
    let sim = match sim {
        IndexConfigValue::String(s) => s.as_str(),
        other => {
            return Err(anyhow!(
                "`vector.similarity_function` must be a string, got {other:?}"
            ))
        }
    };
    if !(sim.eq_ignore_ascii_case("cosine") || sim.eq_ignore_ascii_case("euclidean")) {
        return Err(anyhow!(
            "`vector.similarity_function` must be 'cosine' or 'euclidean', got '{sim}'"
        ));
    }
    Ok(())
}

fn evaluate_literal_expr(expr: &Expr) -> Result<IndexConfigValue> {
    match expr {
        Expr::Integer(v, _) => Ok(IndexConfigValue::Integer(*v)),
        Expr::Float(v, _) => Ok(IndexConfigValue::Number(*v)),
        Expr::String(v, _) => Ok(IndexConfigValue::String(v.clone())),
        Expr::Bool(v, _) => Ok(IndexConfigValue::Bool(*v)),
        Expr::Null(_) => Ok(IndexConfigValue::Null),
        Expr::List(items, _) => {
            let values = items
                .iter()
                .map(evaluate_literal_expr)
                .collect::<Result<Vec<_>>>()?;
            Ok(IndexConfigValue::List(values))
        }
        Expr::Map(entries, _) => {
            let mut map = BTreeMap::new();
            for (k, v) in entries {
                map.insert(k.clone(), evaluate_literal_expr(v)?);
            }
            Ok(IndexConfigValue::Map(map))
        }
        Expr::Unary {
            op: lora_ast::UnaryOp::Neg,
            expr: inner,
            ..
        } => match evaluate_literal_expr(inner)? {
            IndexConfigValue::Integer(v) => Ok(IndexConfigValue::Integer(-v)),
            IndexConfigValue::Number(v) => Ok(IndexConfigValue::Number(-v)),
            other => Err(anyhow!(
                "unary minus only valid on numbers in OPTIONS, found {:?}",
                other
            )),
        },
        other => Err(anyhow!(
            "OPTIONS values must be literals; encountered non-literal expression: {:?}",
            other
        )),
    }
}

fn map_create_index_error(err: CreateIndexError) -> anyhow::Error {
    anyhow!("[{}] {err}", err.gql_status())
}

fn map_drop_index_error(err: DropIndexError) -> anyhow::Error {
    anyhow!("[{}] {err}", err.gql_status())
}

fn map_create_constraint_error(err: CreateConstraintError) -> anyhow::Error {
    anyhow!("[{}] {err}", err.gql_status())
}

fn map_drop_constraint_error(err: DropConstraintError) -> anyhow::Error {
    anyhow!("[{}] {err}", err.gql_status())
}

fn build_constraint_request(
    cmd: &CreateConstraint,
    params: &BTreeMap<String, LoraValue>,
) -> Result<ConstraintRequest> {
    let name = match &cmd.name {
        ConstraintNameSpec::Literal(n) => n.clone(),
        ConstraintNameSpec::Parameter(p) => resolve_string_param(p, params)?,
    };
    let entity = match cmd.entity {
        AstIndexEntityKind::Node => StoredIndexEntity::Node,
        AstIndexEntityKind::Relationship => StoredIndexEntity::Relationship,
    };
    let kind = match &cmd.kind {
        AstConstraintKind::Unique => StoredConstraintKind::Unique,
        AstConstraintKind::Existence => StoredConstraintKind::Existence,
        AstConstraintKind::NodeKey => StoredConstraintKind::NodeKey,
        AstConstraintKind::RelationshipKey => StoredConstraintKind::RelationshipKey,
        AstConstraintKind::PropertyType(expr) => {
            StoredConstraintKind::PropertyType(lower_property_type(expr)?)
        }
    };
    Ok(ConstraintRequest {
        name,
        kind,
        entity,
        label: cmd.label.clone(),
        properties: cmd.properties.clone(),
    })
}

fn lower_property_type(expr: &AstPropertyTypeExpr) -> Result<StoredPropertyType> {
    let mut alternatives = Vec::with_capacity(expr.alternatives.len());
    for term in &expr.alternatives {
        alternatives.push(lower_property_type_term(term)?);
    }
    Ok(StoredPropertyType { alternatives })
}

fn lower_property_type_term(term: &AstPropertyTypeTerm) -> Result<StoredPropertyTypeTerm> {
    match term {
        AstPropertyTypeTerm::Scalar(scalar) => {
            let mapped = match scalar {
                AstScalarType::Boolean => StoredScalarType::Boolean,
                AstScalarType::String => StoredScalarType::String,
                AstScalarType::Integer => StoredScalarType::Integer,
                AstScalarType::Float => StoredScalarType::Float,
                AstScalarType::Date => StoredScalarType::Date,
                AstScalarType::LocalTime => StoredScalarType::LocalTime,
                AstScalarType::ZonedTime => StoredScalarType::ZonedTime,
                AstScalarType::LocalDateTime => StoredScalarType::LocalDateTime,
                AstScalarType::ZonedDateTime => StoredScalarType::ZonedDateTime,
                AstScalarType::Duration => StoredScalarType::Duration,
                AstScalarType::Point => StoredScalarType::Point,
                AstScalarType::Map => {
                    return Err(anyhow!(
                        "[22N90] property type unsupported in constraint: MAP is not supported in property type constraints"
                    ));
                }
                AstScalarType::Any => {
                    return Err(anyhow!(
                        "[22N90] property type unsupported in constraint: ANY is not supported in property type constraints"
                    ));
                }
            };
            Ok(StoredPropertyTypeTerm::Scalar(mapped))
        }
        AstPropertyTypeTerm::List { inner, not_null } => {
            if !not_null {
                return Err(anyhow!(
                    "[22N90] property type unsupported in constraint: LIST element type must be `NOT NULL`"
                ));
            }
            let lowered = lower_property_type_term(inner)?;
            Ok(StoredPropertyTypeTerm::List {
                inner: Box::new(lowered),
                not_null: *not_null,
            })
        }
        AstPropertyTypeTerm::Vector { coord, dimension } => {
            let coord = match coord {
                AstVectorCoordType::Int8 => StoredVectorCoordType::Int8,
                AstVectorCoordType::Int16 => StoredVectorCoordType::Int16,
                AstVectorCoordType::Int32 => StoredVectorCoordType::Int32,
                AstVectorCoordType::Int64 => StoredVectorCoordType::Int64,
                AstVectorCoordType::Float32 => StoredVectorCoordType::Float32,
                AstVectorCoordType::Float64 => StoredVectorCoordType::Float64,
            };
            Ok(StoredPropertyTypeTerm::Vector {
                coord,
                dimension: *dimension,
            })
        }
    }
}

fn constraint_to_row(def: ConstraintDefinition) -> Row {
    let ConstraintDefinition {
        name,
        kind,
        entity,
        label,
        properties,
        owned_index,
    } = def;
    let entity_str = entity.as_str().to_string();
    let type_tag = kind.type_tag(entity).to_string();
    let property_type = property_type_display(&kind);
    let owned_index = owned_index
        .map(LoraValue::String)
        .unwrap_or(LoraValue::Null);

    row_from_columns([
        NamedColumn::new("name", LoraValue::String(name)),
        NamedColumn::new("type", LoraValue::String(type_tag)),
        NamedColumn::new("entityType", LoraValue::String(entity_str)),
        NamedColumn::new(
            "labelsOrTypes",
            LoraValue::List(vec![LoraValue::String(label)]),
        ),
        NamedColumn::new(
            "properties",
            LoraValue::List(properties.into_iter().map(LoraValue::String).collect()),
        ),
        NamedColumn::new("ownedIndex", owned_index),
        NamedColumn::new(
            "propertyType",
            property_type
                .map(LoraValue::String)
                .unwrap_or(LoraValue::Null),
        ),
    ])
}

fn property_type_display(kind: &StoredConstraintKind) -> Option<String> {
    match kind {
        StoredConstraintKind::PropertyType(t) => Some(t.to_string()),
        _ => None,
    }
}

fn definition_to_row(def: IndexDefinition) -> Row {
    let IndexDefinition {
        name,
        kind,
        entity,
        label,
        additional_labels,
        properties,
        state,
        ..
    } = def;
    let labels = label
        .into_iter()
        .chain(additional_labels)
        .map(LoraValue::String)
        .collect();

    row_from_columns([
        NamedColumn::new("name", LoraValue::String(name)),
        NamedColumn::new("type", LoraValue::String(kind.as_str().to_string())),
        NamedColumn::new("entityType", LoraValue::String(entity.as_str().to_string())),
        NamedColumn::new("labelsOrTypes", LoraValue::List(labels)),
        NamedColumn::new(
            "properties",
            LoraValue::List(properties.into_iter().map(LoraValue::String).collect()),
        ),
        NamedColumn::new("state", LoraValue::String(state.as_str().to_string())),
        NamedColumn::new(
            "populationPercent",
            LoraValue::Float(match state {
                lora_store::StoredIndexState::Online => 100.0,
                lora_store::StoredIndexState::Populating => 0.0,
            }),
        ),
    ])
}