Skip to main content

surql_parser/upstream/sql/
field.rs

1use crate::upstream::fmt::{CoverStmts, Fmt};
2use crate::upstream::sql::{Expr, Idiom};
3use surrealdb_types::{SqlFormat, ToSql, write_sql};
4#[derive(Clone, Debug, PartialEq, Eq)]
5#[cfg_attr(feature = "arbitrary", derive(::arbitrary::Arbitrary))]
6pub enum Fields {
7	/// Fields had the `VALUE` clause and should only return the given selector
8	Value(Box<Selector>),
9	/// Normal fields where an object with the selected fields is expected
10	Select(
11		#[cfg_attr(
12            feature = "arbitrary",
13            arbitrary(with = crate::upstream::sql::arbitrary::atleast_one)
14        )]
15		Vec<Field>,
16	),
17}
18impl Fields {
19	pub fn all() -> Fields {
20		Fields::Select(vec![Field::All])
21	}
22	pub fn contains_all(&self) -> bool {
23		match self {
24			Fields::Value(_) => false,
25			Fields::Select(fields) => fields.iter().any(|x| matches!(x, Field::All)),
26		}
27	}
28}
29impl ToSql for Fields {
30	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
31		match self {
32			Fields::Value(v) => {
33				f.push_str("VALUE ");
34				v.fmt_sql(f, fmt);
35			}
36			Fields::Select(x) => write_sql!(f, fmt, "{}", Fmt::comma_separated(x)),
37		}
38	}
39}
40#[derive(Clone, Debug, Default, PartialEq, Eq)]
41#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
42pub enum Field {
43	/// The `*` in `SELECT * FROM ...`
44	#[default]
45	All,
46	/// The 'rating' in `SELECT rating FROM ...`
47	Single(Selector),
48}
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct Selector {
51	pub expr: Expr,
52	pub alias: Option<Idiom>,
53}
54impl ToSql for Field {
55	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
56		match self {
57			Self::All => f.push('*'),
58			Self::Single(s) => s.fmt_sql(f, fmt),
59		}
60	}
61}
62impl ToSql for Selector {
63	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
64		write_sql!(f, fmt, "{}", CoverStmts(&self.expr));
65		if let Some(alias) = &self.alias {
66			f.push_str(" AS ");
67			alias.fmt_sql(f, fmt);
68		}
69	}
70}