node-postgres/lib/connection.js

640 lines
16 KiB
JavaScript
Raw Normal View History

var net = require('net');
var EventEmitter = require('events').EventEmitter;
2011-10-11 08:40:52 +08:00
var util = require('util');
2013-03-17 00:51:26 +08:00
var Writer = require('buffer-writer');
2014-03-14 19:59:19 +08:00
var Reader = require('packet-reader');
var TEXT_MODE = 0;
var BINARY_MODE = 1;
var Connection = function(config) {
EventEmitter.call(this);
config = config || {};
this.stream = config.stream || new net.Stream();
this.lastBuffer = false;
this.lastOffset = 0;
this.buffer = null;
this.offset = null;
this.encoding = 'utf8';
this.parsedStatements = {};
this.writer = new Writer();
this.ssl = config.ssl || false;
2013-03-29 22:38:49 +08:00
this._ending = false;
this._mode = TEXT_MODE;
2013-08-18 06:25:24 +08:00
this._emitMessage = false;
2014-03-14 19:59:19 +08:00
this._reader = new Reader({
headerSize: 1,
lengthPadding: -4
});
2013-08-18 06:25:24 +08:00
var self = this;
this.on('newListener', function(eventName) {
if(eventName == 'message') {
self._emitMessage = true;
}
});
};
2011-10-11 08:40:52 +08:00
util.inherits(Connection, EventEmitter);
Connection.prototype.connect = function(port, host) {
2010-10-24 09:26:24 +08:00
if(this.stream.readyState === 'closed') {
2010-10-24 06:36:04 +08:00
this.stream.connect(port, host);
} else if(this.stream.readyState == 'open') {
2010-10-24 06:36:04 +08:00
this.emit('connect');
}
2010-10-24 09:26:24 +08:00
var self = this;
2010-10-24 06:36:04 +08:00
this.stream.on('connect', function() {
2010-10-24 06:36:04 +08:00
self.emit('connect');
});
2013-01-24 08:08:32 +08:00
this.stream.on('error', function(error) {
2013-08-08 00:57:43 +08:00
//don't raise ECONNRESET errors - they can & should be ignored
2013-03-29 22:38:49 +08:00
//during disconnect
if(self._ending && error.code == 'ECONNRESET') {
return;
}
self.emit('error', error);
});
2010-10-24 06:36:04 +08:00
this.stream.on('close', function() {
// NOTE: node-0.10 emits both 'end' and 'close'
// for streams closed by the peer, while
// node-0.8 only emits 'close'
self.emit('end');
});
if(!this.ssl) {
return this.attachListeners(this.stream);
}
this.stream.once('data', function(buffer) {
var responseCode = buffer.toString('utf8');
if(responseCode != 'S') {
return self.emit('error', new Error('The server does not support SSL connections'));
}
var tls = require('tls');
self.stream = tls.connect({
socket: self.stream,
servername: host,
rejectUnauthorized: self.ssl.rejectUnauthorized,
ca: self.ssl.ca,
pfx: self.ssl.pfx,
key: self.ssl.key,
passphrase: self.ssl.passphrase,
cert: self.ssl.cert,
NPNProtocols: self.ssl.NPNProtocols
});
self.attachListeners(self.stream);
self.emit('sslconnect');
self.stream.on('error', function(error){
self.emit('error', error);
});
});
};
Connection.prototype.attachListeners = function(stream) {
2014-03-14 19:59:19 +08:00
var self = this;
2013-08-18 06:25:24 +08:00
stream.on('data', function(buff) {
2014-03-14 19:59:19 +08:00
self._reader.addChunk(buff);
var packet = self._reader.read();
while(packet) {
var msg = self.parseMessage(packet);
if(self._emitMessage) {
self.emit('message', msg);
2013-08-18 06:25:24 +08:00
}
2014-03-14 19:59:19 +08:00
self.emit(msg.name, msg);
packet = self._reader.read();
}
2014-03-14 19:59:19 +08:00
});
2010-10-24 06:36:04 +08:00
};
2014-04-09 09:02:12 +08:00
Connection.prototype.requestSsl = function() {
this.checkSslResponse = true;
2013-01-24 08:08:32 +08:00
var bodyBuffer = this.writer
.addInt16(0x04D2)
.addInt16(0x162F).flush();
2013-01-24 08:08:32 +08:00
var length = bodyBuffer.length + 4;
2013-01-24 08:08:32 +08:00
var buffer = new Writer()
.addInt32(length)
.add(bodyBuffer)
.join();
this.stream.write(buffer);
};
Connection.prototype.startup = function(config) {
var writer = this.writer
2010-10-24 06:36:04 +08:00
.addInt16(3)
.addInt16(0)
;
Object.keys(config).forEach(function(key){
var val = config[key];
writer.addCString(key).addCString(val);
});
writer.addCString('client_encoding').addCString("'utf-8'");
var bodyBuffer = writer.addCString('').flush();
2010-11-01 07:36:35 +08:00
//this message is sent without a code
var length = bodyBuffer.length + 4;
2010-11-01 07:36:35 +08:00
var buffer = new Writer()
.addInt32(length)
.add(bodyBuffer)
.join();
this.stream.write(buffer);
};
Connection.prototype.cancel = function(processID, secretKey) {
2011-11-02 23:07:14 +08:00
var bodyBuffer = this.writer
.addInt16(1234)
.addInt16(5678)
.addInt32(processID)
.addInt32(secretKey)
.addCString('').flush();
var length = bodyBuffer.length + 4;
var buffer = new Writer()
2010-11-01 07:36:35 +08:00
.addInt32(length)
.add(bodyBuffer)
.join();
this.stream.write(buffer);
};
Connection.prototype.password = function(password) {
2010-11-01 07:36:35 +08:00
//0x70 = 'p'
this._send(0x70, this.writer.addCString(password));
2010-10-24 08:02:13 +08:00
};
Connection.prototype._send = function(code, more) {
if(!this.stream.writable) { return false; }
if(more === true) {
this.writer.addHeader(code);
} else {
return this.stream.write(this.writer.flush(code));
}
};
Connection.prototype.query = function(text) {
2010-11-01 07:36:35 +08:00
//0x51 = Q
this.stream.write(this.writer.addCString(text).flush(0x51));
};
//send parse message
//"more" === true to buffer the message until flush() is called
Connection.prototype.parse = function(query, more) {
//expect something like this:
// { name: 'queryName',
// text: 'select * from blah',
// types: ['int8', 'bool'] }
//normalize missing query names to allow for null
query.name = query.name || '';
if (query.name.length > 63) {
console.error('Warning! Postgres only supports 63 characters for query names.');
console.error('You supplied', query.name, '(', query.name.length, ')');
console.error('This can cause conflicts and silent errors executing queries');
}
//normalize null type array
query.types = query.types || [];
2010-10-24 13:18:48 +08:00
var len = query.types.length;
var buffer = this.writer
.addCString(query.name) //name of query
.addCString(query.text) //actual query text
2010-10-24 13:18:48 +08:00
.addInt16(len);
for(var i = 0; i < len; i++) {
buffer.addInt32(query.types[i]);
}
2010-10-28 13:27:08 +08:00
var code = 0x50;
this._send(code, more);
};
//send bind message
//"more" === true to buffer the message until flush() is called
Connection.prototype.bind = function(config, more) {
//normalize config
config = config || {};
2010-10-25 02:46:50 +08:00
config.portal = config.portal || '';
config.statement = config.statement || '';
config.binary = config.binary || false;
2010-10-25 02:46:50 +08:00
var values = config.values || [];
var len = values.length;
2013-09-18 23:50:42 +08:00
var useBinary = false;
for (var j = 0; j < len; j++)
useBinary |= values[j] instanceof Buffer;
var buffer = this.writer
2010-10-25 02:46:50 +08:00
.addCString(config.portal)
2013-09-18 23:50:42 +08:00
.addCString(config.statement);
if (!useBinary)
buffer.addInt16(0);
else {
buffer.addInt16(len);
for (j = 0; j < len; j++)
buffer.addInt16(values[j] instanceof Buffer);
}
buffer.addInt16(len);
2010-10-25 02:46:50 +08:00
for(var i = 0; i < len; i++) {
var val = values[i];
if(val === null || typeof val === "undefined") {
2010-10-25 02:46:50 +08:00
buffer.addInt32(-1);
2013-09-18 23:50:42 +08:00
} else if (val instanceof Buffer) {
buffer.addInt32(val.length);
buffer.add(val);
2010-10-25 02:46:50 +08:00
} else {
buffer.addInt32(Buffer.byteLength(val));
buffer.addString(val);
2010-10-25 02:46:50 +08:00
}
}
if(config.binary) {
buffer.addInt16(1); // format codes to use binary
buffer.addInt16(1);
}
else {
buffer.addInt16(0); // format codes to use text
}
2010-11-01 07:36:35 +08:00
//0x42 = 'B'
this._send(0x42, more);
};
//send execute message
//"more" === true to buffer the message until flush() is called
Connection.prototype.execute = function(config, more) {
2010-10-25 02:46:50 +08:00
config = config || {};
config.portal = config.portal || '';
config.rows = config.rows || '';
2014-04-09 09:02:12 +08:00
this.writer
2010-10-25 02:46:50 +08:00
.addCString(config.portal)
.addInt32(config.rows);
2010-11-01 07:36:35 +08:00
//0x45 = 'E'
this._send(0x45, more);
};
var emptyBuffer = Buffer(0);
Connection.prototype.flush = function() {
2010-11-01 07:36:35 +08:00
//0x48 = 'H'
this.writer.add(emptyBuffer);
this._send(0x48);
};
Connection.prototype.sync = function() {
//clear out any pending data in the writer
this.writer.flush(0);
2013-01-24 08:08:32 +08:00
this.writer.add(emptyBuffer);
this._ending = true;
this._send(0x53);
};
Connection.prototype.end = function() {
2010-11-01 07:36:35 +08:00
//0x58 = 'X'
this.writer.add(emptyBuffer);
2013-03-29 22:38:49 +08:00
this._ending = true;
this._send(0x58);
2010-10-24 08:28:57 +08:00
};
Connection.prototype.close = function(msg, more) {
this.writer.addCString(msg.type + (msg.name || ''));
this._send(0x43, more);
};
Connection.prototype.describe = function(msg, more) {
this.writer.addCString(msg.type + (msg.name || ''));
this._send(0x44, more);
2010-10-28 13:27:08 +08:00
};
Connection.prototype.sendCopyFromChunk = function (chunk) {
this.stream.write(this.writer.add(chunk).flush(0x64));
};
Connection.prototype.endCopyFrom = function () {
this.stream.write(this.writer.add(emptyBuffer).flush(0x63));
};
Connection.prototype.sendCopyFail = function (msg) {
//this.stream.write(this.writer.add(emptyBuffer).flush(0x66));
this.writer.addCString(msg);
this._send(0x66);
};
var Message = function(name, length) {
this.name = name;
this.length = length;
};
2014-03-14 19:59:19 +08:00
Connection.prototype.parseMessage = function(buffer) {
2014-03-14 19:59:19 +08:00
this.offset = 0;
var length = buffer.length + 4;
switch(this._reader.header)
{
case 0x52: //R
2013-08-18 03:21:19 +08:00
return this.parseR(buffer, length);
case 0x53: //S
2013-08-18 03:21:19 +08:00
return this.parseS(buffer, length);
case 0x4b: //K
2013-08-18 03:21:19 +08:00
return this.parseK(buffer, length);
case 0x43: //C
2013-08-18 03:21:19 +08:00
return this.parseC(buffer, length);
case 0x5a: //Z
2013-08-18 03:21:19 +08:00
return this.parseZ(buffer, length);
case 0x54: //T
2013-08-18 03:21:19 +08:00
return this.parseT(buffer, length);
case 0x44: //D
2013-08-18 03:21:19 +08:00
return this.parseD(buffer, length);
case 0x45: //E
2013-08-18 03:21:19 +08:00
return this.parseE(buffer, length);
case 0x4e: //N
2013-08-18 03:21:19 +08:00
return this.parseN(buffer, length);
case 0x31: //1
2013-08-18 03:21:19 +08:00
return new Message('parseComplete', length);
case 0x32: //2
2013-08-18 03:21:19 +08:00
return new Message('bindComplete', length);
case 0x33: //3
return new Message('closeComplete', length);
case 0x41: //A
2013-08-18 03:21:19 +08:00
return this.parseA(buffer, length);
case 0x6e: //n
2013-08-18 03:21:19 +08:00
return new Message('noData', length);
case 0x49: //I
2013-08-18 03:21:19 +08:00
return new Message('emptyQuery', length);
2010-11-15 07:44:36 +08:00
case 0x73: //s
2013-08-18 03:21:19 +08:00
return new Message('portalSuspended', length);
2010-11-15 07:44:36 +08:00
case 0x47: //G
2013-08-18 03:21:19 +08:00
return this.parseG(buffer, length);
case 0x48: //H
2013-08-18 03:21:19 +08:00
return this.parseH(buffer, length);
case 0x63: //c
2013-08-18 03:21:19 +08:00
return new Message('copyDone', length);
case 0x64: //d
2013-08-18 03:21:19 +08:00
return this.parsed(buffer, length);
}
};
Connection.prototype.parseR = function(buffer, length) {
var code = 0;
var msg = new Message('authenticationOk', length);
if(msg.length === 8) {
2013-08-08 00:57:43 +08:00
code = this.parseInt32(buffer);
if(code === 3) {
msg.name = 'authenticationCleartextPassword';
}
return msg;
}
if(msg.length === 12) {
2013-08-08 00:57:43 +08:00
code = this.parseInt32(buffer);
if(code === 5) { //md5 required
msg.name = 'authenticationMD5Password';
msg.salt = new Buffer(4);
2014-03-14 19:59:19 +08:00
buffer.copy(msg.salt, 0, this.offset, this.offset + 4);
this.offset += 4;
return msg;
}
}
2011-10-11 08:40:52 +08:00
throw new Error("Unknown authenticatinOk message type" + util.inspect(msg));
};
Connection.prototype.parseS = function(buffer, length) {
var msg = new Message('parameterStatus', length);
2013-08-08 00:57:43 +08:00
msg.parameterName = this.parseCString(buffer);
msg.parameterValue = this.parseCString(buffer);
return msg;
};
Connection.prototype.parseK = function(buffer, length) {
var msg = new Message('backendKeyData', length);
2013-08-08 00:57:43 +08:00
msg.processID = this.parseInt32(buffer);
msg.secretKey = this.parseInt32(buffer);
return msg;
};
Connection.prototype.parseC = function(buffer, length) {
var msg = new Message('commandComplete', length);
2013-08-08 00:57:43 +08:00
msg.text = this.parseCString(buffer);
return msg;
};
Connection.prototype.parseZ = function(buffer, length) {
var msg = new Message('readyForQuery', length);
msg.name = 'readyForQuery';
2013-08-08 00:57:43 +08:00
msg.status = this.readString(buffer, 1);
return msg;
};
2013-09-11 22:36:29 +08:00
var ROW_DESCRIPTION = 'rowDescription';
Connection.prototype.parseT = function(buffer, length) {
2013-08-08 01:41:38 +08:00
var msg = new Message(ROW_DESCRIPTION, length);
2013-08-08 00:57:43 +08:00
msg.fieldCount = this.parseInt16(buffer);
var fields = [];
for(var i = 0; i < msg.fieldCount; i++){
2013-08-08 00:57:43 +08:00
fields.push(this.parseField(buffer));
}
msg.fields = fields;
return msg;
};
2013-08-08 01:41:38 +08:00
var Field = function() {
this.name = null;
this.tableID = null;
this.columnID = null;
this.dataTypeID = null;
this.dataTypeSize = null;
this.dataTypeModifier = null;
this.format = null;
};
2013-09-11 22:36:29 +08:00
var FORMAT_TEXT = 'text';
var FORMAT_BINARY = 'binary';
2013-08-08 00:57:43 +08:00
Connection.prototype.parseField = function(buffer) {
2013-08-08 01:41:38 +08:00
var field = new Field();
field.name = this.parseCString(buffer);
field.tableID = this.parseInt32(buffer);
field.columnID = this.parseInt16(buffer);
field.dataTypeID = this.parseInt32(buffer);
field.dataTypeSize = this.parseInt16(buffer);
field.dataTypeModifier = this.parseInt32(buffer);
2013-08-08 00:57:43 +08:00
if(this.parseInt16(buffer) === TEXT_MODE) {
this._mode = TEXT_MODE;
2013-08-08 01:41:38 +08:00
field.format = FORMAT_TEXT;
} else {
this._mode = BINARY_MODE;
2013-08-08 01:41:38 +08:00
field.format = FORMAT_BINARY;
}
return field;
};
2013-09-11 22:36:29 +08:00
var DATA_ROW = 'dataRow';
var DataRowMessage = function(length, fieldCount) {
2013-08-08 01:41:38 +08:00
this.name = DATA_ROW;
2013-08-08 00:57:43 +08:00
this.length = length;
this.fieldCount = fieldCount;
this.fields = [];
2013-08-08 01:41:38 +08:00
};
2013-08-08 00:57:43 +08:00
2013-08-08 01:41:38 +08:00
//extremely hot-path code
2013-08-18 03:21:19 +08:00
Connection.prototype.parseD = function(buffer, length) {
2013-08-08 00:57:43 +08:00
var fieldCount = this.parseInt16(buffer);
2013-08-08 01:41:38 +08:00
var msg = new DataRowMessage(length, fieldCount);
for(var i = 0; i < fieldCount; i++) {
2013-08-08 01:41:38 +08:00
msg.fields.push(this._readValue(buffer));
}
return msg;
};
2013-08-08 01:41:38 +08:00
//extremely hot-path code
2013-08-08 00:57:43 +08:00
Connection.prototype._readValue = function(buffer) {
var length = this.parseInt32(buffer);
if(length === -1) return null;
if(this._mode === TEXT_MODE) {
return this.readString(buffer, length);
}
return this.readBytes(buffer, length);
};
//parses error
Connection.prototype.parseE = function(buffer, length) {
var fields = {};
var msg, item;
var input = new Message('error', length);
2013-08-08 00:57:43 +08:00
var fieldType = this.readString(buffer, 1);
while(fieldType != '\0') {
2013-08-08 00:57:43 +08:00
fields[fieldType] = this.parseCString(buffer);
fieldType = this.readString(buffer, 1);
}
if(input.name === 'error') {
// the msg is an Error instance
msg = new Error(fields.M);
for (item in input) {
// copy input properties to the error
if(input.hasOwnProperty(item)) {
msg[item] = input[item];
}
}
} else {
// the msg is an object literal
msg = input;
msg.message = fields.M;
}
msg.severity = fields.S;
msg.code = fields.C;
msg.detail = fields.D;
msg.hint = fields.H;
msg.position = fields.P;
msg.internalPosition = fields.p;
msg.internalQuery = fields.q;
msg.where = fields.W;
msg.schema = fields.s;
msg.table = fields.t;
msg.column = fields.c;
msg.dataType = fields.d;
msg.constraint = fields.n;
msg.file = fields.F;
msg.line = fields.L;
msg.routine = fields.R;
return msg;
};
2010-10-25 03:43:25 +08:00
//same thing, different name
Connection.prototype.parseN = function(buffer, length) {
var msg = this.parseE(buffer, length);
msg.name = 'notice';
return msg;
};
2010-10-25 03:43:25 +08:00
Connection.prototype.parseA = function(buffer, length) {
var msg = new Message('notification', length);
2013-08-08 00:57:43 +08:00
msg.processId = this.parseInt32(buffer);
msg.channel = this.parseCString(buffer);
msg.payload = this.parseCString(buffer);
2010-10-24 11:31:43 +08:00
return msg;
};
Connection.prototype.parseG = function (buffer, length) {
var msg = new Message('copyInResponse', length);
return this.parseGH(buffer, msg);
};
Connection.prototype.parseH = function(buffer, length) {
var msg = new Message('copyOutResponse', length);
return this.parseGH(buffer, msg);
};
Connection.prototype.parseGH = function (buffer, msg) {
2014-03-14 19:59:19 +08:00
var isBinary = buffer[this.offset] !== 0;
this.offset++;
msg.binary = isBinary;
2013-08-08 00:57:43 +08:00
var columnCount = this.parseInt16(buffer);
msg.columnTypes = [];
for(var i = 0; i<columnCount; i++) {
2013-08-08 00:57:43 +08:00
msg.columnTypes.push(this.parseInt16(buffer));
}
return msg;
};
Connection.prototype.parsed = function (buffer, length) {
var msg = new Message('copyData', length);
msg.chunk = this.readBytes(buffer, msg.length - 4);
return msg;
};
2013-08-08 00:57:43 +08:00
Connection.prototype.parseInt32 = function(buffer) {
var value = buffer.readInt32BE(this.offset, true);
this.offset += 4;
return value;
};
2013-08-08 00:57:43 +08:00
Connection.prototype.parseInt16 = function(buffer) {
var value = buffer.readInt16BE(this.offset, true);
this.offset += 2;
return value;
};
2013-08-08 00:57:43 +08:00
Connection.prototype.readString = function(buffer, length) {
return buffer.toString(this.encoding, this.offset, (this.offset += length));
};
2013-08-08 00:57:43 +08:00
Connection.prototype.readBytes = function(buffer, length) {
return buffer.slice(this.offset, this.offset += length);
};
2013-08-08 00:57:43 +08:00
Connection.prototype.parseCString = function(buffer) {
var start = this.offset;
2013-08-08 00:57:43 +08:00
while(buffer[this.offset++] !== 0) { }
return buffer.toString(this.encoding, start, this.offset - 1);
};
//end parsing methods
2010-10-24 06:36:04 +08:00
module.exports = Connection;