Skip to content

Commit 6c407d3

Browse files
committed
implement Unknown encoding for query parameters
1 parent 8bb5712 commit 6c407d3

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

postgres-types/src/lib.rs

+40-2
Original file line numberDiff line numberDiff line change
@@ -769,6 +769,40 @@ pub trait ToSql: fmt::Debug {
769769
ty: &Type,
770770
out: &mut BytesMut,
771771
) -> Result<IsNull, Box<dyn Error + Sync + Send>>;
772+
773+
/// Specify the encode format
774+
fn encode_format(&self) -> i16 { 1 }
775+
776+
/// return string representation
777+
fn as_string(&self) -> String {
778+
panic!("as_string not implemented for {:?}", self)
779+
}
780+
}
781+
782+
783+
/// A Wrapper type used for sending query parameters encoded as unknown.
784+
#[derive(Debug)]
785+
pub struct Unknown<'a>(pub &'a (dyn ToSql + Sync));
786+
787+
impl ToSql for Unknown<'_> {
788+
fn to_sql(
789+
&self,
790+
_ty: &Type,
791+
out: &mut BytesMut,
792+
) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
793+
match *self {
794+
Unknown(val) => {
795+
types::text_to_sql(&val.as_string(), out);
796+
Ok(IsNull::No)
797+
}
798+
}
799+
}
800+
801+
fn accepts(_ty: &Type) -> bool { true }
802+
803+
fn encode_format(&self) -> i16 { 0 }
804+
805+
to_sql_checked!();
772806
}
773807

774808
impl<'a, T> ToSql for &'a T
@@ -905,7 +939,7 @@ impl<'a> ToSql for &'a str {
905939
_ => false,
906940
}
907941
}
908-
942+
fn as_string(&self) -> String { self.to_string() }
909943
to_sql_checked!();
910944
}
911945

@@ -929,7 +963,7 @@ impl ToSql for String {
929963
fn accepts(ty: &Type) -> bool {
930964
<&str as ToSql>::accepts(ty)
931965
}
932-
966+
fn as_string(&self) -> String { self.clone() }
933967
to_sql_checked!();
934968
}
935969

@@ -944,6 +978,10 @@ macro_rules! simple_to {
944978
Ok(IsNull::No)
945979
}
946980

981+
fn as_string(&self) -> String {
982+
format!("{}", &self)
983+
}
984+
947985
accepts!($($expected),+);
948986

949987
to_sql_checked!();

tokio-postgres/src/query.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,8 @@ where
156156
I: IntoIterator<Item = P>,
157157
I::IntoIter: ExactSizeIterator,
158158
{
159+
160+
let (param_formats, params):(Vec<_>, Vec<_>) = params.into_iter().map(|p| (p.borrow_to_sql().encode_format(),p)).unzip();
159161
let params = params.into_iter();
160162

161163
assert!(
@@ -169,7 +171,7 @@ where
169171
let r = frontend::bind(
170172
portal,
171173
statement.name(),
172-
Some(1),
174+
param_formats,
173175
params.zip(statement.params()).enumerate(),
174176
|(idx, (param, ty)), buf| match param.borrow_to_sql().to_sql_checked(ty, buf) {
175177
Ok(IsNull::No) => Ok(postgres_protocol::IsNull::No),

0 commit comments

Comments
 (0)