Error: cannot insert multiple commands into a prepared statement

一个人想着一个人 提交于 2021-01-27 23:32:47

问题


I am trying to move a row from one table to another.

The problem is that if I put both queries together, I get "error: cannot insert multiple commands into a prepared statement". What can I do?

exports.deletePost = function(id) {
    return db.query(`INSERT INTO deletedjobs
    SELECT *
    FROM jobs
    WHERE id = $1;

    DELETE FROM jobs WHERE id = $1;`, [id]).then(results => {
        console.log("succesfull transfer");
        return results.rows[0];
    });
};

回答1:


  • Maybe you should not use AND clause, try semicolon ;.
  • You used select * you should enter columns name, because in later times you may add a new column, your function does not execute.



回答2:


EDIT: Following Docs v7.0.0, I found out db.multi can execute a multi-query string, you can try this:

db.multi(`INSERT INTO deletedjobs
    SELECT *
    FROM jobs
    WHERE id = $1;DELETE FROM jobs WHERE id = $1`, [id])

Other way I think the better solution is that you should wrap the query into a function for insert-delete at same time, like below:

CREATE FUNCTION moveJob(id character varying) RETURNs void AS
$BODY$
BEGIN
    INSERT INTO deletedjobs
    SELECT *
    FROM jobs
    WHERE id = id;

    DELETE FROM jobs WHERE id = id;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE SECURITY DEFINER
  COST 100;

And call it as postgresql function in your js:

db.any('select moveJob($1)', [id]);



回答3:


You can also use a WITH ... AS clause (https://www.postgresql.org/docs/9.1/queries-with.html) to execute both queries in one go. So it could look something like that:

exports.deletePost = function(id) {
return db.query(`
  WITH 
    A AS (SELECT * FROM jobs WHERE id = $1), 
    B AS (INSERT INTO deletedjobs FROM A),
    DELETE FROM jobs WHERE id IN (SELECT id FROM A);
`, [id]).then(results => {
    console.log("succesfull transfer");
    return results.rows[0];
});
};


来源:https://stackoverflow.com/questions/57221749/error-cannot-insert-multiple-commands-into-a-prepared-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!