I wrote a postgres function which takes an array of integers as an argument
create or replace function f_get_profiles(
exp_array jsonb,
lng_array int[]
)
I am calling this function as :
SELECT * FROM
f_get_profiles(
'[{"role": 1, "experience": 2 }, {"role": 2, "experience": 3}]',
array[1,2,3,4]::int[]
);
And in the function i want to use it as a regular integer array, I've tried it in 2 ways
format(' AND languages && %s', lng_array)
and
format(' AND languages && array[%s]', lng_array)
Both are giving me error :
error :
ERROR: syntax error at or near "{"
LINE 3: ....role == 2 && @.experience >= 3)' AND languages && {1,2,3,4}
and
ERROR: syntax error at or near "{"
LINE 3: ...= 2 && @.experience >= 3)' AND languages && array[{1,2,3,4}]
respectively....
Could anyone please help? Am i missing something here>?
full function
create or replace function f_get_profiles(
exp_array jsonb,
lng_array int[],
_limit int=10,
_offset int=0
)
returns setof profiles
language plpgsql parallel SAFE stable strict as
$func$
declare final_sql text;
begin
select into final_sql
E'SELECT * FROM profiles \nWHERE expertise @? ' ||
string_agg(
quote_nullable(format('$[*] ? (@.role == %s && @.experience >= %s)', f->'role', f->'experience')) || '',
E'\nOR expertise @? '
) || format(' AND languages && %s', lng_array)
|| E'\nLIMIT ' || _limit || E'\nOFFSET ' || _offset
from jsonb_array_elements(exp_array) as f;
if final_sql is null then
raise exception 'SQL statement is NULL. Should not occur!';
else
return query execute final_sql;
end if;
end
$func$;