如何修复多行node-postgres插入 – 在$ 4或附近的语法错误

我有一个多行node-postgres插入,给我的问题。 这是一个参数化查询,它使用公用表expression式来用外键来更新主表和两个表。 该查询与主表的参数一起工作,但是,当我尝试参数化多行的外键表时,会引发语法错误。

首先,我有这个函数接受一个数组并返回一串值。

const buildValues = (id, values) => { return values .map(val => "(" + id + ", '" + val + "', " + false + ")") .join(", "); }; 

这是我的查询:

 app.post('/api/saveperson', function (req, res) { pg.connect(connectionString, (err, client, done) => { const insertPerson = ` WITH x AS ( INSERT INTO people (title, notes, name) VALUES ($1, $2, $3) RETURNING personId ), b AS ( INSERT INTO sports (personid, name, favorite) VALUES $4 ) INSERT INTO instructions (personid, name, favorite) VALUES $5; `; client.query(insertPerson, [ req.body.title , req.body.notes , req.body.name , queries.buildValues("SELECT personId FROM x", req.body.sports) , queries.buildValues("SELECT personId FROM x", req.body.instructions) ] ) .then( () => client.end()) .catch( err => console.log(err)); }); return res.json(req.body); }); 

不知道这是否是最好的解决scheme,但是我最终使用了pg-promise库而不是pg 。 然后我使用一个事务和一个链式查询:

  db.tx(t => { // BEGIN has been executed return t.one( `INSERT INTO people (title, notes, name) VALUES ($[title], $[notes], $[name]) RETURNING personid`, req.body) .then(data => { let sportsQueries = req.body.sports.map(sport => { return t.none(`INSERT INTO sports (personid, name) VALUES ($1, $2)`, [data.personid, sport]); }); let instructionsQueries = req.body.instructions.map(ins => { return t.none(`INSERT INTO instructions (personid, instruction) VALUES ($1, $2)`, [data.personid, ins]); }); return t.batch(sportsQueries.concat(instructionsQueries)); }); }) .then(data => { // Success, and COMMIT has been executed }) .catch(error => { // Failure, and ROLLBACK has been executed })