velesdb-mobile 5.2.0

VelesDB mobile bindings for iOS and Android via UniFFI
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
//! Integration tests for `VelesDatabase::execute_query()` (S4-14).

use crate::query::QueryResultKind;
use crate::types::{DistanceMetric, VelesError};
use crate::VelesDatabase;
use tempfile::TempDir;

/// Opens a temp database with a metadata-only collection named `docs`.
///
/// Metadata collections accept INSERT without a `vector` column, which
/// makes them ideal for testing the full VelesQL CRUD surface.
fn setup_db_with_metadata() -> (TempDir, std::sync::Arc<VelesDatabase>) {
    let tmp = TempDir::new().expect("test: create temp dir");
    let path = tmp.path().to_str().expect("test: path to str").to_string();
    let db = VelesDatabase::open(path).expect("test: open database");
    db.create_metadata_collection("docs".to_string())
        .expect("test: create metadata collection");
    (tmp, db)
}

/// Opens a temp database with a 4-dim cosine vector collection named `vecs`.
fn setup_db_with_vector_collection() -> (TempDir, std::sync::Arc<VelesDatabase>) {
    let tmp = TempDir::new().expect("test: create temp dir");
    let path = tmp.path().to_str().expect("test: path to str").to_string();
    let db = VelesDatabase::open(path).expect("test: open database");
    db.create_collection("vecs".to_string(), 4, DistanceMetric::Cosine)
        .expect("test: create vector collection");
    (tmp, db)
}

/// Inserts seed data into metadata collection `docs` via VelesQL INSERT.
fn seed_metadata_docs(db: &VelesDatabase) {
    let sql = concat!(
        "INSERT INTO docs (id, title, category) VALUES ",
        "(1, 'Rust Programming', 'tech'), ",
        "(2, 'Cooking Basics', 'food'), ",
        "(3, 'Advanced Algorithms', 'tech')"
    );
    let result = db
        .execute_query(sql.to_string(), None)
        .expect("test: seed INSERT into metadata collection");
    assert!(
        matches!(result.kind, QueryResultKind::Mutation),
        "INSERT should return Mutation kind"
    );
    assert_eq!(result.row_count, 3, "3 rows should be inserted");
}

// =========================================================================
// SELECT tests
// =========================================================================

#[test]
fn test_execute_query_select_returns_rows() {
    let (_tmp, db) = setup_db_with_metadata();
    seed_metadata_docs(&db);

    let result = db
        .execute_query("SELECT * FROM docs LIMIT 10".to_string(), None)
        .expect("test: SELECT should succeed");

    assert!(matches!(result.kind, QueryResultKind::Rows));
    assert!(result.row_count >= 3, "should return at least 3 rows");
    assert!(result.message.contains("row(s) returned"));
}

#[test]
fn test_execute_query_select_row_contains_payload() {
    let (_tmp, db) = setup_db_with_metadata();
    seed_metadata_docs(&db);

    let result = db
        .execute_query("SELECT * FROM docs LIMIT 10".to_string(), None)
        .expect("test: SELECT with payload");

    let has_title = result
        .rows
        .iter()
        .any(|row| row.data_json.contains("title"));
    assert!(has_title, "rows should contain title payload field");
}

// =========================================================================
// INSERT tests
// =========================================================================

#[test]
fn test_execute_query_insert_adds_data() {
    let (_tmp, db) = setup_db_with_metadata();

    let result = db
        .execute_query(
            "INSERT INTO docs (id, title) VALUES (10, 'New Doc')".to_string(),
            None,
        )
        .expect("test: INSERT");

    assert!(matches!(result.kind, QueryResultKind::Mutation));
    assert_eq!(result.row_count, 1);

    // Verify the data is retrievable via SELECT
    let select = db
        .execute_query("SELECT * FROM docs LIMIT 10".to_string(), None)
        .expect("test: SELECT after INSERT");
    assert!(
        select.rows.iter().any(|r| r.id == 10),
        "inserted point should be retrievable"
    );
}

#[test]
fn test_execute_query_multi_row_insert() {
    let (_tmp, db) = setup_db_with_metadata();
    seed_metadata_docs(&db);

    let count = db
        .execute_query("SELECT * FROM docs LIMIT 100".to_string(), None)
        .expect("test: count rows")
        .row_count;
    assert_eq!(count, 3);
}

