Skip to main content

vantage_mongodb/select/
render.rs

1//! Human-readable preview rendering for MongoSelect.
2
3use super::MongoSelect;
4
5impl MongoSelect {
6    /// Render a human-readable preview string (for debug/logging).
7    pub fn preview(&self) -> String {
8        let coll = self.collection.as_deref().unwrap_or("?");
9
10        let filter_str = if self.conditions.is_empty() {
11            "{}".to_string()
12        } else {
13            format!("<{} conditions>", self.conditions.len())
14        };
15
16        let mut parts = vec![format!("db.{}.find({})", coll, filter_str)];
17
18        if let Some(proj) = self.build_projection() {
19            parts.push(format!(".projection({})", proj));
20        }
21        if let Some(sort) = self.build_sort() {
22            parts.push(format!(".sort({})", sort));
23        }
24        if let Some(skip) = self.skip {
25            parts.push(format!(".skip({})", skip));
26        }
27        if let Some(limit) = self.limit {
28            parts.push(format!(".limit({})", limit));
29        }
30
31        parts.join("")
32    }
33}
34
35#[cfg(test)]
36mod tests {
37    use bson::doc;
38    use vantage_expressions::Selectable;
39
40    use super::*;
41
42    #[test]
43    fn test_empty_preview() {
44        let s = MongoSelect::new();
45        assert_eq!(s.preview(), "db.?.find({})");
46    }
47
48    #[test]
49    fn test_preview_with_source_and_fields() {
50        let s = MongoSelect::new()
51            .with_source("product")
52            .with_field("name")
53            .with_field("price");
54        let p = s.preview();
55        assert!(p.starts_with("db.product.find({})"));
56        assert!(p.contains("projection"));
57    }
58
59    #[test]
60    fn test_preview_with_conditions() {
61        let s = MongoSelect::new()
62            .with_source("product")
63            .with_condition(doc! { "price": { "$gt": 100 } });
64        assert!(s.preview().contains("<1 conditions>"));
65    }
66
67    #[test]
68    fn test_preview_with_limit_skip() {
69        let s = MongoSelect::new()
70            .with_source("x")
71            .with_limit(Some(10), Some(20));
72        let p = s.preview();
73        assert!(p.contains(".skip(20)"));
74        assert!(p.contains(".limit(10)"));
75    }
76
77    #[test]
78    fn test_preview_with_sort() {
79        use vantage_expressions::Order;
80        let s = MongoSelect::new()
81            .with_source("x")
82            .with_order(doc! { "price": 1 }, Order::Asc);
83        assert!(s.preview().contains(".sort("));
84    }
85}