Create Enum
You can generate SQL statement to create database tables with enum columns via the Schema
helper struct.
String & Integer Enum
This is just an ordinary string / integer column that maps to a Rust enum. Example entity definition:
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(schema_name = "public", table_name = "active_enum")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub category: Option<Category>,
pub color: Option<Color>,
}
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = "String(StringLen::N(1))")]
pub enum Category {
#[sea_orm(string_value = "B")]
Big,
#[sea_orm(string_value = "S")]
Small,
}
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum)]
#[sea_orm(rs_type = "i32", db_type = "Integer")]
pub enum Color {
#[sea_orm(num_value = 0)]
Black,
#[sea_orm(num_value = 1)]
White,
}
As an illustration, the enums are just ordinary database columns.
use sea_orm::{sea_query, Schema};
let builder = db.get_database_backend();
let schema = Schema::new(builder);
assert_eq!(
builder.build(&schema.create_table_from_entity(active_enum::Entity)),
builder.build(
&sea_query::Table::create()
.table(active_enum::Entity.table_ref())
.col(
sea_query::ColumnDef::new(active_enum::Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(sea_query::ColumnDef::new(active_enum::Column::Category).string_len(1))
.col(sea_query::ColumnDef::new(active_enum::Column::Color).integer())
.to_owned()
)
);
Note that non-UAX#31 compliant characters would be converted as illustrated below.
#[derive(Clone, Debug, PartialEq, EnumIter, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = "String(StringLen::None)")]
pub enum StringValue {
#[sea_orm(string_value = "")]
Member1,
#[sea_orm(string_value = "$")]
Member2,
#[sea_orm(string_value = "$$")]
Member3,
#[sea_orm(string_value = "AB")]
Member4,
#[sea_orm(string_value = "A_B")]
Member5,
#[sea_orm(string_value = "A$B")]
Member6,
#[sea_orm(string_value = "0 123")]
Member7,
}
// The following will be generated
pub enum StringValueVariant {
__Empty,
_0x24,
_0x240x24,
Ab,
A0x5Fb,
A0x24B,
_0x300x20123,
}
Native Database Enum
Enum support is different across databases. Let's go through them one-by-one.
Consider the following entity:
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(schema_name = "public", table_name = "active_enum")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub tea: Option<Tea>,
}
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "tea")]
pub enum Tea {
#[sea_orm(string_value = "EverydayTea")]
EverydayTea,
#[sea_orm(string_value = "BreakfastTea")]
BreakfastTea,
}
Note the db_type
and extra enum_name
attributes.
PostgreSQL
Enums in PostgreSQL are defined by TypeCreateStatement
, which can be created from an Entity
with the Schema::create_enum_from_entity
method.
You can also create it from ActiveEnum
with the Schema::create_enum_from_active_enum
method.
use sea_orm::{Schema, Statement};
let db_postgres = DbBackend::Postgres;
let schema = Schema::new(db_postgres);
assert_eq!(
schema
.create_enum_from_entity(active_enum::Entity)
.iter()
.map(|stmt| db_postgres.build(stmt))
.collect::<Vec<_>>(),
[Statement::from_string(
db_postgres,
r#"CREATE TYPE "tea" AS ENUM ('EverydayTea', 'BreakfastTea')"#
),]
);
assert_eq!(
db_postgres.build(&schema.create_enum_from_active_enum::<Tea>()),
Statement::from_string(
db_postgres,
r#"CREATE TYPE "tea" AS ENUM ('EverydayTea', 'BreakfastTea')"#
)
);
assert_eq!(
db_postgres.build(&schema.create_table_from_entity(active_enum::Entity)),
Statement::from_string(
db_postgres,
[
r#"CREATE TABLE "public"."active_enum" ("#,
r#""id" serial NOT NULL PRIMARY KEY,"#,
r#""tea" tea"#,
r#")"#,
]
.join(" ")
),
);
MySQL
In MySQL, enum is defined on table creation so you only need to call Schema::create_table_from_entity
once.
use sea_orm::{Schema, Statement};
let db_mysql = DbBackend::MySql;
let schema = Schema::new(db_mysql);
assert_eq!(
db_mysql.build(&schema.create_table_from_entity(active_enum::Entity)),
Statement::from_string(
db_mysql,
[
"CREATE TABLE `active_enum` (",
"`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,",
"`tea` ENUM('EverydayTea', 'BreakfastTea')",
")",
]
.join(" ")
),
);
SQLite
Enum is not supported in SQLite so it will be stored as TEXT
.
use sea_orm::{Schema, Statement};
let db_sqlite = DbBackend::Sqlite;
let schema = Schema::new(db_sqlite);
assert_eq!(
db_sqlite.build(&schema.create_enum_from_entity(active_enum::Entity)),
Statement::from_string(
db_sqlite,
[
"CREATE TABLE `active_enum` (",
"`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT,",
"`tea` text",
")",
]
.join(" ")
),
);