Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deserializing error for array of enum #940

Open
vargad opened this issue Aug 21, 2022 · 2 comments · May be fixed by #955
Open

Deserializing error for array of enum #940

vargad opened this issue Aug 21, 2022 · 2 comments · May be fixed by #955

Comments

@vargad
Copy link

vargad commented Aug 21, 2022

I'm trying to get an array of enum, but it fails on deserialization. Array seems to work with other types, including Vec and even Vec.

use postgres_types::{ToSql, FromSql};
use postgres::{Client, NoTls, Error};

#[derive(Clone, Debug, ToSql, FromSql)]
pub(crate) enum MyTag
{
    Happy,
    Nature,
}

fn main() -> Result<(), Error>
{
    let mut client = Client::connect("postgresql://postgres@localhost:5432/enum_test", NoTls)?;

    let mut tr = client.transaction()?;

    tr.batch_execute("
            CREATE TYPE my_tag_type AS ENUM ('Happy', 'Squirrel', 'Nature');
            CREATE TABLE test (
                tags_str text[],
                tags_enum my_tag_type[]
            );
            INSERT INTO test (tags_str, tags_enum)
            VALUES (
                ARRAY['Happy', 'Squirrel'],
                ARRAY['Happy', 'Squirrel']::my_tag_type[]
            );
        ")?;

    let results = tr.query("SELECT tags_str, tags_enum FROM test;", &[])?;

    for result in results
    {
        let tags_str: Vec<String> = result.get("tags_str");
        println!("{:?}", tags_str);

        let tags_enum: Vec<MyTag> = result.get("tags_enum");
        println!("{:?}", tags_enum);
    }

    tr.rollback()?;

    Ok(())
}
["Happy", "Squirrel"]
thread 'main' panicked at 'error retrieving column tags_enum:
error deserializing column 1: cannot convert between the Rust type `alloc::vec::Vec<enum_test::MyTag>` and the Postgres type `_my_tag_type`',
/home/vargad/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-postgres-0.7.6/src/row.rs:151:25
@sfackler
Copy link
Owner

The deriving logic validates the name of the Postgres type and its variants against your enum. Either change the Postgres type to CREATE TYPE "MyTag" AS ENUM ... or add a #[postgres(name = "my_tag_type")] to the enum declaration. You'll also need to add the Squirrel variant to the Rust type.

@vargad
Copy link
Author

vargad commented Aug 23, 2022

Thank you @sfackler, it indeed works. Let me see how can I help improving the docs so less likely to miss this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants