Verified Solution[StackOverflow/rust] trouble getting sqlx #[derive(sqlx::Type)] to work with a rust enum using MySQL/MariaDB
Sponsored Content
### ROOT CAUSE
The issue arises because SQLx requires explicit configuration to handle custom Rust enums as database types, especially with MySQL/MariaDB. By default, SQLx doesn't automatically map Rust enums to database ENUM types, leading to deserialization errors. The enum must be explicitly registered with SQLx using `#[derive(sqlx::Type)]` and `#[sqlx(type_name = "...")]`.
---
### CODE FIX
1. **Derive `sqlx::Type` and specify the database type name**:
```rust
use sqlx::Type;
#[derive(sqlx::Type)]
#[sqlx(type_name = "status_enum")] // Match your DB ENUM name
enum Status {
Active,
Inactive,
Pending,
}
```
2. **Ensure the database ENUM exists**:
Create the ENUM in your MySQL/MariaDB database:
```sql
CREATE ENUM status_enum AS ENUM('Active', 'Inactive', 'Pending');
```
3. **Use the enum in a struct (if needed)**:
```rust
#[derive(sqlx::FromRow)]
struct User {
id: i32,
status: Status, // Works with the derived Type
}
```
4. **Handle dynamic values** (if the enum is used in queries):
```rust
let param: Status = Status::Active;
let row = sqlx::query_as!(User, "SELECT * FROM users WHERE status = ?", param)
.fetch_one(&pool)
.await?;
```
**Key Notes**:
- The `type_name` must match the database ENUM name exactly (case-sensitive).
- Use `#[try_into]` if deserializing from database values:
```rust
impl TryFrom for Status {
type Error = sqlx::Error;
fn try_from(value: sqlx::types::Enum) -> Result {
// Map database values to Rust enum
match value.as_str()? {
"Active" => Ok(Status::Active),
// ... other mappings
}
}
}
```
This ensures SQLx properly serializes/deserializes the enum between Rust and MySQL/MariaDB.
Deploy on DigitalOcean ($200 Credit)
Related Fixes
[StackOverflow/reactjs] React form with <Popup> alert message instead of alert()
[StackOverflow/kubernetes] How to create a kubernetes configmap from .env file through a yaml spec?
[StackOverflow/rust] Rust WebSocket Client An established connection was aborted by the software in your host machine. (os error 10053)