Skip to content

Instantly share code, notes, and snippets.

@HarrisonHemstreet
Created September 14, 2023 00:22
Show Gist options
  • Save HarrisonHemstreet/0d89f2a9bdd257d08a10b7e33c5600ae to your computer and use it in GitHub Desktop.
Save HarrisonHemstreet/0d89f2a9bdd257d08a10b7e33c5600ae to your computer and use it in GitHub Desktop.
Rust, SQLx, PostgreSQL error when attempting to read a column of type enum
use serde::{Deserialize, Serialize};
#[derive(sqlx::Type, Serialize, Deserialize, Debug)]
#[sqlx(type_name = "status", rename_all = "lowercase")]
pub enum Status {
Active,
Inactive,
Suspended
}
#[derive(sqlx::FromRow, Serialize, Deserialize, Debug)]
pub struct TestEnum {
pub id: Option<i32>,
pub name: Option<String>,
pub enum_col: Status,
}
let returned: Result<TestEnum, Error> = sqlx::query_as::<_, TestEnum>(
r#"SELECT id, name, enum_col FROM test_enum LIMIT 1"#
)
.fetch_one(&pg)
.await;
/*
PostgreSQL:
CREATE TYPE status AS ENUM ('active', 'inactive', 'suspended');
CREATE TABLE test_enum (
id SERIAL PRIMARY KEY,
name TEXT,
enum_col status NOT NULL DEFAULT 'active'
);
insert into test_enum (name) values ('test');
*/
/*
should produce this error:
```bash
error: unsupported type status of column #3 ("enum_col")
--> src/routes/auth.rs:62:53
|
62 | let returned: Result<TestEnum, Error> = sqlx::query_as!(
| _____________________________________________________^
63 | | TestEnum,
64 | | r#"SELECT id, name, enum_col FROM test_enum LIMIT 1"#
65 | | )
| |_____________^
|
= note: this error originates in the macro `$crate::sqlx_macros::expand_query` which comes from the expansion of the macro `sqlx::query_as` (in Nightly builds, run with -Z macro-backtrace for more info)
```
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment