diff --git a/index.js b/index.js index 6883f4892..87d6c6d2e 100644 --- a/index.js +++ b/index.js @@ -7,6 +7,8 @@ exports.createConnection = function(config) { return new Connection({config: new ConnectionConfig(config)}); }; +exports.createQuery = Connection.createQuery; + exports.Types = Types; exports.escape = SqlString.escape; exports.escapeId = SqlString.escapeId; diff --git a/lib/Connection.js b/lib/Connection.js index 755cac686..544aaf74f 100644 --- a/lib/Connection.js +++ b/lib/Connection.js @@ -2,6 +2,7 @@ var Net = require('net'); var ConnectionConfig = require('./ConnectionConfig'); var Protocol = require('./protocol/Protocol'); var SqlString = require('./protocol/SqlString'); +var Query = require('./protocol/sequences/Query'); var EventEmitter = require('events').EventEmitter; var Util = require('util'); @@ -17,6 +18,30 @@ function Connection(options) { this._connectCalled = false; } +Connection.createQuery = function(sql, values, cb) { + if (sql instanceof Query) { + return sql; + } + + var options = {}; + + if (typeof sql === 'object') { + // query(options, cb) + options = sql; + cb = values; + } else if (typeof values === 'function') { + // query(sql, cb) + cb = values; + options.sql = sql; + options.values = undefined; + } else { + // query(sql, values, cb) + options.sql = sql; + options.values = values; + } + return new Query(options, cb); +}; + Connection.prototype.connect = function(cb) { if (!this._connectCalled) { this._connectCalled = true; @@ -61,33 +86,16 @@ Connection.prototype.changeUser = function(options, cb){ Connection.prototype.query = function(sql, values, cb) { this._implyConnect(); - var options = {}; - - if (typeof sql === 'object') { - // query(options, cb) - options = sql; - cb = values; - values = options.values; + var query = Connection.createQuery(sql, values, cb); - delete options.values; - } else if (typeof values === 'function') { - // query(sql, cb) - cb = values; - options.sql = sql; - values = undefined; - } else { - // query(sql, values, cb) - options.sql = sql; - options.values = values; + if (!(typeof sql == 'object' && 'typeCast' in sql)) { + query.typeCast = this.config.typeCast; } - options.sql = this.format(options.sql, values || []); - - if (!('typeCast' in options)) { - options.typeCast = this.config.typeCast; - } + query.sql = this.format(query.sql, query.values || []); + delete query.values; - return this._protocol.query(options, cb); + return this._protocol._enqueue(query); }; Connection.prototype.ping = function(cb) { diff --git a/lib/protocol/sequences/Query.js b/lib/protocol/sequences/Query.js index 6ff7d6c6b..ba79c7bc0 100644 --- a/lib/protocol/sequences/Query.js +++ b/lib/protocol/sequences/Query.js @@ -11,6 +11,7 @@ function Query(options, callback) { Sequence.call(this, callback); this.sql = options.sql; + this.values = options.values; this.typeCast = (options.typeCast === undefined) ? true : options.typeCast;