我正在尝试遵循 pg-promise 库作者在此处推荐的性能模式。
基本上 Vitaly 建议使用 inserts 这样做:
var users = [['John', 23], ['Mike', 30], ['David', 18]];
// We can use Inserts as an inline function also:
db.none('INSERT INTO Users(name, age) VALUES $1', Inserts('$1, $2', users))
.then(data=> {
// OK, all records have been inserted
})
.catch(error=> {
// Error, no records inserted
});
使用以下辅助函数:
function Inserts(template, data) {
if (!(this instanceof Inserts)) {
return new Inserts(template, data);
}
this._rawDBType = true;
this.formatDBType = function () {
return data.map(d=>'(' + pgp.as.format(template, d) + ')').join(',');
};
}
我的问题是,当插入物有限制时,你会怎么做?我的代码:
db.tx(function (t) {
return t.any("SELECT... ",[params])
.then(function (data) {
var requestParameters = [];
async.each(data,function(entry){
requestParameters.push(entry.application_id,entry.country_id,collectionId)
});
db.none(
" INSERT INTO application_average_ranking (application_id,country_id,collection_id) VALUES ($1)" +
" ON CONFLICT ON CONSTRAINT constraint_name" +
" DO UPDATE SET country_id=$2,collection_id=$3",
[Inserts('$1, $2, $3',requestParameters),entry.country_id,collectionId])
.then(data=> {
console.log('success');
})
.catch(error=> {
console.log('insert error');
});
});
});
显然,我无法访问参数,因为我不在异步循环中。
我也尝试做这样的事情:
db.none(
" INSERT INTO application_average_ranking (application_id,country_id,collection_id) VALUES ($1)" +
" ON CONFLICT ON CONSTRAINT constraint_name" +
" DO UPDATE SET (application_id,country_id,collection_id) = $1",
Inserts('$1, $2, $3',requestParameters));
但当然,它不尊重 postgresql 的标准。
有没有办法做到这一点?
谢谢 !