velesdb-core 5.0.0

High-performance vector database engine written in Rust
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
//! BDD integration tests for `VelesQL` admin statements: ANALYZE, TRUNCATE, ALTER COLLECTION.
//!
//! Tests the full pipeline: parse -> validate -> execute -> verify state.

use super::helpers::{create_test_db, execute_sql};
use velesdb_core::Point;

// ============================================================================
// ANALYZE — nominal
// ============================================================================

#[test]
fn test_analyze_returns_stats() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE COLLECTION docs (dimension = 4, metric = 'cosine')",
    )
    .expect("create");

    let vc = db.get_vector_collection("docs").expect("get collection");
    vc.upsert(vec![
        Point::new(1, vec![1.0, 0.0, 0.0, 0.0], None),
        Point::new(2, vec![0.0, 1.0, 0.0, 0.0], None),
        Point::new(3, vec![0.0, 0.0, 1.0, 0.0], None),
    ])
    .expect("upsert");

    let results = execute_sql(&db, "ANALYZE docs").expect("ANALYZE should succeed");
    assert_eq!(results.len(), 1, "ANALYZE should return one result");

    let total = results[0]
        .point
        .payload
        .as_ref()
        .and_then(|p| p.get("total_points"))
        .and_then(serde_json::Value::as_u64);
    assert_eq!(total, Some(3), "should report 3 total points");
}

#[test]
fn test_analyze_empty_collection() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE COLLECTION empty (dimension = 4, metric = 'cosine')",
    )
    .expect("create");

    let results = execute_sql(&db, "ANALYZE COLLECTION empty")
        .expect("ANALYZE empty collection should succeed");
    assert_eq!(results.len(), 1);

    let total = results[0]
        .point
        .payload
        .as_ref()
        .and_then(|p| p.get("total_points"))
        .and_then(serde_json::Value::as_u64);
    assert_eq!(
        total,
        Some(0),
        "empty collection should have 0 total points"
    );
}

// ============================================================================
// TRUNCATE — nominal
// ============================================================================

#[test]
fn test_truncate_deletes_all_data() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE COLLECTION trunc (dimension = 4, metric = 'cosine')",
    )
    .expect("create");

    let vc = db.get_vector_collection("trunc").expect("get collection");
    vc.upsert(vec![
        Point::new(1, vec![1.0, 0.0, 0.0, 0.0], None),
        Point::new(2, vec![0.0, 1.0, 0.0, 0.0], None),
        Point::new(3, vec![0.0, 0.0, 1.0, 0.0], None),
        Point::new(4, vec![0.0, 0.0, 0.0, 1.0], None),
        Point::new(5, vec![1.0, 1.0, 0.0, 0.0], None),
    ])
    .expect("upsert");
    assert_eq!(vc.len(), 5);

    let results = execute_sql(&db, "TRUNCATE trunc").expect("TRUNCATE should succeed");
    assert_eq!(results.len(), 1, "TRUNCATE returns one result");

    let deleted = results[0]
        .point
        .payload
        .as_ref()
        .and_then(|p| p.get("deleted_count"))
        .and_then(serde_json::Value::as_u64);
    assert_eq!(deleted, Some(5), "should report 5 deleted");

    assert_eq!(vc.len(), 0, "collection should be empty after TRUNCATE");
}

#[test]
fn test_truncate_empty_collection() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE COLLECTION empty_trunc (dimension = 4, metric = 'cosine')",
    )
    .expect("create");

    let results = execute_sql(&db, "TRUNCATE empty_trunc").expect("TRUNCATE empty should succeed");
    assert_eq!(results.len(), 1);

    let deleted = results[0]
        .point
        .payload
        .as_ref()
        .and_then(|p| p.get("deleted_count"))
        .and_then(serde_json::Value::as_u64);
    assert_eq!(
        deleted,
        Some(0),
        "TRUNCATE on empty collection reports 0 deleted"
    );
}

#[test]
fn test_truncate_then_insert() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE COLLECTION reinsert (dimension = 4, metric = 'cosine')",
    )
    .expect("create");

    let vc = db
        .get_vector_collection("reinsert")
        .expect("get collection");
    vc.upsert(vec![Point::new(1, vec![1.0, 0.0, 0.0, 0.0], None)])
        .expect("upsert");

    execute_sql(&db, "TRUNCATE reinsert").expect("TRUNCATE");
    assert_eq!(vc.len(), 0, "should be empty after TRUNCATE");

    // Re-insert works normally
    vc.upsert(vec![Point::new(10, vec![0.0, 1.0, 0.0, 0.0], None)])
        .expect("re-insert");
    assert_eq!(vc.len(), 1, "re-insert should work after TRUNCATE");
}

// ============================================================================
// ALTER COLLECTION — auto_reindex apply + persist
// ============================================================================

