我如何在 rust, diesel 中使用 sql 函数 CAST?

How can I use the sql function CAST in rust, diesel?

我正在使用 Rocket 开发一个新端点,并且正在尝试 return 一个由各种结构组成的 Vec<>。

我想在 diesel 中复制的原始查询是:

select location.id, location.name, w.datetime, t.temp, w.compass, w.speed, r.probability, s.height
from location
inner join rainfall r on location.id = r.location
inner join temperature t on location.id = t.location
inner join wind w on location.id = w.location
inner join swell s on location.id = s.location
where t.datetime = w.datetime
  and s.datetime = t.datetime
  and CAST(t.datetime as date) = CAST(r.datetime as date)
  and t.datetime > now() and t.datetime < NOW() + INTERVAL 1 HOUR;

我认识到,为了使用 CAST 函数,我需要使用 sql_function! 宏:

sql_function! {
#[sql_name="CAST"]
    fn cast(x: sql_types::Nullable<sql_types::Datetime>) -> sql_types::Date;
}

这允许我创建以下查询:

let summaries: Vec<(Location, Swell, Wind, Temperature, Rainfall)> = location::table
        .inner_join(swell::table)
        .inner_join(wind::table)
        .inner_join(temperature::table)
        .inner_join(rainfall::table)
        .filter(temperature::datetime.eq(wind::datetime))
        .filter(temperature::datetime.eq(swell::datetime))
        .filter(temperature::datetime.gt(utilities::today()))
        .filter(temperature::datetime.lt(utilities::future_hour(1)))
        .filter(cast(temperature::datetime).eq(cast(rainfall::datetime)))
        .load(&conn.0)?;

但是,当我 运行 这个查询时,我得到一个 SQL 查询错误:

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \') = CAST('rainfall'.'datetime')\' at line 1"

如原始 SQL 语句所示,它应该显示为 CAST('rainfall'.'datetime' as date)

我的问题是,如何将 'as date' 组件添加到我的 diesel 查询中? sql_function 定义中是否缺少某些内容?

感谢您的帮助。

我在深入研究类似问题后找到了答案。

事实证明,您可以在添加 use diesel::expression::sql_literal::sql;.

后将原始 sql 字符串输入到 .filter 方法中

所以最后的片段变成:

let summaries: Vec<(Location, Swell, Wind, Temperature, Rainfall)> = location::table
        .inner_join(swell::table)
        .inner_join(wind::table)
        .inner_join(temperature::table)
        .inner_join(rainfall::table)
        .filter(temperature::datetime.eq(wind::datetime))
        .filter(temperature::datetime.eq(swell::datetime))
        .filter(temperature::datetime.gt(utilities::today()))
        .filter(temperature::datetime.lt(utilities::future_hour(1)))
        .filter(sql("CAST(`temperature`.`datetime` as date) = CAST(`rainfall`.`datetime` as date)"))
        .load(&conn.0)?;

我希望这对其他人有帮助!