// =========================================================================
// INSERT with vector (vector collection, requires $param for vectors)
// =========================================================================

#[test]
fn test_execute_query_insert_with_vector_param() {
    let (_tmp, db) = setup_db_with_vector_collection();

    // VelesQL requires vector data via $parameter substitution
    let sql = "INSERT INTO vecs (id, vector, tag) VALUES (1, $v, 'a')";
    let params = r#"{"v": [1.0, 0.0, 0.0, 0.0]}"#;
    let result = db
        .execute_query(sql.to_string(), Some(params.to_string()))
        .expect("test: INSERT with vector param");

    assert!(matches!(result.kind, QueryResultKind::Mutation));
    assert_eq!(result.row_count, 1);
}

// =========================================================================
// UPDATE tests
// =========================================================================

#[test]
fn test_execute_query_update_modifies_data() {
    let (_tmp, db) = setup_db_with_metadata();
    seed_metadata_docs(&db);

    let result = db
        .execute_query(
            "UPDATE docs SET title = 'Updated' WHERE id = 1".to_string(),
            None,
        )
        .expect("test: UPDATE");

    assert!(matches!(result.kind, QueryResultKind::Mutation));
    assert!(result.row_count >= 1, "at least 1 row should be updated");

    // Verify update took effect
    let select = db
        .execute_query("SELECT * FROM docs LIMIT 10".to_string(), None)
        .expect("test: SELECT after UPDATE");
    let updated_row = select.rows.iter().find(|r| r.id == 1);
    assert!(updated_row.is_some(), "point 1 should still exist");
    assert!(
        updated_row
            .expect("test: row exists")
            .data_json
            .contains("Updated"),
        "title should be updated"
    );
}

// =========================================================================
// DELETE tests
// =========================================================================

#[test]
fn test_execute_query_delete_removes_data() {
    let (_tmp, db) = setup_db_with_metadata();
    seed_metadata_docs(&db);

    let result = db
        .execute_query("DELETE FROM docs WHERE id = 2".to_string(), None)
        .expect("test: DELETE");

    assert!(matches!(result.kind, QueryResultKind::Deletion));

    // Verify deletion
    let select = db
        .execute_query("SELECT * FROM docs LIMIT 10".to_string(), None)
        .expect("test: SELECT after DELETE");
    assert!(
        !select.rows.iter().any(|r| r.id == 2),
        "point 2 should be deleted"
    );
}

// =========================================================================
// DDL tests
// =========================================================================

#[test]
fn test_execute_query_create_collection() {
    let tmp = TempDir::new().expect("test: temp dir");
    let path = tmp.path().to_str().expect("test: path").to_string();
    let db = VelesDatabase::open(path).expect("test: open db");

    let result = db
        .execute_query(
            "CREATE COLLECTION new_coll (dimension = 128, metric = 'cosine')".to_string(),
            None,
        )
        .expect("test: CREATE COLLECTION");

    assert!(matches!(result.kind, QueryResultKind::Ddl));
    assert!(result.message.contains("DDL"));

    // Verify the collection exists
    assert!(db.list_collections().contains(&"new_coll".to_string()));
}

#[test]
fn test_execute_query_drop_collection() {
    let (_tmp, db) = setup_db_with_metadata();

    let result = db
        .execute_query("DROP COLLECTION docs".to_string(), None)
        .expect("test: DROP COLLECTION");

    assert!(matches!(result.kind, QueryResultKind::Ddl));
    assert!(!db.list_collections().contains(&"docs".to_string()));
}

// =========================================================================
// Introspection tests
// =========================================================================

#[test]
fn test_execute_query_show_collections() {
    let (_tmp, db) = setup_db_with_metadata();

    let result = db
        .execute_query("SHOW COLLECTIONS".to_string(), None)
        .expect("test: SHOW COLLECTIONS");

    assert!(matches!(result.kind, QueryResultKind::Rows));
    assert!(
        result.row_count >= 1,
        "SHOW COLLECTIONS should list at least 1 collection"
    );
}

// =========================================================================
// Admin tests
// =========================================================================

#[test]
fn test_execute_query_flush() {
    let (_tmp, db) = setup_db_with_metadata();
    seed_metadata_docs(&db);

    let result = db
        .execute_query("FLUSH FULL".to_string(), None)
        .expect("test: FLUSH");

    assert!(matches!(result.kind, QueryResultKind::Admin));
    assert!(result.message.contains("Admin"));
}

