|
| 1 | +use std::fmt; |
| 2 | +use std::fmt::{Debug, Display, Formatter}; |
| 3 | +use std::ops::Deref; |
| 4 | +use std::str::FromStr; |
| 5 | +use sqlx_core::decode::Decode; |
| 6 | +use sqlx_core::encode::{Encode, IsNull}; |
| 7 | +use sqlx_core::error::BoxDynError; |
| 8 | +use sqlx_core::types::Type; |
| 9 | +use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueRef, Postgres}; |
| 10 | +use crate::types::array_compatible; |
| 11 | + |
| 12 | +/// Text type for case insensitive searching in Postgres. |
| 13 | +/// |
| 14 | +/// See https://www.postgresql.org/docs/current/citext.html |
| 15 | +/// |
| 16 | +/// ### Note: Extension Required |
| 17 | +/// The `citext` extension is not enabled by default in Postgres. You will need to do so explicitly: |
| 18 | +/// |
| 19 | +/// ```ignore |
| 20 | +/// CREATE EXTENSION IF NOT EXISTS "citext"; |
| 21 | +/// ``` |
| 22 | +
|
| 23 | +#[derive(Clone, Debug, Default, PartialEq)] |
| 24 | +pub struct PgCitext(String); |
| 25 | + |
| 26 | +impl PgCitext { |
| 27 | + pub fn new(s: String) -> Self { |
| 28 | + Self(s) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl Type<Postgres> for PgCitext { |
| 33 | + fn type_info() -> PgTypeInfo { |
| 34 | + // Since `ltree` is enabled by an extension, it does not have a stable OID. |
| 35 | + PgTypeInfo::with_name("citext") |
| 36 | + } |
| 37 | + |
| 38 | + fn compatible(ty: &PgTypeInfo) -> bool { |
| 39 | + <&str as Type<Postgres>>::compatible(ty) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl Deref for PgCitext { |
| 44 | + type Target = str; |
| 45 | + |
| 46 | + fn deref(&self) -> &Self::Target { |
| 47 | + self.0.as_str() |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl From<String> for PgCitext { |
| 52 | + fn from(value: String) -> Self { |
| 53 | + Self::new(value) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl FromStr for PgCitext { |
| 58 | + type Err = core::convert::Infallible; |
| 59 | + |
| 60 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 61 | + Ok(PgCitext(s.parse()?)) |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +impl Display for PgCitext { |
| 66 | + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { |
| 67 | + write!(f, "{}", self.0) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +impl PgHasArrayType for PgCitext { |
| 72 | + fn array_type_info() -> PgTypeInfo { |
| 73 | + PgTypeInfo::with_name("_citext") |
| 74 | + } |
| 75 | + |
| 76 | + fn array_compatible(ty: &PgTypeInfo) -> bool { |
| 77 | + array_compatible::<&str>(ty) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | + |
| 82 | +impl Encode<'_, Postgres> for PgCitext { |
| 83 | + fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull { |
| 84 | + <&str as Encode<Postgres>>::encode(&**self, buf) |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +impl Decode<'_, Postgres> for PgCitext { |
| 89 | + fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> { |
| 90 | + Ok(PgCitext(value.as_str()?.to_owned())) |
| 91 | + } |
| 92 | +} |
0 commit comments