1

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,

asked Nov 28, 2015 at 23:56
1
  • 1
    I'm not aware of any good way to do this. Access to the call stack via 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. Commented Nov 29, 2015 at 5:23

2 Answers 2

1

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.

answered Nov 29, 2015 at 16:09
0

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
answered Nov 22, 2022 at 11:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.