0

I have a postgres function which i am using to obtain data. Sometime it give a strange error in program like this:

Caused by: org.postgresql.util.PSQLException: ERROR: cursor "q" already in use

Here is my function:

CREATE OR REPLACE FUNCTION myArray(domain_name varchar, val json) RETURNS varchar LANGUAGE plpgsql STABLE AS $$
DECLARE
  result varchar;
  isarray BOOLEAN;
    q cursor for
    select json_agg(blogIn(null,b.value))
    from json_array_elements_text(val) b;
BEGIN
  SELECT json_typeof(val) = 'array' into isarray;
  if not isarray THEN
    return val;
  end if;
  open q;
  fetch q into result;
  close q;
  if result is null then
    return val;
  end if;
  return result;
END;
$$;

I am closing a cursor after using it but still it gave exception. Can someone tell me a reason of that.

6
  • Why do you use a cursor to begin with? Why don't you use a select ... into from ... instead?
    – user330315
    Nov 28, 2018 at 12:30
  • Well i finally understand and resolve this problem. This is because of using same cursor variable name (q cursor ...) both in functions, and one function is calling from another function. So before closing a cursor with same name when you try to use it within other function postgres gives you this problem.
    – user565
    Nov 28, 2018 at 14:45
  • 1
    Still, you don't need the cursor at all. You can simplify your function to something like this: cryptb.in/FniyDsVro
    – user330315
    Nov 28, 2018 at 14:48
  • i will change it like this
    – user565
    Nov 28, 2018 at 14:51
  • Also - unrelated - but: you should avoid using select for simple assignments. SELECT json_typeof(val) = 'array' into isarray; is better written as isarray := json_typeof(val) = 'array'; (but the variable is useless to begin with)
    – user330315
    Nov 28, 2018 at 14:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.