I’m trying to extract a query as a csv file. I tried to use copy
with pg-query-stream
to execute the query but I’m facing this error:
error: bind message supplies 1 parameters, but prepared statement "" requires 0
when removing copy
from the query it works fine with the placeholders also if I provided a query with copy
and no placeholders it works fine.
JavaScript
x
12
12
1
const pgp = require('pg-promise')
2
const QueryStream = require('pg-query-stream')
3
query1 = "copy (select * from real_state WHERE town_code= $1 ) TO '/tmp/file.csv'"
4
const qs = new QueryStream(query1, [22])
5
await db.stream(qs, s => {
6
// initiate streaming into the console:
7
s.pipe(JSONStream.stringify()).pipe(process.stdout)
8
}).then(data => {
9
}).catch(error => {
10
console.log('ERROR:', error)
11
})
12
JavaScript
1
4
1
query1 = "copy (select * from real_state WHERE town_code= $1 ) TO '/tmp/file.csv'" ==> error
2
query2 = "copy (select * from real_state) TO '/tmp/file.csv'" ==> It works
3
query3 = "select * from real_state WHERE town_code= $1" ==> It works
4
Advertisement
Answer
There is a limitation there within the COPY
context, which prohibits you from using any parameters.
But you can work-around that limitation, using pg-promise
query formatting:
JavaScript
1
3
1
const query = pgp.as.format('COPY(SELECT * FROM real_state WHERE town_code = $1) TO $2',
2
[22, '/tmp/file.csv']);
3