Skip to content

Commit cfa7b77

Browse files
Update 04-enumeration.md (#124)
Updated Postgres native database enum examples to show how to use the enum for various migration purposes.
1 parent 33caf1c commit cfa7b77

File tree

1 file changed

+43
-2
lines changed

1 file changed

+43
-2
lines changed

SeaORM/docs/04-generate-entity/04-enumeration.md

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,21 @@ manager
132132
```
133133

134134
#### 2. `create_enum_from_active_enum`
135+
This method will provide an interface for adding the type to the database, using the type for table columns, and adding values of this type to rows when seeding data.
135136

137+
##### 1. Define a native database `ActiveEnum`
138+
```rust
139+
#[derive(EnumIter, DeriveActiveEnum)]
140+
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "tea_type")]
141+
pub enum TeaType {
142+
#[sea_orm(string_value = "EverydayTea")]
143+
EverydayTea,
144+
#[sea_orm(string_value = "BreakfastTea")]
145+
BreakfastTea,
146+
}
147+
```
148+
149+
##### 2. Create the type in the database:
136150
```rust
137151
// we can do this in migration:
138152

@@ -141,12 +155,39 @@ let schema = Schema::new(DbBackend::Postgres);
141155

142156
manager
143157
.create_type(
144-
// CREATE TYPE "tea" AS ENUM ('EverydayTea', 'BreakfastTea')
145-
schema.create_enum_from_active_enum::<Tea>(),
158+
// CREATE TYPE "tea_type" AS ENUM ('EverydayTea', 'BreakfastTea')
159+
schema.create_enum_from_active_enum::<TeaType>(),
146160
)
147161
.await?;
148162
```
149163

164+
##### 3. Use the type as a table column type when creating a table:
165+
```rust diff
166+
// in a migration
167+
168+
manager::create()
169+
.table(Tea::Table)
170+
.if_not_exists()
171+
.col(Column::new(Tea::Type).custom(TeaType::name())) // use the type for a table column
172+
// ... more columns
173+
```
174+
* see also [Schema Creation Methods - Create Table](https://www.sea-ql.org/SeaORM/docs/migration/writing-migration/#schema-creation-methods)
175+
176+
##### 4. Use the type when populating the database:
177+
```rust
178+
// in a migration
179+
180+
let insert = Query::insert()
181+
.into_table(Tea::Table)
182+
.columns([Tea::TeaType])
183+
.values_panic([TeaType::EverydayTea.as_enum()]) // call `as_enum` to convert the variant into a SimpleExpr
184+
.to_owned();
185+
186+
manager.exec_stmt(insert).await?;
187+
// ...
188+
```
189+
* see also [Seeding Data - with sea_query statement](https://www.sea-ql.org/SeaORM/docs/migration/seeding-data/#:~:text=write%20SeaQuery%20statement%20to%20seed%20the%20table)
190+
150191
## Implementations
151192

152193
You can implement [`ActiveEnum`](https://docs.rs/sea-orm/*/sea_orm/entity/trait.ActiveEnum.html) by using the [`DeriveActiveEnum`](https://docs.rs/sea-orm/*/sea_orm/derive.DeriveActiveEnum.html) macro.

0 commit comments

Comments
 (0)