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

feat: method takes generic IntoActiveModel argument #1623

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
18 changes: 11 additions & 7 deletions src/entity/base_entity.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
ActiveModelTrait, ColumnTrait, Delete, DeleteMany, DeleteOne, FromQueryResult, Insert,
ModelTrait, PrimaryKeyToColumn, PrimaryKeyTrait, QueryFilter, Related, RelationBuilder,
RelationTrait, RelationType, Select, Update, UpdateMany, UpdateOne,
IntoActiveModel, ModelTrait, PrimaryKeyToColumn, PrimaryKeyTrait, QueryFilter, Related,
RelationBuilder, RelationTrait, RelationType, Select, Update, UpdateMany, UpdateOne,
};
use sea_query::{Alias, Iden, IntoIden, IntoTableRef, IntoValueTuple, TableRef};
use std::fmt::Debug;
Expand Down Expand Up @@ -362,9 +362,10 @@ pub trait EntityTrait: EntityName {
/// # Ok(())
/// # }
/// ```
fn insert<A>(model: A) -> Insert<A>
fn insert<A, M>(model: M) -> Insert<A>
where
A: ActiveModelTrait<Entity = Self>,
M: IntoActiveModel<A>,
{
Insert::one(model)
}
Expand Down Expand Up @@ -459,10 +460,11 @@ pub trait EntityTrait: EntityName {
/// # Ok(())
/// # }
/// ```
fn insert_many<A, I>(models: I) -> Insert<A>
fn insert_many<A, I, M>(models: I) -> Insert<A>
where
A: ActiveModelTrait<Entity = Self>,
I: IntoIterator<Item = A>,
I: IntoIterator<Item = M>,
M: IntoActiveModel<A>,
{
Insert::many(models)
}
Expand Down Expand Up @@ -584,9 +586,10 @@ pub trait EntityTrait: EntityName {
/// # Ok(())
/// # }
/// ```
fn update<A>(model: A) -> UpdateOne<A>
fn update<A, M>(model: M) -> UpdateOne<A>
where
A: ActiveModelTrait<Entity = Self>,
M: IntoActiveModel<A>,
{
Update::one(model)
}
Expand Down Expand Up @@ -689,9 +692,10 @@ pub trait EntityTrait: EntityName {
/// # Ok(())
/// # }
/// ```
fn delete<A>(model: A) -> DeleteOne<A>
fn delete<A, M>(model: M) -> DeleteOne<A>
where
A: ActiveModelTrait<Entity = Self>,
M: IntoActiveModel<A>,
{
Delete::one(model)
}
Expand Down
17 changes: 9 additions & 8 deletions src/executor/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,15 @@ impl Updater {
})
}

async fn exec_update_and_return_updated<A, C>(
async fn exec_update_and_return_updated<A, C, M>(
mut self,
model: A,
model: M,
db: &C,
) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
where
A: ActiveModelTrait,
C: ConnectionTrait,
M: IntoActiveModel<A>,
{
type Entity<A> = <A as ActiveModelTrait>::Entity;
type Model<A> = <Entity<A> as EntityTrait>::Model;
Expand Down Expand Up @@ -128,18 +129,20 @@ impl Updater {
}
}

async fn find_updated_model_by_id<A, C>(
model: A,
async fn find_updated_model_by_id<A, C, M>(
model: M,
db: &C,
) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
where
A: ActiveModelTrait,
C: ConnectionTrait,
M: IntoActiveModel<A>,
{
type Entity<A> = <A as ActiveModelTrait>::Entity;
type ValueType<A> = <<Entity<A> as EntityTrait>::PrimaryKey as PrimaryKeyTrait>::ValueType;

let primary_key_value = match model.get_primary_key_value() {
let active_model = model.into_active_model();
let primary_key_value = match active_model.get_primary_key_value() {
Some(val) => ValueType::<A>::from_value_tuple(val),
None => return Err(DbErr::UpdateGetPrimaryKey),
};
Expand Down Expand Up @@ -255,9 +258,7 @@ mod tests {
);

assert_eq!(
cake::Entity::update(updated_cake.clone().into_active_model())
.exec(&db)
.await?,
cake::Entity::update(updated_cake.clone()).exec(&db).await?,
updated_cake
);

Expand Down
4 changes: 1 addition & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,9 +240,7 @@
//! // delete one
//! let orange: Option<fruit::Model> = Fruit::find_by_id(1).one(db).await?;
//! let orange: fruit::Model = orange.unwrap();
//! fruit::Entity::delete(orange.into_active_model())
//! .exec(db)
//! .await?;
//! fruit::Entity::delete(orange).exec(db).await?;
//!
//! // or simply
//! let orange: Option<fruit::Model> = Fruit::find_by_id(1).one(db).await?;
Expand Down
10 changes: 3 additions & 7 deletions src/query/insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ mod tests {
use sea_query::OnConflict;

use crate::tests_cfg::cake;
use crate::{ActiveValue, DbBackend, DbErr, EntityTrait, Insert, IntoActiveModel, QueryTrait};
use crate::{ActiveValue, DbBackend, DbErr, EntityTrait, Insert, QueryTrait};

#[test]
fn insert_1() {
Expand Down Expand Up @@ -391,9 +391,7 @@ mod tests {
.append_query_results([[model.clone()]])
.into_connection();

post::Entity::insert(model.into_active_model())
.exec(&db)
.await?;
post::Entity::insert(model).exec(&db).await?;

assert_eq!(
db.into_transaction_log(),
Expand Down Expand Up @@ -460,9 +458,7 @@ mod tests {
}])
.into_connection();

post::Entity::insert(model.into_active_model())
.exec(&db)
.await?;
post::Entity::insert(model).exec(&db).await?;

assert_eq!(
db.into_transaction_log(),
Expand Down
15 changes: 9 additions & 6 deletions src/query/update.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, Iterable, PrimaryKeyToColumn,
QueryFilter, QueryTrait,
ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, IntoActiveModel, Iterable,
PrimaryKeyToColumn, QueryFilter, QueryTrait,
};
use core::marker::PhantomData;
use sea_query::{Expr, IntoIden, SimpleExpr, UpdateStatement};
Expand Down Expand Up @@ -45,16 +45,17 @@ impl Update {
/// r#"UPDATE "cake" SET "name" = 'Apple Pie' WHERE "cake"."id" = 1"#,
/// );
/// ```
pub fn one<E, A>(model: A) -> UpdateOne<A>
pub fn one<E, A, M>(model: M) -> UpdateOne<A>
where
E: EntityTrait,
A: ActiveModelTrait<Entity = E>,
M: IntoActiveModel<A>,
{
UpdateOne {
query: UpdateStatement::new()
.table(A::Entity::default().table_ref())
.to_owned(),
model,
model: model.into_active_model(),
}
.prepare_filters()
.prepare_values()
Expand Down Expand Up @@ -184,12 +185,14 @@ where
E: EntityTrait,
{
/// Add the models to update to Self
pub fn set<A>(mut self, model: A) -> Self
pub fn set<A, M>(mut self, model: M) -> Self
where
A: ActiveModelTrait<Entity = E>,
M: IntoActiveModel<A>,
{
let active_model = model.into_active_model();
for col in E::Column::iter() {
match model.get(col) {
match active_model.get(col) {
ActiveValue::Set(value) => {
let expr = col.save_as(Expr::val(value));
self.query.value(col, expr);
Expand Down
4 changes: 1 addition & 3 deletions tests/byte_primary_key_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ pub async fn create_and_update(db: &DatabaseConnection) -> Result<(), DbErr> {
value: "First Row".to_owned(),
};

let res = Entity::insert(model.clone().into_active_model())
.exec(db)
.await?;
let res = Entity::insert(model.clone()).exec(db).await?;

assert_eq!(Entity::find().one(db).await?, Some(model.clone()));

Expand Down
10 changes: 3 additions & 7 deletions tests/delete_by_id_tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod common;
pub use common::{features::*, setup::*, TestContext};
use sea_orm::{entity::prelude::*, DatabaseConnection, IntoActiveModel};
use sea_orm::{entity::prelude::*, DatabaseConnection};

#[sea_orm_macros::test]
#[cfg(any(
Expand All @@ -26,9 +26,7 @@ pub async fn create_and_delete_applog(db: &DatabaseConnection) -> Result<(), DbE
created_at: "2021-09-17T17:50:20+08:00".parse().unwrap(),
};

Applog::insert(log1.clone().into_active_model())
.exec(db)
.await?;
Applog::insert(log1.clone()).exec(db).await?;

let log2 = applog::Model {
id: 2,
Expand All @@ -37,9 +35,7 @@ pub async fn create_and_delete_applog(db: &DatabaseConnection) -> Result<(), DbE
created_at: "2022-09-17T17:50:20+08:00".parse().unwrap(),
};

Applog::insert(log2.clone().into_active_model())
.exec(db)
.await?;
Applog::insert(log2.clone()).exec(db).await?;

let delete_res = Applog::delete_by_id(2).exec(db).await?;
assert_eq!(delete_res.rows_affected, 1);
Expand Down
4 changes: 1 addition & 3 deletions tests/string_primary_key_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,7 @@ pub async fn create_and_update_repository(db: &DatabaseConnection) -> Result<(),
description: None,
};

let res = Repository::insert(repository.clone().into_active_model())
.exec(db)
.await?;
let res = Repository::insert(repository.clone()).exec(db).await?;

assert_eq!(Repository::find().one(db).await?, Some(repository.clone()));

Expand Down
4 changes: 2 additions & 2 deletions tests/time_crate_tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod common;
pub use common::{features::*, setup::*, TestContext};
use sea_orm::{entity::prelude::*, DatabaseConnection, IntoActiveModel};
use sea_orm::{entity::prelude::*, DatabaseConnection};
use serde_json::json;
use time::macros::{date, time};

Expand Down Expand Up @@ -29,7 +29,7 @@ pub async fn create_transaction_log(db: &DatabaseConnection) -> Result<(), DbErr
.assume_utc(),
};

let res = TransactionLog::insert(transaction_log.clone().into_active_model())
let res = TransactionLog::insert(transaction_log.clone())
.exec(db)
.await?;

Expand Down
10 changes: 3 additions & 7 deletions tests/timestamp_tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub mod common;
pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, DatabaseConnection, IntoActiveModel};
use sea_orm::{entity::prelude::*, DatabaseConnection};

#[sea_orm_macros::test]
#[cfg(any(
Expand All @@ -28,9 +28,7 @@ pub async fn create_applog(db: &DatabaseConnection) -> Result<(), DbErr> {
created_at: "2021-09-17T17:50:20+08:00".parse().unwrap(),
};

let res = Applog::insert(log.clone().into_active_model())
.exec(db)
.await?;
let res = Applog::insert(log.clone()).exec(db).await?;

assert_eq!(log.id, res.last_insert_id);
assert_eq!(Applog::find().one(db).await?, Some(log.clone()));
Expand Down Expand Up @@ -77,9 +75,7 @@ pub async fn create_satellites_log(db: &DatabaseConnection) -> Result<(), DbErr>
deployment_date: "2022-01-07T12:11:23Z".parse().unwrap(),
};

let res = Satellite::insert(archive.clone().into_active_model())
.exec(db)
.await?;
let res = Satellite::insert(archive.clone()).exec(db).await?;

assert_eq!(archive.id, res.last_insert_id);
assert_eq!(Satellite::find().one(db).await?, Some(archive.clone()));
Expand Down
4 changes: 1 addition & 3 deletions tests/uuid_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,7 @@ pub async fn create_and_update_metadata(db: &DatabaseConnection) -> Result<(), D
time: Some(Time::from_hms_opt(11, 32, 55).unwrap()),
};

let res = Metadata::insert(metadata.clone().into_active_model())
.exec(db)
.await?;
let res = Metadata::insert(metadata.clone()).exec(db).await?;

assert_eq!(Metadata::find().one(db).await?, Some(metadata.clone()));

Expand Down