Here are the two cases:
- Function fA fetches some rows and returns a table
- Function fB calls function fA and returns a table
Within fA, how could I know whether it's been called from the program or by fB?
Is there some @@nestlevel that can count how deep in the stack are the functions running?
Big thank you in advance,
2 Answers 2
There's a different, simpler, solution for this. Add an argument to function fA
with a default value, for instance: called_from_b BOOLEAN DEFAULT FALSE
. Then, provide that argument when calling fA
from fB
.
I understand that this doesn't directly answer your question, but it does provide a solution for the example usecase that you provide.
As of 2022, this is now possible (and easy) in all currently supported PostgreSQL versions, thanks to GET DIAGNOSTICS
:
BEGIN TRANSACTION;
CREATE TYPE stuff AS (
nestlevel int
,arbitrary text
);
CREATE OR REPLACE FUNCTION fa()
RETURNS stuff
LANGUAGE plpgsql
AS $$
DECLARE
_stack text;
BEGIN
GET DIAGNOSTICS _stack = PG_CONTEXT;
RETURN ROW(
array_length(string_to_array(_stack, E'\n'), 1) - 1,
'Some text'
)::stuff;
END;
$$;
CREATE OR REPLACE FUNCTION fb()
RETURNS stuff
LANGUAGE plpgsql
AS $$
BEGIN
RETURN fa();
END;
$$;
SELECT fa();
SELECT fb();
ROLLBACK TRANSACTION;
BEGIN
CREATE TYPE
CREATE FUNCTION
CREATE FUNCTION
fa
-----------------
(0,"Some text")
(1 row)
fb
-----------------
(1,"Some text")
(1 row)
ROLLBACK
GET DISAGNOSTICS
has been discussed and may be implemented for 9.6. Ask on pgsql-general and suggest it as a feature - or even better, implement it and send in a patch to plpgsql.