SQL Server has a feature whereby you can call a function or stored procedure with a variable name for the func/proc name. Toy example:
declare @name sysname;
declare @method int = 1;
set @name = IIF(@method = 1, N'Newton', N'Taylor')
declare @sqrt float;
exec @sqrt = @name 42
This will call either Newton or Taylor depending on the value of @method. Using this, it is possible to implement the strategy or command OOP patterns in T-SQL. Where I work, we use it for just that purpose.
Now that I'm learning Postgresql, I'm wondering how I would do something similar in pgplsql. Any tips appreciated!
If all called functions return a single value of the same data type and take a single parameter of the same data type, you can do that with dynamic SQL in Postgres as well:
create or replace function evaluate(p_input integer, p_method text)
returns float
as
$$
declare
l_result float;
begin
execute 'select '||p_method||'($1)'
using p_input
into l_result;
return l_result;
end;
$$
language plpgsql;
select evaluate(42, 'sqrt');
returns 6.48074069840786select evaluate(1, 'exp');
returns 2.718281828459045This works with multiple parameters as well:
create or replace function evaluate(p_arg_1 integer, p_arg_2 text, p_method text)
returns float
as
$$
declare
l_result float;
begin
execute 'select '||p_method||'($1, $2)'
using p_arg_1, p_arg_2
into l_result;
return l_result;
end;
$$
language plpgsql;
Nice! Can that approach work with more than one arg?
@user1443098: as long as all called functions accept multiple arguments, yes.
perfect for strategy pattern. I'll take it