Skip to content

Implement ToSql for AsRef<str>? #280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
djc opened this issue Aug 2, 2017 · 1 comment
Closed

Implement ToSql for AsRef<str>? #280

djc opened this issue Aug 2, 2017 · 1 comment

Comments

@djc
Copy link
Contributor

djc commented Aug 2, 2017

I tried this:

diff --git a/postgres-shared/src/types/mod.rs b/postgres-shared/src/types/mod.rs
index 4937cc3..06d0814 100644
--- a/postgres-shared/src/types/mod.rs
+++ b/postgres-shared/src/types/mod.rs
@@ -618,9 +618,9 @@ impl ToSql for Vec<u8> {
     to_sql_checked!();
 }
 
-impl<'a> ToSql for &'a str {
+impl ToSql for AsRef<str> {
     fn to_sql(&self, _: &Type, w: &mut Vec<u8>) -> Result<IsNull, Box<Error + Sync + Send>> {
-        types::text_to_sql(*self, w);
+        types::text_to_sql(*self.as_ref(), w);
         Ok(IsNull::No)
     }
 
@@ -635,18 +635,6 @@ impl<'a> ToSql for &'a str {
     to_sql_checked!();
 }
 
-impl ToSql for String {
-    fn to_sql(&self, ty: &Type, w: &mut Vec<u8>) -> Result<IsNull, Box<Error + Sync + Send>> {
-        <&str as ToSql>::to_sql(&&**self, ty, w)
-    }
-
-    fn accepts(ty: &Type) -> bool {
-        <&str as ToSql>::accepts(ty)
-    }
-
-    to_sql_checked!();
-}
-
 macro_rules! simple_to {
     ($t:ty, $f:ident, $($expected:pat),+) => {
         impl ToSql for $t {

But that fails with the following:

error[E0277]: the trait bound `std::convert::AsRef<str> + 'static: std::fmt::Debug` is not satisfied
   --> postgres-shared/src/types/mod.rs:621:6
    |
621 | impl ToSql for AsRef<str> {
    |      ^^^^^ the trait `std::fmt::Debug` is not implemented for `std::convert::AsRef<str> + 'static`
    |
    = note: `std::convert::AsRef<str> + 'static` cannot be formatted using `:?`; if it is defined in your crate, add `#[derive(Debug)]` or manually implement it
    = note: required by `types::ToSql`

Which I'm not sure how to solve. I was wondering if we can make it more ergonomic to use Cow<str> in ToSql positions.

@sfackler
Copy link
Owner

sfackler commented Aug 2, 2017

That implementation is for AsRef<str> the trait, as opposed to types implementing AsRef<str>. I don't think either approach will work, unfortunately. It seems reasonable to just add a concrete implementation for Cow<str> though!

djc added a commit to djc/rust-postgres that referenced this issue Aug 3, 2017
sfackler added a commit that referenced this issue Aug 3, 2017
Add impl ToSql for Cow<str> (see #280)
@sfackler sfackler closed this as completed Aug 9, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants