You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm trying to persist a list of enums on an object. I'm getting a confusing error that I don't understand.
Use following code:
use std::io::Write;use anyhow::Result;use diesel::deserialize;use diesel::deserialize::FromSql;use diesel::deserialize::FromSqlRow;use diesel::expression::AsExpression;use diesel::pg::Pg;use diesel::pg::PgValue;use diesel::prelude::*;use diesel::serialize;use diesel::serialize::IsNull;use diesel::serialize::Output;use diesel::serialize::ToSql;use diesel_async::{AsyncConnection,AsyncPgConnection,RunQueryDsl,SimpleAsyncConnection};pubmod postgres {pubmod schema {pubmod sql_types {#[derive(diesel::sql_types::SqlType)]#[diesel(postgres_type(name = "action"))]pubstructAction;}
diesel::table! {use diesel::sql_types::*;
usesuper::sql_types::Action;
directory_actions (id){
id -> Int4,
credentials_id -> Int4,
#[max_length = 255]
directory_path -> Varchar,
actions -> Array<Nullable<Action>>,
}}}}#[derive(Debug,FromSqlRow,AsExpression,Clone)]#[diesel(sql_type = crate::postgres::schema::sql_types::Action)]pubenumAction{Read,Write,Delete,List,Admin,}// Implement ToSql for the custom enumimplToSql<crate::postgres::schema::sql_types::Action,Pg>forAction{fnto_sql<'b>(&'b self,out:&mutOutput<'b,'_,Pg>) -> serialize::Result{match*self{Action::Read => out.write_all(b"read")?,Action::Write => out.write_all(b"write")?,Action::Delete => out.write_all(b"delete")?,Action::List => out.write_all(b"list")?,Action::Admin => out.write_all(b"admin")?,}Ok(IsNull::No)}}// Implement FromSql for the custom enumimplFromSql<crate::postgres::schema::sql_types::Action,Pg>forAction{fnfrom_sql(bytes:PgValue) -> deserialize::Result<Self>{match bytes.as_bytes(){b"read" => Ok(Action::Read),b"write" => Ok(Action::Write),b"delete" => Ok(Action::Delete),b"list" => Ok(Action::List),b"admin" => Ok(Action::Admin),
_ => Err("Unrecognized enum variant".into()),}}}#[derive(Debug,Identifiable,Queryable,Selectable,Insertable)]#[diesel(table_name = crate::postgres::schema::directory_actions)]#[diesel(check_for_backend(diesel::pg::Pg))]pubstructDirectoryActions{pubid:i32,pubcredentials_id:i32,pubdirectory_path:String,pubactions:Vec<Option<Action>>,}#[tokio::main]asyncfnmain() -> Result<()>{letmut conn =
AsyncPgConnection::establish("postgres://localhost/diesel_test").await.unwrap();
conn.begin_test_transaction().await.unwrap();
conn.batch_execute("CREATE TYPE Action AS ENUM ('read', 'write', 'delete', 'list', 'admin');CREATE TABLE directory_actions ( id SERIAL PRIMARY KEY, credentials_id INTEGER NOT NULL, directory_path VARCHAR(255) NOT NULL, actions Action[] NOT NULL check (actions <> '{}' and array_position(actions, null) is null) );",).await.unwrap();let directory_actions = vec![DirectoryActions{
id: 1,
credentials_id: 1,
directory_path: "".into(),
actions: vec![Some(Action::Read)],
}];
diesel::insert_into(crate::postgres::schema::directory_actions::table).values(&directory_actions).execute(&mut conn).await.unwrap();let res = crate::postgres::schema::directory_actions::table
.select(DirectoryActions::as_select()).load(&mut conn).await.unwrap();dbg!(res);Ok(())}
Cargo.toml:
[dependencies]
tokio = { version = "1.32.0", features = ["full"] }
diesel = { version = "2.1.3", features = ["postgres", "chrono"] }
diesel-async = { version = "0.4.1", features = [
"postgres",
"deadpool",
"async-connection-wrapper",
"tokio"
] }
anyhow = "1.0"
What are you trying to accomplish?
Persist a list of enums
What is the expected output?
No error
What is the actual output?
thread 'main' panicked at src/main.rs:122:10:
called Result::unwrap() on an Err value: SerializationError(FailedToLookupTypeError(PgMetadataCacheKey { schema: None, type_name: "action" }))
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace
Are you seeing any additional errors?
No
The text was updated successfully, but these errors were encountered:
Setup
Versions
Feature Flags
Problem Description
I'm trying to persist a list of enums on an object. I'm getting a confusing error that I don't understand.
Use following code:
Cargo.toml:
What are you trying to accomplish?
Persist a list of enums
What is the expected output?
No error
What is the actual output?
thread 'main' panicked at src/main.rs:122:10:
called
Result::unwrap()
on anErr
value: SerializationError(FailedToLookupTypeError(PgMetadataCacheKey { schema: None, type_name: "action" }))note: run with
RUST_BACKTRACE=1
environment variable to display a backtraceAre you seeing any additional errors?
No
The text was updated successfully, but these errors were encountered: