How to fix postgres-utils eval() error: missing FROM-clause entry for table "foo"?

How to fix postgres-utils eval() error: missing FROM-clause entry for table "foo"?

我正在寻找一种方法来评估存储在 Postgres 9.1+ 数据库中的价格表达式

我尝试了以下答案中的代码 How to evaluate expression in select statement in Postgres

但出现错误

ERROR:  missing FROM-clause entry for table "product"
LINE 1: select product.price*0.95

如何解决?

也许可以将客户和产品当前行作为评估参数传递并在评估表达式中使用它们?

create or replace function eval( sql  text ) returns text as $$
declare
  as_txt  text;
begin
  execute 'select ' ||   sql  into  as_txt ;
  return  as_txt ;
end;
$$ language plpgsql;


create table customer
( id int primary key,
  priceexpression text );
insert into customer values (1, 'product.price*0.95'),(2,'cost+12.0' );

create table product
( id char(20) primary key,
   price numeric(12,4),
   cost numeric(12,4) );
insert into product values ('PRODUCT1', 120, 80),('PRODUCT2', 310.5, 290);


select
  customer.id as customer,
  product.id as product,
  eval(priceexpression) as price
 from customer,product

只需在某处添加 table 名称。可能是

insert into customer values (1, 'product.price*0.95 FROM product'),(2,'cost+12.0 FROM product' );

或者可能是

 execute 'select ' ||   sql || ' FROM product' into  as_txt ;

任您选择。

希望这个 priceexpression 不会暴露给用户,而只暴露给有限数量的管理员,因为它很危险 sql 注入安全漏洞。

Serg 基本上是对的。 你的 dyna-SQL 被执行 "on its own" 所以它需要是一个有效的 SQL 语句(有 "to know" 所有涉及的表 )。我updated my answer in the referred thread反映了这一点。

但要在此处正确引用它,您的示例应该类似于(实际上您应该 使用第二个 eval( sql text, keys text[], vals text[] ) 变体!):

eval(  
  'select '||c.price_expression||' from product where id=:pid',
  '{"{cost}",:pid}',  
  array[ p.cost, p.id ]  
)      as cust_cost

这应该比 Serg 的建议更直接、健壮和模块化。