Skip to content

Implement ToSql for AsRef<str>? #280

Closed
@djc

Description

@djc

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions