Skip to main content

surrealdb_sql/
order.rs

1use std::ops::Deref;
2
3use common::fmt::Fmt;
4use surrealdb_types::{SqlFormat, ToSql, write_sql};
5
6use crate::Idiom;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
9#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
10pub enum Ordering {
11	Random,
12	Order(OrderList),
13}
14
15impl surrealdb_types::ToSql for Ordering {
16	fn fmt_sql(&self, f: &mut String, fmt: surrealdb_types::SqlFormat) {
17		match self {
18			Ordering::Random => f.push_str("ORDER BY RAND()"),
19			Ordering::Order(list) => {
20				write_sql!(f, fmt, "ORDER BY {}", list);
21			}
22		}
23	}
24}
25
26#[derive(Clone, Debug, PartialEq, Eq)]
27#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
28pub struct OrderList(
29	#[cfg_attr(feature = "arbitrary", arbitrary(with = crate::arbitrary::atleast_one))]
30	pub  Vec<Order>,
31);
32
33impl Deref for OrderList {
34	type Target = Vec<Order>;
35	fn deref(&self) -> &Self::Target {
36		&self.0
37	}
38}
39
40impl ToSql for OrderList {
41	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
42		write_sql!(f, fmt, "{}", Fmt::comma_separated(&self.0))
43	}
44}
45
46#[derive(Clone, Debug, Default, Eq, PartialEq)]
47#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
48pub struct Order {
49	/// The value to order by
50	#[cfg_attr(feature = "arbitrary", arbitrary(with = crate::arbitrary::basic_idiom))]
51	pub value: Idiom,
52	pub collate: bool,
53	pub numeric: bool,
54	/// true if the direction is ascending
55	pub direction: bool,
56}
57
58impl ToSql for Order {
59	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
60		self.value.fmt_sql(f, fmt);
61		if self.collate {
62			f.push_str(" COLLATE");
63		}
64		if self.numeric {
65			f.push_str(" NUMERIC");
66		}
67		if !self.direction {
68			f.push_str(" DESC");
69		}
70	}
71}