1 | 'use strict'
|
2 | var mysql = require('mysql')
|
3 | var Connection = require('mysql/lib/Connection')
|
4 | var ConnectionConfig = require('mysql/lib/ConnectionConfig')
|
5 |
|
6 | var inherits = require('inherits')
|
7 |
|
8 | var adapter = exports
|
9 |
|
10 | adapter.name = 'mysql'
|
11 |
|
12 | adapter.createQuery = function (text, values, callback) {
|
13 | if (text.query) return text
|
14 |
|
15 | var highWaterMark = 128;
|
16 |
|
17 | if (typeof callback == 'number') {
|
18 |
|
19 | highWaterMark = callback
|
20 | callback = undefined
|
21 | }
|
22 | if (!callback) {
|
23 | switch (typeof values) {
|
24 | case 'number':
|
25 | highWaterMark = values
|
26 | break
|
27 | case 'function':
|
28 | callback = values
|
29 | values = []
|
30 | break
|
31 | default:
|
32 | values = values || []
|
33 | }
|
34 | }
|
35 |
|
36 | var query = mysql.createQuery(text, values)
|
37 | var stream = query.stream({highWaterMark: highWaterMark})
|
38 |
|
39 | var _read = stream._read
|
40 | stream._read = function () {
|
41 |
|
42 | query._connection && _read.call(this)
|
43 | }
|
44 | stream.query = query
|
45 | stream.text = text
|
46 | stream.values = values
|
47 |
|
48 | if (stream.callback = callback) {
|
49 | var result = {rowCount: 0, rows: [], lastInsertId: null, fields: null}
|
50 | var errored = false
|
51 | stream
|
52 | .on('error', function (err) {
|
53 | errored = true
|
54 | this.callback(err)
|
55 | })
|
56 | .on('fields', function (fields) {
|
57 | result.fields = fields
|
58 | })
|
59 | .on('data', function (row) {
|
60 | if (row.constructor.name == 'OkPacket') {
|
61 | result.fieldCount = row.fieldCount
|
62 | result.rowCount = result.affectedRows = row.affectedRows
|
63 | result.changedRows = row.changedRows
|
64 | result.lastInsertId = row.insertId
|
65 | } else {
|
66 | result.rowCount = result.rows.push(row)
|
67 | }
|
68 | })
|
69 | .on('end', function () {
|
70 | if (!errored) this.callback(null, result)
|
71 | })
|
72 | }
|
73 |
|
74 | stream.once('end', function () { delete this.query })
|
75 | return stream
|
76 | }
|
77 |
|
78 | adapter.createConnection = function createConnection(opts, callback) {
|
79 | var conn = new MySQLConnection(opts)
|
80 |
|
81 | conn.connect(function (err) {
|
82 | if (err) return callback ? callback(err) : conn.emit('error', err)
|
83 | conn.emit('open')
|
84 | if (callback) callback(null, conn)
|
85 | })
|
86 |
|
87 | return conn
|
88 | }
|
89 |
|
90 | inherits(MySQLConnection, Connection)
|
91 | function MySQLConnection (opts) {
|
92 | Connection.call(this, {config: new ConnectionConfig(opts)})
|
93 | }
|
94 |
|
95 | MySQLConnection.prototype.adapter = adapter
|
96 |
|
97 | MySQLConnection.prototype.query = function (text, params, callback) {
|
98 | var stream = adapter.createQuery(text, params, callback)
|
99 | this.emit('query', stream)
|
100 | Connection.prototype.query.call(this, stream.query)
|
101 | return stream
|
102 | }
|