query.js
1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
var Utils = require("../../utils")
, AbstractQuery = require('../abstract/query')
module.exports = (function() {
var Query = function(client, sequelize, callee, options) {
this.client = client
this.callee = callee
this.sequelize = sequelize
this.options = Utils._.extend({
logging: console.log,
plain: false,
raw: false
}, options || {})
this.checkLoggingOption()
this.bindClientFunction = function(err) { onFailure.call(this, err) }.bind(this)
}
Utils.inherit(Query, AbstractQuery)
Query.prototype.run = function(sql) {
this.sql = sql
bindClient.call(this)
if(this.options.logging !== false) {
this.options.logging('Executing: ' + this.sql)
}
this.client.query(this.sql, function(err, results, fields) {
this.emit('sql', this.sql)
if (err) {
onFailure.call(this, err)
} else {
if (Array.isArray(results) && !!results[0] && Utils._.keys(results[0]).length === 1) {
results = results.map(function(result){ return Utils._.values(result)[0] })
}
onSuccess.call(this, results, fields)
}
}.bind(this)).setMaxListeners(100)
return this
}
//private
var bindClient = function() {
this.client.on('error', this.bindClientFunction)
}
var unbindClient = function() {
this.client.removeListener('error', this.bindClientFunction)
}
var onSuccess = function(results, fields) {
unbindClient.call(this)
this.emit('success', this.formatResults(results))
}
var onFailure = function(err) {
unbindClient.call(this)
this.emit('error', err, this.callee)
}
return Query
})()