Postgres +节点-使用$ 1,$ 2,$ 3给出错误的参数查询

时间:2019-06-07 22:46:39

标签: javascript sql node.js postgresql parameterized-query

当我尝试使用参数($ 1,$ 2,$ 3)运行查询时,出现此nodejs错误。该查询在postgres中工作。如果我不使用参数($ 1,$ 2,$ 3),而是用值代替它们,它也可以工作。有人可以帮我找出问题吗?

   error: bind message supplies 3 parameters, but prepared statement "" requires 0 

我要运行的查询:

var theQuery =   `DO
                $do$
                BEGIN
                IF EXISTS (SELECT * FROM commentsvoted WHERE id = $1 AND user_id = $2) THEN
                    with t as (
                      SELECT votes FROM commentsvoted WHERE commentsvoted.id = $1 AND 
                 commentsvoted.user_id = $2
                     ),
                     cv as (
                      UPDATE commentsvoted
                          SET votes = (CASE WHEN t.votes THEN NULL ELSE true END)
                          FROM t
                          WHERE commentsvoted.id = $1 AND commentsvoted.user_id = $2
                     )
                      UPDATE comments
                      SET upvoted = (CASE WHEN t.votes THEN upvoted - 1
                                          WHEN t.votes IS NULL THEN upvoted + 1
                                          ELSE upvoted 
                                     END),
                          downvoted = (CASE WHEN NOT t.votes THEN downvoted - 1
                                            ELSE downvoted 
                                       END)

                      FROM t
                      WHERE comment_id = $1 AND posted_by = $2;
                ELSE
                    with t as (UPDATE comments SET upvoted = upvoted + 1 
                    WHERE comment_id = $1 AND posted_by = $2)
                    INSERT INTO commentsvoted(id, user_id, votes, thread_id) 
                    VALUES($1, $2, true, $3);
                END IF;
                END
                $do$`;


        client.query(theQuery, [commentId, userId, threadId])

1 个答案:

答案 0 :(得分:3)

Postgresql不支持匿名块的参数

相关文档https://www.postgresql.org/docs/9.4/sql-do.html

相关票证https://github.com/brianc/node-postgres/issues/812

迁移到使用存储过程或函数似乎是进行操作的最佳方法。票证使用CREATE TEMPORARY FUNCTION进行建议