Skip to content

Commit

Permalink
Casting columns as a different data type on select, insert and update (
Browse files Browse the repository at this point in the history
  • Loading branch information
billy1624 committed Feb 2, 2023
1 parent 5f05e84 commit 8c05ab7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
12 changes: 12 additions & 0 deletions SeaORM/docs/04-generate-entity/02-entity-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,18 @@ If you want to ignore a particular model attribute such that it maps to no datab
pub ignore_me: String
```

### Cast Column Type on Select and Save

If you need to select a column as one type but save it into the database as another, you can specify the `select_as` and the `save_as` attributes to perform the casting. A typical use case is selecting a column of type `citext` (case-insensitive text) as `String` in Rust and saving it into the database as `citext`. One should define the model field as below:

```rust
#[sea_orm(
select_as = "text",
save_as = "citext",
)]
pub case_insensitive_text: String
```

## Primary Key

Use the `primary_key` attribute to mark a column as the primary key.
Expand Down
24 changes: 24 additions & 0 deletions SeaORM/docs/04-generate-entity/03-expanded-entity-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,30 @@ To specify the datatype of each column, the [`ColumnType`](https://docs.rs/sea-o
ColumnType::String(None).def().default_value("Sam").unique().indexed().nullable()
```

### Cast Column Type on Select and Save

If you need to select a column as one type but save it into the database as another, you can override the `select_as` and the `save_as` methods to perform the casting. A typical use case is selecting a column of type `citext` (case-insensitive text) as `String` in Rust and saving it into the database as `citext`. One should override the `ColumnTrait`'s methods as below:

```rust
use sea_orm::sea_query::{Expr, SimpleExpr, Alias}

impl ColumnTrait for Column {
// Snipped...

/// Cast column expression used in select statement.
fn select_as(&self, expr: Expr) -> SimpleExpr {
Column::CaseInsensitiveText => expr.cast_as(Alias::new("text")),
_ => self.select_enum_as(expr),
}

/// Cast value of a column into the correct type for database storage.
fn save_as(&self, val: Expr) -> SimpleExpr {
Column::CaseInsensitiveText => val.cast_as(Alias::new("citext")),
_ => self.save_enum_as(val),
}
}
```

## Primary Key

An enum representing the primary key of this table. A composite key is represented by an enum with multiple variants.
Expand Down

0 comments on commit 8c05ab7

Please sign in to comment.