我正在编写API,它插入到具有多行的表中,我使用UNNEST使其工作。
我做了什么:
在js文件中:
api.post(PREFIX + '/class/insert', function (request) {
var db = pgp(dbconnect);
//Params
var data = request.body; //should be an array
var classes = [];
var starts = [];
var ends = [];
for (var i = 0; i < data.length; i++) {
classes.push(data[i].class_id);
starts.push(data[i].timestamp_start);
ends.push(data[i].timestamp_end);
}
const PQ = require('pg-promise').ParameterizedQuery;
var sql =
"INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
"VALUES( "+
"UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + ")"
const final_sql = new PQ(sql);
return db.any(final_sql)
.then(function (data) {
pgp.end();
return 'successful';
})
.catch(function (error) {
console.log("Error: " + error);
pgp.end();
});
}
请求正文
[{
"class_id":"1",
"timestamp_start":"2017-11-14 14:01:23.634437+00",
"timestamp_end":"2017-11-14 15:20:23.634437+00"
}, {
"class_id":"2",
"timestamp_start":"2017-11-14 15:01:23.634437+00",
"timestamp_end": "2017-11-14 16:20:23.634437+00"
}]
当我在邮递员中运行api时,我得到的错误是:
列&#34; timestamp_start&#34;是带时区的时间戳类型但是 表达式是文本类型
问题显然来自我在sql中使用的ARRAY字符串,我的问题是如何为UNNEST创建时间戳的ARRAY,或者任何建议都值得赞赏。
由于
答案 0 :(得分:0)
pgp-end()
,它会破坏所有连接池。db.any
返回,在这种情况下没有意义class_id
提供了令人困惑的语义。为什么会这样调用并转换为timestamp
?none
,而不是any
。const db = pgp(/*connection*/);
const cs = new pgp.helpers.ColumnSet([
'class_id',
{
name: 'timestamp_start',
cast: 'timestamp'
},
{
name: 'timestamp_end',
cast: 'timestamp'
}
], {table: {table: 'class', schema: 'sa1'}});
。请参阅:https://github.com/vitaly-t/pg-promise#methods api.post(PREFIX + '/class/insert', request => {
const sql = pgp.helpers.insert(request.body, cs);
db.none(sql)
.then(data => {
// provide an HTTP response here
})
.catch(error => {
console.log('Error:', error);
// provide an HTTP response here
});
}
实现处理程序:
from tkinter import *
root = Tk()
root.geometry("400x400")
lb = PhotoImage(file="Background image.png") # repalce with your file name
label = Label(root, image=lb)
label.place(x=0, y=0, relwidth=1, relheight=1)
Button1 = Button(root, text="my button one").pack(side="left")
Button = Button(root, text="my button two").pack(side="right")
root.mainloop()
答案 1 :(得分:-1)
非常感谢@JustMe,
在投射数组后它起作用
var sql =
"INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
"VALUES( "+
"UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "::timestamp[]), " +
"UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + "::timestamp[])"