在 copy 和 pg-query-stream 中使用占位符

Using placeholders with copy and pg-query-stream

我正在尝试将查询提取为 csv 文件。我尝试使用 copypg-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=  ) 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=  ) 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= " ==>  It works

我认为您将两个功能混合在一起。

pg-query-stream returns 行作为流,不需要在 select 中使用复制。只需使用一个简单的 select,然后将结果通过管道传输到文件流。

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= ", [22]
const stream = pool.query(query)
const fileStream = fs.createReadStream('/tmp/file.csv')
fileStream.pipe(stream)

如果你想使用复制然后使用 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= ', [22])
const fileStream = fs.createReadStream('/tmp/file.csv')

fileStream.pipe(stream)

COPY 上下文中存在限制,禁止您使用任何参数。

但是您可以work-around限制,使用pg-promise查询格式:

const query = pgp.as.format('COPY(SELECT * FROM real_state WHERE town_code = ) TO ',
                            [22, '/tmp/file.csv']);