derive_sql/structs/order/
condition.rs

1use super::*;
2
3pub enum Operator
4{
5  Ascending,
6  Descending,
7}
8
9/// Describe a single ordering condition using a label and an operator
10pub struct Condition
11{
12  table: Option<String>,
13  label: String,
14  operator: Operator,
15}
16
17impl Condition
18{
19  /// Create a condition from a table name, column name and an operator
20  pub fn from_table_label_operator(table: Option<String>, label: String, operator: Operator) -> Condition {
21    Condition { table, label, operator }
22  }
23
24  /// Create a condition from a column name and an operator
25  pub fn from_label_operator(label: String, operator: Operator) -> Condition {
26    Condition { table: None, label, operator }
27  }
28}
29
30impl traits::FlavoredOrder for Condition
31{
32  /// Return the `ORDER BY` clause associated with the condition
33  fn as_order_clause<C, R>(&self, conn: &C) -> Result<String> 
34  where C: traits::Connection<R>, R: traits::Row
35  {
36    let flavor = conn.flavor();
37    let label = if let Some(table) = &self.table {
38      format!("{table}.{label}", 
39        table=flavor.table(table)?,
40        label=flavor.column(self.label.as_str())?)
41    } else {
42      format!("{label}",
43        label=flavor.column(self.label.as_str())?)
44    };
45    let r = match &self.operator {
46      Operator::Ascending   => format!("{label} ASC"),
47      Operator::Descending  => format!("{label} DESC"),
48    };
49    Ok(r)
50  }
51}
52
53#[cfg(test)]
54mod tests {
55  use super::*;
56
57  #[cfg(test)]
58  fn it_display_correct_clause() -> Result<()> {
59    use traits::FlavoredOrder;
60    let conn = traits::tests::SQLiteFlavoredConnection {};
61    type Row = traits::tests::Row;
62
63    assert!(Condition::from_label_operator("key".to_string(), Operator::Ascending).as_order_clause::<_, Row>(&conn)?.eq("`key` ASC"));
64    assert!(Condition::from_label_operator("key".to_string(), Operator::Descending).as_order_clause::<_, Row>(&conn)?.eq("`key` DESC"));
65
66    Ok(())
67  }
68}