2013-10-29 06:31:11 +08:00
|
|
|
var CopyToQueryStream = require('./copy-to')
|
|
|
|
module.exports = {
|
2014-09-16 03:01:39 +08:00
|
|
|
to: function(txt, options) {
|
|
|
|
return new CopyToQueryStream(txt, options)
|
2013-10-29 06:31:11 +08:00
|
|
|
},
|
2014-09-16 03:01:39 +08:00
|
|
|
from: function (txt, options) {
|
|
|
|
return new CopyStreamQuery(txt, options)
|
2013-10-29 06:31:11 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var Transform = require('stream').Transform
|
|
|
|
var util = require('util')
|
2016-07-27 03:39:48 +08:00
|
|
|
var code = require('./message-formats')
|
2013-10-29 06:31:11 +08:00
|
|
|
|
2014-09-16 03:01:39 +08:00
|
|
|
var CopyStreamQuery = function(text, options) {
|
|
|
|
Transform.call(this, options)
|
2013-10-29 06:31:11 +08:00
|
|
|
this.text = text
|
|
|
|
this._listeners = null
|
|
|
|
this._copyOutResponse = null
|
2013-10-29 10:50:45 +08:00
|
|
|
this.rowCount = 0
|
2013-10-29 06:31:11 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
util.inherits(CopyStreamQuery, Transform)
|
|
|
|
|
|
|
|
CopyStreamQuery.prototype.submit = function(connection) {
|
|
|
|
this.connection = connection
|
|
|
|
connection.query(this.text)
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2016-07-27 03:39:48 +08:00
|
|
|
var copyDataBuffer = Buffer([code.CopyData])
|
2013-10-29 06:31:11 +08:00
|
|
|
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)
|
|
|
|
cb()
|
|
|
|
}
|
|
|
|
|
|
|
|
CopyStreamQuery.prototype._flush = function(cb) {
|
2016-07-27 03:39:48 +08:00
|
|
|
var finBuffer = Buffer([code.CopyDone, 0, 0, 0, 4])
|
2013-10-29 06:31:11 +08:00
|
|
|
this.push(finBuffer)
|
2016-07-27 03:39:33 +08:00
|
|
|
cb()
|
2013-10-29 06:31:11 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
CopyStreamQuery.prototype.handleError = function(e) {
|
|
|
|
this.emit('error', e)
|
|
|
|
}
|
|
|
|
|
2013-12-10 00:40:59 +08:00
|
|
|
CopyStreamQuery.prototype.handleCopyInResponse = function(connection) {
|
2016-07-27 03:39:33 +08:00
|
|
|
this.pipe(connection.stream, { end: false })
|
2013-10-29 06:31:11 +08:00
|
|
|
}
|
|
|
|
|
2016-05-25 06:20:16 +08:00
|
|
|
CopyStreamQuery.prototype.handleCommandComplete = function(msg) {
|
|
|
|
// Parse affected row count as in
|
|
|
|
// https://github.com/brianc/node-postgres/blob/35e5567f86774f808c2a8518dd312b8aa3586693/lib/result.js#L37
|
|
|
|
var match = /COPY (\d+)/.exec((msg || {}).text)
|
|
|
|
if (match) {
|
|
|
|
this.rowCount = parseInt(match[1], 10)
|
|
|
|
}
|
|
|
|
|
2013-10-29 06:31:11 +08:00
|
|
|
this.unpipe()
|
|
|
|
this.emit('end')
|
|
|
|
}
|
|
|
|
|
|
|
|
CopyStreamQuery.prototype.handleReadyForQuery = function() {
|
|
|
|
}
|