postgresql: converting CTE column to array - postgresql

I am trying to convert one of the columns of CTE to array. I keep on getting "syntax error at or near" followed by "ret := array(".
My objective is that the table I am returning from a_function() in example below is stored as a variable to be referred later in function. But I could not find a syntax to do so. So, instead of using CTE, if I can use something else, that would work just as nicely.
Note: I am trying this in pgAdmin III.
create or replace function a_function()
--returns int[][] as
returns table(column1 int, column2 int) as
$body$
begin
return query
select 1,2;
end;
$body$
language 'plpgsql'
;
--select * from a_function();
create or replace function test_a_function()
returns void as
$body$
declare ret int[];
begin
with ret_cte(column1, column2) as (
select * from a_function()
)
ret := array(
select column1 from ret_cte
)
;
--raise notice '%', array_to_string(ret, ',');
end;
$body$
language 'plpgsql'
;
--select test_a_function();

I am trying to convert one of the columns of CTE to array. I keep on getting "syntax error at or near" followed by "ret := array("
You could use:
ret :=array(with ret_cte(column1, column2) as (
select * from a_function()
)
select column1 from ret_cte
);
Rextester Demo

Arrays can be built and returned using the array_agg() function. For example, your second function could be written using a SQL language function that returns the array as follows:
create or replace function test_a_function()
returns int[] as
$body$
select array_agg(column1) from a_function();
$body$
language 'sql';
Alternatively, you can assign the array to a variable like this:
create or replace function test_a_function()
returns void as
$body$
declare
ret int[];
begin
select array_agg(column1)
into ret
from a_function();
raise info '%', ret;
end;
$body$
language 'plpgsql';

Related

Declare type of setof bigint in plpgsql function and assign into from select union

The following code currently works on PostgreSQL 13.3 (via Supabase.io). Both functions get_owned_base_ids and get_bases_editable have return type of setof bigint:
CREATE FUNCTION get_owned_base_ids()
returns setof bigint
stable
language sql
as $$
select id
from bases
where bases.owner_user_id = auth.uid();
$$;
-- CREATE FUNCTION get_bases_editable()
-- returns setof bigint
-- ... similar to get_owned_base_ids()
-- $$;
CREATE FUNCTION xyz (base_id bigint)
returns int
language plpgsql
as $$
BEGIN
IF base_id not in (select get_owned_base_ids() UNION select get_bases_editable()) THEN
-- note: actual function logic is simplified for this question
return 1;
END IF;
return 0;
END;
$$;
Is it possible to define a setof bigint and assign that from the select union? Something like this:
CREATE FUNCTION xyz (base_id bigint)
returns int
language plpgsql
as $$
DECLARE
allowed_base_ids bigint; -- needs to be a setof
BEGIN
select into allowed_base_ids get_owned_base_ids() UNION select get_bases_editable();
IF kv.base_id not in allowed_base_ids THEN
-- note: actual function logic is simplified for this question
return 1;
END IF;
return 0;
END;
$$;
It usually does not make much sense and use much memory of the result set is large, but you can use an array:
DECLARE
allowed_base_ids bigint[];
BEGIN
allowed_base_ids := array(SELECT * FROM get_owned_base_ids()
UNION ALL
SELECT * FROM get_bases_editable());
IF kv.base_id <> ALL (allowed_base_ids) THEN
...
END IF;
END;

WITH clause containing a data-modifying statement must be at the top level SQL-state: 0A000

I wrote function, which using WITH construction with insert into table like this:
CREATE OR REPLACE FUNCTION test_func()
RETURNS json AS
$BODY$
begin
return (
with t as (
insert into t(id)
select 1
returning *
)
select '{"a":"a"}'::json
);
end;
$BODY$
LANGUAGE plpgsql VOLATILE;
select test_func()
Thats return error:
ERROR: WITH clause containing a data-modifying statement must be at the top level
SQL-состояние: 0A000
If execute
with t as (
insert into t(id)
select 1
returning *
)
select '{"a":"a"}'::json
Result without errors.
Why this take place and how get round this?
You are doing subselect on that query, with is why it doesn't work.
This won't work either:
select * from (
with t as (
insert into t(id)
select 10
returning *
)
select '{"a":"a"}'::json
) as sub
There are a few solutions to this.
a) Declare it as returning setof and use return query
CREATE OR REPLACE FUNCTION test_func()
RETURNS setof json AS
$BODY$
begin
return query
with t as (
insert into t(id)
select 7
returning *
)
select '{"a":"a"}'::json;
end;
$BODY$
LANGUAGE plpgsql VOLATILE;
b) Declare it as language sql
CREATE OR REPLACE FUNCTION test_func()
RETURNS json AS
$BODY$
with t as (
insert into t(id)
select 8
returning *
)
select '{"a":"a"}'::json;
$BODY$
LANGUAGE sql VOLATILE;
c) Declare output variable(s) in argument list and assign result to them
CREATE OR REPLACE FUNCTION test_func(OUT my_out_var json)
AS
$BODY$
begin
with t as (
insert into t(id)
select 9
returning *
)
select '{"a":"a"}'::json INTO my_out_var;
end;
$BODY$
LANGUAGE plpgsql VOLATILE;

Syntax error at or near "unnest"

