我正在尝试使用节点对PostgreSQL数据库执行更新,但我正在执行Error: Connection terminated
执行UPDATE
操作。在以适当的异步方式处理连接时,我可能会搞砸过早地终止它们,但是我无法理解我是如何正确执行它的。
对于大块代码感到抱歉,但它非常简单。
//main.js
var result = require('./processes.js');
result.check(function(message) {
console.log(message);
});
result.decrease(); //Throws an error.
//workers.js
var pg = require ('pg');
var fs = require('fs');
var db = JSON.parse(fs.readFileSync('../config.json', 'utf8')).db;
var querydb = require('./querydb.js');
var self = module.exports = {
check: function(callback) {
querydb.select("SELECT size FROM workers WHERE id = 1", function(results) {
callback(results[0].size);
});
},
increase: function() {
self.check(function(workers) {
querydb.update("UPDATE workers SET size = " + (workers + 1) + " WHERE id = 1");
});
},
decrease: function() {
self.check(function(workers) {
querydb.update("UPDATE workers SET size = " + (workers - 1) + " WHERE id = 1");
});
}
};
//querydb.js
var pg = require ('pg');
var fs = require('fs');
var db = JSON.parse(fs.readFileSync('../config.json', 'utf8')).db;
var select = function(statement, callback) {
pg.connect(db, function(err, client, done) {
var results = [];
//Handle errors
if(err) {
done();
console.log(err);
}
var query = client.query(statement);
//Stream results back
query.on('row', function(row) {
results.push(row);
});
//When all data is returned.
query.on('end', function() {
done();
callback(results);
client.end();
});
});
}
var update = function(statement) {
pg.connect(db, function(err, client, done) {
var results = [];
//Handle errors
if(err) {
done();
console.log(err);
}
var query = client.query(statement);
//When all data is returned.
query.on('end', function() {
done();
client.end();
});
});
}
module.exports = {
select: select,
update: update
};
答案 0 :(得分:0)
好吧,这可能不是本身的答案,而是更多的解决方法,但对这种脚本(即不是网络服务器)进行同步调用是我想要的所需行为,所以我最后使用pg-native代替pg并重构我的querydb
和workers
模块以使用它,现在一切正常!