Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 779
minhee Avatar asked Sep 15 '11 15:09

minhee


People also ask

How do I match a string in PostgreSQL?

We can compare the string using like clause in PostgreSQL, we can also compare the string using the =, != , <>, <, >, <= and >= character string operator. Basically character string operator in PostgreSQL is used to compare the string and return the result as we specified input within the query.

Which function is used to execute query in PostgreSQL?

To do this in PL/pgSQL, use the PERFORM statement: PERFORM query ; This executes query and discards the result. Write the query the same way you would write an SQL SELECT command, but replace the initial keyword SELECT with PERFORM .

What does := mean in PostgreSQL?

:= is the assignment operator in PL/pgSQL.


2 Answers

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);     
like image 34
Peter Krauss Avatar answered Oct 05 '22 08:10

Peter Krauss


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.

like image 111
a_horse_with_no_name Avatar answered Oct 05 '22 07:10

a_horse_with_no_name