#[test]
fn test_alter_collection_set_auto_reindex_succeeds() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE COLLECTION alter_test (dimension = 4, metric = 'cosine')",
    )
    .expect("create");

    // ALTER COLLECTION SET (auto_reindex = true) attaches and persists the
    // policy on the collection, returning no rows.
    let results = execute_sql(&db, "ALTER COLLECTION alter_test SET (auto_reindex = true)")
        .expect("ALTER COLLECTION SET auto_reindex must succeed");
    assert!(results.is_empty(), "ALTER returns no rows");

    let vc = db
        .get_vector_collection("alter_test")
        .expect("get collection");
    assert!(
        vc.auto_reindex_manager().is_some_and(|m| m.is_enabled()),
        "auto_reindex must be attached and enabled after ALTER"
    );
}

// ============================================================================
// Complex / lifecycle scenarios
// ============================================================================

#[test]
fn test_analyze_truncate_lifecycle() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE COLLECTION lifecycle (dimension = 4, metric = 'cosine')",
    )
    .expect("create");

    let vc = db
        .get_vector_collection("lifecycle")
        .expect("get collection");
    vc.upsert(vec![
        Point::new(1, vec![1.0, 0.0, 0.0, 0.0], None),
        Point::new(2, vec![0.0, 1.0, 0.0, 0.0], None),
        Point::new(3, vec![0.0, 0.0, 1.0, 0.0], None),
    ])
    .expect("upsert");

    // ANALYZE with data
    let stats1 = execute_sql(&db, "ANALYZE lifecycle").expect("first ANALYZE");
    let count1 = stats1[0]
        .point
        .payload
        .as_ref()
        .and_then(|p| p.get("total_points"))
        .and_then(serde_json::Value::as_u64);
    assert_eq!(count1, Some(3));

    // TRUNCATE
    execute_sql(&db, "TRUNCATE lifecycle").expect("TRUNCATE");
    assert_eq!(vc.len(), 0);

    // ANALYZE after TRUNCATE
    let stats2 = execute_sql(&db, "ANALYZE lifecycle").expect("second ANALYZE");
    let count2 = stats2[0]
        .point
        .payload
        .as_ref()
        .and_then(|p| p.get("total_points"))
        .and_then(serde_json::Value::as_u64);
    assert_eq!(count2, Some(0));
}

#[test]
fn test_truncate_preserves_collection() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE COLLECTION preserved (dimension = 4, metric = 'cosine')",
    )
    .expect("create");

    let vc = db
        .get_vector_collection("preserved")
        .expect("get collection");
    vc.upsert(vec![Point::new(1, vec![1.0, 0.0, 0.0, 0.0], None)])
        .expect("upsert");

    execute_sql(&db, "TRUNCATE COLLECTION preserved").expect("TRUNCATE");

    // Collection still shows in SHOW COLLECTIONS
    let show = execute_sql(&db, "SHOW COLLECTIONS").expect("SHOW");
    let names: Vec<&str> = show
        .iter()
        .filter_map(|r| {
            r.point
                .payload
                .as_ref()
                .and_then(|p| p.get("name"))
                .and_then(serde_json::Value::as_str)
        })
        .collect();
    assert!(
        names.contains(&"preserved"),
        "collection should still exist after TRUNCATE"
    );

    // Can re-insert
    vc.upsert(vec![Point::new(99, vec![0.0, 0.0, 0.0, 1.0], None)])
        .expect("re-insert after TRUNCATE");
    assert_eq!(vc.len(), 1, "re-insert works after TRUNCATE");
}

// ============================================================================
// Negative — nonexistent collections
// ============================================================================

#[test]
fn test_analyze_nonexistent_fails() {
    let (_dir, db) = create_test_db();

    let result = execute_sql(&db, "ANALYZE ghost");
    assert!(result.is_err(), "ANALYZE nonexistent should fail");
    let msg = result.expect_err("error").to_string();
    assert!(
        msg.contains("ghost") || msg.contains("not found") || msg.contains("NotFound"),
        "error should mention missing collection, got: {msg}"
    );
}

#[test]
fn test_truncate_nonexistent_fails() {
    let (_dir, db) = create_test_db();

    let result = execute_sql(&db, "TRUNCATE ghost");
    assert!(result.is_err(), "TRUNCATE nonexistent should fail");
    let msg = result.expect_err("error").to_string();
    assert!(
        msg.contains("ghost") || msg.contains("not found") || msg.contains("NotFound"),
        "error should mention missing collection, got: {msg}"
    );
}

#[test]
fn test_alter_nonexistent_fails() {
    let (_dir, db) = create_test_db();

    let result = execute_sql(&db, "ALTER COLLECTION ghost SET (auto_reindex = true)");
    assert!(result.is_err(), "ALTER nonexistent should fail");
    let msg = result.expect_err("error").to_string();
    assert!(
        msg.contains("ghost") || msg.contains("not found") || msg.contains("NotFound"),
        "error should mention missing collection, got: {msg}"
    );
}

