This is a proposal on automated query joiner.

Let's assume we have 2 queries:

user_query = User.select(:id, :login).filter{:name !=
"guest"}.sort_by(:id.desc)
group_query = Group.select(:id, :name).filter{:id !=
1}.sort_by(:id.asc)

Let's say we want to fetch this all in one query. In current sequel
implementation we do this:

User.select(:user__id, :user__login, :group__id, :group__name).join(:groups, 
:user__group_id
=> :group__id).filter{:user__name != "guest" && :group__id !=
1}.order_by(:user__id.desc, :group__id.asc).sql

=> "SELECT user.`id`, user.`login`, group.`id`, group.`name` FROM
users INNER JOIN groups ON (user.`group_id` = group.`id`) WHERE ((NOT
(user.`name` = 'guest')) AND (NOT (group.`id` = 1))) ORDER BY
user.`id` DESC, group.`id` ASC"

Mess? Yes it is. Not much different from usual SQL. Not even shorter.

Now, let's try this:


user_query << [group_query, :user__group_id => :group__id]
# << is for left join
# >> is for right

=> "SELECT user.`id`, user.`login`, group.`id`, group.`name` FROM
users INNER JOIN groups ON (user.`group_id` = group.`id`) WHERE ((NOT
(user.`name` = 'guest')) AND (NOT (group.`id` = 1))) ORDER BY
user.`id` DESC, group.`id` ASC"

What it does is conjucts 2 already built query objects. Conjucts and
automatically prefixes *select* statements. Conjucts orders and
conditions.

We can make it a little bit magical.

imagine this:
class User
  def group
    Group.select(:id => group_id)
  end
end

user_query << group_query #here we omit the JOIN conditions, sequel
take it from "group" definition of User.

Isn't that readable and cool? It even can use built in subsets
feature!
That's the bomb. And pretty easy to implement

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sequel-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to