Skip to content

Commit f6fbc6a

Browse files
committed
feat(query): Display SqlBuilder as SQL string.
Allow to print the current SQL query, whether it's bound or not. Useful for logging and diagnostics.
1 parent 5ccae0b commit f6fbc6a

File tree

1 file changed

+42
-3
lines changed

1 file changed

+42
-3
lines changed

src/sql/mod.rs

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::fmt::Display;
1+
use std::fmt::{self, Display};
22

33
use crate::{
44
error::{Error, Result},
@@ -11,19 +11,38 @@ mod bind;
1111
pub(crate) mod escape;
1212
mod ser;
1313

14-
#[derive(Clone)]
14+
#[derive(Debug, Clone)]
1515
pub(crate) enum SqlBuilder {
1616
InProgress(Vec<Part>),
1717
Failed(String),
1818
}
1919

20-
#[derive(Clone)]
20+
#[derive(Debug, Clone)]
2121
pub(crate) enum Part {
2222
Arg,
2323
Fields,
2424
Text(String),
2525
}
2626

27+
/// Display SQL query as string.
28+
impl fmt::Display for SqlBuilder {
29+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30+
match self {
31+
SqlBuilder::InProgress(parts) => {
32+
for part in parts {
33+
match part {
34+
Part::Arg => write!(f, "?")?,
35+
Part::Fields => write!(f, "?fields")?,
36+
Part::Text(text) => write!(f, "{text}")?,
37+
}
38+
}
39+
}
40+
SqlBuilder::Failed(err) => write!(f, "{err}")?,
41+
}
42+
Ok(())
43+
}
44+
}
45+
2746
impl SqlBuilder {
2847
pub(crate) fn new(template: &str) -> Self {
2948
let mut iter = template.split('?');
@@ -141,9 +160,29 @@ mod tests {
141160
#[test]
142161
fn bound_args() {
143162
let mut sql = SqlBuilder::new("SELECT ?fields FROM test WHERE a = ? AND b < ?");
163+
assert_eq!(
164+
sql.to_string(),
165+
"SELECT ?fields FROM test WHERE a = ? AND b < ?"
166+
);
167+
144168
sql.bind_arg("foo");
169+
assert_eq!(
170+
sql.to_string(),
171+
"SELECT ?fields FROM test WHERE a = 'foo' AND b < ?"
172+
);
173+
145174
sql.bind_arg(42);
175+
assert_eq!(
176+
sql.to_string(),
177+
"SELECT ?fields FROM test WHERE a = 'foo' AND b < 42"
178+
);
179+
146180
sql.bind_fields::<Row>();
181+
assert_eq!(
182+
sql.to_string(),
183+
"SELECT `a`,`b` FROM test WHERE a = 'foo' AND b < 42"
184+
);
185+
147186
assert_eq!(
148187
sql.finish().unwrap(),
149188
r"SELECT `a`,`b` FROM test WHERE a = 'foo' AND b < 42"

0 commit comments

Comments
 (0)