I need to implement the tokio_postgres::types::ToSql for an enum type (rust and db as enum implemented) and I had no idea how to ...
Example
enum Flag {MyFlag1, MyFlag2, MyFlag3};
// on postgres db :
// CREATE TYPE flag AS ENUM ('my_flag_1', 'my_flag_2', 'my_flag_3');
impl ToSql for Flag {
fn to_sql(&self, ty: &Type, out: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
// ???
}
fn accepts(ty: &Type) -> bool {
// ???
}
}
Can someone help me?
From the
postgres-typesdocumentation (which bothtokio-postgresandpostgresare based on so this will work for both crates):Postgres enums correspond to C-like enums in Rust:
and for naming:
You can use
#[postgres(name = "flag")]to adjust the enum name andrename_all = "snake_case"to adjust the variant names (for more extensive information see the docs I linked). In your case the final code would look like this:This will correctly parse your postgres enum created with