Skip to main content

postgrest_parser/ast/
order.rs

1use super::Field;
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
5#[serde(rename_all = "snake_case")]
6pub enum Direction {
7    Asc,
8    Desc,
9}
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum Nulls {
14    First,
15    Last,
16}
17
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
19pub struct OrderTerm {
20    pub field: Field,
21    pub direction: Direction,
22    pub nulls: Option<Nulls>,
23}
24
25impl OrderTerm {
26    pub fn new(field: Field) -> Self {
27        Self {
28            field,
29            direction: Direction::Asc,
30            nulls: None,
31        }
32    }
33
34    pub fn with_direction(mut self, direction: Direction) -> Self {
35        self.direction = direction;
36        self
37    }
38
39    pub fn with_nulls(mut self, nulls: Nulls) -> Self {
40        self.nulls = Some(nulls);
41        self
42    }
43
44    pub fn desc(mut self) -> Self {
45        self.direction = Direction::Desc;
46        self
47    }
48
49    pub fn asc(mut self) -> Self {
50        self.direction = Direction::Asc;
51        self
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn test_order_term_new() {
61        let field = Field::new("id");
62        let term = OrderTerm::new(field);
63        assert_eq!(term.direction, Direction::Asc);
64        assert!(term.nulls.is_none());
65    }
66
67    #[test]
68    fn test_order_term_desc() {
69        let field = Field::new("created_at");
70        let term = OrderTerm::new(field).desc();
71        assert_eq!(term.direction, Direction::Desc);
72    }
73
74    #[test]
75    fn test_order_term_with_nulls() {
76        let field = Field::new("name");
77        let term = OrderTerm::new(field).with_nulls(Nulls::Last);
78        assert_eq!(term.nulls, Some(Nulls::Last));
79    }
80
81    #[test]
82    fn test_order_term_serialization() {
83        let field = Field::new("id");
84        let term = OrderTerm::new(field).desc();
85        let json = serde_json::to_string(&term).unwrap();
86        assert!(json.contains("desc"));
87    }
88}