Skip to main content

ngb_sqlbuilder/
clause.rs

1use std::marker::PhantomData;
2use tokio_postgres::types::ToSql;
3
4#[derive(Debug, Clone)]
5pub struct Clause<'q, T> {
6    pub(crate) sql: String,
7    pub(crate) params: Vec<&'q (dyn ToSql + Sync)>,
8    _ph: PhantomData<T>,
9}
10impl<'q, T> Clause<'q, T> {
11    pub(crate) fn new(sql: String, params: Vec<&'q (dyn ToSql + Sync)>) -> Self {
12        Self {
13            sql,
14            params,
15            _ph: PhantomData,
16        }
17    }
18    // pub fn alias(mut self, name: &str) -> Self {
19    //     self.sql.push_str(format!(" as \"{}\"", name).as_str());
20    //     self
21    // }
22    /// Build and compile query into SQL syntax with numbered parameters
23    pub fn build(self) -> (String, Vec<&'q (dyn ToSql + Sync)>) {
24        let init_capacity = self.sql.len() + self.params.len();
25        let mut result = String::with_capacity(init_capacity);
26        let mut start = 0;
27        let mut count = 1;
28        for (i, _) in self.sql.match_indices("$") {
29            result.push_str(&self.sql[start..i]);
30            result.push_str(&format!("${count}"));
31            count += 1;
32            start = i + 1;
33        }
34        result.push_str(&self.sql[start..]);
35        (result, self.params)
36    }
37    pub fn this(self) -> Self {
38        self
39    }
40
41    pub fn into<C>(self) -> Clause<'q, C> {
42        Clause::new(self.sql, self.params)
43    }
44}