Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions sqlx-core/src/any/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,44 @@ impl<'r> ValueRef<'r> for AnyValueRef<'r> {
}
}
}

macro_rules! impl_try_from_any_value_ref {
($(
#[cfg(feature = $feature:literal)]
$db_name:ident => $value_ref:ty,
)*) => {
$(
#[cfg(feature = $feature)]
impl<'r> TryFrom<AnyValueRef<'r>> for $value_ref {
type Error = crate::error::Error;

fn try_from(value: AnyValueRef<'r>) -> Result<Self, Self::Error> {
#[allow(unreachable_patterns)]
match value.kind {
AnyValueRefKind::$db_name(value) => Ok(value),
_ => Err(crate::error::Error::Configuration(
format!("Expected {}, got {:?}", stringify!($value_ref), value.type_info()).into(),
)),
}
}
}
)*
};
}

impl_try_from_any_value_ref! {
#[cfg(feature = "postgres")]
Postgres => PgValueRef<'r>,

#[cfg(feature = "mysql")]
MySql => MySqlValueRef<'r>,

#[cfg(feature = "sqlite")]
Sqlite => SqliteValueRef<'r>,

#[cfg(feature = "mssql")]
Mssql => MssqlValueRef<'r>,

#[cfg(feature = "odbc")]
Odbc => OdbcValueRef<'r>,
}
20 changes: 20 additions & 0 deletions tests/any/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,3 +337,23 @@ async fn it_fails_to_prepare_invalid_statements() -> anyhow::Result<()> {

Ok(())
}

#[sqlx_macros::test]
#[cfg(feature = "postgres")]
async fn it_converts_any_value_ref_to_specific_postgres_types() -> anyhow::Result<()> {
let mut conn = new::<Any>().await?;
let dbms_name = conn.dbms_name().await.unwrap_or_default().to_lowercase();

if !dbms_name.contains("postgres") {
return Ok(());
}

use sqlx_oldapi::postgres::{types::PgRange, PgValueRef, Postgres};
use std::ops::Bound;
let row = conn.fetch_one("SELECT int4range(1, 10)").await?;
let pgrange: PgValueRef<'_> = row.try_get_raw(0)?.try_into()?;
let decoded: PgRange<i32> = <PgRange<i32> as Decode<'_, Postgres>>::decode(pgrange).unwrap();
assert_eq!(decoded.start, Bound::Included(1));
assert_eq!(decoded.end, Bound::Excluded(10));
Ok(())
}
Loading