Skip to content

Commit 32382c9

Browse files
committed
Server side parameters via with_param
Fixes #142
1 parent 1f136af commit 32382c9

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

src/lib.rs

Lines changed: 12 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,16 @@ impl Client {
160161
self
161162
}
162163

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

src/query.rs

Lines changed: 11 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,16 @@ impl Query {
195195
self.client.add_option(name, value);
196196
self
197197
}
198+
199+
pub fn with_param(
200+
self,
201+
name: &str,
202+
value: impl Bind + Serialize,
203+
) -> Result<Self, String> {
204+
let mut param = String::from("");
205+
Bind::write(&value, &mut param)?;
206+
Ok(self.with_option(format!("param_{name}"), param))
207+
}
198208
}
199209

200210
/// 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: String}) 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("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)