Skip to main content

sql_builder/backend/
bound_sql.rs

1//! SQL text with the values it binds in place.
2
3use super::SqlDialect;
4use crate::{
5    Expr, Value,
6    expr::{CustomExpr, CustomExprPart},
7};
8
9/// A piece of SQL with the values it binds standing where they are bound.
10///
11/// No marker is written until the piece renders: an [`Expr`] made from it
12/// binds each value in place, and [`build_after`](Self::build_after) numbers
13/// the markers after the values a statement already binds, so its text is
14/// never read back for markers.
15#[derive(Debug, Clone, Default, PartialEq)]
16pub struct BoundSql {
17    parts: Vec<BoundPart>,
18}
19
20/// One part of a [`BoundSql`].
21#[derive(Debug, Clone, PartialEq)]
22pub enum BoundPart {
23    /// SQL text.
24    Sql(String),
25    /// A value, bound where it stands.
26    Value(Value),
27}
28
29/// What a [`BoundSql`] is built from: text, a [`Value`] bound in place, or
30/// another [`BoundSql`].
31pub trait BoundPiece {
32    /// Append `self` to `bound`.
33    fn append_to(self, bound: &mut BoundSql);
34}
35
36impl BoundPiece for &str {
37    fn append_to(self, bound: &mut BoundSql) {
38        if self.is_empty() {
39            return;
40        }
41        match bound.parts.last_mut() {
42            Some(BoundPart::Sql(text)) => text.push_str(self),
43            _ => bound.parts.push(BoundPart::Sql(self.to_owned())),
44        }
45    }
46}
47
48impl BoundPiece for String {
49    fn append_to(self, bound: &mut BoundSql) {
50        self.as_str().append_to(bound);
51    }
52}
53
54impl BoundPiece for &String {
55    fn append_to(self, bound: &mut BoundSql) {
56        self.as_str().append_to(bound);
57    }
58}
59
60impl BoundPiece for Value {
61    fn append_to(self, bound: &mut BoundSql) {
62        bound.parts.push(BoundPart::Value(self));
63    }
64}
65
66impl BoundPiece for BoundSql {
67    fn append_to(self, bound: &mut BoundSql) {
68        for part in self.parts {
69            match part {
70                BoundPart::Sql(text) => text.append_to(bound),
71                BoundPart::Value(value) => value.append_to(bound),
72            }
73        }
74    }
75}
76
77impl BoundSql {
78    /// The SQL text `sql`, binding nothing.
79    pub fn sql(sql: impl Into<String>) -> Self {
80        let mut bound = Self::default();
81        sql.into().append_to(&mut bound);
82        bound
83    }
84
85    /// Append `piece`.
86    pub fn push(&mut self, piece: impl BoundPiece) -> &mut Self {
87        piece.append_to(self);
88        self
89    }
90
91    /// `items` with `separator` between them.
92    pub fn join(items: impl IntoIterator<Item = BoundSql>, separator: &str) -> Self {
93        let mut joined = Self::default();
94        for (index, item) in items.into_iter().enumerate() {
95            if index > 0 {
96                joined.push(separator);
97            }
98            joined.push(item);
99        }
100        joined
101    }
102
103    /// Its parts, in order.
104    pub fn parts(&self) -> &[BoundPart] {
105        &self.parts
106    }
107
108    /// Whether it holds no SQL and no value.
109    pub fn is_empty(&self) -> bool {
110        self.parts.is_empty()
111    }
112
113    /// The SQL with `dialect`'s markers, numbered after the values already
114    /// in `values`, to which its own are appended.
115    pub fn build_after(
116        self,
117        dialect: &(impl SqlDialect + ?Sized),
118        values: &mut Vec<Value>,
119    ) -> String {
120        let mut sql = String::new();
121        for part in self.parts {
122            match part {
123                BoundPart::Sql(text) => sql.push_str(&text),
124                BoundPart::Value(value) => {
125                    values.push(value);
126                    sql.push_str(&dialect.marker(values.len()));
127                }
128            }
129        }
130        sql
131    }
132
133    /// The SQL with `dialect`'s markers, numbered from 1, and its values.
134    pub fn build(self, dialect: &(impl SqlDialect + ?Sized)) -> (String, Vec<Value>) {
135        let mut values = Vec::new();
136        let sql = self.build_after(dialect, &mut values);
137        (sql, values)
138    }
139}
140
141/// A query builder writes into a [`BoundSql`] with each value in place, so a
142/// statement it renders can be spliced into another without reading markers.
143impl std::fmt::Write for BoundSql {
144    fn write_str(&mut self, text: &str) -> std::fmt::Result {
145        self.push(text);
146        Ok(())
147    }
148}
149
150impl crate::SqlWriter for BoundSql {
151    fn push_param<T: crate::QueryBuilder>(
152        &mut self,
153        value: Value,
154        _: &T,
155    ) -> Result<(), crate::error::RenderError> {
156        self.push(value);
157        Ok(())
158    }
159}
160
161/// The text with a `?` standing for each value.
162impl std::fmt::Display for BoundSql {
163    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164        for part in &self.parts {
165            match part {
166                BoundPart::Sql(text) => f.write_str(text)?,
167                BoundPart::Value(_) => f.write_str("?")?,
168            }
169        }
170        Ok(())
171    }
172}
173
174impl BoundSql {
175    /// `expr` followed by this SQL, as one expression.
176    pub(crate) fn following(self, expr: Expr) -> Expr {
177        let parts = std::iter::once(CustomExprPart::Expression(expr))
178            .chain(self.parts.into_iter().map(CustomExprPart::from))
179            .collect();
180        Expr::CustomWithExpr(CustomExpr { parts })
181    }
182}
183
184impl From<BoundPart> for CustomExprPart {
185    fn from(part: BoundPart) -> Self {
186        match part {
187            BoundPart::Sql(text) => CustomExprPart::Text(text),
188            BoundPart::Value(value) => CustomExprPart::Expression(Expr::Value(value)),
189        }
190    }
191}
192
193impl From<BoundSql> for Expr {
194    fn from(bound: BoundSql) -> Self {
195        let parts = bound.parts.into_iter().map(CustomExprPart::from).collect();
196        Expr::CustomWithExpr(CustomExpr { parts })
197    }
198}
199
200/// A [`BoundSql`] of the given pieces, in order.
201macro_rules! bound {
202    ($($piece:expr),* $(,)?) => {{
203        let mut bound = $crate::backend::BoundSql::default();
204        $( bound.push($piece); )*
205        bound
206    }};
207}
208pub(crate) use bound;