Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Implement Query#nestTables to deal with JOINs

This helps when a JOIN produces overlapping column names by nesting the
table name before the column names in the returned result objects.

Fixes #93
  • Loading branch information...
commit b8cfbb1e5f08a209f43b646a1ab0e03c82354bf7 1 parent f711de9
@felixge authored
View
11 lib/protocol/packets/RowDataPacket.js
@@ -5,13 +5,20 @@ module.exports = RowDataPacket;
function RowDataPacket() {
}
-RowDataPacket.prototype.parse = function(parser, fieldPackets, typeCast) {
+RowDataPacket.prototype.parse = function(parser, fieldPackets, typeCast, nestTables) {
for (var i = 0; i < fieldPackets.length; i++) {
var fieldPacket = fieldPackets[i];
- this[fieldPacket.name] = (typeCast)
+ var value = (typeCast)
? this._typeCast(fieldPacket, parser)
: parser.parseLengthCodedString();
+
+ if (nestTables) {
+ this[fieldPacket.table] = this[fieldPacket.table] || {};
+ this[fieldPacket.table][fieldPacket.name] = value;
+ } else {
+ this[fieldPacket.name] = value;
+ }
}
};
View
3  lib/protocol/sequences/Query.js
@@ -13,6 +13,7 @@ function Query(options, callback) {
this.typeCast = (options.typeCast === undefined)
? true
: options.typeCast;
+ this.nestTables = false;
this._resultSet = null;
this._results = [];
@@ -118,7 +119,7 @@ Query.prototype._handleFinalResultPacket = function(packet) {
};
Query.prototype['RowDataPacket'] = function(packet, parser) {
- packet.parse(parser, this._resultSet.fieldPackets, this.typeCast);
+ packet.parse(parser, this._resultSet.fieldPackets, this.typeCast, this.nestTables);
if (this._callback) {
this._resultSet.rows.push(packet);
View
33 test/integration/test-nested-tables-query.js
@@ -0,0 +1,33 @@
+var common = require('../common');
+var connection = common.createConnection();
+var assert = require('assert');
+
+common.useTestDb(connection);
+
+var table = 'nested_test';
+connection.query([
+ 'CREATE TEMPORARY TABLE `' + table + '` (',
+ '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,',
+ '`title` varchar(255),',
+ 'PRIMARY KEY (`id`)',
+ ') ENGINE=InnoDB DEFAULT CHARSET=utf8'
+].join('\n'));
+
+connection.query('INSERT INTO ' + table + ' SET ?', {title: 'test'});
+
+var rows;
+var query = connection.query('SELECT * FROM ' + table, function(err, _rows) {
+ if (err) throw err;
+
+ rows = _rows;
+});
+
+query.nestTables = true;
+
+connection.end();
+
+process.on('exit', function() {
+ assert.equal(rows.length, 1);
+ assert.equal(rows[0].nested_test.id, 1);
+ assert.equal(rows[0].nested_test.title, 'test');
+});
Please sign in to comment.
Something went wrong with that request. Please try again.