我正在尝试将查询提取为csv文件。我试图将copy
与pg-query-stream
一起使用来执行查询,但是我遇到了这个错误:
error: bind message supplies 1 parameters, but prepared statement "" requires 0
从查询中删除copy
时,如果我提供的查询带有copy
且没有占位符,则该占位符也可以正常工作。
const pgp = require('pg-promise')
const QueryStream = require('pg-query-stream')
query1 = "copy (select * from real_state WHERE town_code= $1 ) TO '/tmp/file.csv'"
const qs = new QueryStream(query1, [22])
await db.stream(qs, s => {
// initiate streaming into the console:
s.pipe(JSONStream.stringify()).pipe(process.stdout)
}).then(data => {
}).catch(error => {
console.log('ERROR:', error)
})
query1 = "copy (select * from real_state WHERE town_code= $1 ) TO '/tmp/file.csv'" ==> error
query2 = "copy (select * from real_state) TO '/tmp/file.csv'" ==> It works
query3 = "select * from real_state WHERE town_code= $1" ==> It works
答案 0 :(得分:1)
COPY
上下文中有一个限制,它禁止您使用任何参数。
但是您可以使用pg-promise
查询格式来解决该限制:
const query = pgp.as.format('COPY(SELECT * FROM real_state WHERE town_code = $1) TO $2',
[22, '/tmp/file.csv']);
答案 1 :(得分:0)
我认为您正在将两个功能混在一起。
pg-query-stream将这些行作为流返回,不需要在select中使用copy。只需使用简单的选择,然后将结果通过管道传输到文件流即可。
const fs = require('fs')
const { Pool } = require('pg')
const QueryStream = require('pg-query-stream')
const query = new QueryStream("select * from real_state WHERE town_code= $1", [22]
const stream = pool.query(query)
const fileStream = fs.createReadStream('/tmp/file.csv')
fileStream.pipe(stream)
如果要使用copy,请使用pg-copy-streams:https://github.com/brianc/node-pg-copy-streams
const fs = require('fs')
const { Pool } = require('pg')
const copyFrom = require('pg-copy-streams').from
const stream = db.query(copyFrom('COPY real_state FROM stdin WHERE town_code= $1', [22])
const fileStream = fs.createReadStream('/tmp/file.csv')
fileStream.pipe(stream)