Query that checks overlap with composed timeframe (postgres, ActiveRecord)

114 Views Asked by At

I have a Schema like this:

User(:id)
Event(:id, :start_date, :end_date,:duration, :recurrence_pattern)
EventAssignment(:user_id, :event_id, :date)

recurrence_pattern is a rrule string (see https://icalendar.org/rrule-tool.html, https://github.com/square/ruby-rrule)

date is a date formatted like 'YYYY-MM-DD'

start_date and end_date are timestamps like 'YYYY-MM-DDTHH:MM:SS'

I want to find all users that have at least one allocation overlapping with 2 timestamps, say from and to

So I wrote a bit of postgres and arel

assignment_subquery = EventAssignment.joins(:event).where(
    '"user_id" = users.id AND
    (?) <= "event_assignments".date + (to_char("events".start_date, \'HH24:MI\'))::time + make_interval(mins => "events".duration) AND
    (event_assignments.date) + (to_char(events.start_date, \'HH24:MI\'))::time <= (?)',
from, to).arel.exists

User.where(assignment_subquery)

edit: some more postgres(@max)

assignment_subquery = EventAssignment.joins(:event).where(
'"user_id" = users.id AND
    ("event_assignments".date + (to_char("events".start_date, \'HH24:MI\'))::time + make_interval(mins => "events".duration),
    (event_assignments.date) + (to_char(events.start_date, \'HH24:MI\'))::time) 
 OVERLAPS ((?), (?))'
, from, to).arel.exists

Which works fine

my question is: Is there a better more rails way to do this?

0

There are 0 best solutions below