You need to enable JavaScript to run this app. 如何安全优雅地动态构造SQL/JSON路径查询字符串
优惠活动
大模型
产品
解决方案
定价
更多

如何安全优雅地动态构造SQL/JSON路径查询字符串

最优实现方案

你可以利用PostgreSQL jsonpath支持的变量注入能力实现完全免手动转义的动态构造,只有键名需要用%I做标识符格式化,匹配值直接通过USING子句传入,完全规避字符串拼接带来的转义问题和注入风险:

核心写法示例

  • 正则匹配场景
end_user.profile @? format('$.%I ? (@ like_regex $val flag "i")', condition.field)::jsonpath
  USING condition.value AS val;
  • 普通等值匹配场景
end_user.profile @? format('$.%I ? (@ == $val)', condition.field)::jsonpath
  USING condition.value AS val;

完整函数封装

create function private.end_user_profile_filter(end_user private.end_user, condition private.profile_filter)
returns boolean as $$
select case
  when condition.condition = 'REGEX_MATCH'
    then end_user.profile @? format('$.%I ? (@ like_regex $val flag "i")', condition.field)::jsonpath
      using condition.value as val
  else
    end_user.profile @? format('$.%I ? (@ == $val)', condition.field)::jsonpath
      using condition.value as val
end;
$$ language sql stable;

方案优势

  • 所有动态值由数据库原生处理转义,不存在注入风险,也不需要手动写任何转义逻辑
  • 键名用%I做标识符格式化,自动处理含特殊字符的JSON键名场景
  • 代码简洁易读,维护成本远低于手动转义方案

内容的提问来源于stack exchange,提问作者Tim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 13:18:03