1

I am trying to use Jsonb in a postgres function. I am not able to send parameters properly.

mac=# CREATE TABLE json_test (id serial, json jsonb);
CREATE TABLE
mac=# INSERT INTO json_test (json) VALUES ('{"key": "value"}');
INSERT 0 1
mac=# SELECT * FROM json_test;
 id |       json       
----+------------------
  1 | {"key": "value"}
(1 row)

mac=# SELECT * FROM json_test WHERE json->'key' @> '"value"';
 id |       json       
----+------------------
  1 | {"key": "value"}
(1 row)

mac=# CREATE OR REPLACE FUNCTION testando() RETURNS setof int AS $$
mac$#   SELECT id FROM json_test WHERE json->'key' @> '"value"';
mac$# $$ LANGUAGE SQL;
CREATE FUNCTION
mac=# SELECT * FROM testando();
 testando 
----------
    1
(1 row)

mac=# CREATE OR REPLACE FUNCTION testando(value_param varchar) RETURNS setof int AS $$
mac$#   SELECT id FROM json_test WHERE json->'key' @> '"$1"';
mac$# $$ LANGUAGE SQL;
CREATE FUNCTION
mac=# SELECT * FROM testando('value');
 testando 
----------
(0 rows)

This query should return value:

SELECT * FROM testando('value');

Does anyone know how to send a parameter properly in this case ?

1 Answer 1

1

When writing json->'key' @> '"$1"'; you are using '"$1"' as a literal constant with the value $1. Don't wrap your parameter in quotes so it actually references the parameter:

CREATE OR REPLACE FUNCTION testando(value_param varchar) RETURNS setof int AS $$
SELECT id FROM json_test WHERE json->'key' @> $1::jsonb;
$$ LANGUAGE SQL;
SELECT * FROM testando('"value"');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.