velesdb-cli 1.8.0

Interactive CLI and REPL for VelesDB with VelesQL support
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
//! Tests for CLI import module (EPIC-061/US-007 refactoring).
//!
//! Extracted from import.rs to improve modularity.

use super::*;
use std::io::Write;
use tempfile::tempdir;

// =========================================================================
// Unit tests for parse_vector
// =========================================================================

#[test]
fn test_parse_vector_json_array() {
    let input = "[1.0, 2.0, 3.0]";
    let result = parse_vector(input).unwrap();
    assert_eq!(result, vec![1.0, 2.0, 3.0]);
}

#[test]
fn test_parse_vector_json_array_with_whitespace() {
    let input = "  [ 1.0 , 2.0 , 3.0 ]  ";
    let result = parse_vector(input).unwrap();
    assert_eq!(result, vec![1.0, 2.0, 3.0]);
}

#[test]
fn test_parse_vector_comma_separated() {
    let input = "1.0, 2.0, 3.0";
    let result = parse_vector(input).unwrap();
    assert_eq!(result, vec![1.0, 2.0, 3.0]);
}

#[test]
fn test_parse_vector_comma_separated_no_spaces() {
    let input = "1.0,2.0,3.0";
    let result = parse_vector(input).unwrap();
    assert_eq!(result, vec![1.0, 2.0, 3.0]);
}

#[test]
fn test_parse_vector_invalid_json() {
    let input = "[1.0, 2.0, invalid]";
    let result = parse_vector(input);
    assert!(result.is_err());
}

#[test]
fn test_parse_vector_invalid_csv() {
    let input = "1.0, not_a_number, 3.0";
    let result = parse_vector(input);
    assert!(result.is_err());
}

// =========================================================================
// Unit tests for ImportStats
// =========================================================================

#[test]
fn test_import_stats_default() {
    let stats = ImportStats::default();
    assert_eq!(stats.total, 0);
    assert_eq!(stats.imported, 0);
    assert_eq!(stats.errors, 0);
    assert_eq!(stats.duration_ms, 0);
}

#[test]
fn test_import_stats_records_per_sec() {
    let stats = ImportStats {
        total: 100,
        imported: 1000,
        errors: 0,
        duration_ms: 500,
    };
    assert!((stats.records_per_sec() - 2000.0).abs() < 0.001);
}

#[test]
fn test_import_stats_records_per_sec_zero_duration() {
    let stats = ImportStats {
        total: 100,
        imported: 1000,
        errors: 0,
        duration_ms: 0,
    };
    assert_eq!(stats.records_per_sec(), 0.0);
}

// =========================================================================
// Unit tests for ImportConfig
// =========================================================================

#[test]
fn test_import_config_default() {
    let config = ImportConfig::default();
    assert!(config.collection.is_empty());
    assert!(config.dimension.is_none());
    assert_eq!(config.batch_size, 1000);
    assert_eq!(config.id_column, "id");
    assert_eq!(config.vector_column, "vector");
    assert!(config.show_progress);
}

// =========================================================================
// Integration tests for JSONL import
// =========================================================================

#[test]
fn test_import_jsonl_basic() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("db");
    let jsonl_path = dir.path().join("data.jsonl");

    // Create test JSONL file
    let mut file = File::create(&jsonl_path).unwrap();
    writeln!(file, r#"{{"id": 1, "vector": [1.0, 0.0, 0.0]}}"#).unwrap();
    writeln!(file, r#"{{"id": 2, "vector": [0.0, 1.0, 0.0]}}"#).unwrap();
    writeln!(file, r#"{{"id": 3, "vector": [0.0, 0.0, 1.0]}}"#).unwrap();

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "test".to_string(),
        show_progress: false,
        ..Default::default()
    };

    let stats = import_jsonl(&db, &jsonl_path, &config).unwrap();

    assert_eq!(stats.total, 3);
    assert_eq!(stats.imported, 3);
    assert_eq!(stats.errors, 0);

    let col = db.get_vector_collection("test").unwrap();
    assert_eq!(col.len(), 3);
}

#[test]
fn test_import_jsonl_with_payload() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("db");
    let jsonl_path = dir.path().join("data.jsonl");

    let mut file = File::create(&jsonl_path).unwrap();
    writeln!(
        file,
        r#"{{"id": 1, "vector": [1.0, 0.0, 0.0], "payload": {{"title": "Doc 1"}}}}"#
    )
    .unwrap();
    writeln!(
        file,
        r#"{{"id": 2, "vector": [0.0, 1.0, 0.0], "payload": {{"title": "Doc 2"}}}}"#
    )
    .unwrap();

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "test".to_string(),
        show_progress: false,
        ..Default::default()
    };

    let stats = import_jsonl(&db, &jsonl_path, &config).unwrap();

    assert_eq!(stats.imported, 2);

    let col = db.get_vector_collection("test").unwrap();
    let points = col.get(&[1, 2]);
    assert!(points[0].as_ref().unwrap().payload.is_some());
}

#[test]
fn test_import_jsonl_with_errors() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("db");
    let jsonl_path = dir.path().join("data.jsonl");

    let mut file = File::create(&jsonl_path).unwrap();
    writeln!(file, r#"{{"id": 1, "vector": [1.0, 0.0, 0.0]}}"#).unwrap();
    writeln!(file, r#"invalid json line"#).unwrap();
    writeln!(file, r#"{{"id": 3, "vector": [0.0, 0.0, 1.0]}}"#).unwrap();

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "test".to_string(),
        show_progress: false,
        ..Default::default()
    };

    let stats = import_jsonl(&db, &jsonl_path, &config).unwrap();

    assert_eq!(stats.total, 3);
    assert_eq!(stats.imported, 2);
    assert_eq!(stats.errors, 1);
}

#[test]
fn test_import_jsonl_dimension_mismatch() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("db");
    let jsonl_path = dir.path().join("data.jsonl");

    let mut file = File::create(&jsonl_path).unwrap();
    writeln!(file, r#"{{"id": 1, "vector": [1.0, 0.0, 0.0]}}"#).unwrap();
    writeln!(file, r#"{{"id": 2, "vector": [0.0, 1.0]}}"#).unwrap(); // Wrong dimension
    writeln!(file, r#"{{"id": 3, "vector": [0.0, 0.0, 1.0]}}"#).unwrap();

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "test".to_string(),
        show_progress: false,
        ..Default::default()
    };

    let stats = import_jsonl(&db, &jsonl_path, &config).unwrap();

    assert_eq!(stats.imported, 2);
    assert_eq!(stats.errors, 1);
}

// =========================================================================
// Integration tests for CSV import
// =========================================================================

#[test]
fn test_import_csv_basic() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("db");
    let csv_path = dir.path().join("data.csv");

    let mut file = File::create(&csv_path).unwrap();
    writeln!(file, "id,vector").unwrap();
    writeln!(file, "1,\"[1.0, 0.0, 0.0]\"").unwrap();
    writeln!(file, "2,\"[0.0, 1.0, 0.0]\"").unwrap();
    writeln!(file, "3,\"[0.0, 0.0, 1.0]\"").unwrap();

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "test".to_string(),
        show_progress: false,
        ..Default::default()
    };

    let stats = import_csv(&db, &csv_path, &config).unwrap();

    assert_eq!(stats.total, 3);
    assert_eq!(stats.imported, 3);
    assert_eq!(stats.errors, 0);
}

#[test]
fn test_import_csv_comma_separated_vector() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("db");
    let csv_path = dir.path().join("data.csv");

    let mut file = File::create(&csv_path).unwrap();
    writeln!(file, "id,vector").unwrap();
    writeln!(file, "1,\"1.0,0.0,0.0\"").unwrap();
    writeln!(file, "2,\"0.0,1.0,0.0\"").unwrap();

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "test".to_string(),
        show_progress: false,
        ..Default::default()
    };

    let stats = import_csv(&db, &csv_path, &config).unwrap();

    assert_eq!(stats.imported, 2);
}

#[test]
fn test_import_csv_with_extra_columns() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("db");
    let csv_path = dir.path().join("data.csv");

    let mut file = File::create(&csv_path).unwrap();
    writeln!(file, "id,vector,title,category").unwrap();
    writeln!(file, "1,\"[1.0, 0.0, 0.0]\",Document 1,tech").unwrap();
    writeln!(file, "2,\"[0.0, 1.0, 0.0]\",Document 2,science").unwrap();

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "test".to_string(),
        show_progress: false,
        ..Default::default()
    };

    let stats = import_csv(&db, &csv_path, &config).unwrap();

    assert_eq!(stats.imported, 2);

    // Extra columns should be stored as payload
    let col = db.get_vector_collection("test").unwrap();
    let points = col.get(&[1]);
    let payload = points[0].as_ref().unwrap().payload.as_ref().unwrap();
    assert_eq!(payload["title"], "Document 1");
    assert_eq!(payload["category"], "tech");
}

#[test]
fn test_import_csv_custom_columns() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("db");
    let csv_path = dir.path().join("data.csv");

    let mut file = File::create(&csv_path).unwrap();
    writeln!(file, "doc_id,embedding").unwrap();
    writeln!(file, "1,\"[1.0, 0.0, 0.0]\"").unwrap();
    writeln!(file, "2,\"[0.0, 1.0, 0.0]\"").unwrap();

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "test".to_string(),
        id_column: "doc_id".to_string(),
        vector_column: "embedding".to_string(),
        show_progress: false,
        ..Default::default()
    };

    let stats = import_csv(&db, &csv_path, &config).unwrap();

    assert_eq!(stats.imported, 2);
}

// =========================================================================
// Integration tests for typical usage scenarios
// =========================================================================

