gorm/sql/
sql_enum.rs

1use std::fmt::Display;
2
3use super::IntoSqlType;
4use crate::error::*;
5
6/// An enum consisting of only empty variants, backed up by an integer type,
7/// which can be used in sql statements.
8pub trait SqlEnum: Sized + 'static + Clone {
9    /// The smallest integer type needed to represent this enum.
10    type IntegerType: Display + TryInto<usize> + IntoSqlType;
11
12    // The name of the enum.
13    const ENUM_NAME: &'static str;
14
15    /// The variants of the enum, in order.
16    const VARIANTS_IN_ORDER: &'static [Self];
17
18    /// Converts an integer to a variant of this enum.
19    fn from_integer(integer: Self::IntegerType) -> Result<Self> {
20        let err = Error::NoSuchEnumVariant {
21            enum_name: Self::ENUM_NAME,
22            integer_string: integer.to_string(),
23        };
24
25        let as_usize: usize = match integer.try_into() {
26            Ok(v) => v,
27            Err(_) => return Err(err),
28        };
29
30        Self::VARIANTS_IN_ORDER.get(as_usize).cloned().ok_or(err)
31    }
32
33    /// Converts a variant of this enum to an integer.
34    fn to_integer(self) -> Self::IntegerType;
35}