如何使用npm pg-promise包编写以下postgresql查询?
update schedule
set student_id = 'a1ef71bc6d02124977d4'
where teacher_id = '6b33092f503a3ddcc34' and (start_day_of_week, start_time) in (VALUES ('M', (cast('17:00:00' as time))), ('T', (cast('19:00:00' as time))));
我没有在formatter命名空间中看到任何可以帮助实现此目的的内容。 https://vitaly-t.github.io/pg-promise/formatting.html
我无法注入'演员'进入' 00:00'值而不将其视为时间字符串本身的一部分。
第一部分查询很简单。它是VALUES之后我无法弄清楚的部分。
第一篇:
var query = `update schedule
set student_id = $1
where teacher_id = $2 and (start_day_of_week, start_time) in (VALUES $3)`;
var inserts = [studentId,teacherId,values];
我现在以3美元(还没有工作)使用这种混乱,但它完全绕过了pg-promise内置的所有转义/安全性:
const buildPreparedParams = function(arr, colNames){
let newArr = [];
let rowNumber = 0
arr.forEach((row) => {
const rowVal = (rowNumber > 0 ? ', ' : '') +
`('${row.startDayOfWeek}', (cast('${row.startTime}' as time)))`;
newArr.push(rowVal);
});
return newArr;
};
我试图转换为这个SQL查询的结构是:
[{
"startTime":"17:00:00",
"startDayOfWeek":"U"
},
{
"startTime":"16:00:00",
"startDayOfWeek":"T"
}]
答案 0 :(得分:0)
使用CSV Filter作为最后一部分:IN (VALUES $3:csv)
。
要正确生成数组格式的每个项目,请应用Custom Type Formatting:
const data = [{
startTime: '17:00:00',
startDayOfWeek: 'U'
},
{
startTime: '16:00:00',
startDayOfWeek: 'T'
}];
const values = data.map(d => ({
toPostgres: () => pgp.as.format('(${startDayOfWeek},(cast(${startTime} as time))', d),
rawType: true
}));
现在传入values
$3:csv
会正确格式化您的值:
('U',(cast('17:00:00' as time)),('T',(cast('16:00:00' as time))