Thanks to visit codestin.com
Credit goes to docs.rs

sqlmo/query/
cte.rs

1use crate::{Dialect, Insert, Select, ToSql};
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub enum CteQuery {
5    Select(Select),
6    Insert(Insert),
7    Raw(String),
8}
9
10impl ToSql for CteQuery {
11    fn write_sql(&self, buf: &mut String, dialect: Dialect) {
12        match self {
13            CteQuery::Select(s) => s.write_sql(buf, dialect),
14            CteQuery::Insert(i) => i.write_sql(buf, dialect),
15            CteQuery::Raw(s) => buf.push_str(s),
16        }
17    }
18}
19
20impl Into<CteQuery> for Select {
21    fn into(self) -> CteQuery {
22        CteQuery::Select(self)
23    }
24}
25
26impl Into<CteQuery> for Insert {
27    fn into(self) -> CteQuery {
28        CteQuery::Insert(self)
29    }
30}
31
32impl Into<CteQuery> for String {
33    fn into(self) -> CteQuery {
34        CteQuery::Raw(self)
35    }
36}
37
38/// Common table expression
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Cte {
41    pub name: String,
42    pub query: CteQuery,
43}
44
45impl Cte {
46    pub fn new(name: impl Into<String>, query: impl Into<CteQuery>) -> Self {
47        Self {
48            name: name.into(),
49            query: query.into(),
50        }
51    }
52}
53
54impl ToSql for Cte {
55    fn write_sql(&self, buf: &mut String, dialect: Dialect) {
56        buf.push_str(&self.name);
57        buf.push_str(" AS (");
58        buf.push_str(&self.query.to_sql(dialect));
59        buf.push(')');
60    }
61}