node-pg-copy-streams/index.js
Brian C c4a0e6dd58 Fix compatibility with newer versions of node (#39)
* Eliminate detach/reattach strategy as it isn't able to differentiate between on/once and inconsistenly loses unshifted data depending on node version.  Instead just split stream and send it to copy stream and the connection.stream at the same time.  Disconnecting copy stream just means unpiping.  Added handleCopyData to fulfill query contract but ignore the incoming data.

Add node 4.2.2 to Travis
Minimum postgres 9.2 to allow tests to complete in Travis

Remove test that is no longer needed since we no longer disconnect/reconnect listeners

* Add resume

* Remove node 0.10 and add 0.12

* Re-enable old tests

* Add more versions to the travis test matrix
2016-05-03 13:20:04 -05:00

68 lines
1.5 KiB
JavaScript

var CopyToQueryStream = require('./copy-to')
module.exports = {
to: function(txt, options) {
return new CopyToQueryStream(txt, options)
},
from: function (txt, options) {
return new CopyStreamQuery(txt, options)
}
}
var Transform = require('stream').Transform
var util = require('util')
var CopyStreamQuery = function(text, options) {
Transform.call(this, options)
this.text = text
this._listeners = null
this._copyOutResponse = null
this.rowCount = 0
}
util.inherits(CopyStreamQuery, Transform)
CopyStreamQuery.prototype.submit = function(connection) {
this.connection = connection
connection.query(this.text)
}
var code = {
H: 72, //CopyOutResponse
d: 0x64, //CopyData
c: 0x63 //CopyDone
}
var copyDataBuffer = Buffer([code.d])
CopyStreamQuery.prototype._transform = function(chunk, enc, cb) {
this.push(copyDataBuffer)
var lenBuffer = Buffer(4)
lenBuffer.writeUInt32BE(chunk.length + 4, 0)
this.push(lenBuffer)
this.push(chunk)
this.rowCount++
cb()
}
CopyStreamQuery.prototype._flush = function(cb) {
var finBuffer = Buffer([code.c, 0, 0, 0, 4])
this.push(finBuffer)
//never call this callback, do not close underlying stream
//cb()
}
CopyStreamQuery.prototype.handleError = function(e) {
this.emit('error', e)
}
CopyStreamQuery.prototype.handleCopyInResponse = function(connection) {
this.pipe(connection.stream)
}
CopyStreamQuery.prototype.handleCommandComplete = function() {
this.unpipe()
this.emit('end')
}
CopyStreamQuery.prototype.handleReadyForQuery = function() {
}