Enums

Define type-safe enumerated values for your database fields with compile-time checking.

What are Enums?

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.

Benefits

  • • Type-safe in Rust code
  • • Database-level validation
  • • Self-documenting schema
  • • Compile-time error checking
  • • IDE autocompletion

Use Cases

  • • User roles and permissions
  • • Order/payment status
  • • Content visibility
  • • Notification types
  • • Category classifications

Basic Definition

Define an enum with the enum keyword followed by the name and values in curly braces. Values use SCREAMING_SNAKE_CASE by convention.

Custom Database Values

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.

Documented Enums

Add documentation comments to your enums and their values using triple-slash comments. This documentation is preserved in generated code and API schemas.

Complete Example

Here's a realistic example showing multiple enums used together in a notification system:

Enum Arrays

Fields can hold arrays of enum values, allowing multiple selections. Use GIN indexes in PostgreSQL for efficient querying of enum arrays.

Database Representation

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

Using Enums in Queries

Prax generates type-safe Rust enums that you can use directly in your queries:

Best Practices

Naming Conventions

Use PascalCase for enum names and SCREAMING_SNAKE_CASE for values. Be descriptive and consistent across your schema.

Adding New Values

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.

Default 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.