Define type-safe enumerated values for your database fields with compile-time checking.
Enums (enumerations) define a fixed set of allowed values for a field. They provide type safety at both the database level and in your Rust code, preventing invalid values from being stored.
Define an enum with the enum keyword
followed by the name and values in curly braces. Values use SCREAMING_SNAKE_CASE by convention.
Use @map() to store different values
in the database than the enum variant name. This is useful when integrating with existing databases
or when you need human-readable database values.
Add documentation comments to your enums and their values using triple-slash comments. This documentation is preserved in generated code and API schemas.
Here's a realistic example showing multiple enums used together in a notification system:
Fields can hold arrays of enum values, allowing multiple selections. Use GIN indexes in PostgreSQL for efficient querying of enum arrays.
Prax handles enum storage differently based on the database provider:
| Database | Implementation | Notes |
|---|---|---|
PostgreSQL |
Native ENUM type | Best performance, type-safe at DB level |
MySQL |
ENUM column type | Compact storage, limited to 65,535 values |
SQLite |
TEXT with CHECK constraint | Validation at insert/update time |
Prax generates type-safe Rust enums that you can use directly in your queries:
Use PascalCase for enum names and
SCREAMING_SNAKE_CASE for values.
Be descriptive and consistent across your schema.
When adding new enum values, always add them at the end. Removing or reordering values may cause issues with existing data. Consider using soft-deprecation with documentation instead of removing values.
Always consider whether a field should have a default enum value. This makes the API easier to use and reduces required fields during record creation.