Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

find_by_id and delete_by_id take any Into primary key value #1362

Merged
merged 1 commit into from
Jan 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 51 additions & 4 deletions src/entity/base_entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,10 +256,13 @@ pub trait EntityTrait: EntityName {
/// # Ok(())
/// # }
/// ```
fn find_by_id(values: <Self::PrimaryKey as PrimaryKeyTrait>::ValueType) -> Select<Self> {
fn find_by_id<T>(values: T) -> Select<Self>
where
T: Into<<Self::PrimaryKey as PrimaryKeyTrait>::ValueType>,
{
let mut select = Self::find();
let mut keys = Self::PrimaryKey::iter();
for v in values.into_value_tuple() {
for v in values.into().into_value_tuple() {
if let Some(key) = keys.next() {
let col = key.into_column();
select = select.filter(col.eq(v));
Expand Down Expand Up @@ -819,10 +822,13 @@ pub trait EntityTrait: EntityName {
/// # Ok(())
/// # }
/// ```
fn delete_by_id(values: <Self::PrimaryKey as PrimaryKeyTrait>::ValueType) -> DeleteMany<Self> {
fn delete_by_id<T>(values: T) -> DeleteMany<Self>
where
T: Into<<Self::PrimaryKey as PrimaryKeyTrait>::ValueType>,
{
let mut delete = Self::delete_many();
let mut keys = Self::PrimaryKey::iter();
for v in values.into_value_tuple() {
for v in values.into().into_value_tuple() {
if let Some(key) = keys.next() {
let col = key.into_column();
delete = delete.filter(col.eq(v));
Expand Down Expand Up @@ -914,4 +920,45 @@ mod tests {
assert_eq!(hello::Entity.table_name(), "hello");
assert_eq!(hello::Entity.schema_name(), Some("world"));
}

#[test]
#[cfg(feature = "macros")]
fn entity_model_3() {
use crate::{entity::*, query::*, DbBackend};
use std::borrow::Cow;

mod hello {
use crate as sea_orm;
use crate::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "hello", schema_name = "world")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: String,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
}

fn delete_by_id<T>(value: T)
where
T: Into<<<hello::Entity as EntityTrait>::PrimaryKey as PrimaryKeyTrait>::ValueType>,
{
assert_eq!(
hello::Entity::delete_by_id(value)
.build(DbBackend::Sqlite)
.to_string(),
r#"DELETE FROM "world"."hello" WHERE "hello"."id" = 'UUID'"#
);
}

delete_by_id(format!("UUID"));
delete_by_id("UUID".to_string());
delete_by_id("UUID");
delete_by_id(Cow::from("UUID"));
}
}
28 changes: 13 additions & 15 deletions src/executor/update.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
cast_enum_as_text, error::*, ActiveModelTrait, ConnectionTrait, EntityTrait, IntoActiveModel,
Iterable, SelectModel, SelectorRaw, Statement, UpdateMany, UpdateOne,
Iterable, PrimaryKeyTrait, SelectModel, SelectorRaw, Statement, UpdateMany, UpdateOne,
};
use sea_query::{Expr, FromValueTuple, Query, UpdateStatement};
use std::future::Future;
Expand Down Expand Up @@ -89,20 +89,20 @@ where
A: ActiveModelTrait,
C: ConnectionTrait,
{
type Entity<A> = <A as ActiveModelTrait>::Entity;
type Model<A> = <Entity<A> as EntityTrait>::Model;
type Column<A> = <Entity<A> as EntityTrait>::Column;
type ValueType<A> = <<Entity<A> as EntityTrait>::PrimaryKey as PrimaryKeyTrait>::ValueType;
match db.support_returning() {
true => {
let returning = Query::returning().exprs(
<A::Entity as EntityTrait>::Column::iter()
.map(|c| cast_enum_as_text(Expr::col(c), &c)),
);
let returning = Query::returning()
.exprs(Column::<A>::iter().map(|c| cast_enum_as_text(Expr::col(c), &c)));
query.returning(returning);
let db_backend = db.get_database_backend();
let found: Option<<A::Entity as EntityTrait>::Model> =
SelectorRaw::<SelectModel<<A::Entity as EntityTrait>::Model>>::from_statement(
db_backend.build(&query),
)
.one(db)
.await?;
let found: Option<Model<A>> =
SelectorRaw::<SelectModel<Model<A>>>::from_statement(db_backend.build(&query))
.one(db)
.await?;
// If we got `None` then we are updating a row that does not exist.
match found {
Some(model) => Ok(model),
Expand All @@ -115,12 +115,10 @@ where
// If we updating a row that does not exist then an error will be thrown here.
Updater::new(query).check_record_exists().exec(db).await?;
let primary_key_value = match model.get_primary_key_value() {
Some(val) => FromValueTuple::from_value_tuple(val),
Some(val) => ValueType::<A>::from_value_tuple(val),
None => return Err(DbErr::UpdateGetPrimaryKey),
};
let found = <A::Entity as EntityTrait>::find_by_id(primary_key_value)
.one(db)
.await?;
let found = Entity::<A>::find_by_id(primary_key_value).one(db).await?;
// If we cannot select the updated row from db by the cached primary key
match found {
Some(model) => Ok(model),
Expand Down