Cancel streamed postgres query in knex.js

Viewed 244

Is there a way to cancel a streamed, long running query in knex.js? Tried stream.emit('close') but it doesn't seem to close the query, as a knex.destroy() call never resolves.

const query = knex('tablename')
const stream = query.stream({ batchSize: 2000 })

process.on('SIGINT', () => stream.emit('close', 128 + 2))
process.on('SIGTERM', () => stream.emit('close', 128 + 15))

stream
  .on('data', onData)
  .on('close', (exitCode = 0) => {
    knex.destroy()
      .then(() => console.log('This is never resolved if the query has finished'))
      .catch(err => console.error('could not close connection gracefully', err))

    console.log('Finished')
    process.exitCode = exitCode
  })
  .on('end', () => {
    console.log('End')
    stream.emit('close')
  })
0 Answers
Related