mirror of
https://github.com/launchbadge/sqlx.git
synced 2026-03-20 09:04:10 +00:00
feat: Text adapter (#2894)
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
use sqlx_core::bytes::Buf;
|
||||
use sqlx_core::types::Text;
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::decode::Decode;
|
||||
@@ -67,6 +68,16 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PgHasArrayType for Text<T> {
|
||||
fn array_type_info() -> PgTypeInfo {
|
||||
String::array_type_info()
|
||||
}
|
||||
|
||||
fn array_compatible(ty: &PgTypeInfo) -> bool {
|
||||
String::array_compatible(ty)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Type<Postgres> for [T]
|
||||
where
|
||||
T: PgHasArrayType,
|
||||
|
||||
@@ -193,6 +193,7 @@ mod oid;
|
||||
mod range;
|
||||
mod record;
|
||||
mod str;
|
||||
mod text;
|
||||
mod tuple;
|
||||
mod void;
|
||||
|
||||
|
||||
50
sqlx-postgres/src/types/text.rs
Normal file
50
sqlx-postgres/src/types/text.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use crate::{PgArgumentBuffer, PgTypeInfo, PgValueRef, Postgres};
|
||||
use sqlx_core::decode::Decode;
|
||||
use sqlx_core::encode::{Encode, IsNull};
|
||||
use sqlx_core::error::BoxDynError;
|
||||
use sqlx_core::types::{Text, Type};
|
||||
use std::fmt::Display;
|
||||
use std::str::FromStr;
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
impl<T> Type<Postgres> for Text<T> {
|
||||
fn type_info() -> PgTypeInfo {
|
||||
<String as Type<Postgres>>::type_info()
|
||||
}
|
||||
|
||||
fn compatible(ty: &PgTypeInfo) -> bool {
|
||||
<String as Type<Postgres>>::compatible(ty)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'q, T> Encode<'q, Postgres> for Text<T>
|
||||
where
|
||||
T: Display,
|
||||
{
|
||||
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
|
||||
// Unfortunately, our API design doesn't give us a way to bubble up the error here.
|
||||
//
|
||||
// Fortunately, writing to `Vec<u8>` is infallible so the only possible source of
|
||||
// errors is from the implementation of `Display::fmt()` itself,
|
||||
// where the onus is on the user.
|
||||
//
|
||||
// The blanket impl of `ToString` also panics if there's an error, so this is not
|
||||
// unprecedented.
|
||||
//
|
||||
// However, the panic should be documented anyway.
|
||||
write!(**buf, "{}", self.0).expect("unexpected error from `Display::fmt()`");
|
||||
IsNull::No
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r, T> Decode<'r, Postgres> for Text<T>
|
||||
where
|
||||
T: FromStr,
|
||||
BoxDynError: From<<T as FromStr>::Err>,
|
||||
{
|
||||
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
let s: &str = Decode::<Postgres>::decode(value)?;
|
||||
Ok(Self(s.parse()?))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user