activegraph icon indicating copy to clipboard operation
activegraph copied to clipboard

'none' for empty result set

Open dpisarewski opened this issue 10 years ago • 7 comments

It would be great if there were a 'none' method returning empty result set like active_record does it.

http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-none

dpisarewski avatar Nov 10 '14 14:11 dpisarewski

I started playing around with this earlier, seems doable. I got it working as a class method but we're going to need to make QueryProxy aware of it, otherwise things will break, and I'm not sure of the best way to do that just yet.

subvertallchris avatar Nov 11 '14 01:11 subvertallchris

I defined a scope 'none' as a workaround.

scope :none, -> { where('1 = 0') }

dpisarewski avatar Nov 11 '14 09:11 dpisarewski

Interestingly that seems to be just how it's implemented in ActiveRecord ;)

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation/query_methods.rb#L692

I didn't know about this extending business. Looks pretty cool. I wonder how new it is

cheerfulstoic avatar Nov 11 '14 12:11 cheerfulstoic

Ah, interesting, I guess not quite because the NullRelation introduces a lot:

https://github.com/rails/rails/blob/08754f12e65a9ec79633a605e986d0f1ffa4b251/activerecord/lib/active_record/null_relation.rb

cheerfulstoic avatar Nov 11 '14 12:11 cheerfulstoic

I think, NullRelation is just an optimization that prevents firing database queries or doing unnecessary computations.

dpisarewski avatar Nov 11 '14 12:11 dpisarewski

Ah, that makes sense ;)

Might be simpler to just have some variable state which is propogated down the chain. Maybe that's what @subvertallchris was working on anyway

cheerfulstoic avatar Nov 11 '14 13:11 cheerfulstoic

Yup, that is what I was talking about! The problem with scope :none, -> { where('1 = 0') } is that it's going to query the DB. I think we can avoid it entirely if we can find a clever way to tell it that it's a null object.

subvertallchris avatar Nov 11 '14 18:11 subvertallchris