我找不到如何用rom-sql编写此查询的方法。可以将纯SQL添加到where
吗?
它查找与请求不相交的公告。
announcements.when
和requests.when
是postgres中的tstzrange列。
SELECT "announcements".* FROM "announcements" WHERE (
(SELECT COUNT(requests.id)
FROM requests
WHERE requests.id IN (1,2,3) AND
(TSTZRANGE(lower(requests.when) - INTERVAL '1 HOUR', upper(requests.when) + INTERVAL '1 HOUR', '()') &&
TSTZRANGE(lower(announcements.when)), upper(announcements.when), '()') AND
requests.user_id = 42
) = 0
)
答案 0 :(得分:1)
查看文档的“高级Postgres支持”部分,http://api.rom-rb.org/rom-sql/ROM/SQL/Postgres/Types看起来像是对TsTzRange range('tstzrange', range_read_type(:tstzrange))
的支持
答案 1 :(得分:0)
我找到了解决问题的方法。 不确定rom-sql中是否正确。 如果有的话,我会接受更好的答案。
在此之前,这是我的解决方案-Sequel.lit
在我的情况下,我在“公告”关系中定义了一个方法:
def available(user_id)
request_ids = requests.by_user_id(user_id).confirmed.pluck(:id)
# +- 1 hour around request is not available
# last argument '()' means "do not include boundaries"
request_when = "TSTZRANGE(
lower(requests.when) - INTERVAL '1 HOUR',
upper(requests.when) + INTERVAL '1 HOUR',
'()'
)"
announcement_when = "TSTZRANGE(lower(announcements.when), upper(announcements.when), '()')"
where(Sequel.lit(
"(SELECT COUNT(requests.id)
FROM requests
WHERE requests.id IN (:request_ids) AND
#{request_when} && #{announcement_when} AND
requests.user_id = :user_id) = 0",
user_id: user_id, request_ids: request_ids
))
end