[英]Return query result state from PostgreSQL query in node.js
我有一個使用pg
模塊連接到PostgreSQL數據庫的node.js
服務器。 某一時刻,我將為單個HTTP POST
將數據插入到兩個不同的數據庫表中。 如果第一個查詢失敗,則不應該執行第二個查詢,但是在實現此操作時遇到了一些麻煩。
我的廣義查詢函數如下所示:
// 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();
}
});
}
});
}
后來,我有如下內容:
// 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);
我試過從performInsertQuery
函數返回true
和false
,但是由於這些是內部函數,因此無法從外部函數正確返回結果。 另外,如果某些程序是異步運行的,這也會使事情變得更加困難。 我也無法使其與對performInsertQuery
的調用的try/catch
performInsertQuery
使用。 我想我可以再執行一次查詢以查看是否插入了數據,但這似乎是不必要的,也不是很可靠。
從performInsertQuery
返回成功或失敗狀態的最佳方法是什么?
我知道這並不能完全按照您的意圖處理您的問題(完全在node.js中處理),但這聽起來像是Postgres事務的絕佳用例。...除非所有插入/更新成功,否則不要提交結果。 SQL事務是針對像您這樣的方案構建的。
這是您的節點模塊的文檔和示例代碼。 https://github.com/brianc/node-postgres/wiki/Transactions
http://www.postgresql.org/docs/9.2/static/tutorial-transactions.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.