1use dpp::platform_value::Value;
5use grovedb::Error;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
9#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10pub struct OrderClause {
11 pub field: String,
13 pub ascending: bool,
15}
16
17impl OrderClause {
18 pub fn from_components(clause_components: &[Value]) -> Result<Self, Error> {
20 if clause_components.len() != 2 {
21 return Err(Error::InvalidQuery(
22 "order clause should have exactly 2 components",
23 ));
24 }
25
26 let field_value = clause_components
27 .first()
28 .expect("check above enforces it exists");
29 let field_ref = field_value.as_text().ok_or(Error::InvalidQuery(
30 "first field of where component should be a string",
31 ))?;
32 let field = String::from(field_ref);
33
34 let asc_string_value = clause_components.get(1).unwrap();
35 let asc_string = match asc_string_value {
36 Value::Text(asc_string) => Some(asc_string.as_str()),
37 _ => None,
38 }
39 .ok_or(Error::InvalidQuery(
40 "orderBy right component must be a string",
41 ))?;
42 let ascending = match asc_string {
43 "asc" => true,
44 "desc" => false,
45 _ => {
46 return Err(Error::InvalidQuery(
47 "orderBy right component must be either a asc or desc string",
48 ));
49 }
50 };
51
52 Ok(OrderClause { field, ascending })
53 }
54}
55
56impl From<OrderClause> for Value {
57 fn from(order: OrderClause) -> Self {
58 let direction = match order.ascending {
59 true => "asc",
60 false => "desc",
61 };
62
63 Self::Array(vec![order.field.into(), direction.into()])
64 }
65}