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

distinct support in sea-orm #902

Merged
merged 3 commits into from
Sep 25, 2022
Merged
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
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 @@ -149,6 +151,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