Skip to content

Commit 135598b

Browse files
committed
Server side parameters via with_param
Fixes #142
1 parent 1f136af commit 135598b

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

src/lib.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
#[macro_use]
66
extern crate static_assertions;
77

8-
use self::{error::Result, http_client::HttpClient};
8+
use self::{error::Result, http_client::HttpClient, sql::Bind};
9+
use ::serde::Serialize;
910
use std::{collections::HashMap, fmt::Display, sync::Arc};
1011

1112
pub use self::{compression::Compression, row::Row};
@@ -160,6 +161,12 @@ impl Client {
160161
self
161162
}
162163

164+
pub fn with_param(self, name: &str, value: impl Bind + Serialize) -> Result<Self, String> {
165+
let mut param = String::from("");
166+
Bind::write(&value, &mut param)?;
167+
Ok(self.with_option(format!("param_{name}"), param))
168+
}
169+
163170
/// Used to specify a header that will be passed to all queries.
164171
///
165172
/// # Example

src/query.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use hyper::{header::CONTENT_LENGTH, Method, Request};
2-
use serde::Deserialize;
2+
use serde::{Deserialize, Serialize};
33
use std::fmt::Display;
44
use url::Url;
55

@@ -195,6 +195,12 @@ impl Query {
195195
self.client.add_option(name, value);
196196
self
197197
}
198+
199+
pub fn with_param(self, name: &str, value: impl Bind + Serialize) -> Result<Self, String> {
200+
let mut param = String::from("");
201+
Bind::write(&value, &mut param)?;
202+
Ok(self.with_option(format!("param_{name}"), param))
203+
}
198204
}
199205

200206
/// A cursor that emits rows.

tests/it/query.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,31 @@ async fn fetch_one_and_optional() {
8585
assert_eq!(got_string, "bar");
8686
}
8787

88+
#[tokio::test]
89+
async fn server_side_param() {
90+
let client = prepare_database!()
91+
.with_param("val1", 42)
92+
.expect("failed to bind 42");
93+
94+
let result = client
95+
.query("SELECT plus({val1: Int32}, {val2: Int32}) AS result")
96+
.with_param("val2", 144)
97+
.expect("failed to bind 144")
98+
.fetch_one::<u64>()
99+
.await
100+
.expect("failed to fetch u64");
101+
assert_eq!(result, 186);
102+
103+
let result = client
104+
.query("SELECT {val1: String} AS result")
105+
.with_param("val1", "string")
106+
.expect("failed to bind \"string\"")
107+
.fetch_one::<String>()
108+
.await
109+
.expect("failed to fetch string");
110+
assert_eq!(result, "string");
111+
}
112+
88113
// See #19.
89114
#[tokio::test]
90115
async fn long_query() {

0 commit comments

Comments
 (0)