vantage-mongodb 0.6.1

MongoDB persistence backend for Vantage framework
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
//! Integration tests for MongoDB TableSource.
//!
//! Requires a running MongoDB instance. Set MONGODB_URL env var or defaults
//! to mongodb://localhost:27017. Uses a randomised database name so tests
//! don't collide.

use bson::doc;
use vantage_dataset::prelude::*;
use vantage_mongodb::MongoId;
use vantage_mongodb::{AnyMongoType, MongoDB};
use vantage_table::table::Table;
use vantage_table::traits::table_source::TableSource;
use vantage_types::{EmptyEntity, Record};

fn mongo_url() -> String {
    std::env::var("MONGODB_URL").unwrap_or_else(|_| "mongodb://localhost:27017".into())
}

async fn setup() -> (MongoDB, String) {
    let db_name = format!("vantage_test_{}", bson::oid::ObjectId::new().to_hex());
    let db = MongoDB::connect(&mongo_url(), &db_name)
        .await
        .expect("Failed to connect to MongoDB");
    (db, db_name)
}

async fn teardown(db: &MongoDB, db_name: &str) {
    db.database()
        .drop()
        .await
        .unwrap_or_else(|e| eprintln!("Failed to drop test db {}: {}", db_name, e));
}

fn product_table(db: MongoDB) -> Table<MongoDB, EmptyEntity> {
    Table::new("product", db)
        .with_column_of::<String>("name")
        .with_column_of::<i64>("price")
        .with_column_of::<i64>("calories")
        .with_column_of::<bool>("is_deleted")
}

fn record(fields: &[(&str, AnyMongoType)]) -> Record<AnyMongoType> {
    fields
        .iter()
        .map(|(k, v)| (k.to_string(), v.clone()))
        .collect()
}

// ── Read operations ──────────────────────────────────────────────────

#[tokio::test]
async fn test_list_empty() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    let values = table.list_values().await.unwrap();
    assert_eq!(values.len(), 0);

    teardown(&db, &db_name).await;
}

#[tokio::test]
async fn test_insert_and_list() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    let id = MongoId::from(bson::oid::ObjectId::new());
    let rec = record(&[
        ("name", AnyMongoType::new("Cupcake".to_string())),
        ("price", AnyMongoType::new(250i64)),
        ("calories", AnyMongoType::new(300i64)),
        ("is_deleted", AnyMongoType::new(false)),
    ]);

    table.insert_value(id.clone(), &rec).await.unwrap();

    let values = table.list_values().await.unwrap();
    assert_eq!(values.len(), 1);
    assert!(values.contains_key(&id));

    let fetched = &values[&id];
    assert_eq!(fetched["name"].try_get::<String>(), Some("Cupcake".into()));
    assert_eq!(fetched["price"].try_get::<i64>(), Some(250));

    teardown(&db, &db_name).await;
}

#[tokio::test]
async fn test_get_value_by_id() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    let id = MongoId::from(bson::oid::ObjectId::new());
    let rec = record(&[
        ("name", AnyMongoType::new("Tart".to_string())),
        ("price", AnyMongoType::new(180i64)),
        ("calories", AnyMongoType::new(200i64)),
        ("is_deleted", AnyMongoType::new(false)),
    ]);
    table.insert_value(id.clone(), &rec).await.unwrap();

    let fetched = table
        .get_value(id.clone())
        .await
        .unwrap()
        .expect("row exists");
    assert_eq!(fetched["name"].try_get::<String>(), Some("Tart".into()));

    teardown(&db, &db_name).await;
}

#[tokio::test]
async fn test_get_some_value() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    // Empty table → None
    assert!(table.get_some_value().await.unwrap().is_none());

    let id = MongoId::from(bson::oid::ObjectId::new());
    let rec = record(&[("name", AnyMongoType::new("Pie".to_string()))]);
    table.insert_value(id.clone(), &rec).await.unwrap();

    let (got_id, got_rec) = table.get_some_value().await.unwrap().unwrap();
    assert_eq!(got_id, id);
    assert_eq!(got_rec["name"].try_get::<String>(), Some("Pie".into()));

    teardown(&db, &db_name).await;
}

// ── Count ────────────────────────────────────────────────────────────

#[tokio::test]
async fn test_count() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    assert_eq!(table.get_count().await.unwrap(), 0);

    for i in 0..3 {
        let rec = record(&[("name", AnyMongoType::new(format!("Item {}", i)))]);
        table
            .insert_value(MongoId::from(bson::oid::ObjectId::new()), &rec)
            .await
            .unwrap();
    }

    assert_eq!(table.get_count().await.unwrap(), 3);

    teardown(&db, &db_name).await;
}

// ── Aggregates ───────────────────────────────────────────────────────

#[tokio::test]
async fn test_sum_max_min() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    let prices = [100i64, 250, 400];
    for p in prices {
        let rec = record(&[
            ("name", AnyMongoType::new(format!("P{}", p))),
            ("price", AnyMongoType::new(p)),
        ]);
        table
            .insert_value(MongoId::from(bson::oid::ObjectId::new()), &rec)
            .await
            .unwrap();
    }

    let price_col = db.to_any_column(db.create_column::<i64>("price"));

    let sum = db.get_table_sum(&table, &price_col).await.unwrap();
    assert_eq!(sum.try_get::<i64>(), Some(750));

    let max = db.get_table_max(&table, &price_col).await.unwrap();
    assert_eq!(max.try_get::<i64>(), Some(400));

    let min = db.get_table_min(&table, &price_col).await.unwrap();
    assert_eq!(min.try_get::<i64>(), Some(100));

    teardown(&db, &db_name).await;
}

// ── Write operations ─────────────────────────────────────────────────

#[tokio::test]
async fn test_replace() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    let id = MongoId::from(bson::oid::ObjectId::new());
    let rec = record(&[
        ("name", AnyMongoType::new("Old".to_string())),
        ("price", AnyMongoType::new(10i64)),
    ]);
    table.insert_value(id.clone(), &rec).await.unwrap();

    let replacement = record(&[
        ("name", AnyMongoType::new("New".to_string())),
        ("price", AnyMongoType::new(99i64)),
    ]);
    table.replace_value(id.clone(), &replacement).await.unwrap();

    let fetched = table
        .get_value(id.clone())
        .await
        .unwrap()
        .expect("row exists");
    assert_eq!(fetched["name"].try_get::<String>(), Some("New".into()));
    assert_eq!(fetched["price"].try_get::<i64>(), Some(99));

    teardown(&db, &db_name).await;
}

#[tokio::test]
async fn test_patch() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    let id = MongoId::from(bson::oid::ObjectId::new());
    let rec = record(&[
        ("name", AnyMongoType::new("Original".to_string())),
        ("price", AnyMongoType::new(50i64)),
        ("calories", AnyMongoType::new(200i64)),
    ]);
    table.insert_value(id.clone(), &rec).await.unwrap();

    // Patch only the price — name and calories should be untouched
    let patch = record(&[("price", AnyMongoType::new(75i64))]);
    table.patch_value(id.clone(), &patch).await.unwrap();

    let fetched = table
        .get_value(id.clone())
        .await
        .unwrap()
        .expect("row exists");
    assert_eq!(fetched["name"].try_get::<String>(), Some("Original".into()));
    assert_eq!(fetched["price"].try_get::<i64>(), Some(75));
    assert_eq!(fetched["calories"].try_get::<i64>(), Some(200));

    teardown(&db, &db_name).await;
}

#[tokio::test]
async fn test_delete() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    let id = MongoId::from(bson::oid::ObjectId::new());
    let rec = record(&[("name", AnyMongoType::new("Gone".to_string()))]);
    table.insert_value(id.clone(), &rec).await.unwrap();
    assert_eq!(table.get_count().await.unwrap(), 1);

    WritableValueSet::delete(&table, id.clone()).await.unwrap();
    assert_eq!(table.get_count().await.unwrap(), 0);

    teardown(&db, &db_name).await;
}

#[tokio::test]
async fn test_delete_all() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    for i in 0..4 {
        let rec = record(&[("name", AnyMongoType::new(format!("X{}", i)))]);
        table
            .insert_value(MongoId::from(bson::oid::ObjectId::new()), &rec)
            .await
            .unwrap();
    }
    assert_eq!(table.get_count().await.unwrap(), 4);

    WritableValueSet::delete_all(&table).await.unwrap();
    assert_eq!(table.get_count().await.unwrap(), 0);

    teardown(&db, &db_name).await;
}

