query-composer icon indicating copy to clipboard operation
query-composer copied to clipboard

query composer with ActiveRecord (4.2)

Open morus opened this issue 9 years ago • 2 comments
trafficstars

I was trying to use query-composer to combine several queries generated from ActiveRecord (4.2.6) While I got most of that working, the sql generated contains placeholders ($1) for substitution of parameters which does not really work out when one tries to feed that to find_by_sql.

Basically my sample looks like (pseudo code)

instance = Model.find(id)
composer = Query::Composer.new
composer.use(:subquery) { instance.some_scope }
composer.use(:main_query) do | subquery |
   instance.another_scope.joins("left join subquery on <condition>").
      where("<more conditions>").limit(limit)
end
query = composer.build(:subprocesses, use_cte: true, use_aliases: false)
puts query.to_sql

The joins can probably be done in a nicer way but as a first version this seems to work out pretty well, except that the generated sql contains $1 where the id of the instance is expected.

If I check the parts, to_sql provides me nice sql queries with parameters inserted, but an AR relation responds to arel and to_sql and the query composer prefers the former. I tried to wrap the AR relations into a wrapper exposing only the to_sql method, but leads to different errors during query building (depending on details a method with is missing, or (main query unwrapped) it says TypeError: Cannot visit Wrapper or (no build options) a method as is missing.

Am I doing something wrong? What's the expected object to be provided when a component provides to_sql (I assumed a string but maybe that was naive)? Can the query composer be used in combination with Rails 4.2 generated relations? That's what I would be interested in. I have several components already that could be combined and I'm not too interested to rewrite these queries using plain arel.

morus avatar Apr 26 '16 09:04 morus

Hey, I'm sorry I didn't see your post earlier. (Somehow, I wasn't set to watch this repo. Not sure how that happened).

What database are you using? I think you should be able to use AR relations like in your example, but I don't know that I've explicitly done that in any of the work I've needed the composer for. Let me know what DB you're using, and I'll see if I can duplicate the issue.

jamis avatar May 13 '16 03:05 jamis

sorry for the lacking info: I'm on postgres 9.3

morus avatar May 13 '16 05:05 morus