From 13bad8eb175625313dfa7611b787a1112441fe8f Mon Sep 17 00:00:00 2001 From: Chris Tsang Date: Wed, 19 May 2021 21:38:17 +0800 Subject: [PATCH] Find by composite key --- src/entity/base.rs | 43 +++++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/src/entity/base.rs b/src/entity/base.rs index c1d1dc90..c2046b4b 100644 --- a/src/entity/base.rs +++ b/src/entity/base.rs @@ -1,8 +1,8 @@ use crate::{ ColumnTrait, ModelTrait, PrimaryKeyOfModel, PrimaryKeyTrait, QueryHelper, RelationBuilder, - RelationTrait, RelationType, Select, + RelationTrait, RelationType, Select }; -use sea_query::{Iden, Value}; +use sea_query::{Iden, IntoValueTuple}; use std::fmt::Debug; pub use strum::IntoEnumIterator as Iterable; @@ -21,10 +21,6 @@ pub trait EntityTrait: EntityName { type PrimaryKey: PrimaryKeyTrait + Iterable; - fn auto_increment() -> bool { - true - } - fn has_one(entity: R) -> RelationBuilder where R: EntityTrait, @@ -64,18 +60,37 @@ pub trait EntityTrait: EntityName { /// r#"SELECT "cake"."id", "cake"."name" FROM "cake" WHERE "cake"."id" = 11"# /// ); /// ``` - fn find_by(v: V) -> Select + /// Find by composite key + /// ``` + /// use sea_orm::{ColumnTrait, EntityTrait, tests_cfg::cake_filling, sea_query::PostgresQueryBuilder}; + /// + /// assert_eq!( + /// cake_filling::Entity::find_by((2, 3)) + /// .build(PostgresQueryBuilder) + /// .to_string(), + /// [ + /// r#"SELECT "cake_filling"."cake_id", "cake_filling"."filling_id" FROM "cake_filling""#, + /// r#"WHERE "cake_filling"."cake_id" = 2 AND "cake_filling"."filling_id" = 3"#, + /// ].join(" ") + /// ); + /// ``` + fn find_by(values: V) -> Select where - V: Into, + V: IntoValueTuple, Self::PrimaryKey: PrimaryKeyOfModel, { let mut select = Self::find(); - if let Some(key) = Self::PrimaryKey::iter().next() { - // TODO: supporting composite primary key - let col = key.into_column(); - select = select.filter(col.eq(v)); - } else { - panic!("undefined primary key"); + let mut keys = Self::PrimaryKey::iter(); + for v in values.into_value_tuple() { + if let Some(key) = keys.next() { + let col = key.into_column(); + select = select.filter(col.eq(v)); + } else { + panic!("primary key arity mismatch"); + } + } + if keys.next().is_some() { + panic!("primary key arity mismatch"); } select }