Skip to content

Commit

Permalink
Server side parameters via with_param
Browse files Browse the repository at this point in the history
Fixes #142
  • Loading branch information
serprex committed Sep 24, 2024
1 parent 1f136af commit edbd788
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
9 changes: 8 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
#[macro_use]
extern crate static_assertions;

use self::{error::Result, http_client::HttpClient};
use self::{error::Result, http_client::HttpClient, sql::Bind};
use ::serde::Serialize;
use std::{collections::HashMap, fmt::Display, sync::Arc};

pub use self::{compression::Compression, row::Row};
Expand Down Expand Up @@ -160,6 +161,12 @@ impl Client {
self
}

pub fn with_param(self, name: &str, value: impl Bind + Serialize) -> Result<Self, String> {
let mut param = String::from("");
Bind::write(&value, &mut param)?;
Ok(self.with_option(format!("param_{name}"), param))
}

/// Used to specify a header that will be passed to all queries.
///
/// # Example
Expand Down
8 changes: 7 additions & 1 deletion src/query.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use hyper::{header::CONTENT_LENGTH, Method, Request};
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use url::Url;

Expand Down Expand Up @@ -195,6 +195,12 @@ impl Query {
self.client.add_option(name, value);
self
}

pub fn with_param(self, name: &str, value: impl Bind + Serialize) -> Result<Self, String> {
let mut param = String::from("");
Bind::write(&value, &mut param)?;
Ok(self.with_option(format!("param_{name}"), param))
}
}

/// A cursor that emits rows.
Expand Down
25 changes: 25 additions & 0 deletions tests/it/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,31 @@ async fn fetch_one_and_optional() {
assert_eq!(got_string, "bar");
}

#[tokio::test]
async fn server_side_param() {
let client = prepare_database!()
.with_param("val1", 42)
.expect("failed to bind 42");

let result = client
.query("SELECT plus({val1: Int32}, {val2: String}) AS result")
.with_param("val2", 144)
.expect("failed to bind 144")
.fetch_one::<u64>()
.await
.expect("failed to fetch u64");
assert_eq!(result, 186);

let result = client
.query("SELECT {val1: String} AS result")
.with_param("param_val1", "string")
.expect("failed to bind \"string\"")
.fetch_one::<String>()
.await
.expect("failed to fetch string");
assert_eq!(result, "string");
}

// See #19.
#[tokio::test]
async fn long_query() {
Expand Down

0 comments on commit edbd788

Please sign in to comment.