From 1be7743ed351d1ccde686931e3c489fd9cd49c08 Mon Sep 17 00:00:00 2001 From: Charles Pick Date: Thu, 6 Nov 2014 23:31:57 +0000 Subject: [PATCH] fix #139, allow embedded queries in FROM --- lib/db/index.js | 10 ++++++++++ lib/db/statement.js | 11 ++++++++++- test/db/statement-test.js | 10 ++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/lib/db/index.js b/lib/db/index.js index 23240d2..de0370d 100644 --- a/lib/db/index.js +++ b/lib/db/index.js @@ -320,6 +320,16 @@ Db.prototype.createQuery = function () { return new Query(this); }; +/** + * Create a create query. + * + * @return {Query} The query instance. + */ +Db.prototype.create = function () { + var query = this.createQuery(); + return query.create.apply(query, arguments); +}; + /** * Create a select query. * diff --git a/lib/db/statement.js b/lib/db/statement.js index ccd5452..b1d8ddb 100644 --- a/lib/db/statement.js +++ b/lib/db/statement.js @@ -330,7 +330,16 @@ Statement.prototype.buildStatement = function () { if (state.from && state.from.length) { statement.push('FROM'); statement.push(state.from.map(function (item) { - if (typeof item === 'string') { + if (typeof item === 'function') { + var child = new Statement(self.db); + child._state.paramIndex = self._state.paramIndex; + item(child); + return '(' + child.toString() + ')'; + } + else if (item instanceof Statement) { + return '(' + item.toString() + ')'; + } + else if (typeof item === 'string') { return item; } else { diff --git a/test/db/statement-test.js b/test/db/statement-test.js index 77f1998..de84907 100644 --- a/test/db/statement-test.js +++ b/test/db/statement-test.js @@ -180,6 +180,16 @@ COMMIT \n\ this.statement.select().from('(SELECT * FROM OUser)'); this.statement.buildStatement().should.equal('SELECT * FROM (SELECT * FROM OUser)'); }); + it('should select from a subquery', function () { + this.statement.select().from((new Statement(this.db).select().from('OUser'))); + this.statement.buildStatement().should.equal('SELECT * FROM (SELECT * FROM OUser)'); + }); + it('should select from a subquery, using a function', function () { + this.statement.select().from(function (s) { + s.select().from('OUser'); + }); + this.statement.buildStatement().should.equal('SELECT * FROM (SELECT * FROM OUser)'); + }); }); describe('Statement::to()', function () {