Warm tip: This article is reproduced from stackoverflow.com, please click
postgresql

Porting strategy pattern from SQL Server to Postgresql

发布于 2020-03-27 10:20:05

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!

Questioner
user1443098
Viewed
106
a_horse_with_no_name 2019-07-03 22:50

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.48074069840786
  • select evaluate(1, 'exp'); returns 2.718281828459045

This 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;