工作 SQL 在 pg-promise 中产生语法错误

Working SQL yields Syntax Error in pg-promise

我的一个端点中有以下代码:

    let setText = ''
    for (const [ key, value ] of Object.entries(req.body.info)) {
        setText = setText.concat(`${key} = ${value}, `)
    }
    // Last character always an extra comma and whitespace
    setText = setText.substring(0, setText.length - 2)

    db.one('UPDATE students SET ${setText} WHERE id = ${id} RETURNING *', { setText, id: req.body.id })
        .then(data => {
            res.json({ data })
        })
        .catch(err => {
            res.status(400).json({'error': err.message})
        })

它应该从请求正文中动态生成 SQL。当我记录创建的 SQL 时,它会正确生成。当我直接查询数据库时它甚至可以工作。但是,每当我 运行 端点时,无论 setText 是什么,我都会收到“在或附近”的语法错误。我试过使用 slice 而不是 substring 没有改变。

你永远不应该手动连接值,因为它们没有被正确转义,并打开你的代码以进行可能的 SQL 注入。

使用图书馆提供的工具。对于来自动态对象的 UPDATE,请参见下文:

const cs = new pgp.helpers.ColumnSet(req.body.info, {table: 'students'});

const query = pgp.helpers.update(req.body.info, cs) +
                  pgp.as.format(' WHERE id = ${id} RETURNING *', req.body);

db.one(query)
    .then(data => {
        res.json({ data });
    })
    .catch(err => {
        res.status(400).json({error: err.message})
    });