Skip to main content

surrealdb_core/sql/
idiom.rs

1use std::fmt::{self, Display, Formatter};
2use std::ops::Deref;
3
4use crate::sql::fmt::{Fmt, fmt_separated_by};
5use crate::sql::{Ident, Part};
6
7// TODO: Remove unnessacry newtype.
8#[derive(Clone, Debug, Default, Eq, PartialEq)]
9#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
10pub struct Idioms(pub Vec<Idiom>);
11
12impl Deref for Idioms {
13	type Target = Vec<Idiom>;
14	fn deref(&self) -> &Self::Target {
15		&self.0
16	}
17}
18
19impl IntoIterator for Idioms {
20	type Item = Idiom;
21	type IntoIter = std::vec::IntoIter<Self::Item>;
22	fn into_iter(self) -> Self::IntoIter {
23		self.0.into_iter()
24	}
25}
26
27impl Display for Idioms {
28	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
29		Display::fmt(&Fmt::comma_separated(&self.0), f)
30	}
31}
32
33impl From<Idioms> for crate::expr::Idioms {
34	fn from(v: Idioms) -> Self {
35		crate::expr::Idioms(v.0.into_iter().map(Into::into).collect())
36	}
37}
38impl From<crate::expr::Idioms> for Idioms {
39	fn from(v: crate::expr::Idioms) -> Self {
40		Idioms(v.0.into_iter().map(Into::into).collect())
41	}
42}
43
44#[derive(Clone, Debug, Default, PartialEq, Eq)]
45#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
46pub struct Idiom(pub Vec<Part>);
47
48impl Idiom {
49	/// Simplifies this Idiom for use in object keys
50	pub(crate) fn simplify(&self) -> Idiom {
51		Idiom(
52			self.0
53				.iter()
54				.filter(|&p| matches!(p, Part::Field(_) | Part::Start(_) | Part::Graph(_)))
55				.cloned()
56				.collect(),
57		)
58	}
59
60	pub fn field(name: Ident) -> Self {
61		Idiom(vec![Part::Field(name)])
62	}
63}
64
65impl From<Idiom> for crate::expr::Idiom {
66	fn from(v: Idiom) -> Self {
67		crate::expr::Idiom(v.0.into_iter().map(Into::into).collect())
68	}
69}
70
71impl From<crate::expr::Idiom> for Idiom {
72	fn from(v: crate::expr::Idiom) -> Self {
73		Idiom(v.0.into_iter().map(Into::into).collect())
74	}
75}
76
77impl Display for Idiom {
78	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79		Display::fmt(
80			&Fmt::new(
81				self.0.iter().enumerate().map(|args| {
82					Fmt::new(args, |(i, p), f| match (i, p) {
83						(0, Part::Field(v)) => Display::fmt(v, f),
84						_ => Display::fmt(p, f),
85					})
86				}),
87				fmt_separated_by(""),
88			),
89			f,
90		)
91	}
92}