繁体   English   中英

转义PL / pgSQL变量

[英]Escape an PL/pgSQL variable

我在PostgreSQL 9上有一个触发器,如下所示:

CREATE OR REPLACE FUNCTION clients_update_billingdata_trigger()
RETURNS trigger AS
$BODY$
DECLARE
  columnsUpdate  TEXT;
BEGIN
   columnsUpdate := '';

   IF (NEW.rsocial IS DISTINCT FROM OLD.rsocial) THEN
      columnsUpdate := columnsUpdate || 'RSocial before: ' || OLD.rsocial || '. RSocial after: ' || NEW.rsocial || E'\n';
   END IF;

   IF (NEW.legalidentifier IS DISTINCT FROM OLD.legalidentifier) THEN
      columnsUpdate := columnsUpdate || 'ILegal before: ' || OLD.legalidentifier || '. ILegal after: ' || NEW.legalidentifier || E'\n';
   END IF;

   [...]

   IF (columnsUpdate != '') THEN
      SELECT dblink_exec ('dbname=xxx user=xxx password=xxxxx',
                          'INSERT INTO BillingDataUpdate (client_id, columnsupdate)
                           VALUES (''' || NEW.idclient || ''', ''' || columnsUpdate || ''');');
   END IF;
   RETURN NEW;
 END;
 $BODY$
 LANGUAGE plpgsql;

NEW.rsocial的值可以是,例如: Tommy的服务 如果我关闭触发器,记录会正确保存(在other表中,在客户端中),因为我使用pg_escape_string函数在PHP中转义字符串。 问题是,如何逃避NEW.rsocial运行触发器?

提前致谢。

函数quote_literalquote_nullable可能很有用。 但请注意,这些是PostgreSQL函数,因此请确保DBLINK的另一端了解结果。

您可能还会看一下这部分文档:

http://www.postgresql.org/docs/9.1/interactive/plpgsql-statements.html#PLPGSQL-QUOTE-LITERAL-EXAMPLE

编辑

quote_xyz不能应用于rsocial的用法,而应用于dblink_exec

  SELECT dblink_exec ('dbname=xxx user=xxx password=xxxxx',
                      'INSERT INTO BillingDataUpdate (client_id, columnsupdate) '
                       || 'VALUES (' || quote_nullable(NEW.idclient) || ', ' 
                       || quote_nullable(columnsUpdate) || ');');

请注意字符串连接中更改的'数字'

虽然这篇文章已经有了接受的答案,但我建议使用FORMAT函数

FORMAT(E'%s', YOUR_VARIABLE)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM