vantage-mongodb 0.5.6

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
//! Test 3: MongoSelect builder + SelectableDataSource execution against seeded v2 data.
//!
//! Requires a running MongoDB with v2.js loaded.
//! Builder tests (preview, build_*) are sync. Live tests need the database.

use bson::doc;
use vantage_expressions::{Order, Selectable};
use vantage_mongodb::{AnyMongoType, MongoDB, MongoSelect};

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

async fn db() -> MongoDB {
    MongoDB::connect(&mongo_url(), "vantage")
        .await
        .expect("Failed to connect to MongoDB")
}

// ── Builder / preview tests (no database needed) ─────────────────────────

#[test]
fn test_select_all() {
    let s = MongoSelect::new().with_source("product");
    assert_eq!(s.preview(), "db.product.find({})");
}

#[test]
fn test_select_fields() {
    let s = MongoSelect::new()
        .with_source("product")
        .with_field("name")
        .with_field("price");
    let p = s.preview();
    assert!(p.starts_with("db.product.find({})"));
    assert!(p.contains(".projection("));
}

#[test]
fn test_select_with_condition() {
    let s = MongoSelect::new()
        .with_source("product")
        .with_condition(doc! { "price": { "$gt": 100 } });
    assert!(s.preview().contains("<1 conditions>"));
}

#[test]
fn test_select_order_and_limit() {
    let s = MongoSelect::new()
        .with_source("product")
        .with_order(doc! { "price": 1 }, Order::Desc)
        .with_limit(Some(2), None);
    let p = s.preview();
    assert!(p.contains(".sort("));
    assert!(p.contains(".limit(2)"));
}

#[test]
fn test_select_distinct() {
    let mut s = MongoSelect::new().with_source("product").with_field("name");
    s.set_distinct(true);
    assert!(s.is_distinct());
}

#[test]
fn test_as_count_preview() {
    let s = MongoSelect::new().with_source("product");
    let expr = s.as_count();
    assert_eq!(expr.preview(), "db.product.countDocuments()");
}

#[test]
fn test_build_projection() {
    let s = MongoSelect::new().with_field("name").with_field("price");
    let proj = s.build_projection().unwrap();
    assert_eq!(proj, doc! { "name": 1, "price": 1 });
}

#[test]
fn test_build_projection_empty_means_all() {
    let s = MongoSelect::new();
    assert!(s.build_projection().is_none());
}

#[test]
fn test_build_sort() {
    let s = MongoSelect::new()
        .with_order(doc! { "price": 1 }, Order::Asc)
        .with_order(doc! { "name": 1 }, Order::Desc);
    let sort = s.build_sort().unwrap();
    assert_eq!(sort, doc! { "price": 1, "name": -1 });
}

#[test]
fn test_build_find_options() {
    let s = MongoSelect::new()
        .with_field("name")
        .with_limit(Some(5), Some(10));
    let opts = s.build_find_options();
    assert!(opts.projection.is_some());
    assert_eq!(opts.limit, Some(5));
    assert_eq!(opts.skip, Some(10));
}

#[tokio::test]
async fn test_build_filter_empty() {
    let s = MongoSelect::new();
    let filter = s.build_filter().await.unwrap();
    assert_eq!(filter, doc! {});
}

#[tokio::test]
async fn test_build_filter_single() {
    let s = MongoSelect::new().with_condition(doc! { "active": true });
    let filter = s.build_filter().await.unwrap();
    assert_eq!(filter, doc! { "active": true });
}

#[tokio::test]
async fn test_build_filter_multiple_uses_and() {
    let s = MongoSelect::new()
        .with_condition(doc! { "active": true })
        .with_condition(doc! { "price": { "$gt": 100 } });
    let filter = s.build_filter().await.unwrap();
    assert_eq!(
        filter,
        doc! { "$and": [{ "active": true }, { "price": { "$gt": 100 } }] }
    );
}

#[tokio::test]
async fn test_count_pipeline_empty() {
    let s = MongoSelect::new();
    let pipeline = s.as_count_pipeline().await.unwrap();
    assert_eq!(pipeline.len(), 1);
    assert_eq!(pipeline[0], doc! { "$count": "count" });
}

