简体   繁体   English

如何将间隔参数传递给准备好的语句?

[英]How to pass an interval parameter to a prepared statement?

I want to delete all database entries in my Postgres database that are older than X minutes.我想删除我的 Postgres 数据库中早于 X 分钟的所有数据库条目。 My prepared statement in go looks like this:我在 go 中准备好的语句如下所示:

delete
from my_table
where expires < (to_timestamp($1) - '$2 minutes'::interval);

How can I correctly pass the second parameter $2 ?如何正确传递第二个参数$2


PS: I know there's different statements to solve the problem, but I am explicitly interested in how to pass parameters that are quoted. PS:我知道有不同的语句可以解决这个问题,但我对如何传递引用的参数很感兴趣。

You can cast the parameter to text and then concatenate it with the string ' minutes' .您可以参数转换为text ,然后将其与字符串' minutes' 连接起来。

delete from my_table
where expires < (to_timestamp($1) - ($2::text || ' minutes')::interval

UPDATE: actually, since postgres does have a any || text更新:实际上,因为 postgres 确实有一个any || text any || text operator, the result of which is text , you shouldn't need to type cast the parameter. any || text运算符,其结果是text ,您不需要键入参数。

There is no way to interpolate a parameter into a string literal.无法将参数插入字符串文字。

A possible solution for your case would be to multiply a number with an interval:您的情况的可能解决方案是将一个数字乘以一个间隔:

where expires < (to_timestamp($1) - $2 * '1 minute'::interval)

You can use make_interval你可以使用make_interval

delete from my_table
where expires < (to_timestamp($1) - make_interval(mins => $2));

You can also parametrize the entire interval string instead.您也可以参数化整个间隔字符串。 This removes the need for an intermediate cast to text and concat.这消除了对text和连接的中间转换的需要。

query := `
  delete from my_table
  where expires < (to_timestamp($1) - $2::interval);
`
interval := fmt.Sprintf("%d minutes", mins)
db.Exec(query, timestamp, interval)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM