Function as parameter to another function in Postgres

ⅰ亾dé卋堺 提交于 2019-12-07 08:10:42

问题


Can I create a user defined function in Postgres either through the C-Language Function API or by using pl/pgsql which accepts a callback function as parameter?

As far as I see there is no way to do this through the C-Language API since it only accepts sql datatypes and there is no datatype for function. But maybe I'm missing something?


回答1:


I think you can't, but since there are no anonymous functions, passing function name should do.




回答2:


Since each function / procedure must have an entry in pg_proc, you can use the primary key for identifying the procedure. This would also eliminate the problems with procedures having the same name but different number of parameters or different parameter types.

Shorthands for this are the types regproc and regprocedure with the associated casts for easier handling. Lookup the manual for these.

Identifying the function and passing it around is no problem:

select 'pg_database_size(oid)'::regprocedure; -- create "reference"
     regprocedure      
-----------------------
 pg_database_size(oid)

Use regprocedure as the parameter type.

The problem I did not yet figure out is how to actually call such a thing in a convenient way.




回答3:


Old question and already has an accepted answer. But it doesn't clearly explain how to do this. So I thought of adding a more clear answer.

Let's assume you pass the callback function's name to your main function as a varchar value.

CREATE OR REPLACE FUNCTION public.get_function_fields(fn_name character varying)
    ...
    ...

Now if you want to call this fn_name function inside a query, you need to use EXECUTE command, and properly cast your function name using regproc as below.

EXECUTE 'create temp table if not exists temp_call as select * from ' || fn_name::regproc || '() limit 1';

Important part is this: ...|| fn_name::regproc || '()... As you can see, you have to append the parenthesis and cast the function name with ::regproc.

Hope it will help someone!



来源:https://stackoverflow.com/questions/8346065/function-as-parameter-to-another-function-in-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!