// =========================================================================
// Error handling tests (negative cases)
// =========================================================================

#[test]
fn test_execute_query_invalid_sql_returns_error() {
    let (_tmp, db) = setup_db_with_metadata();

    let result = db.execute_query("NOT VALID SQL AT ALL".to_string(), None);

    assert!(result.is_err(), "invalid SQL should return an error");
    let err = result.expect_err("test: error expected");
    match err {
        VelesError::Database { message, .. } => {
            assert!(
                message.contains("parse error"),
                "error should mention parse error, got: {message}"
            );
        }
        other => panic!("expected VelesError::Database, got: {other:?}"),
    }
}

#[test]
fn test_execute_query_nonexistent_collection() {
    let tmp = TempDir::new().expect("test: temp dir");
    let path = tmp.path().to_str().expect("test: path").to_string();
    let db = VelesDatabase::open(path).expect("test: open db");

    let result = db.execute_query("SELECT * FROM ghost_collection LIMIT 5".to_string(), None);

    assert!(
        result.is_err(),
        "query on nonexistent collection should fail"
    );
}

#[test]
fn test_execute_query_invalid_params_json() {
    let (_tmp, db) = setup_db_with_metadata();

    let result = db.execute_query(
        "SELECT * FROM docs LIMIT 5".to_string(),
        Some("not-json".to_string()),
    );

    assert!(result.is_err(), "invalid params JSON should fail");
}

#[test]
fn test_execute_query_vector_insert_missing_vector() {
    let (_tmp, db) = setup_db_with_vector_collection();

    // INSERT without vector column on a vector collection should fail
    let result = db.execute_query(
        "INSERT INTO vecs (id, title) VALUES (1, 'no vec')".to_string(),
        None,
    );

    assert!(
        result.is_err(),
        "INSERT without vector on vector collection should fail"
    );
}

// =========================================================================
// train_pq non-regression
// =========================================================================

#[test]
fn test_train_pq_still_works_after_execute_query() {
    let (_tmp, db) = setup_db_with_vector_collection();

    // Insert a point via $param so the collection has data
    let sql = "INSERT INTO vecs (id, vector) VALUES (1, $v)";
    let params = r#"{"v": [1.0, 0.0, 0.0, 0.0]}"#;
    let _ = db.execute_query(sql.to_string(), Some(params.to_string()));

    let config = crate::types::PqTrainConfig {
        m: 2,
        k: 4,
        opq: false,
    };
    // PQ training on 1 point fails (k=4 centroids > 1 vector). Assert the
    // mobile layer reaches the core training path and wraps the error.
    let err = db
        .train_pq("vecs".to_string(), config)
        .expect_err("PQ training on 1 point with k=4 must fail");
    let msg = err.to_string();
    assert!(
        msg.contains("PQ training failed"),
        "expected mobile-wrapped training error, got: {msg}"
    );
}

// =========================================================================
// Params forwarding test
// =========================================================================

#[test]
fn test_execute_query_with_params() {
    let (_tmp, db) = setup_db_with_metadata();
    seed_metadata_docs(&db);

    let result = db
        .execute_query(
            "SELECT * FROM docs LIMIT 5".to_string(),
            Some("{}".to_string()),
        )
        .expect("test: query with empty params");

    assert!(matches!(result.kind, QueryResultKind::Rows));
    assert!(result.row_count >= 1);
}

// =========================================================================
// QueryResult structure tests
// =========================================================================

#[test]
fn test_query_result_row_json_structure() {
    let (_tmp, db) = setup_db_with_metadata();
    seed_metadata_docs(&db);

    let result = db
        .execute_query("SELECT * FROM docs LIMIT 1".to_string(), None)
        .expect("test: SELECT for row structure");

    assert!(!result.rows.is_empty(), "should return at least 1 row");
    let row = &result.rows[0];

    // Verify the JSON is parseable
    let parsed: serde_json::Value =
        serde_json::from_str(&row.data_json).expect("test: row data_json should be valid JSON");
    assert!(
        parsed.get("id").is_some(),
        "row JSON should contain 'id' field"
    );
    assert!(
        parsed.get("score").is_some(),
        "row JSON should contain 'score' field"
    );
}