#[tokio::test]
async fn test_insert_return_id() {
    let (db, db_name) = setup().await;
    let table = product_table(db.clone());

    let rec = record(&[
        ("name", AnyMongoType::new("Auto".to_string())),
        ("price", AnyMongoType::new(42i64)),
    ]);
    let id = table.insert_return_id_value(&rec).await.unwrap();

    let fetched = table
        .get_value(id.clone())
        .await
        .unwrap()
        .expect("row exists");
    assert_eq!(fetched["name"].try_get::<String>(), Some("Auto".into()));

    teardown(&db, &db_name).await;
}

// ── Conditions (native bson::Document) ───────────────────────────────

#[tokio::test]
async fn test_condition_filter() {
    let (db, db_name) = setup().await;
    let mut table = product_table(db.clone());

    // Insert mix of deleted / not deleted
    for (name, deleted) in [("A", false), ("B", true), ("C", false)] {
        let rec = record(&[
            ("name", AnyMongoType::new(name.to_string())),
            ("is_deleted", AnyMongoType::new(deleted)),
        ]);
        table
            .insert_value(MongoId::from(bson::oid::ObjectId::new()), &rec)
            .await
            .unwrap();
    }

    // Add native MongoDB condition
    table.add_condition(doc! { "is_deleted": false });

    assert_eq!(table.get_count().await.unwrap(), 2);

    let values = table.list_values().await.unwrap();
    assert_eq!(values.len(), 2);
    let names: Vec<String> = values
        .values()
        .filter_map(|r| r["name"].try_get::<String>())
        .collect();
    assert!(names.contains(&"A".to_string()));
    assert!(names.contains(&"C".to_string()));

    teardown(&db, &db_name).await;
}

#[tokio::test]
async fn test_condition_gt() {
    let (db, db_name) = setup().await;
    let mut table = product_table(db.clone());

    for (name, price) in [("Cheap", 50i64), ("Mid", 150), ("Expensive", 300)] {
        let rec = record(&[
            ("name", AnyMongoType::new(name.to_string())),
            ("price", AnyMongoType::new(price)),
        ]);
        table
            .insert_value(MongoId::from(bson::oid::ObjectId::new()), &rec)
            .await
            .unwrap();
    }

    table.add_condition(doc! { "price": { "$gt": 100 } });

    assert_eq!(table.get_count().await.unwrap(), 2);

    let values = table.list_values().await.unwrap();
    let names: Vec<String> = values
        .values()
        .filter_map(|r| r["name"].try_get::<String>())
        .collect();
    assert!(names.contains(&"Mid".to_string()));
    assert!(names.contains(&"Expensive".to_string()));
    assert!(!names.contains(&"Cheap".to_string()));

    teardown(&db, &db_name).await;
}

#[tokio::test]
async fn test_multiple_conditions() {
    let (db, db_name) = setup().await;
    let mut table = product_table(db.clone());

    for (name, price, deleted) in [
        ("A", 50i64, false),
        ("B", 200, false),
        ("C", 300, true),
        ("D", 400, false),
    ] {
        let rec = record(&[
            ("name", AnyMongoType::new(name.to_string())),
            ("price", AnyMongoType::new(price)),
            ("is_deleted", AnyMongoType::new(deleted)),
        ]);
        table
            .insert_value(MongoId::from(bson::oid::ObjectId::new()), &rec)
            .await
            .unwrap();
    }

    // price > 100 AND not deleted
    table.add_condition(doc! { "price": { "$gt": 100 } });
    table.add_condition(doc! { "is_deleted": false });

    assert_eq!(table.get_count().await.unwrap(), 2);

    let values = table.list_values().await.unwrap();
    let names: Vec<String> = values
        .values()
        .filter_map(|r| r["name"].try_get::<String>())
        .collect();
    assert!(names.contains(&"B".to_string()));
    assert!(names.contains(&"D".to_string()));

    teardown(&db, &db_name).await;
}