I have a function that takes two optional filtering arguments, and filters the data in a table if these arguments are provided. To do this, I created a boxed query. I would like to create a right join with this boxed query. Diesel's current documentation doesn't mention right join, but it seems to prefer the belonging_to
method. I have reduced my code to a single example:
#[macro_use] extern crate diesel;
use diesel::prelude::*;
table! {
groups (id) {
id -> Int4,
name -> Text,
}
}
table! {
user_groups (id) {
id -> Int4,
user_id -> Int4,
group_id -> Int4,
}
}
allow_tables_to_appear_in_same_query!(groups, user_groups);
#[derive(Debug, Queryable)]
struct Group {
id: i32,
name: String,
}
#[derive(Debug, Queryable, Associations)]
#[belongs_to(Group)]
struct UserGroup {
id: i32,
user_id: i32,
group_id: i32,
}
fn filter(
name: Option<&str>,
user_id: Option<i32>,
conn: &diesel::PgConnection,
) -> Result<Vec<(Group, Vec<UserGroup>)>, Box<dyn std::error::Error>> {
let mut query = groups::table
.right_join(user_groups::table.on(groups::id.eq(user_groups::group_id))) // this method does not exist
.into_boxed();
if let Some(name) = name {
query = query.filter(groups::name.eq(name));
}
if let Some(user_id) = user_id {
query = query.filter(user_groups::user_id.contains(user_id)); // so this is just a guess
}
Ok(query.get_results(conn)?)
}
fn main() {
let url = "postgres://question_usr:question_pwd:localhost:5432/question_db";
let conn = diesel::PgConnection::establish(url).unwrap();
let _ = filter(Some("groupname"), Some(4), &conn).unwrap();
}
The intent is that if the argument user_id
is specified, only rows of Groups
are returned which have at least one UserGroup
such that user_group.user_id == user_id
. How do I run this query? Do I need to use the belonging_to
function somehow?
A right join is in every case equivalent to a left join with inverted table order. (See here for example). Therefore Diesel only provides functions to construct a LEFT JOIN
.
Your example then looks like this:
fn filter(
name: Option<&str>,
user_id: Option<i32>,
conn: &diesel::PgConnection,
) -> Result<Vec<(UserGroup, Option<Group>)>, Box<dyn std::error::Error>> {
let mut query = user_groups::table
.left_join(groups::table.on(groups::id.eq(user_groups::group_id))) /
.into_boxed();
if let Some(name) = name {
query = query.filter(groups::name.eq(name));
}
if let Some(user_id) = user_id {
query = query.filter(user_groups::user_id.eq(user_id));
}
Ok(query.get_results(conn)?)
}
Please note that this returns a Vec<(UserGroup, Option<Group>)>
by default. If you want something different you need to write a custom select clause specifying the required result shape.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With