Skip to main content

postgrest_parser/ast/
field.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
4pub struct Field {
5    pub name: String,
6    pub json_path: Vec<JsonOp>,
7    pub cast: Option<String>,
8}
9
10#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12pub enum JsonOp {
13    Arrow(String),
14    DoubleArrow(String),
15    ArrayIndex(i32),
16}
17
18impl Field {
19    pub fn new(name: impl Into<String>) -> Self {
20        Self {
21            name: name.into(),
22            json_path: Vec::new(),
23            cast: None,
24        }
25    }
26
27    pub fn with_json_path(mut self, ops: Vec<JsonOp>) -> Self {
28        self.json_path = ops;
29        self
30    }
31
32    pub fn with_cast(mut self, cast: impl Into<String>) -> Self {
33        self.cast = Some(cast.into());
34        self
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn test_field_new() {
44        let field = Field::new("id");
45        assert_eq!(field.name, "id");
46        assert!(field.json_path.is_empty());
47        assert!(field.cast.is_none());
48    }
49
50    #[test]
51    fn test_field_with_json_path() {
52        let field = Field::new("data").with_json_path(vec![JsonOp::Arrow("key".to_string())]);
53        assert_eq!(field.name, "data");
54        assert_eq!(field.json_path.len(), 1);
55    }
56
57    #[test]
58    fn test_field_with_cast() {
59        let field = Field::new("price").with_cast("numeric");
60        assert_eq!(field.name, "price");
61        assert_eq!(field.cast, Some("numeric".to_string()));
62    }
63
64    #[test]
65    fn test_json_op_serialization() {
66        let op = JsonOp::Arrow("key".to_string());
67        let json = serde_json::to_string(&op).unwrap();
68        assert!(json.contains("arrow"));
69    }
70}