在存储过程中转义 Postgres 8.4 中的 LIKE 模式或正则表达式字符串

Escaping a LIKE pattern or regexp string in Postgres 8.4 inside a stored procedure

我正在编写一个存储过程来查找主项的子项并更新它。场景是这样的

Id  Item Name               Parent Id  
1   Item A 14.1             NULL  
2   Item B 14.1.1           1      
3   Item C 14.1.2           1       
4   Item B 14.1.3           1       
5   Item A 14.1.1.1         2 

我已经在 SO 上发布了另一个问题来获取项目的子项。根据那个答案,我必须转义项目代码并必须在查询中使用它。但是我没有任何方法可以避免这种情况。 SP如下:

CREATE OR REPLACE FUNCTION updateitemparentnew(bigint, int) RETURNS text
    LANGUAGE plpgsql STRICT
    AS $$
DECLARE
    itemdetail RECORD;    
    codeSearch text;
    codeEscapedSearch text;
    result text;
BEGIN   

--Get th details of the current item
SELECT INTO itemdetail * FROM om_item WHERE item_id = ;

codeSearch = itemdetail.item_code||'.';
codeEscapedSearch = codeSearch;  --Need to be corrected. It should escape the item code

-- Event 1=> add 2 => edit 3 => delete
IF  = 1 THEN
    --Find new children and update then
    result =  'UPDATE om_item SET item_parentid = '||itemdetail.item_id
           ||' WHERE item_id IN (
                 SELECT item_id FROM om_item
                 WHERE  item_code LIKE \''||codesearch||'%\'
                 AND item_code ~ \''||codeEscapedsearch||'[^.]+$\');';

END IF;

return result;
END;
$$;

查询中的 codeEscapedSearch 应该转义以处理代码本身中的 . 和正则表达式中的 .

由于没有确定合适的解决方案,我决定使用简单的 replace
codeEscapedSearch = replace(codeSearch,'.','\.');

考虑这种直接的方法:

CREATE OR REPLACE FUNCTION updateitemparentnew(_id bigint, _operation text)
  RETURNS void LANGUAGE plpgsql STRICT AS
$func$
DECLARE
   code_like text;
   code_regex text;
BEGIN

SELECT INTO code_like, code_regex
       p.item_code || '.%'
     , '^' || replace(p.item_code, '.', '\.') || '\.[^.]+$'
FROM   om_item p
WHERE  p.item_id = _id;

CASE _operation  -- ins / upd / del
WHEN 'upd' THEN  -- Find new children and update then
   UPDATE om_item c
   SET    item_parentid = _id
   WHERE  c.item_code LIKE code_like
   AND    c.item_code ~ code_regex;

-- WHEN 'ins' THEN ...
-- WHEN 'del' THEN ...
END CASE;

END
$func$;

这不是 return 查询字符串,而是直接执行 UPDATE。更短更快。

也使用 replace(),顺便说一句。

转义所有 LIKE 和正则表达式模式的彻底解决方案:

  • Escape function for regular expression or LIKE patterns