implement Unknown encoding for query parameters

This commit is contained in:
Ruslan Talpa 2021-11-01 12:31:59 +02:00
parent 8bb5712406
commit 6c407d39d5
2 changed files with 43 additions and 3 deletions

View File

@ -769,6 +769,40 @@ pub trait ToSql: fmt::Debug {
ty: &Type,
out: &mut BytesMut,
) -> Result<IsNull, Box<dyn Error + Sync + Send>>;
/// Specify the encode format
fn encode_format(&self) -> i16 { 1 }
/// return string representation
fn as_string(&self) -> String {
panic!("as_string not implemented for {:?}", self)
}
}
/// A Wrapper type used for sending query parameters encoded as unknown.
#[derive(Debug)]
pub struct Unknown<'a>(pub &'a (dyn ToSql + Sync));
impl ToSql for Unknown<'_> {
fn to_sql(
&self,
_ty: &Type,
out: &mut BytesMut,
) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
match *self {
Unknown(val) => {
types::text_to_sql(&val.as_string(), out);
Ok(IsNull::No)
}
}
}
fn accepts(_ty: &Type) -> bool { true }
fn encode_format(&self) -> i16 { 0 }
to_sql_checked!();
}
impl<'a, T> ToSql for &'a T
@ -905,7 +939,7 @@ impl<'a> ToSql for &'a str {
_ => false,
}
}
fn as_string(&self) -> String { self.to_string() }
to_sql_checked!();
}
@ -929,7 +963,7 @@ impl ToSql for String {
fn accepts(ty: &Type) -> bool {
<&str as ToSql>::accepts(ty)
}
fn as_string(&self) -> String { self.clone() }
to_sql_checked!();
}
@ -944,6 +978,10 @@ macro_rules! simple_to {
Ok(IsNull::No)
}
fn as_string(&self) -> String {
format!("{}", &self)
}
accepts!($($expected),+);
to_sql_checked!();

View File

@ -156,6 +156,8 @@ where
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
let (param_formats, params):(Vec<_>, Vec<_>) = params.into_iter().map(|p| (p.borrow_to_sql().encode_format(),p)).unzip();
let params = params.into_iter();
assert!(
@ -169,7 +171,7 @@ where
let r = frontend::bind(
portal,
statement.name(),
Some(1),
param_formats,
params.zip(statement.params()).enumerate(),
|(idx, (param, ty)), buf| match param.borrow_to_sql().to_sql_checked(ty, buf) {
Ok(IsNull::No) => Ok(postgres_protocol::IsNull::No),