Skip to content

Commit

Permalink
distinct support in sea-orm (#902)
Browse files Browse the repository at this point in the history
* distinct support

* remove feature flag

* fix argument
  • Loading branch information
kyoto7250 authored Sep 25, 2022
1 parent 597f515 commit ba5a83d
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/query/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use sea_query::{
};
pub use sea_query::{Condition, ConditionalStatement, DynIden, JoinType, Order, OrderedStatement};

use sea_query::IntoColumnRef;

// LINT: when the column does not appear in tables selected from
// LINT: when there is a group by clause, but some columns don't have aggregate functions
// LINT: when the join table or column does not exists
Expand Down Expand Up @@ -172,6 +174,61 @@ pub trait QuerySelect: Sized {
self
}

/// Add a DISTINCT expression
/// ```
/// use sea_orm::{entity::*, query::*, tests_cfg::cake, DbBackend};
/// struct Input {
/// name: Option<String>,
/// }
/// let input = Input {
/// name: Some("cheese".to_owned()),
/// };
/// assert_eq!(
/// cake::Entity::find()
/// .filter(
/// Condition::all().add_option(input.name.map(|n| cake::Column::Name.contains(&n)))
/// )
/// .distinct()
/// .build(DbBackend::MySql)
/// .to_string(),
/// "SELECT DISTINCT `cake`.`id`, `cake`.`name` FROM `cake` WHERE `cake`.`name` LIKE '%cheese%'"
/// );
/// ```
fn distinct(mut self) -> Self {
self.query().distinct();
self
}

/// Add a DISTINCT ON expression
/// NOTE: this function is only supported by `sqlx-postgres`
/// ```
/// use sea_orm::{entity::*, query::*, tests_cfg::cake, DbBackend};
/// struct Input {
/// name: Option<String>,
/// }
/// let input = Input {
/// name: Some("cheese".to_owned()),
/// };
/// assert_eq!(
/// cake::Entity::find()
/// .filter(
/// Condition::all().add_option(input.name.map(|n| cake::Column::Name.contains(&n)))
/// )
/// .distinct_on([cake::Column::Name])
/// .build(DbBackend::Postgres)
/// .to_string(),
/// "SELECT DISTINCT ON (\"name\") \"cake\".\"id\", \"cake\".\"name\" FROM \"cake\" WHERE \"cake\".\"name\" LIKE '%cheese%'"
/// );
/// ```
fn distinct_on<T, I>(mut self, cols: I) -> Self
where
T: IntoColumnRef,
I: IntoIterator<Item = T>,
{
self.query().distinct_on(cols);
self
}

#[doc(hidden)]
fn join_join(mut self, join: JoinType, rel: RelationDef, via: Option<RelationDef>) -> Self {
if let Some(via) = via {
Expand Down

0 comments on commit ba5a83d

Please sign in to comment.