【问题标题】:How do I sanitize ILIKE query in Node-pg如何清理 Node-pg 中的 ILIKE 查询
【发布时间】:2021-11-02 22:22:16
【问题描述】:

我正在尝试为按名称过滤的 findAll 函数创建过滤器。此函数中的其他过滤器工作正常,但我无法让名称过滤器工作。

下面的函数接受过滤器参数(如果有)并根据任何传入的过滤器添加到 WHERE 查询。现在,当我传入一个名称时,除非查询与数据库中的名称匹配,否则它不会返回任何内容,但我试图返回包含 name 值的任何结果(即“net”的名称查询将给你“神经网络”)

这是我目前所拥有的:

static async findAll(searchFilters = {}) {
    let query = `SELECT handle, name, description, num_employees AS "numEmployees", logo_url AS "logoUrl"
           FROM companies`;
    let whereStatement = []
    let values = []
    const {name, minEmployees, maxEmployees} = searchFilters

    if (minEmployees > maxEmployees) throw new BadRequestError('minEmployees cannot be greater than maxEmployees!')
    
    if (!!minEmployees) {
      values.push(minEmployees)
      whereStatement.push(`num_employees >= $${values.length}`)
    }
    if (!!maxEmployees) {
      values.push(maxEmployees)
      whereStatement.push(`num_employees <= $${values.length}`)
    }
    if (!!name) {
      values.push(name)
      whereStatement.push(`name ILIKE $${values.length}`)
    }

    if (whereStatement.length > 0) {
      query += ` WHERE ${whereStatement.join(" AND ")}`
    }
    query += ' ORDER BY name'
    const companiesRes = await db.query(query, values)
    return companiesRes.rows;
  }

我试着这样输入:

name ILIKE '%$${values.length}%'

但我收到了这条消息:

"error": {
    "message": "bind message supplies 1 parameters, but prepared statement \"\" requires 0",
    "status": 500
  }

有没有一种特定的方法来清理 Node-pg 中的 ILIKE 查询,或者我的语法刚刚关闭?

【问题讨论】:

    标签: javascript sql node.js postgresql


    【解决方案1】:

    我认为附加名称过滤器的代码应如下所示:

    ...
        if (!!name) {
          values.push(`%${name}%`)
          whereStatement.push(`name ILIKE $${values.length}`)
        }
    ...
    

    503#issuecomment-32055380

    【讨论】:

    • 哇,就是这样。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-06-11
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2021-07-11
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多