我一直在尝试使用过滤器表达式构造一个柴油查询,该表达式对时间戳和时间间隔进行算术和比较。我相信使用开箱即用的柴油无法编写以下表达式。不幸的是,我求助于使用sql(...)
函数的大锤方法:
let query = videos::table
.inner_join(events::table)
.filter(sql(r#""events"."start_date" <= NOW() + interval '60 seconds'"#))
.filter(sql(r#""events"."start_date" + ("videos"."duration" * interval '1 second') > NOW()"#))
我的(缩写)模式:
table! {
events (id) {
id -> Int4,
video_id -> Int4,
start_date -> Timestamp,
}
}
table! {
videos (id) {
id -> Int4,
duration -> Float4,
}
}
我的问题:
最佳答案
Am I wrong? Can this be written in diesel with no custom types?
是的,可以使用柴油提供的方法和一些小的模式更改来编写。参见相应的documentation
Diesel要求您只能在时间戳上添加/减去间隔。这意味着您需要一点模式来使其成为可能:
table! {
videos (id) {
id -> Int4,
duration -> Interval,
}
}
然后,您的查询是这样写的:
let query = videos::table
.inner_join(events::table)
.filter(events::start_date.le(now + 60.seconds()))
.filter(now.lt(events::start_date + videos::duration))
If this cannot be written in vanilla diesel, how can I break this up into a more type-safe, diesel-friendly expression? Which parts are custom and what traits do I need to implement?
从理论上讲,应该有可能在柴油机之外实现。该代码很可能与用于在柴油机本身中实现的代码相同。可能您将需要使用局部类型和更具体的方式。因此,如果您不能更改
videos::duration
的类型,那么沿着这条路线走可能是有意义的。
关于rust - 如何在Rust Diesel中使用时间戳和时间间隔进行算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59989388/