// ============================================================================
// TRUNCATE on graph collections
// ============================================================================

#[test]
fn test_truncate_graph_collection_removes_nodes_and_edges() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE GRAPH COLLECTION kg (dimension = 4, metric = 'cosine') SCHEMALESS",
    )
    .expect("create graph");

    // Insert nodes.
    let gc = db.get_graph_collection("kg").expect("get graph");
    gc.upsert_node_payload(1, &serde_json::json!({"name": "Alice"}))
        .expect("node 1");
    gc.upsert_node_payload(2, &serde_json::json!({"name": "Bob"}))
        .expect("node 2");

    // Insert edges.
    execute_sql(
        &db,
        "INSERT EDGE INTO kg (id = 10, source = 1, target = 2, label = 'KNOWS')",
    )
    .expect("edge");

    assert!(!gc.all_node_ids().is_empty(), "graph should have nodes");
    assert!(gc.edge_count() > 0, "graph should have edges");

    // TRUNCATE graph collection.
    let results = execute_sql(&db, "TRUNCATE kg").expect("TRUNCATE graph should succeed");
    assert_eq!(results.len(), 1);

    let payload = results[0].point.payload.as_ref().expect("payload");
    let deleted_count = payload
        .get("deleted_count")
        .and_then(serde_json::Value::as_u64)
        .unwrap_or(0);
    assert!(deleted_count > 0, "should have deleted nodes + edges");

    // Verify empty.
    let gc = db
        .get_graph_collection("kg")
        .expect("get graph after truncate");
    assert_eq!(gc.edge_count(), 0, "edges should be empty after TRUNCATE");
}

#[test]
fn test_truncate_empty_graph_collection() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE GRAPH COLLECTION empty_g (dimension = 4, metric = 'cosine') SCHEMALESS",
    )
    .expect("create");

    // TRUNCATE on empty graph should succeed with 0 deleted.
    let results = execute_sql(&db, "TRUNCATE empty_g").expect("TRUNCATE empty graph");
    assert_eq!(results.len(), 1);

    let count = results[0]
        .point
        .payload
        .as_ref()
        .and_then(|p| p.get("deleted_count"))
        .and_then(serde_json::Value::as_u64)
        .unwrap_or(999);
    assert_eq!(count, 0, "empty graph should report 0 deletions");
}

#[test]
fn test_truncate_graph_then_reinsert() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE GRAPH COLLECTION reuse_g (dimension = 4, metric = 'cosine') SCHEMALESS",
    )
    .expect("create");

    let gc = db.get_graph_collection("reuse_g").expect("get");
    gc.upsert_node_payload(1, &serde_json::json!({"name": "Alice"}))
        .expect("node");
    execute_sql(
        &db,
        "INSERT EDGE INTO reuse_g (id = 1, source = 1, target = 1, label = 'SELF')",
    )
    .expect("edge");

    // TRUNCATE then re-insert.
    execute_sql(&db, "TRUNCATE reuse_g").expect("truncate");

    let gc = db
        .get_graph_collection("reuse_g")
        .expect("get after truncate");
    assert_eq!(gc.edge_count(), 0);
    assert!(gc.all_node_ids().is_empty());

    // Re-insert should work normally.
    gc.upsert_node_payload(10, &serde_json::json!({"name": "Bob"}))
        .expect("re-insert node");
    execute_sql(
        &db,
        "INSERT EDGE INTO reuse_g (id = 20, source = 10, target = 10, label = 'NEW')",
    )
    .expect("re-insert edge");

    assert_eq!(gc.edge_count(), 1, "new edge should exist");
    assert!(!gc.all_node_ids().is_empty(), "new node should exist");
}

#[test]
fn test_truncate_graph_edges_only_no_node_payloads() {
    let (_dir, db) = create_test_db();

    execute_sql(
        &db,
        "CREATE GRAPH COLLECTION edges_only (dimension = 4, metric = 'cosine') SCHEMALESS",
    )
    .expect("create");

    // Edge endpoints must exist before an edge can reference them (#1442).
    for id in [100, 200] {
        execute_sql(
            &db,
            &format!("INSERT NODE INTO edges_only (id = {id}, payload = '{{}}')"),
        )
        .expect("node");
    }
    execute_sql(
        &db,
        "INSERT EDGE INTO edges_only (id = 1, source = 100, target = 200, label = 'REF')",
    )
    .expect("edge");

    let gc = db.get_graph_collection("edges_only").expect("get");
    assert_eq!(gc.edge_count(), 1);

    // TRUNCATE should still succeed.
    let results = execute_sql(&db, "TRUNCATE edges_only").expect("truncate edges-only graph");
    assert_eq!(results.len(), 1);

    let gc = db.get_graph_collection("edges_only").expect("get after");
    assert_eq!(gc.edge_count(), 0, "edges should be cleared");
}