如何为枚举类型(rust、postgres)实现 tokio_postgres::types::ToSql

Sia*_*sei 5 rust rust-tokio tokio-postgres

我需要为枚举类型实现 tokio_postgres::types::ToSql (rust 和 db 作为枚举实现),但我不知道如何...

例子

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 {
    // ???
  }
}
Run Code Online (Sandbox Code Playgroud)

有人能帮我吗?

Ein*_*che 0

postgres-types文档中( 和 均tokio-postgres基于postgres该文档,因此这适用于两个板条箱):

Postgres 枚举对应于 Rust 中类似 C 的枚举:

CREATE TYPE "Mood" AS ENUM (
    'Sad',
    'Ok',
    'Happy'
);
Run Code Online (Sandbox Code Playgroud)
use postgres_types::{ToSql, FromSql};

#[derive(Debug, ToSql, FromSql)]
enum Mood {
    Sad,
    Ok,
    Happy,
}
Run Code Online (Sandbox Code Playgroud)

以及命名

您可以用来#[postgres(name = "flag")]调整枚举名称并rename_all = "snake_case"调整变体名称(有关更广泛的信息,请参阅我链接的文档)。在您的情况下,最终代码将如下所示:

// tokio_postgres reexports postgres_types as the types module
use tokio_postgres::types::ToSql;

#[derive(Debug, ToSql)] // ToSql requires Debug
#[postgres(name = "flag", rename_all = "snake_case")]
enum Flag {
    MyFlag1, 
    MyFlag2, 
    MyFlag3
}
Run Code Online (Sandbox Code Playgroud)

这将正确解析使用创建的 postgres 枚举

CREATE TYPE flag AS ENUM ('my_flag_1', 'my_flag_2', 'my_flag_3');
Run Code Online (Sandbox Code Playgroud)