简体   繁体   中英

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. My prepared statement in go looks like this:

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

How can I correctly pass the second parameter $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.

You can cast the parameter to text and then concatenate it with the string ' minutes' .

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

UPDATE: actually, since postgres does have a any || text any || text operator, the result of which is text , you shouldn't need to type cast the parameter.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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