#[tokio::test]
async fn test_count_pipeline_with_filter() {
    let s = MongoSelect::new().with_condition(doc! { "is_deleted": false });
    let pipeline = s.as_count_pipeline().await.unwrap();
    assert_eq!(pipeline.len(), 2);
    assert_eq!(pipeline[0], doc! { "$match": { "is_deleted": false } });
    assert_eq!(pipeline[1], doc! { "$count": "count" });
}

#[tokio::test]
async fn test_aggregate_pipeline_sum() {
    let s = MongoSelect::new();
    let pipeline = s.as_aggregate_pipeline("$sum", "price").await.unwrap();
    assert_eq!(pipeline.len(), 1);
    assert_eq!(
        pipeline[0],
        doc! { "$group": { "_id": null, "val": { "$sum": "$price" } } }
    );
}

// ── Clear / has methods ──────────────────────────────────────────────────

#[test]
fn test_clear_and_has() {
    let mut s = MongoSelect::new()
        .with_source("product")
        .with_field("name")
        .with_condition(doc! { "a": 1 })
        .with_order(doc! { "price": 1 }, Order::Asc)
        .with_limit(Some(10), None);

    assert!(s.has_fields());
    assert!(s.has_where_conditions());
    assert!(s.has_order_by());
    assert_eq!(s.get_limit(), Some(10));
    assert_eq!(s.get_skip(), None);

    s.clear_fields();
    s.clear_where_conditions();
    s.clear_order_by();

    assert!(!s.has_fields());
    assert!(!s.has_where_conditions());
    assert!(!s.has_order_by());
    // limit untouched
    assert_eq!(s.get_limit(), Some(10));
}

// ── Live execution via SelectableDataSource (seeded v2 data) ─────────────

#[tokio::test]
async fn test_execute_select_all_products() {
    use vantage_expressions::SelectableDataSource;

    let db = db().await;
    let select = MongoSelect::new().with_source("product");
    let results = db.execute_select(&select).await.unwrap();

    // v2 seeds 5 products
    assert_eq!(results.len(), 5);
}

#[tokio::test]
async fn test_execute_select_with_fields() {
    use vantage_expressions::SelectableDataSource;

    let db = db().await;
    let select = MongoSelect::new()
        .with_source("product")
        .with_field("name")
        .with_field("price");
    let results = db.execute_select(&select).await.unwrap();

    assert_eq!(results.len(), 5);
    // Each result should be a document with projected fields
    let first: vantage_types::Record<AnyMongoType> = results[0].clone().try_into().unwrap();
    assert!(first.get("name").is_some());
    assert!(first.get("price").is_some());
}

#[tokio::test]
async fn test_execute_select_with_condition() {
    use vantage_expressions::SelectableDataSource;

    let db = db().await;
    let select = MongoSelect::new()
        .with_source("product")
        .with_condition(doc! { "price": { "$gt": 200 } });
    let results = db.execute_select(&select).await.unwrap();

    // sea_pie (299) and time_tart (220) have price > 200
    assert_eq!(results.len(), 2);
}

#[tokio::test]
async fn test_execute_select_with_order() {
    use vantage_expressions::SelectableDataSource;

    let db = db().await;
    let select = MongoSelect::new()
        .with_source("product")
        .with_order(doc! { "price": 1 }, Order::Asc);
    let results = db.execute_select(&select).await.unwrap();

    // Verify ascending price order
    let mut prices: Vec<i64> = Vec::new();
    for r in &results {
        let rec: vantage_types::Record<AnyMongoType> = r.clone().try_into().unwrap();
        if let Some(p) = rec
            .get("price")
            .and_then(|v| v.try_get::<i64>().or(v.try_get::<i32>().map(|i| i as i64)))
        {
            prices.push(p);
        }
    }
    assert_eq!(prices.len(), 5);
    for w in prices.windows(2) {
        assert!(w[0] <= w[1], "Expected ascending: {} <= {}", w[0], w[1]);
    }
}

#[tokio::test]
async fn test_execute_select_with_limit() {
    use vantage_expressions::SelectableDataSource;

    let db = db().await;
    let select = MongoSelect::new()
        .with_source("product")
        .with_limit(Some(2), None);
    let results = db.execute_select(&select).await.unwrap();

    assert_eq!(results.len(), 2);
}

#[tokio::test]
async fn test_execute_select_with_skip_and_limit() {
    use vantage_expressions::SelectableDataSource;

    let db = db().await;
    let select = MongoSelect::new()
        .with_source("product")
        .with_order(doc! { "price": 1 }, Order::Asc)
        .with_limit(Some(2), Some(1));
    let results = db.execute_select(&select).await.unwrap();

    assert_eq!(results.len(), 2);
    // Skipped the cheapest (120), should start from 135
    let rec: vantage_types::Record<AnyMongoType> = results[0].clone().try_into().unwrap();
    let price = rec["price"]
        .try_get::<i64>()
        .or(rec["price"].try_get::<i32>().map(|i| i as i64))
        .unwrap();
    assert_eq!(price, 135);
}

#[tokio::test]
async fn test_execute_select_multiple_conditions() {
    use vantage_expressions::SelectableDataSource;

    let db = db().await;
    let select = MongoSelect::new()
        .with_source("product")
        .with_condition(doc! { "is_deleted": false })
        .with_condition(doc! { "price": { "$gte": 199 } });
    let results = db.execute_select(&select).await.unwrap();

    // Not deleted AND price >= 199: sea_pie(299), time_tart(220), hover_cookies(199)
    assert_eq!(results.len(), 3);
}

#[tokio::test]
async fn test_execute_select_clients() {
    use vantage_expressions::SelectableDataSource;

    let db = db().await;
    let select = MongoSelect::new()
        .with_source("client")
        .with_condition(doc! { "is_paying_client": true });
    let results = db.execute_select(&select).await.unwrap();

    // marty and doc are paying clients
    assert_eq!(results.len(), 2);
}

#[tokio::test]
async fn test_execute_select_empty_result() {
    use vantage_expressions::SelectableDataSource;

    let db = db().await;
    let select = MongoSelect::new()
        .with_source("product")
        .with_condition(doc! { "price": { "$gt": 10000 } });
    let results = db.execute_select(&select).await.unwrap();

    assert!(results.is_empty());
}

// ── table.select() integration ───────────────────────────────────────────
// Verifies that Table<MongoDB, E> can produce a MongoSelect via table.select()

#[tokio::test]
async fn test_table_select_products() {
    use vantage_expressions::SelectableDataSource;
    use vantage_table::table::Table;
    use vantage_types::EmptyEntity;

    let db = db().await;
    let table = Table::<MongoDB, EmptyEntity>::new("product", db.clone())
        .with_id_column("_id")
        .with_column_of::<String>("name")
        .with_column_of::<i64>("price")
        .with_column_of::<bool>("is_deleted");

    let select = table.select();

    assert_eq!(select.collection, Some("product".to_string()));
    assert!(select.has_fields());
    // Should have _id, name, price, is_deleted
    assert_eq!(select.fields.len(), 4);

    // Execute it
    let results = db.execute_select(&select).await.unwrap();
    assert_eq!(results.len(), 5);
}

#[tokio::test]
async fn test_table_select_with_condition() {
    use vantage_expressions::SelectableDataSource;
    use vantage_table::table::Table;
    use vantage_types::EmptyEntity;

    let db = db().await;
    let mut table = Table::<MongoDB, EmptyEntity>::new("product", db.clone())
        .with_id_column("_id")
        .with_column_of::<String>("name")
        .with_column_of::<i64>("price")
        .with_column_of::<bool>("is_deleted");

    table.add_condition(doc! { "is_deleted": false });

    let select = table.select();
    assert!(select.has_where_conditions());

    let results = db.execute_select(&select).await.unwrap();
    assert_eq!(results.len(), 5); // all v2 products have is_deleted: false
}

#[tokio::test]
async fn test_table_select_with_condition_and_limit() {
    use vantage_expressions::SelectableDataSource;
    use vantage_table::table::Table;
    use vantage_types::EmptyEntity;

    let db = db().await;
    let mut table = Table::<MongoDB, EmptyEntity>::new("product", db.clone())
        .with_id_column("_id")
        .with_column_of::<String>("name")
        .with_column_of::<i64>("price");

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

    let mut select = table.select();
    select.set_limit(Some(2), None);

    let results = db.execute_select(&select).await.unwrap();
    assert_eq!(results.len(), 2);
}