Skip to content
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

feat: impl Encode, Decode and Type for Cow<T> where T: Encode + Decode + Type #3102

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 14 additions & 1 deletion sqlx-core/src/decode.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
//! Provides [`Decode`] for decoding values from the database.

use std::borrow::Cow;

use crate::database::{Database, HasValueRef};
use crate::error::BoxDynError;

use crate::value::ValueRef;

/// A type that can be decoded from the database.
Expand Down Expand Up @@ -77,3 +78,15 @@ where
}
}
}

impl<'r, DB, T> Decode<'r, DB> for Cow<'_, T>
where
T: ToOwned + ?Sized + 'r,
T::Owned: Decode<'r, DB>,
DB: Database,
{
fn decode(value: <DB as HasValueRef<'r>>::ValueRef) -> Result<Self, BoxDynError> {
let decoded = <T::Owned as Decode<'r, DB>>::decode(value)?;
Ok(Cow::Owned(decoded))
}
}
28 changes: 28 additions & 0 deletions sqlx-core/src/encode.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//! Provides [`Encode`] for encoding values for the database.

use std::borrow::Cow;
use std::mem;
use std::ops::Deref;

use crate::database::{Database, HasArguments};

Expand Down Expand Up @@ -117,3 +119,29 @@ macro_rules! impl_encode_for_option {
}
};
}

impl<'q, T, DB: Database> Encode<'q, DB> for Cow<'_, T>
where
T: ToOwned + ?Sized,
T: Encode<'q, DB>,
{
#[inline]
fn encode(self, buf: &mut <DB as HasArguments<'q>>::ArgumentBuffer) -> IsNull {
<T as Encode<'q, DB>>::encode_by_ref(self.deref(), buf)
}

#[inline]
fn encode_by_ref(&self, buf: &mut <DB as HasArguments<'q>>::ArgumentBuffer) -> IsNull {
<T as Encode<'q, DB>>::encode_by_ref(self, buf)
}

#[inline]
fn produces(&self) -> Option<DB::TypeInfo> {
<T as Encode<'q, DB>>::produces(self)
}

#[inline]
fn size_hint(&self) -> usize {
<T as Encode<'q, DB>>::size_hint(self)
}
}
3 changes: 2 additions & 1 deletion sqlx-core/src/migrate/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ pub struct ResolveError {

// FIXME: paths should just be part of `Migration` but we can't add a field backwards compatibly
// since it's `#[non_exhaustive]`.
pub fn resolve_blocking(path: PathBuf) -> Result<Vec<(Migration, PathBuf)>, ResolveError> {
pub fn resolve_blocking(path: impl AsRef<Path>) -> Result<Vec<(Migration, PathBuf)>, ResolveError> {
let path = path.as_ref().to_path_buf();
let mut s = fs::read_dir(&path).map_err(|e| ResolveError {
message: format!("error reading migration directory {}: {e}", path.display()),
source: Some(e),
Expand Down
16 changes: 16 additions & 0 deletions sqlx-core/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
//!

use crate::database::Database;
use std::borrow::Cow;

#[cfg(feature = "bstr")]
#[cfg_attr(docsrs, doc(cfg(feature = "bstr")))]
Expand Down Expand Up @@ -237,3 +238,18 @@ impl<T: Type<DB>, DB: Database> Type<DB> for Option<T> {
<T as Type<DB>>::compatible(ty)
}
}

impl<T, DB> Type<DB> for Cow<'_, T>
where
T: ToOwned + ?Sized,
T::Owned: Type<DB>,
DB: Database,
{
fn type_info() -> DB::TypeInfo {
<T::Owned as Type<DB>>::type_info()
}

fn compatible(ty: &DB::TypeInfo) -> bool {
<T::Owned as Type<DB>>::compatible(ty)
}
}
2 changes: 1 addition & 1 deletion sqlx-macros-core/src/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ pub(crate) fn expand_migrator(path: &Path) -> crate::Result<TokenStream> {
})?;

// Use the same code path to resolve migrations at compile time and runtime.
let migrations = sqlx_core::migrate::resolve_blocking(path)?
let migrations = sqlx_core::migrate::resolve_blocking(&path)?
.into_iter()
.map(|(migration, path)| QuoteMigration { migration, path });

Expand Down
25 changes: 0 additions & 25 deletions sqlx-mysql/src/types/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use crate::protocol::text::{ColumnFlags, ColumnType};
use crate::types::Type;
use crate::{MySql, MySqlTypeInfo, MySqlValueRef};
use std::borrow::Cow;

Check failure on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / Check (async-std, none)

unused import: `std::borrow::Cow`

Check failure on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / Check (tokio, none)

unused import: `std::borrow::Cow`

Check failure on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / Check (async-std, rustls)

unused import: `std::borrow::Cow`

Check warning on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / Unit Test (tokio, none)

unused import: `std::borrow::Cow`

Check warning on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / Unit Test (async-std, none)

unused import: `std::borrow::Cow`

Check warning on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / Unit Test (async-std, rustls)

unused import: `std::borrow::Cow`

Check warning on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / Unit Test (tokio, rustls)

unused import: `std::borrow::Cow`

Check warning on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / Unit Test (tokio, native-tls)

unused import: `std::borrow::Cow`

Check failure on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / Build SQLx CLI

unused import: `std::borrow::Cow`

Check warning on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / Unit Test (async-std, native-tls)

unused import: `std::borrow::Cow`

Check warning on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / CLI Unit Test

unused import: `std::borrow::Cow`

Check warning on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / CLI Binaries (ubuntu-latest)

unused import: `std::borrow::Cow`

Check warning on line 8 in sqlx-mysql/src/types/str.rs

View workflow job for this annotation

GitHub Actions / CLI Binaries (windows-latest)

unused import: `std::borrow::Cow`

const COLLATE_UTF8_GENERAL_CI: u16 = 33;
const COLLATE_UTF8_UNICODE_CI: u16 = 192;
Expand Down Expand Up @@ -105,28 +105,3 @@
<&str as Decode<MySql>>::decode(value).map(ToOwned::to_owned)
}
}

impl Type<MySql> for Cow<'_, str> {
fn type_info() -> MySqlTypeInfo {
<&str as Type<MySql>>::type_info()
}

fn compatible(ty: &MySqlTypeInfo) -> bool {
<&str as Type<MySql>>::compatible(ty)
}
}

