Eval Calculation-string: “2 * 3 + 4 * 5” in Postgresql

喜欢而已 提交于 2019-12-12 04:25:50

问题


I would like to evaluate a pure-calculation string in Postgres.

For example: eval('234 + 65 * 3')

The function is NOT constant, so could also simply be 2 + 2

Expecting something like SELECT eval('2 + 2') AS result

I read about huge security issues regarding eval() functions, but those seem to incorporate SELECT statements. Here pure calculation requirements.


回答1:


You need PL/pgSQL:

create or replace function f(_s text)
returns numeric as $$
declare i numeric;
begin
    execute format('select %s', _s) into i;
    return i;
end;
$$ language plpgsql;

select f('1 + 1');
 f 
---
 2


来源:https://stackoverflow.com/questions/43118512/eval-calculation-string-2-3-4-5-in-postgresql

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