#[test]
fn test_scenario_rag_document_import() {
    // Simulates importing embeddings for a RAG application
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("rag_db");
    let jsonl_path = dir.path().join("embeddings.jsonl");

    // Create embeddings file (768D like BERT)
    let mut file = File::create(&jsonl_path).unwrap();
    for i in 0..100 {
        let vector: Vec<f32> = (0..768).map(|j| ((i + j) % 100) as f32 / 100.0).collect();
        let payload = serde_json::json!({
            "content": format!("Document {} content about topic {}", i, i % 10),
            "source": format!("file_{}.txt", i),
            "chunk_id": i
        });
        writeln!(
            file,
            r#"{{"id": {}, "vector": {:?}, "payload": {}}}"#,
            i, vector, payload
        )
        .unwrap();
    }

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "documents".to_string(),
        batch_size: 50,
        show_progress: false,
        ..Default::default()
    };

    let stats = import_jsonl(&db, &jsonl_path, &config).unwrap();

    assert_eq!(stats.imported, 100);
    assert!(stats.duration_ms > 0);
    assert!(stats.records_per_sec() > 0.0);

    // Verify search works
    let col = db.get_vector_collection("documents").unwrap();
    let query: Vec<f32> = (0..768).map(|i| i as f32 / 100.0).collect();
    let results = col.search(&query, 10).unwrap();
    assert_eq!(results.len(), 10);
}

#[test]
fn test_scenario_product_catalog_import() {
    // Simulates importing product embeddings from CSV
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("catalog_db");
    let csv_path = dir.path().join("products.csv");

    let mut file = File::create(&csv_path).unwrap();
    writeln!(file, "id,vector,name,price,category").unwrap();
    for i in 0..50 {
        let vector: Vec<f32> = (0..128).map(|j| ((i + j) % 50) as f32 / 50.0).collect();
        writeln!(
            file,
            "{},\"{:?}\",Product {},{:.2},Category {}",
            i,
            vector,
            i,
            (i as f32) * 9.99,
            i % 5
        )
        .unwrap();
    }

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "products".to_string(),
        batch_size: 20,
        show_progress: false,
        ..Default::default()
    };

    let stats = import_csv(&db, &csv_path, &config).unwrap();

    assert_eq!(stats.imported, 50);

    // Verify metadata is preserved
    let col = db.get_vector_collection("products").unwrap();
    let points = col.get(&[0]);
    let payload = points[0].as_ref().unwrap().payload.as_ref().unwrap();
    assert_eq!(payload["name"], "Product 0");
    assert_eq!(payload["category"], "Category 0");
}

#[test]
fn test_scenario_incremental_import() {
    // Simulates importing data in multiple batches within same session
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("incremental_db");
    let jsonl_path1 = dir.path().join("batch1.jsonl");
    let jsonl_path2 = dir.path().join("batch2.jsonl");

    // Create both files
    let mut file1 = File::create(&jsonl_path1).unwrap();
    for i in 0..50 {
        let vector: Vec<f32> = (0..64).map(|j| ((i + j) % 50) as f32 / 50.0).collect();
        writeln!(file1, r#"{{"id": {}, "vector": {:?}}}"#, i, vector).unwrap();
    }
    drop(file1);

    let mut file2 = File::create(&jsonl_path2).unwrap();
    for i in 50..100 {
        let vector: Vec<f32> = (0..64).map(|j| ((i + j) % 50) as f32 / 50.0).collect();
        writeln!(file2, r#"{{"id": {}, "vector": {:?}}}"#, i, vector).unwrap();
    }
    drop(file2);

    // Import both batches in same session
    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "data".to_string(),
        show_progress: false,
        ..Default::default()
    };

    // First batch
    let stats1 = import_jsonl(&db, &jsonl_path1, &config).unwrap();
    assert_eq!(stats1.imported, 50);

    // Second batch (same collection)
    let stats2 = import_jsonl(&db, &jsonl_path2, &config).unwrap();
    assert_eq!(stats2.imported, 50);

    // Verify final state
    let col = db.get_vector_collection("data").unwrap();
    assert_eq!(col.len(), 100);

    // Verify random access works across both batches
    let points = col.get(&[0, 50, 99]);
    assert!(points.iter().all(|p| p.is_some()));
}

#[test]
fn test_scenario_large_dimension_vectors() {
    // Simulates importing high-dimensional vectors (1536D like GPT-4)
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("gpt_db");
    let jsonl_path = dir.path().join("gpt_embeddings.jsonl");

    let mut file = File::create(&jsonl_path).unwrap();
    for i in 0..20 {
        let vector: Vec<f32> = (0..1536).map(|j| ((i + j) % 100) as f32 / 100.0).collect();
        writeln!(file, r#"{{"id": {}, "vector": {:?}}}"#, i, vector).unwrap();
    }

    let db = Database::open(&db_path).unwrap();
    let config = ImportConfig {
        collection: "gpt_embeddings".to_string(),
        dimension: Some(1536),
        show_progress: false,
        ..Default::default()
    };

    let stats = import_jsonl(&db, &jsonl_path, &config).unwrap();

    assert_eq!(stats.imported, 20);

    let col = db.get_vector_collection("gpt_embeddings").unwrap();
    assert_eq!(col.config().dimension, 1536);
}