Skip to content

Instantly share code, notes, and snippets.

@amitu
Last active June 28, 2020 01:34
Show Gist options
  • Save amitu/11177bffa3b26be4b91cb9b146ccc4f2 to your computer and use it in GitHub Desktop.
Save amitu/11177bffa3b26be4b91cb9b146ccc4f2 to your computer and use it in GitHub Desktop.
citext for diesel/postgresql
diesel print-schema > src/schema.rs
sed -i '' -e 's/Citext/mycrate::sql_types::Citext/g' src/schema.rs
use diesel::{
deserialize::{self, FromSql},
pg::Pg,
serialize::{self, Output, ToSql},
sql_types::Text,
};
use std::io::Write;
#[derive(Debug, Clone, Copy, SqlType, QueryId)]
#[postgres(type_name = "citext")]
pub struct Citext;
#[derive(Clone, Debug, FromSqlRow, AsExpression, PartialOrd, PartialEq)]
#[sql_type = "Citext"]
pub struct CiString(pub String);
pub fn citext(s: &str) -> CiString {
CiString(s.into())
}
impl ToSql<Citext, Pg> for CiString {
fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result {
ToSql::<Text, Pg>::to_sql(&self.0, out)
}
}
impl FromSql<Citext, Pg> for CiString {
fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
Ok(CiString(FromSql::<Text, Pg>::from_sql(bytes)?))
}
}
diesel::insert_into(users_namespace::table)
.values((
users_namespace::user_id.eq(Some(uid)),
users_namespace::namespace.eq(citext(&username)),
)).execute(conn)?;
@manonthemat
Copy link

Would love to have citext support for diesel via a crate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment