Я использую nodejs 8.11.1, pg-обещание 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
.Но этот случай также зависит от переменной, поэтому она может быть истинной или нет, поэтому она меняет всю структуру транзакции.
Примеры здесь и здесь могут использовать массив 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
.Если fullInsertQueryTwo
должен быть выполнен, то fullInsertQueryThree
также всегда должен быть выполнен, используя результаты fullInsertQueryTwo
.Если fullInsertQueryTwo
не будет выполняться, то fullInsertQueryThree
также не будет выполнено.
Есть примеры или псевдокод?
Спасибо