1

Let's say I have a function show_files(IN file text, IN suffix text, OUT statement text). In next step the function is called:

 SELECT * FROM show_files(file := 'example', suffix := '.png');

My question is: Is there any solution that I could get statement that has called this function from inside that function?

I mean, after running the SELECT the output of function (OUT statement text) should be: 'SELECT * FROM show_files(file := 'example', suffix := '.png');', or is it possible to assign this statement to the variable inside the function?

I need the functionality like those with TG_NAME, TG_OP, etc. in trigger procedures.

Maybe is it possible to retrieve this statement from SELECT current_query FROM pg_stat_activity ?

When I'm trying to use it inside a function I've got an empty record:

CREATE OR REPLACE FUNCTION f_snitch(text)
  RETURNS text AS
$BODY$
declare
rr text;
BEGIN
    RAISE NOTICE '.. from f_snitch.';
    -- do stuff
    SELECT current_query  into rr FROM pg_stat_activity 
    WHERE current_query ilike 'f_snitch';
    RETURN rr;
END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

Any help and suggestions would be happily welcome!

4

2 回答 2

1

TG_NAME和朋友是只存在于触发函数的特殊变量。常规的 plpgsql 函数没有这样的东西。我对如何在 plpgsql 中的被调用函数中获得这个想法感到新鲜。

可以添加RAISE NOTICE到您的功能,以便获得所需的信息

CREATE OR REPLACE FUNCTION f_snitch(text)
  RETURNS text LANGUAGE plpgsql AS
$func$
BEGIN
    RAISE NOTICE '.. from f_snitch.';
    -- do stuff
    RETURN 'Snitch says hi!';
END
$func$;

称呼:

SELECT f_snitch('foo')

除了结果之外,这还会返回一个通知:

NOTICE:  .. from f_snitch.

未能取悦于两个方面:

  1. 来电声明不在通知中。
  2. 通知中没有上下文

对于1.您可以RAISE LOG改用(或将您的集群设置为也记录通知 - 我通常不这样做,对我来说太冗长了)。STATEMENT使用标准设置,您会在数据库日志中获得额外的一行:

LOG:  .. from f_snitch.
STATEMENT:  SELECT f_snitch('foo')

对于2. ,请查看dba.SE上的这个相关问题。CONTEXT看起来像:

CONTEXT:  SQL statement "SELECT f_raise('LOG', 'My message')"
    PL/pgSQL function "f_snitch" line 5 at PERFORM
于 2012-10-26T19:58:55.360 回答
0

好的,我知道了!

CREATE OR REPLACE FUNCTION f_snitch(text)
  RETURNS setof record AS
$BODY$
BEGIN
   RETURN QUERY
    SELECT current_query 
    FROM pg_stat_activity 
    <strike>ORDER BY length(current_query) DESC LIMIT 1;</strike>
    where current_query ilike 'select * from f_snitch%';
    -- much more reliable solution

END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

  select * from f_snitch('koper') AS (tt text);

结果如下:

在此处输入图像描述

它可能不是 100% 可靠的解决方案,但对于小型系统(对于少数用户)来说,这还不错。

于 2012-10-30T14:58:31.307 回答