简体   繁体   English

从node.js中的PostgreSQL查询返回查询结果状态

[英]Return query result state from PostgreSQL query in node.js

I have a node.js server connected to a PostgreSQL database using the pg module. 我有一个使用pg模块连接到PostgreSQL数据库的node.js服务器。 At one point I will insert data into two different database tables for a single HTTP POST . 某一时刻,我将为单个HTTP POST将数据插入到两个不同的数据库表中。 If the first query fails, the second should not be executed, but I have some trouble achieving this. 如果第一个查询失败,则不应该执行第二个查询,但是在实现此操作时遇到了一些麻烦。

My generalized query function looks like this: 我的广义查询函数如下所示:

// General insertion function. If endResponse is true, the response will be ended,
// if it is false it will just write to the response and not end it (unless errors occurs).
function performInsertQuery(request, response, query, endResponse) {
    var pg = require('pg');

    var client = new pg.Client(request.app.get('postgreConnection'));
    client.connect(function(error) {
        if (error)
        {
            message = 'Could not connect to PostgreSQL database: ' + error;
            response.end(message);
            console.error(message);
            client.end();
        }
        else
        {            
            client.query(query, function (error, result)
            {
                if (error)
                {
                    var message = 'Error running query ' + query + ': ' + error;
                    response.writeHead(500, {'content-type':'application/json'});
                    response.end(message);
                    console.error(message);
                    client.end();
                }
                else
                {
                    var message = 'Query performed: ' + query;
                    if (endResponse)
                    {
                        response.end(message);
                    }
                    else
                    {
                        response.write(message + '\n');
                    }
                    console.log(message);
                    client.end();
                }

            });
        }
    });
}

Later, I have something like the following: 后来,我有如下内容:

// query = some query
performInsertQuery(request, response, query, false);

// Stop running here if there was any errors running the query.

// Currently, this gets executed even though the first query fails.
// anotherQuery = another query
performInsertQuery(request, response, anotherQuery, true);

I have tried returning true and false from the function performInsertQuery , but since these are inner functions the result is not returned properly from the outer functions. 我试过从performInsertQuery函数返回truefalse ,但是由于这些是内部函数,因此无法从外部函数正确返回结果。 Also, some if it is run asynchronously, which makes things a bit harder as well. 另外,如果某些程序是异步运行的,这也会使事情变得更加困难。 I was not able to make it work with try/catch around the call to performInsertQuery either. 我也无法使其与对performInsertQuery的调用的try/catch performInsertQuery使用。 I guess I could do another query to see if data was inserted, but this seems unnecessary and not very robust. 我想我可以再执行一次查询以查看是否插入了数据,但这似乎是不必要的,也不是很可靠。

What would be the best way to return a success or failure state from performInsertQuery ? performInsertQuery返回成功或失败状态的最佳方法是什么?

I know this doesn't exactly handle your question as you intended(dealing with this entirely in node.js), but this sounds like an excellent usecase for a Postgres transaction....Do not commit results unless all insertions/updates are successful. 我知道这并不能完全按照您的意图处理您的问题(完全在node.js中处理),但这听起来像是Postgres事务的绝佳用例。...除非所有插入/更新成功,否则不要提交结果。 SQL transactions are built for scenarios like yours. SQL事务是针对像您这样的方案构建的。

Here are the docs and example code for it with your node module. 这是您的节点模块的文档和示例代码。 https://github.com/brianc/node-postgres/wiki/Transactions https://github.com/brianc/node-postgres/wiki/Transactions

http://www.postgresql.org/docs/9.2/static/tutorial-transactions.html http://www.postgresql.org/docs/9.2/static/tutorial-transactions.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM