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

Handle duplicate joins #451

Merged
merged 3 commits into from
Oct 14, 2020

Conversation

matthewmcgarvey
Copy link
Member

Fixes #370

Summary

Querying with joins can sometimes produce invalid sql. The two cases that this PR handles are:

  1. When they potential join is to the table being queried
  2. When the potential join has already been joined

Description

These situations are rather easy to get to when users attempt to make composable methods that limit the scope of queries. Say an app has the concept of a Business and a User and if the user belongs to a business they are considered an Employee of that business. If the app allowed users to access the api, it might make sense to limit their API access to businesses they are an employee of. Rather than having to remember how to scope their access correctly every time you have a new query, you could make helper methods like (granted this is convoluted, I'm sure there are more realistic ways to get in this situation):

def user_scoped(query)
  scoped_user_query = UserQuery.new.id(current_user.id)
  query.where_users(scoped_user_query)
end

def business_scoped(query)
  scoped_business_query = user_scoped(BusinessQuery.new.id(current_business.id))
  query.where_businesses(scoped_business_query)
end

(Those methods would require that Business has a has many through association to User through Employee)
The problem arises when you want to provide an endpoint that returns all the employees for the user's current business. The action would do something like:

employees = business_scoped(EmployeeQuery.new)

You end up with an error: table name "employees" specified more than once (PQ::PQError) because the BusinessQuery adds a join to limit by the user id and the main query is on the employees table.

Note

I'm sure there are situations this doesn't handle and this might even cause issues so PLEASE poke holes in this change.

Copy link
Member

@jwoertink jwoertink left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! Just needs a rebase or pull from master. After everything passes feel free to merge 👍

@matthewmcgarvey matthewmcgarvey merged commit 73b114c into luckyframework:master Oct 14, 2020
@matthewmcgarvey matthewmcgarvey deleted the join-update branch October 14, 2020 22:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Querying with a join table can produce invalid SQL
2 participants