Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean combinations of Sequel datasets

Tags:

ruby

sequel

Given I have some dataset methods foo, bar and baz

class User < Sequel::Model
  dataset_module do
    def foo
      # Some complicated dataset here
      where(:c => 42, :d => 23)
    end

    def bar
      # Even more complicated dataset here
      where(:a => 5, :b => 23).or(:a => 23, :b => 5)
    end

    def baz
      where(:d => 17)
    end
  end
end

I want to query the database for (foo || bar) && (bar || baz) (or some other complicated dataset). So I tried

User.where{|u| (u.foo | u.bar) & (u.bar | u.baz)}

EDIT: Clarification:

What I got

SELECT * FROM users WHERE ((`foo` OR `bar`) AND (`bar` OR `baz`))

What I wanted

SELECT * FROM users WHERE ((<dataset foo> OR <dataset bar>) AND (<dataset bar> OR <dataset baz>))

where <dataset xyz> means my defined datasets. So

<dataset foo> is defined as (c = 42 AND d = 23)

<dataset bar> is defined as ((a = 5 AND b = 23) OR (a = 23, b = 5))

<dataset baz> is defined as (d = 17)

How do I chain dataset methods with AND, OR and (most important) brackets?

like image 864
iblue Avatar asked Nov 11 '22 10:11

iblue


1 Answers

Are you not looking for union and intersection methods. These work on datasets and can be used as replacement for 'AND' and 'OR' in set theory.

Wouldn't something like this work for you?

fooOrbar = User.foo.union(User.bar)
barOrbaz = User.bar.union(User.baz)
result = fooOrbar.intersect(barOrbaz)
like image 187
System123 Avatar answered Nov 15 '22 05:11

System123