This request:
unnest('{1,2}'::int[]);
gives to me this error:
syntax error at or near "unnest"
neither unnest('{1,2}'); works
Why?
intire:
CREATE OR REPLACE FUNCTION result() RETURNS setof users AS
$$
DECLARE
BEGIN
unnest('{1,2}'::int[]);
RETURN QUERY SELECT * FROM users;
END;
$$ LANGUAGE plpgsql;
SELECT result();
EDIT
The core idea:
To retrive and manipualate with the bigint[] which is stored inside in a column.
So, i have got this:
SELECT * FROM users WHERE email = email_ LIMIT 1 INTO usr;
Then, usr.chain contains some bigint[] data. For example, {1,2,3,4,5,6,7,8,9,10}. I want to save only the 4 last of them.
How to retrieve {7,8,9,10} and {1,2,3,4,5,6} and iterate over these arrays?
I only found the solution is to use SELECT FROM unnest(usr.chain) AS x ORDER BY x ASC LIMIT (sdl - mdl) OFFSET mchain and so on. but unnest function gives to me this stupid error. I'm really do not understand why it happends. It doesn't work in sucj easy case I wrote at the beginning of the question. subarray function doesn't work because of the data type is bigint[] not int[]
Futher more, the code unnest(ARRAY[1,2]) gives to me the same error.
http://www.postgresql.org/docs/9.2/static/functions-array.html
The same error for array_append function
to iterate over array:
CREATE OR REPLACE FUNCTION someresult(somearr bigint[] ) RETURNS setof bigint AS
$$
DECLARE
i integer;
x bigint;
BEGIN
for x in select unnest($1)
loop
-- do something
return next x;
end loop;
-- or
FOR i IN array_lower($1, 1) .. array_upper($1, 1)
LOOP
-- do something like:
return next ($1)[i];
end loop;
END;
$$ LANGUAGE plpgsql;
select someresult('{1,2,3,4}') ;
array_append ....
CREATE OR REPLACE FUNCTION someresult2(somearr bigint[],val bigint ) RETURNS bigint[] AS
$$
DECLARE
somenew_arr bigint[];
BEGIN
somenew_arr = array_append($1, $2 );
return somenew_arr;
END;
$$ LANGUAGE plpgsql;
select someresult2('{1,2,3,4}' ,222) ;
so, here you have basic example how to iterate and append arrays. Now can you write step by step what you want to do, to achieve .

I am trying to unnet an array in other to query the postgres DB

I am call the function but it is returning error that array value must start with "{" or dimension information using
Create or Replace Function get_post_process_info(IN v_esdt_pp character varying[])
Returns setof Record as
$$
Declare
post_processes RECORD;
esdt_value character varying;
v_sdsname character varying[];
v_dimension character varying[];
counter int := 1;
Begin
-- to loop through the array and get the values for the esdt_values
FOR esdt_value IN select * from unnest(v_esdt_pp)
LOOP
-- esdt_values as a key for the multi-dimensional arrays and also as the where clause value
SELECT distinct on ("SdsName") "SdsName" into v_sdsname from "Collection_ESDT_SDS_Def" where "ESDT" = esdt_values;
raise notice'esdt_value: %',esdt_value;
END LOOP;
Return ;
End
$$ Language plpgsql;
Select get_post_process_info(array['ab','bc]);
Your function sanitized:
CREATE OR REPLACE FUNCTION get_post_process_info(v_esdt_pp text[])
RETURNS SETOF record AS
$func$
DECLARE
esdt_value text;
v_sdsname text[];
v_dimension text[];
counter int := 1;
BEGIN
FOR esdt_value IN
SELECT * FROM unnest(v_esdt_pp) t
LOOP
SELECT distinct "SdsName" INTO v_sdsname
FROM "Collection_ESDT_SDS_Def"
WHERE "ESDT" = esdt_value;
RAISE NOTICE 'esdt_value: %', esdt_value;
END LOOP;
END
$func$ Language plpgsql;
Call:
Select get_post_process_info('{ab,bc}'::text[]);
DISTINCT instead of DISTINCT ON, missing table alias, formatting, some cruft, ...
Finally the immediate cause of the error: a missing quote in the call.
The whole shebang can possibly be replaced with a single SQL statement.
But, obviously, your function is incomplete. Nothing is returned yet. Information is missing.

PostgreSQL functions select*

How can I use:
select * from <some_table>;
in a FUNCTION in Postgres?
CREATE OR REPLACE FUNCTION my_function() RETURNS INTEGER AS '
DECLARE
your_record your_table%ROWTYPE;
BEGIN
FOR your_record IN SELECT * FROM your_table
LOOP
--
-- You can access fields of your table using .
-- your_record.your_field
...
END LOOP;
END;
' LANGUAGE 'plpgsql'
STABLE;
or
CREATE OR REPLACE FUNCTION my_function() RETURNS INTEGER AS '
DECLARE
your_record your_table%ROWTYPE;
BEGIN
SELECT * INTO your_record FROM your_table;
--
-- You can access fields of your table using .
-- your_record.your_field
END;
' LANGUAGE 'plpgsql'
STABLE;
EDIT:
With join returning a record:
CREATE OR REPLACE FUNCTION my_function() RETURNS SETOF record AS '
DECLARE
your_record record;
BEGIN
--
-- You should specify a list of fields instead of *
--
FOR your_record IN SELECT * FROM your_table INNER JOIN ...
RETURN NEXT your_record;
END LOOP;
END;
' LANGUAGE 'plpgsql'
STABLE;
To use my_function(), you have to specify fields and datatypes:
See details here
There is a smipler method, if you want to use SQL in the function, use SQL language in the function:
CREATE FUNCTION getallzipcodes()
RETURNS SETOF zip AS
$BODY$
SELECT * FROM zip;
$BODY$
LANGUAGE 'sql';
And this might be useful too (how to call the function)
SELECT function_returning_setof(); -- Wrong!
SELECT * FROM function_returning_setof(); -- OK!
SELECT function_returning_scalar(); -- OK
reference