Filter rows with IS IN enum values expression (#1183)

* [demo] filter rows with enum value is in list

* Fix clippy
This commit is contained in:
Billy Chan 2022-11-15 13:20:47 +08:00 committed by GitHub
parent b859b4cb37
commit 73e56e5531
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 2 deletions

View File

@ -1,5 +1,5 @@
use crate::{ColumnDef, DbErr, Iterable, TryGetable};
use sea_query::{DynIden, Nullable, Value, ValueType};
use sea_query::{DynIden, Expr, Nullable, SimpleExpr, Value, ValueType};
/// A Rust representation of enum defined in database.
///
@ -131,6 +131,11 @@ pub trait ActiveEnum: Sized + Iterable {
Self::to_value(&self)
}
/// Construct a enum expression with casting
fn as_enum(&self) -> SimpleExpr {
Expr::val(Self::to_value(self)).as_enum(Self::name())
}
/// Get the name of all enum variants
fn values() -> Vec<Self::Value> {
Self::iter().map(Self::into_value).collect()

View File

@ -4,7 +4,12 @@ use active_enum::Entity as ActiveEnum;
use active_enum_child::Entity as ActiveEnumChild;
pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
use sea_orm::{
entity::prelude::*,
entity::*,
sea_query::{BinOper, Expr},
ActiveEnum as ActiveEnumTrait, DatabaseConnection,
};
#[sea_orm_macros::test]
#[cfg(any(
@ -88,6 +93,29 @@ pub async fn insert_active_enum(db: &DatabaseConnection) -> Result<(), DbErr> {
.await?
.unwrap()
);
assert_eq!(
model,
Entity::find()
.filter(
Expr::col(Column::Tea)
.binary(BinOper::In, Expr::tuple([Tea::EverydayTea.as_enum()]))
)
.one(db)
.await?
.unwrap()
);
assert_eq!(
model,
Entity::find()
.filter(Column::Tea.is_not_null())
.filter(
Expr::col(Column::Tea)
.binary(BinOper::NotIn, Expr::tuple([Tea::BreakfastTea.as_enum()]))
)
.one(db)
.await?
.unwrap()
);
let res = model.delete(db).await?;