开发者

Are there any way to execute a query inside the string value (like eval) in PostgreSQL?

I want to do like this:

SELECT (EVAL 'SELECT 1') + 1;

Are there any way to do like this (EVAL) in PostgreSQL开发者_JAVA技巧?


If the statements you are trying to "eval" always return the same data type, you could write an eval() function that uses the EXECUTE mentioned by Grzegorz.

create or replace function eval(expression text) returns integer
as
$body$
declare
  result integer;
begin
  execute expression into result;
  return result;
end;
$body$
language plpgsql

Then you could do something like

SELECT eval('select 41') + 1;

But this approach won't work if your dynamic statements return something different for each expression that you want to evaluate.

Also bear in mind that this opens a huge security risk by running arbitrary statements. If that is a problem depends on your environment. If that is only used in interactive SQL sessions then it isn't a problem.


NOTES

The language PLpgSQL syntax have many ways to say:

 Y := f(X);

The EXECUTE clause is only for "dynamic execution" (less performance),

 EXECUTE 'f(X)' INTO Y;     

Use Y := f(X); or SELECT for execute static declarations,

 SELECT f(X) INTO Y;

Use PERFORM statment when discard the results or to work with void returns:

 PERFORM f(X);     


I'd go with data type text since it's more flexible using casting operators like ::int if needed:

create or replace function eval( sql  text ) returns text as $$
declare
  as_txt  text;
begin
  if  sql is null  then  return null ;  end if ;
  execute  sql  into  as_txt ;
  return  as_txt ;
end;
$$ language plpgsql
-- select eval('select 1')::int*2         -- => 2
-- select eval($$ select 'a'||1||'b' $$)  -- => a1b
-- select eval( null )                    -- => null

I also added this and another eval( sql, keys_arr, vals_arr ) function supporting some custom key-value substitutions, e.g. for handy :param1 substitutions to postgres-utils


I am not sure if it suits you but PostgreSQL has EXECUTE statement.


Good idea. You can modify to perform direct expressions:

create or replace function eval(expression text) returns integer
as
$body$
declare
  result integer;
begin
  execute 'SELECT ' || expression into result;
  return result;
end;
$body$
language plpgsql;

To run just type this:

SELECT eval('2*2');


Assuming that most sql queries are a part of a bigger system, there mostly will be cases where you form a query with your backend code and then execute it.

So if that’s the case for you, you can just use subselects or common table expressions that are put into your query string by the backend code before execution.

I have trouble coming up with cases where the solution you want works and my solution doesn’t, apart from not having any backend app, of course.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