impl Encode<'_, MySql> for Cow<'_, str> {
fn encode_by_ref(&self, buf: &mut Vec<u8>) -> IsNull {
match self {
Cow::Borrowed(str) => <&str as Encode<MySql>>::encode(*str, buf),
Cow::Owned(str) => <&str as Encode<MySql>>::encode(&**str, buf),
}
}
}

impl<'r> Decode<'r, MySql> for Cow<'r, str> {
fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
value.as_str().map(Cow::Borrowed)
}
}
25 changes: 0 additions & 25 deletions sqlx-postgres/src/types/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,6 @@ impl Type<Postgres> for str {
}
}

impl Type<Postgres> for Cow<'_, str> {
fn type_info() -> PgTypeInfo {
<&str as Type<Postgres>>::type_info()
}

fn compatible(ty: &PgTypeInfo) -> bool {
<&str as Type<Postgres>>::compatible(ty)
}
}

impl Type<Postgres> for Box<str> {
fn type_info() -> PgTypeInfo {
<&str as Type<Postgres>>::type_info()
Expand Down Expand Up @@ -102,15 +92,6 @@ impl Encode<'_, Postgres> for &'_ str {
}
}

impl Encode<'_, Postgres> for Cow<'_, str> {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
match self {
Cow::Borrowed(str) => <&str as Encode<Postgres>>::encode(*str, buf),
Cow::Owned(str) => <&str as Encode<Postgres>>::encode(&**str, buf),
}
}
}

impl Encode<'_, Postgres> for Box<str> {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
<&str as Encode<Postgres>>::encode(&**self, buf)
Expand All @@ -129,12 +110,6 @@ impl<'r> Decode<'r, Postgres> for &'r str {
}
}

impl<'r> Decode<'r, Postgres> for Cow<'r, str> {
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
Ok(Cow::Borrowed(value.as_str()?))
}
}

impl<'r> Decode<'r, Postgres> for Box<str> {
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
Ok(Box::from(value.as_str()?))
Expand Down
30 changes: 0 additions & 30 deletions sqlx-sqlite/src/types/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,33 +80,3 @@ impl<'r> Decode<'r, Sqlite> for String {
value.text().map(ToOwned::to_owned)
}
}

impl Type<Sqlite> for Cow<'_, str> {
fn type_info() -> SqliteTypeInfo {
<&str as Type<Sqlite>>::type_info()
}

fn compatible(ty: &SqliteTypeInfo) -> bool {
<&str as Type<Sqlite>>::compatible(ty)
}
}

impl<'q> Encode<'q, Sqlite> for Cow<'q, str> {
fn encode(self, args: &mut Vec<SqliteArgumentValue<'q>>) -> IsNull {
args.push(SqliteArgumentValue::Text(self));

IsNull::No
}

fn encode_by_ref(&self, args: &mut Vec<SqliteArgumentValue<'q>>) -> IsNull {
args.push(SqliteArgumentValue::Text(self.clone()));

IsNull::No
}
}

impl<'r> Decode<'r, Sqlite> for Cow<'r, str> {
fn decode(value: SqliteValueRef<'r>) -> Result<Self, BoxDynError> {
value.text().map(Cow::Borrowed)
}
}