node-postgres/lib/native/query.js

81 lines
1.9 KiB
JavaScript
Raw Normal View History

2011-08-30 12:06:07 +08:00
var EventEmitter = require('events').EventEmitter;
2011-10-11 08:40:52 +08:00
var util = require('util');
2011-08-30 12:06:07 +08:00
var types = require(__dirname + '/../types');
var utils = require(__dirname + '/../utils');
2011-08-30 12:06:07 +08:00
//event emitter proxy
var NativeQuery = function(text, values, callback) {
//TODO there are better ways to detect overloads
if(typeof text == 'object') {
this.text = text.text;
this.values = text.values;
this.name = text.name;
if(typeof values === 'function') {
this.callback = values;
} else if(values) {
this.values = values;
this.callback = callback;
}
} else {
this.text = text;
this.values = values;
this.callback = callback;
if(typeof values == 'function') {
this.values = null;
this.callback = values;
}
}
if(this.callback) {
this.rows = [];
}
//normalize values
if(this.values) {
for(var i = 0, len = this.values.length; i < len; i++) {
this.values[i] = utils.prepareValue(this.values[i]);
2011-08-30 12:06:07 +08:00
}
}
EventEmitter.call(this);
};
2011-10-11 08:40:52 +08:00
util.inherits(NativeQuery, EventEmitter);
2011-08-30 12:06:07 +08:00
var p = NativeQuery.prototype;
//maps from native rowdata into api compatible row object
var mapRowData = function(row) {
var result = {};
for(var i = 0, len = row.length; i < len; i++) {
var item = row[i];
result[item.name] = item.value == null ? null : types.getTypeParser(item.type, 'text')(item.value);
2011-08-30 12:06:07 +08:00
}
return result;
}
p.handleRow = function(rowData) {
var row = mapRowData(rowData);
if(this.callback) {
this.rows.push(row);
}
this.emit('row', row);
};
p.handleError = function(error) {
if(this.callback) {
this.callback(error);
this.callback = null;
} else {
this.emit('error', error);
}
}
p.handleReadyForQuery = function(meta) {
2011-08-30 12:06:07 +08:00
if(this.callback) {
(meta || {}).rows = this.rows;
this.callback(null, meta);
2011-08-30 12:06:07 +08:00
}
this.emit('end');
};
module.exports = NativeQuery;