This crate allows one to automatically derive the Diesel boilerplate necessary to use Rust enums directly with Postgres databases.
It is a fairly literal translation of this code from the Diesel test suite.
```rust // define your enum
pub enum MyEnum { // All enum variants must be fieldless Foo, Bar, BazQuxx, }
// define your table table! { use diesel::types::Integer; use super::MyType; mytable { id -> Integer, myenum -> MyType, // A Diesel type "MyType" has been created corresponding to my_type } }
// define a struct with which to populate/query the table
struct MyRow { id: i32, my_enum: MyEnum, } ```
SQL to create corresponding table:
sql
CREATE TYPE my_type AS ENUM ('foo', 'bar', 'baz_quxx');
-- Note: the postgres ENUM values must correspond to snake_cased Rust enum variant names
CREATE TABLE my_table (
id SERIAL PRIMARY KEY,
my_enum my_type NOT NULL
);
Now we can insert and retrieve MyEnum directly:
rust
let data = vec![
MyRow {
id: 1,
my_enum: MyEnum::Foo,
},
MyRow {
id: 2,
my_enum: MyEnum::BazQuxx,
},
];
let connection = PgConnection::establish(/*...*/).unwrap();
let inserted = insert_into(my_table::table)
.values(&data)
.get_results(&connection)
.unwrap();
assert_eq!(data, inserted);
See this test for a full working example.
Licensed under either of these: