how do i pass a list of variable values to a SQL statement in a postgres dblink function?

72 Views Asked by At

i have a multivalue variable called countries. i am forced to deal with multiple postgres databases in a monitoring situation so i need to use a dblink to generate a table alias. how do i call the below function passing the countries in the IN clause?

dblink(
 'link1',
 'select * from table where country_id in (' || ${countries} || ')'
) as (
  col1 text,
 col2 text etc...
)

the variable is passed early and results in

dblink(
 'link1',
 'select * from table where country_id in (' || 'IN','CN' || ')'
) as (
  col1 text,
 col2 text etc...
)

this results in

dblink(
 'link1',
 'select * from table where country_id in (IN',
 'CN)'
) as (
  col1 text,
 col2 text etc...
)

which is basically wrong number of arguments being passed to dblink() and more importantly a nonsensical query. i could not figure out a way of wrapping the variable value in a set of quotes.. so that dblink would not parse the comma.

Any suggestions?

I tried using replace function to escape single quotes. tried using the grafana join() function to concatenate countries with '','' etc. all suggestions from chatgpt.

EDIT: For now i have solved this problem by using a numeric field. I luckily had the option of joining an addition table to use a numeric field. the reason i picked this option is because ${countries.csv} was rightly producing IN,CN so i changed it to country_id so that i ended up with 1,2 instead which doesnt have to deal with quotes. here is the final solution that works.

dblink(
 'link1',
 'select * from table where country_id_pk in (' || '${countries:csv}' || ')'
) as (
  col1 text,
 col2 text etc...
)
0

There are 0 best solutions below