使用pg-promise创建带有动态零件的交易序列

时间:2018-10-22 17:18:28

标签: sql transactions pg-promise

我使用nodejs 8.11.1,pg-promise 8.4.4,postgreSQL,并且我想创建一个包含动态部分的事务,但是我不知道如何正确地对其进行语法化。

在实践中,我有一些来自应用程序中表单的值,如果它们为空,则必须基于它们创建查询。

我猜伪代码看起来像这样

let batchArray=[];
let insert ='insert into table (name,type) values '; 
if(insertWherePart != null){
 let fullInsertQuery = insert + inserWherePart;
 batchArray.push(fullInsertQuery);
}

let anotherinsert ='insert into anothertable (name,type) values '; 
if(anotherinsertWherePart != null){
 let anotherfullInsertQuery = anotherinsert + anotherinserWherePart;
 batchArray.push(anotherfullInsertQuery);
}

db.tx(t => {
  return t.batch(batchArray);
})
.then(data => {
  // success, COMMIT was executed
})
.catch(error => {
  // failure, ROLLBACK was executed
});

棘手的部分是当我遇到这种情况时 insert into a table, get the ids, insert them in another table also。但是这种情况也取决于变量,因此它可能是正确的还是不正确的,因此会更改整个事务结构。

示例herehere可能使用t.batch数组,但是事务的结构是固定的。我需要一个更抽象的结构,这样我就可以将查询插入数组中并执行它们,同时在必要时还将结果传递给另一个。

我想要类似的东西

let batchArray=[];
let delete='delete from table  '; 
if(deleteWherePart != null){
 let deleteQuery = delete + deleteWherePart ;
 batchArray.push(deleteQuery);
}

let insert ='insert into table (name,type) values '; 
if(insertWherePart != null){
 let fullInsertQuery = insert + inserWherePart;
 batchArray.push(fullInsertQuery);
}

let insertTwo ='insert into table (name,type) values '; 
if(insertWherePartTwo != null){
 let fullInsertQueryTwo = insert + inserWherePartTwo + 'RETURNING ID';
 batchArray.push(fullInsertQueryTwo);
}

let insertThree ='insert into table (name,type) values where '; 
let fullInsertQueryThree = insert + fullInsertQueryTwo.id;
batchArray.push(fullInsertQueryThree);


db.tx(t => {
  return t.batch(batchArray);
})
.then(data => {
  // success, COMMIT was executed
})
.catch(error => {
  // failure, ROLLBACK was executed
});

因此,t.batch(batchArray)现在在该行中执行deleteQuery, fullInsertQuery, fullInsertQueryTwo, fullInsertQueryThree,并且fullInsertQueryTwo的where部分将使用从fullInsertQueryThree返回的ID。如果要执行fullInsertQueryTwo,则还必须始终使用fullInsertQueryThree结果执行fullInsertQueryTwo。如果fullInsertQueryTwo将不会执行,那么fullInsertQueryThree也将不会执行。

是否有任何示例或伪代码?

谢谢

0 个答案:

没有答案