I have this stored procedure T1 which returns a refcursor.
create procedure t1(inout rr refcursor)
as $$
begin
open rr for select 'receiving it';
end;
$$ language plpgsql;
Another stored procedure t_main calls T1 and it needs to return the same refcursor result set of T1.
create or replace procedure t_main(inout rc refcursor)
as
$$
declare
rc_in refcursor;
begin
call t1(rc_in);
rc := rc_in;
end;
$$
language plpgsql;
The part rc := rc_in; is not passing the refcursor rc_in to rc. When I execute t_main, I get error saying cursor 'rc' does not exist.
Thanks in advance.
The solution is as below
create or replace procedure t_main(inout rc refcursor)
as
$$
begin
call t1(rc );
end;
$$
language plpgsql;
Using the same refcursor parameter of the main procedure in the dependent procedure solved the issue.
Related
May I ask on how to call a method when the content of the stored procedure is about select statement? (Using postgreSQL)
CREATE OR REPLACE PROCEDURE select_table(table_name VARCHAR(255))
language plpgsql
as $$
BEGIN
EXECUTE('SELECT * FROM' || ' ' || quote_ident(table_name));
END $$;
CALL select_table('employee_table');
EDITED(USING FUNCTION)
CREATE OR REPLACE FUNCTION select_table(table_name VARCHAR(255))
language plpgsql
as $$
BEGIN
SELECT * FROM table_name
RETURN table_name;
END $$;
In PostgreSQL procedures doesn't execute any select statements and doesn't have return.
For returning data you can use functions. But functions also cannot return different structural data, examples:
CREATE OR REPLACE FUNCTION fr_test()
RETURNS TABLE(id integer, bookname character varying)
LANGUAGE plpgsql
AS $function$
begin
return QUERY
SELECT tb.id, tb.bookname from rbac.books tb;
end;
$function$
;
or
CREATE OR REPLACE FUNCTION fr_test()
RETURNS setof public.books
LANGUAGE plpgsql
AS $function$
begin
return QUERY
SELECT * from public.books;
end;
$function$
;
But for returning difference tables you can do it using procedures and using out refcursor, like as in Oracle. For example:
create or replace procedure pr_test(OUT r1 refcursor)
as $$
begin
open r1 for
select * from public.books;
end;
$$ language plpgsql;
I am creating a stored procedure in PostgreSQL 9.6 but I am getting syntax error. I am new to PostgreSQL. Are there more syntax errors in my code?
CREATE OR REPLACE FUNCTION DBO.Proc_Activity()
DECLARE
a_sActivityName TYPE VARCHAR(30);
a_sActivityDescription TYPE VARCHAR(2000);
a_sUserName TYPE VARCHAR(30);
a_sErrDesc TYPE VARCHAR(500);
RETURNS VOID AS $$
BEGIN
insert into Activity_Log (sActivityName,sActivityDescription,sError,dCreatedDate,sCreatedBy)values( a_sActivityName ,a_sActivityDescription, a_sErrDesc ,NOW(),a_sUserName)
END;
$$ LANGUAGE plpgsql;
And also: how can I call this procedure to test if its working ?
Thanks
Declare your function like this
CREATE OR REPLACE FUNCTION Proc_Activity()
RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
a_sActivityName VARCHAR;
a_sActivityDescription VARCHAR;
a_sUserName VARCHAR;
a_sErrDesc VARCHAR;
BEGIN
insert into Activity_Log (sActivityName,sActivityDescription,sError,dCreatedDate,sCreatedBy)values( a_sActivityName ,a_sActivityDescription, a_sErrDesc ,NOW(),a_sUserName);
END;
$$;
Documentation : Create function
I have a stored procedure(P1) that returns a refcursor and few other text datatype values.
I have another procedure(P2) where I need to the fetch P1's refcursor output and insert it into a temporary table. The temporary table has matching columns and datatypes.
create or replace procedure P1(inout rfcur refcursor, in dtl text)
as
$$
begin
open rfcur for select * from tst_dump where ident = dtl;
end;
$$
language plpgsql;
create or replace P2(inout rfc refcursor, in dt_array text[])
as
$$
declare
i record;
cur refcursor;
begin
for i in array_lower(dt_array, 1)..array_upper(dt_array, 1) loop
call P1(cur, i);
--I need to fetch the result set from `cur` and store into a temp table `t_tab1`.
end loop;
end;
$$
language plpgsql;
Is it possible to achieve this in Postgres?
NOTE: I'm not supposed to make any changes to the procedure P1.
p2 could look like this:
CREATE PROCEDURE p2(IN dt_array text[])
LANGUAGE plpgsql AS
$$DECLARE
r record;
i integer;
cur refcursor;
BEGIN
FOR i IN array_lower(dt_array, 1)..array_upper(dt_array, 1) LOOP
CALL p1(cur, i::text);
LOOP
FETCH cur INTO r;
EXIT WHEN NOT FOUND;
INSERT INTO t_tab1 (...) VALUES (r.col1, r.col2, ...;
END LOOP;
END LOOP;
END;$$;
You should indent your code. That's the basic requirement when you program.
It seems to me that you are doing something the wrong way. Using procedures and cursors complicates everything and makes it slower.
You should do something like
INSERT INTO t_tab
SELECT /* your original query */;
I am trying to have a parameter when creating a trigger function.
I have been trying to use this code:
DO $DO$
BEGIN
EXECUTE format($TRIGGER$
CREATE OR REPLACE FUNCTION my_schema.my_trigger_fcn() RETURNS trigger AS
$BODY$
DECLARE
my_geom geometry(MultiPoint,%1$s);
BEGIN
my_geom = st_collect(NEW.situation_geometry)::geometry(MultiPoint,%$1s);
NEW.geometry = my_geom;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
$TRIGGER$, :SRID);
END
$DO$;
and trying to run this code with psql -v SRID=2056 -f myfile.
But I get a syntax error.
I have also tried the SQL execute command, but prepared statements are not allowed to create trigger function.
Any idea?
SOLUTION:
Thanks to #Pavel Stehule, here is the code that works:
SELECT set_config('my.srid', :SRID::text, false);
DO $DO$
BEGIN
EXECUTE format($TRIGGER$
CREATE OR REPLACE FUNCTION qgep_od.my_trigger_fcn() RETURNS trigger AS
$BODY$
DECLARE
my_geom geometry(MultiPoint,%1$s);
BEGIN
my_geom = st_collect(NEW.situation_geometry)::geometry(MultiPoint,%1$s);
NEW.geometry = my_geom;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
$TRIGGER$, current_setting('my.srid'));
END
$DO$;
You cannot to use psql variables inside any SQL string. The string is body of DO command too. You can use session variables:
\set myvar xxx
select set_config('my.myvar', :'myvar', false);
do $$
begin
execute format('create or replace function fx() returns void as $_$begin raise notice %L; end$_$ language plpgsql', current_setting('my.myvar'));
end;
$$;
postgres=# \sf fx
CREATE OR REPLACE FUNCTION public.fx()
RETURNS void
LANGUAGE plpgsql
AS $function$begin raise notice 'xxx'; end$function$
Other possibility is do this replacement before psql - you can use sed
I have a Postgres function with a lot of duplicated logic. If I were writing this in, say, Ruby, I would extract the duplicated logic into a few private helper methods. But there doesn't seem to be an equivalent of "private methods" in Postgres.
Original Function
CREATE OR REPLACE FUNCTION drop_create_idx_constraint(in_operation varchar, in_table_name_or_all_option varchar) RETURNS integer AS $$
DECLARE
cur_drop_for_specific_tab CURSOR (tab_name varchar) IS SELECT drop_stmt FROM table_indexes WHERE table_indexes.table_name = table_name_to_drop;
cur_drop_for_all_tab CURSOR IS SELECT drop_stmt FROM table_indexes;
cur_create_for_specific_tab CURSOR (tab_name varchar) IS SELECT recreate_stmt FROM table_indexes WHERE table_indexes.table_name = table_name_to_drop;
cur_create_for_all_tab CURSOR IS SELECT recreate_stmt FROM table_indexes;
BEGIN
IF upper(in_operation) = 'DROP' THEN
IF upper(in_table_name_or_all_option) ='ALL' THEN
FOR table_record IN cur_drop_for_all_tab LOOP
EXECUTE table_record.drop_stmt;
END LOOP;
ELSE
FOR table_record IN cur_drop_for_specific_tab(in_table_name_or_all_option) LOOP
EXECUTE table_record.drop_stmt;
END LOOP;
END IF;
ELSIF upper(in_operation) = 'CREATE' THEN
IF upper(in_table_name_or_all_option) ='ALL' THEN
FOR table_record IN cur_create_for_all_tab LOOP
EXECUTE table_record.recreate_stmt;
END LOOP;
ELSE
FOR table_record IN cur_create_for_specific_tab(in_table_name_or_all_option) LOOP
EXECUTE table_record.recreate_stmt;
END LOOP;
END IF;
END IF;
RETURN 1;
END;
$$ LANGUAGE plpgsql;
Refactored Function(s)
CREATE OR REPLACE FUNCTION execute_recreate_stmt_from_records(input_cursor refcursor) RETURNS integer AS $$
BEGIN
FOR table_record IN input_cursor LOOP
EXECUTE table_record.recreate_stmt;
END LOOP;
RETURN 1;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION execute_drop_stmt_from_records(input_cursor refcursor) RETURNS integer AS $$
BEGIN
FOR table_record IN input_cursor LOOP
EXECUTE table_record.drop_stmt;
END LOOP;
RETURN 1;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION drop_indexes_and_constraints(table_name_to_drop varchar) RETURNS integer AS $$
DECLARE
indexes_and_constraints CURSOR IS SELECT drop_stmt FROM table_indexes WHERE table_indexes.table_name = table_name_to_drop;
SELECT execute_drop_stmt_from_records(indexes_and_constraints);
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION drop_all_indexes_and_constraints() RETURNS integer AS $$
DECLARE
indexes_and_constraints CURSOR IS SELECT drop_stmt FROM table_indexes;
SELECT execute_drop_stmt_from_records(indexes_and_constraints);
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION recreate_indexes_and_constraints(table_name_to_recreate varchar) RETURNS integer AS $$
DECLARE
indexes_and_constraints CURSOR IS SELECT recreate_stmt FROM table_indexes WHERE table_indexes.table_name = table_name_to_recreate;
SELECT execute_recreate_stmt_from_records(indexes_and_constraints);
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION recreate_all_indexes_and_constraints() RETURNS integer AS $$
DECLARE
indexes_and_constraints CURSOR IS SELECT recreate_stmt FROM table_indexes;
SELECT execute_recreate_stmt_from_records(indexes_and_constraints);
$$ LANGUAGE plpgsql;
I believe the underlying problem with my refactor is that the helper functions, execute_recreate_stmt_from_records and execute_drop_stmt_from_records, are way too powerful to be publicly accessible, especially since Heroku (which hosts this DB) only allows one DB user. Of course, if there are other problems with the above refactor, feel free to point them out.
You can reach separation by moving "private" procedures into a new schema, limiting access to it. Then use a SECURITY DEFINER to allow calls to "private" functions.
Although, this will be hard to achieve if you are limited to a single user by your hosting service.
Example:
CREATE USER app_user;
CREATE USER private_user;
GRANT ALL ON DATABASE my_database TO app_user;
GRANT CONNECT, CREATE ON DATABASE my_database TO private_user;
-- With private_user:
CREATE SCHEMA private;
CREATE OR REPLACE FUNCTION private.test_func1()
RETURNS integer AS
$BODY$
BEGIN
RETURN 123;
END
$BODY$
LANGUAGE plpgsql STABLE
COST 100;
CREATE OR REPLACE FUNCTION public.my_function_1()
RETURNS integer AS
$BODY$
DECLARE
BEGIN
RETURN private.test_func1();
END
$BODY$
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
COST 100;
-- With app_user:
SELECT private.test_func1(); -- ERROR: permission denied for schema private
SELECT my_function_1(); -- Returns 123