knex/src/dialects/mysql2/index.js

84 lines
2.0 KiB
JavaScript
Raw Normal View History

2015-05-09 13:58:18 -04:00
// MySQL2 Client
// -------
import inherits from 'inherits';
import Client_MySQL from '../mysql';
import Promise from 'bluebird';
import * as helpers from '../../helpers';
import { map, assign } from 'lodash'
import Transaction from './transaction';
2015-05-09 13:58:18 -04:00
// Always initialize with the "QueryBuilder" and "QueryCompiler"
// objects, which extend the base 'lib/query/builder' and
// 'lib/query/compiler', respectively.
function Client_MySQL2(config) {
Client_MySQL.call(this, config)
}
inherits(Client_MySQL2, Client_MySQL)
assign(Client_MySQL2.prototype, {
// The "dialect", for reference elsewhere.
driverName: 'mysql2',
2016-09-12 18:45:35 -04:00
transaction() {
return new Transaction(this, ...arguments)
},
2015-05-09 13:58:18 -04:00
_driver() {
2015-05-09 13:58:18 -04:00
return require('mysql2')
2015-07-02 18:28:34 -04:00
},
2015-05-09 13:58:18 -04:00
validateConnection(connection) {
if(connection._fatalError) {
return Promise.resolve(false);
}
return Promise.resolve(true);
2016-09-13 18:12:23 -04:00
},
2015-05-09 13:58:18 -04:00
// Get a raw connection, called by the `pool` whenever a new
// connection needs to be added to the pool.
acquireRawConnection() {
const connection = this.driver.createConnection(this.connectionSettings)
connection.on('error', err => {
connection.__knex__disposed = err
})
2016-09-13 18:12:23 -04:00
return new Promise((resolver, rejecter) => {
connection.connect((err) => {
if (err) {
return rejecter(err)
}
2015-05-09 13:58:18 -04:00
resolver(connection)
})
})
},
processResponse(obj, runner) {
const { response } = obj
const { method } = obj
const rows = response[0]
const fields = response[1]
2015-05-09 13:58:18 -04:00
if (obj.output) return obj.output.call(runner, rows, fields)
switch (method) {
case 'select':
case 'pluck':
case 'first': {
const resp = helpers.skim(rows)
2016-03-02 16:52:32 +01:00
if (method === 'pluck') return map(resp, obj.pluck)
2015-05-09 13:58:18 -04:00
return method === 'first' ? resp[0] : resp
}
2015-05-09 13:58:18 -04:00
case 'insert':
return [rows.insertId]
case 'del':
case 'update':
case 'counter':
return rows.affectedRows
default:
return response
}
}
})
export default Client_MySQL2;