Skip to main content

supabase_client_query/
modifier.rs

1use crate::sql::{CountOption, NullsPosition, OrderClause, OrderDirection, SqlParts, validate_column_name};
2
3/// Trait providing modifier methods (order, limit, range, single, count).
4pub trait Modifiable: Sized {
5    /// Get a mutable reference to the SQL parts.
6    fn parts_mut(&mut self) -> &mut SqlParts;
7
8    /// Order by a column.
9    fn order(mut self, column: &str, direction: OrderDirection) -> Self {
10        if let Err(e) = validate_column_name(column) {
11            tracing::error!("Invalid column name in order: {e}");
12            return self;
13        }
14        self.parts_mut().orders.push(OrderClause {
15            column: column.to_string(),
16            direction,
17            nulls: None,
18        });
19        self
20    }
21
22    /// Order by a column with explicit nulls positioning.
23    fn order_with_nulls(
24        mut self,
25        column: &str,
26        direction: OrderDirection,
27        nulls: NullsPosition,
28    ) -> Self {
29        if let Err(e) = validate_column_name(column) {
30            tracing::error!("Invalid column name in order_with_nulls: {e}");
31            return self;
32        }
33        self.parts_mut().orders.push(OrderClause {
34            column: column.to_string(),
35            direction,
36            nulls: Some(nulls),
37        });
38        self
39    }
40
41    /// Limit the number of rows returned.
42    fn limit(mut self, count: i64) -> Self {
43        self.parts_mut().limit = Some(count);
44        self
45    }
46
47    /// Set the range of rows to return (offset..offset+limit).
48    fn range(mut self, from: i64, to: i64) -> Self {
49        self.parts_mut().offset = Some(from);
50        self.parts_mut().limit = Some(to - from + 1);
51        self
52    }
53
54    /// Expect exactly one row. Returns error if 0 or >1 rows.
55    fn single(mut self) -> Self {
56        self.parts_mut().single = true;
57        self.parts_mut().limit = Some(2); // Fetch 2 to detect >1
58        self
59    }
60
61    /// Expect zero or one row. Returns error if >1 rows.
62    fn maybe_single(mut self) -> Self {
63        self.parts_mut().maybe_single = true;
64        self.parts_mut().limit = Some(2);
65        self
66    }
67
68    /// Request an exact row count.
69    fn count(mut self) -> Self {
70        self.parts_mut().count = CountOption::Exact;
71        self
72    }
73
74    /// Request a row count with a specific counting strategy.
75    fn count_option(mut self, option: CountOption) -> Self {
76        self.parts_mut().count = option;
77        self
78    }
79}