2013-10-03 21:50:38 +00:00
|
|
|
/*!
|
2012-12-14 14:01:44 +00:00
|
|
|
* Module dependencies
|
|
|
|
*/
|
|
|
|
var mysql = require('mysql');
|
2013-06-17 21:25:57 +00:00
|
|
|
|
2014-05-23 11:25:12 +00:00
|
|
|
var SqlConnector = require('loopback-connector').SqlConnector;
|
2013-07-21 05:37:59 +00:00
|
|
|
var EnumFactory = require('./enumFactory').EnumFactory;
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-04-08 05:16:26 +00:00
|
|
|
var debug = require('debug')('loopback:connector:mysql');
|
|
|
|
|
2013-10-03 21:50:38 +00:00
|
|
|
/**
|
|
|
|
* @module loopback-connector-mysql
|
|
|
|
*
|
|
|
|
* Initialize the MySQL connector against the given data source
|
|
|
|
*
|
|
|
|
* @param {DataSource} dataSource The loopback-datasource-juggler dataSource
|
|
|
|
* @param {Function} [callback] The callback function
|
|
|
|
*/
|
2013-07-23 19:47:02 +00:00
|
|
|
exports.initialize = function initializeDataSource(dataSource, callback) {
|
2014-02-13 00:57:06 +00:00
|
|
|
if (!mysql) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
var s = dataSource.settings;
|
|
|
|
|
|
|
|
if (s.collation) {
|
|
|
|
s.charset = s.collation.substr(0, s.collation.indexOf('_')); // Charset should be first 'chunk' of collation.
|
|
|
|
} else {
|
|
|
|
s.collation = 'utf8_general_ci';
|
|
|
|
s.charset = 'utf8';
|
|
|
|
}
|
|
|
|
|
|
|
|
s.supportBigNumbers = (s.supportBigNumbers || false);
|
|
|
|
s.timezone = (s.timezone || 'local');
|
|
|
|
|
|
|
|
if (!isNaN(s.connectionLimit)) {
|
|
|
|
s.connectionLimit = 10;
|
|
|
|
}
|
|
|
|
|
|
|
|
var options = {
|
|
|
|
host: s.host || s.hostname || 'localhost',
|
|
|
|
port: s.port || 3306,
|
|
|
|
user: s.username || s.user,
|
|
|
|
password: s.password,
|
|
|
|
timezone: s.timezone,
|
|
|
|
socketPath: s.socketPath,
|
|
|
|
charset: s.collation.toUpperCase(), // Correct by docs despite seeming odd.
|
|
|
|
supportBigNumbers: s.supportBigNumbers,
|
|
|
|
connectionLimit: s.connectionLimit
|
|
|
|
};
|
|
|
|
|
|
|
|
// Don't configure the DB if the pool can be used for multiple DBs
|
|
|
|
if (!s.createDatabase) {
|
|
|
|
options.database = s.database;
|
|
|
|
}
|
|
|
|
|
|
|
|
dataSource.client = mysql.createPool(options);
|
|
|
|
|
|
|
|
dataSource.client.on('error', function (err) {
|
|
|
|
dataSource.emit('error', err);
|
|
|
|
dataSource.connected = false;
|
|
|
|
dataSource.connecting = false;
|
|
|
|
});
|
|
|
|
|
2014-04-08 05:16:26 +00:00
|
|
|
if (debug.enabled) {
|
|
|
|
debug('Settings: %j', s);
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
dataSource.connector = new MySQL(dataSource.client, s);
|
|
|
|
dataSource.connector.dataSource = dataSource;
|
|
|
|
|
2014-05-23 11:25:12 +00:00
|
|
|
defineMySQLTypes(dataSource);
|
2014-02-13 00:57:06 +00:00
|
|
|
|
|
|
|
dataSource.EnumFactory = EnumFactory; // factory for Enums. Note that currently Enums can not be registered.
|
|
|
|
|
|
|
|
process.nextTick(function () {
|
|
|
|
callback && callback();
|
|
|
|
});
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
2013-07-21 06:38:40 +00:00
|
|
|
exports.MySQL = MySQL;
|
|
|
|
|
2014-05-23 11:25:12 +00:00
|
|
|
function defineMySQLTypes(dataSource) {
|
|
|
|
var modelBuilder = dataSource.modelBuilder;
|
|
|
|
var defineType = modelBuilder.defineValueType ?
|
|
|
|
// loopback-datasource-juggler 2.x
|
|
|
|
modelBuilder.defineValueType.bind(modelBuilder) :
|
|
|
|
// loopback-datasource-juggler 1.x
|
|
|
|
modelBuilder.constructor.registerType.bind(modelBuilder.constructor);
|
|
|
|
|
|
|
|
// The Point type is inherited from jugglingdb mysql adapter.
|
|
|
|
// LoopBack uses GeoPoint instead.
|
|
|
|
// The Point type can be removed at some point in the future.
|
|
|
|
defineType(function Point() {
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2012-12-14 14:01:44 +00:00
|
|
|
/**
|
2013-10-03 21:50:38 +00:00
|
|
|
* @constructor
|
|
|
|
* Constructor for MySQL connector
|
|
|
|
* @param {Object} client The node-mysql client object
|
2012-12-14 14:01:44 +00:00
|
|
|
*/
|
2013-10-07 21:46:05 +00:00
|
|
|
function MySQL(client, settings) {
|
2014-02-13 00:57:06 +00:00
|
|
|
this.name = 'mysql';
|
|
|
|
this._models = {};
|
|
|
|
this.client = client;
|
|
|
|
this.settings = settings;
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
|
|
|
|
2014-05-23 11:25:12 +00:00
|
|
|
require('util').inherits(MySQL, SqlConnector);
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2013-10-03 21:50:38 +00:00
|
|
|
/**
|
|
|
|
* Execute the sql statement
|
|
|
|
*
|
|
|
|
* @param {String} sql The SQL statement
|
|
|
|
* @param {Function} [callback] The callback after the SQL statement is executed
|
|
|
|
*/
|
2012-12-14 14:01:44 +00:00
|
|
|
MySQL.prototype.query = function (sql, callback) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var self = this;
|
|
|
|
if (!this.dataSource.connected) {
|
|
|
|
return this.dataSource.on('connected', function () {
|
|
|
|
this.query(sql, callback);
|
|
|
|
}.bind(this));
|
|
|
|
}
|
|
|
|
var client = this.client;
|
|
|
|
var time = Date.now();
|
2014-04-08 05:16:26 +00:00
|
|
|
var debugEnabled = debug.enabled;
|
2014-02-13 00:57:06 +00:00
|
|
|
var db = this.settings.database;
|
|
|
|
var log = this.log;
|
|
|
|
if (typeof callback !== 'function') throw new Error('callback should be a function');
|
2014-04-08 05:16:26 +00:00
|
|
|
if (debugEnabled) {
|
|
|
|
debug('SQL: %s', sql);
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function releaseConnectionAndCallback(connection, err, result) {
|
|
|
|
connection.release();
|
|
|
|
callback && callback(err, result);
|
|
|
|
}
|
|
|
|
|
|
|
|
function runQuery(connection) {
|
|
|
|
connection.query(sql, function (err, data) {
|
2014-04-08 05:16:26 +00:00
|
|
|
if (debugEnabled) {
|
2014-02-13 00:57:06 +00:00
|
|
|
if (err) {
|
2014-04-08 05:16:26 +00:00
|
|
|
console.error('Error: ', err);
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
2014-04-08 05:16:26 +00:00
|
|
|
debug('Data: ', data);
|
|
|
|
}
|
|
|
|
if (log) {
|
|
|
|
log(sql, time);
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
releaseConnectionAndCallback(connection, err, data);
|
|
|
|
});
|
|
|
|
}
|
2013-11-27 16:42:40 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
client.getConnection(function (err, connection) {
|
|
|
|
if (err) {
|
|
|
|
callback && callback(err);
|
|
|
|
return;
|
2013-11-27 17:08:03 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
if (self.settings.createDatabase) {
|
|
|
|
// Call USE db ...
|
|
|
|
connection.query('USE `' + db + '`', function (err) {
|
2013-11-27 01:40:31 +00:00
|
|
|
if (err) {
|
2014-02-13 00:57:06 +00:00
|
|
|
if (err && err.message.match(/(^|: )unknown database/i)) {
|
|
|
|
var charset = self.settings.charset;
|
|
|
|
var collation = self.settings.collation;
|
|
|
|
var q = 'CREATE DATABASE ' + db + ' CHARACTER SET ' + charset + ' COLLATE ' + collation;
|
|
|
|
connection.query(q, function (err) {
|
|
|
|
if (!err) {
|
|
|
|
connection.query('USE `' + db + '`', function (err) {
|
|
|
|
runQuery(connection);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
releaseConnectionAndCallback(connection, err);
|
|
|
|
}
|
2013-11-27 16:42:40 +00:00
|
|
|
});
|
2014-02-13 00:57:06 +00:00
|
|
|
return;
|
|
|
|
} else {
|
|
|
|
releaseConnectionAndCallback(connection, err);
|
|
|
|
return;
|
|
|
|
}
|
2013-11-27 16:42:40 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
runQuery(connection);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
// Bypass USE db
|
|
|
|
runQuery(connection);
|
|
|
|
}
|
|
|
|
});
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2013-10-03 21:50:38 +00:00
|
|
|
* Create the data model in MySQL
|
|
|
|
*
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} data The model instance data
|
|
|
|
* @param {Function} [callback] The callback function
|
2012-12-14 14:01:44 +00:00
|
|
|
*/
|
|
|
|
MySQL.prototype.create = function (model, data, callback) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var fields = this.toFields(model, data);
|
|
|
|
var sql = 'INSERT INTO ' + this.tableEscaped(model);
|
|
|
|
if (fields) {
|
|
|
|
sql += ' SET ' + fields;
|
|
|
|
} else {
|
|
|
|
sql += ' VALUES ()';
|
|
|
|
}
|
|
|
|
this.query(sql, function (err, info) {
|
|
|
|
callback(err, info && info.insertId);
|
|
|
|
});
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
2013-10-03 21:50:38 +00:00
|
|
|
/**
|
|
|
|
* Update if the model instance exists with the same id or create a new instance
|
|
|
|
*
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} data The model instance data
|
|
|
|
* @param {Function} [callback] The callback function
|
|
|
|
*/
|
2014-05-30 22:15:27 +00:00
|
|
|
MySQL.prototype.updateOrCreate = MySQL.prototype.save = function (model, data, callback) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var mysql = this;
|
|
|
|
var fieldsNames = [];
|
|
|
|
var fieldValues = [];
|
|
|
|
var combined = [];
|
|
|
|
var props = this._models[model].properties;
|
|
|
|
Object.keys(data).forEach(function (key) {
|
|
|
|
if (props[key] || mysql.id(model, key)) {
|
|
|
|
var k = mysql.columnEscaped(model, key);
|
|
|
|
var v;
|
2014-04-16 20:37:28 +00:00
|
|
|
v = mysql.toDatabase(props[key], data[key]);
|
Prevent inserting undefined values
The following SQL query was executed:
INSERT INTO `cv` (`first_name`, `last_name`, `father_name`, `city`, `district`, `transfer`, `nationality`, `email`, `icq`, `skype`, `birth_date`, `marital_status`, `gender`, `children_status`, `id`) VALUES ('asdsd', , , '', '', , , 'i@marat.by', , , , , , , 2) ON DUPLICATE KEY UPDATE `first_name` = 'asdsd', `last_name` = undefined, `father_name` = undefined, `city` = '', `district` = '', `transfer` = undefined, `nationality` = undefined, `email` = 'i@marat.by', `icq` = undefined, `skype` = undefined, `birth_date` = undefined, `marital_status` = undefined, `gender` = undefined, `children_status` = undefined;
2014-03-08 18:44:49 +00:00
|
|
|
if (v !== undefined) {
|
|
|
|
fieldsNames.push(k);
|
|
|
|
fieldValues.push(v);
|
|
|
|
if (!mysql.id(model, key)) {
|
|
|
|
combined.push(k + ' = ' + v);
|
|
|
|
}
|
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
});
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
var sql = 'INSERT INTO ' + this.tableEscaped(model);
|
|
|
|
sql += ' (' + fieldsNames.join(', ') + ')';
|
|
|
|
sql += ' VALUES (' + fieldValues.join(', ') + ')';
|
|
|
|
sql += ' ON DUPLICATE KEY UPDATE ' + combined.join(', ');
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
this.query(sql, function (err, info) {
|
|
|
|
if (!err && info && info.insertId) {
|
|
|
|
data.id = info.insertId;
|
|
|
|
}
|
|
|
|
callback(err, data);
|
|
|
|
});
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
MySQL.prototype.toFields = function (model, data) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var self = this;
|
|
|
|
var fields = [];
|
|
|
|
var props = this._models[model].properties;
|
|
|
|
Object.keys(data).forEach(function (key) {
|
|
|
|
if (props[key]) {
|
|
|
|
var value = this.toDatabase(props[key], data[key]);
|
2014-05-30 22:15:27 +00:00
|
|
|
if (undefined === value) {
|
|
|
|
return;
|
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
fields.push(self.columnEscaped(model, key) + ' = ' + value);
|
|
|
|
}
|
|
|
|
}.bind(this));
|
|
|
|
return fields.join(',');
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
function dateToMysql(val) {
|
2014-02-13 00:57:06 +00:00
|
|
|
return val.getUTCFullYear() + '-' +
|
|
|
|
fillZeros(val.getUTCMonth() + 1) + '-' +
|
|
|
|
fillZeros(val.getUTCDate()) + ' ' +
|
|
|
|
fillZeros(val.getUTCHours()) + ':' +
|
|
|
|
fillZeros(val.getUTCMinutes()) + ':' +
|
|
|
|
fillZeros(val.getUTCSeconds());
|
|
|
|
|
|
|
|
function fillZeros(v) {
|
|
|
|
return v < 10 ? '0' + v : v;
|
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
|
|
|
|
2013-10-03 21:50:38 +00:00
|
|
|
/*!
|
|
|
|
* Convert property name/value to a DB column
|
|
|
|
* @param prop
|
|
|
|
* @param val
|
|
|
|
* @returns {*}
|
|
|
|
*/
|
2012-12-14 14:01:44 +00:00
|
|
|
MySQL.prototype.toDatabase = function (prop, val) {
|
2014-05-30 22:15:27 +00:00
|
|
|
if (val === null || val === undefined) {
|
|
|
|
return 'NULL';
|
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
if (val.constructor.name === 'Object') {
|
|
|
|
var operator = Object.keys(val)[0]
|
|
|
|
val = val[operator];
|
|
|
|
if (operator === 'between') {
|
|
|
|
return this.toDatabase(prop, val[0]) +
|
|
|
|
' AND ' +
|
|
|
|
this.toDatabase(prop, val[1]);
|
2014-05-30 22:15:27 +00:00
|
|
|
} else if (operator === 'inq' || operator === 'nin') {
|
|
|
|
if (Array.isArray(val)) { //if value is array
|
2014-02-13 00:57:06 +00:00
|
|
|
for (var i = 0; i < val.length; i++) {
|
2014-05-30 22:15:27 +00:00
|
|
|
val[i] = this.toDatabase(prop, val[i]);
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
return val.join(',');
|
|
|
|
} else {
|
2014-05-30 22:15:27 +00:00
|
|
|
return this.toDatabase(prop, val);
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
2014-06-10 23:06:16 +00:00
|
|
|
return this.toDatabase(prop, val);
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
2014-05-30 22:15:27 +00:00
|
|
|
if (!prop) {
|
|
|
|
return this.client.escape(val);
|
|
|
|
}
|
|
|
|
if (prop.type === Number) {
|
|
|
|
val = Number(val);
|
|
|
|
return isNaN(val) ? 'NULL' : val;
|
|
|
|
}
|
|
|
|
if (prop.type === Date) {
|
|
|
|
if (!val) {
|
|
|
|
return 'NULL';
|
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
if (!val.toUTCString) {
|
|
|
|
val = new Date(val);
|
2013-10-07 21:46:05 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
return '"' + dateToMysql(val) + '"';
|
|
|
|
}
|
2014-05-30 22:15:27 +00:00
|
|
|
if (prop.type === Boolean) {
|
|
|
|
return val ? 1 : 0;
|
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
if (prop.type.name === 'GeoPoint') {
|
|
|
|
return val ? 'Point(' + val.lat + ',' + val.lng + ')' : 'NULL';
|
|
|
|
}
|
2014-05-25 16:46:55 +00:00
|
|
|
if (prop.type === Object) {
|
|
|
|
return this.client.escape(val);
|
|
|
|
}
|
|
|
|
if (typeof prop.type === 'function') {
|
|
|
|
return this.client.escape(prop.type(val));
|
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
return this.client.escape(val.toString());
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
2013-10-03 21:50:38 +00:00
|
|
|
/*!
|
|
|
|
* Convert the data from database
|
|
|
|
* @param model
|
|
|
|
* @param data
|
|
|
|
* @returns {*}
|
|
|
|
*/
|
2012-12-14 14:01:44 +00:00
|
|
|
MySQL.prototype.fromDatabase = function (model, data) {
|
2014-02-13 00:57:06 +00:00
|
|
|
if (!data) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
var props = this._models[model].properties;
|
|
|
|
var json = {};
|
|
|
|
for (var p in props) {
|
|
|
|
var key = this.column(model, p);
|
|
|
|
var val = data[key];
|
|
|
|
if (typeof val === 'undefined' || val === null) {
|
|
|
|
continue;
|
2013-10-22 18:25:17 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
if (props[p]) {
|
|
|
|
switch (props[p].type.name) {
|
|
|
|
case 'Date':
|
|
|
|
val = new Date(val.toString().replace(/GMT.*$/, 'GMT'));
|
|
|
|
break;
|
|
|
|
case 'Boolean':
|
|
|
|
val = Boolean(val);
|
|
|
|
break;
|
|
|
|
case 'GeoPoint':
|
|
|
|
case 'Point':
|
|
|
|
val = {
|
|
|
|
lat: val.x,
|
|
|
|
lng: val.y
|
|
|
|
};
|
|
|
|
break;
|
|
|
|
}
|
2013-10-22 18:25:17 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
json[p] = val;
|
|
|
|
}
|
|
|
|
return json;
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
MySQL.prototype.escapeName = function (name) {
|
2014-02-13 00:57:06 +00:00
|
|
|
return '`' + name.replace(/\./g, '`.`') + '`';
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
2013-11-27 01:40:31 +00:00
|
|
|
MySQL.prototype.getColumns = function (model, props) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var cols = this._models[model].properties;
|
|
|
|
if (!cols) {
|
|
|
|
return '*';
|
|
|
|
}
|
|
|
|
var self = this;
|
|
|
|
var keys = Object.keys(cols);
|
|
|
|
if (Array.isArray(props) && props.length > 0) {
|
|
|
|
// No empty array, including all the fields
|
|
|
|
keys = props;
|
|
|
|
} else if ('object' === typeof props && Object.keys(props).length > 0) {
|
|
|
|
// { field1: boolean, field2: boolean ... }
|
|
|
|
var included = [];
|
|
|
|
var excluded = [];
|
|
|
|
keys.forEach(function (k) {
|
|
|
|
if (props[k]) {
|
|
|
|
included.push(k);
|
|
|
|
} else if ((k in props) && !props[k]) {
|
|
|
|
excluded.push(k);
|
|
|
|
}
|
2013-07-21 05:37:59 +00:00
|
|
|
});
|
2014-02-13 00:57:06 +00:00
|
|
|
if (included.length > 0) {
|
|
|
|
keys = included;
|
|
|
|
} else if (excluded.length > 0) {
|
|
|
|
excluded.forEach(function (e) {
|
|
|
|
var index = keys.indexOf(e);
|
|
|
|
keys.splice(index, 1);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
var names = keys.map(function (c) {
|
|
|
|
return self.columnEscaped(model, c);
|
|
|
|
});
|
|
|
|
return names.join(', ');
|
2013-08-18 17:04:58 +00:00
|
|
|
};
|
|
|
|
|
2014-05-15 04:21:00 +00:00
|
|
|
MySQL.prototype.buildWhere = function (model, conds) {
|
2014-05-15 17:32:31 +00:00
|
|
|
var where = this._buildWhere(model, conds);
|
|
|
|
return where? 'WHERE ' + where : '';
|
|
|
|
};
|
|
|
|
|
|
|
|
MySQL.prototype._buildWhere = function (model, conds) {
|
2014-05-30 22:15:27 +00:00
|
|
|
if (conds === null || conds === undefined || (typeof conds !== 'object')) {
|
|
|
|
return '';
|
|
|
|
}
|
2014-05-15 04:21:00 +00:00
|
|
|
var self = this;
|
2014-02-13 00:57:06 +00:00
|
|
|
var props = self._models[model].properties;
|
|
|
|
|
|
|
|
var cs = [];
|
|
|
|
Object.keys(conds).forEach(function (key) {
|
2014-05-15 04:21:00 +00:00
|
|
|
if (key === 'and' || key === 'or') {
|
|
|
|
var clauses = conds[key];
|
|
|
|
if (Array.isArray(clauses)) {
|
|
|
|
clauses = clauses.map(function (c) {
|
2014-05-15 17:32:31 +00:00
|
|
|
return '(' + self._buildWhere(model, c) + ')';
|
2014-05-15 04:21:00 +00:00
|
|
|
});
|
2014-05-15 17:32:31 +00:00
|
|
|
return cs.push(clauses.join(' ' + key.toUpperCase() + ' '));
|
2014-05-15 04:21:00 +00:00
|
|
|
}
|
|
|
|
// The value is not an array, fall back to regular fields
|
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
var keyEscaped = self.columnEscaped(model, key);
|
|
|
|
var val = self.toDatabase(props[key], conds[key]);
|
|
|
|
if (conds[key] === null || conds[key] === undefined) {
|
|
|
|
cs.push(keyEscaped + ' IS NULL');
|
|
|
|
} else if (conds[key] && conds[key].constructor.name === 'Object') {
|
|
|
|
var condType = Object.keys(conds[key])[0];
|
|
|
|
var sqlCond = keyEscaped;
|
|
|
|
if ((condType === 'inq' || condType === 'nin') && val.length === 0) {
|
|
|
|
cs.push(condType === 'inq' ? 0 : 1);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
switch (condType) {
|
|
|
|
case 'gt':
|
|
|
|
sqlCond += ' > ';
|
|
|
|
break;
|
|
|
|
case 'gte':
|
|
|
|
sqlCond += ' >= ';
|
|
|
|
break;
|
|
|
|
case 'lt':
|
|
|
|
sqlCond += ' < ';
|
|
|
|
break;
|
|
|
|
case 'lte':
|
|
|
|
sqlCond += ' <= ';
|
|
|
|
break;
|
|
|
|
case 'between':
|
|
|
|
sqlCond += ' BETWEEN ';
|
|
|
|
break;
|
|
|
|
case 'inq':
|
|
|
|
sqlCond += ' IN ';
|
|
|
|
break;
|
|
|
|
case 'nin':
|
|
|
|
sqlCond += ' NOT IN ';
|
|
|
|
break;
|
|
|
|
case 'neq':
|
|
|
|
sqlCond += ' != ';
|
|
|
|
break;
|
2014-05-29 22:16:14 +00:00
|
|
|
case 'like':
|
|
|
|
sqlCond += ' LIKE ';
|
|
|
|
break;
|
|
|
|
case 'nlike':
|
|
|
|
sqlCond += ' NOT LIKE ';
|
|
|
|
break;
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
sqlCond += (condType === 'inq' || condType === 'nin') ? '(' + val + ')' : val;
|
|
|
|
cs.push(sqlCond);
|
|
|
|
} else {
|
|
|
|
cs.push(keyEscaped + ' = ' + val);
|
2013-08-18 17:04:58 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
});
|
|
|
|
if (cs.length === 0) {
|
|
|
|
return '';
|
|
|
|
}
|
2014-05-15 17:32:31 +00:00
|
|
|
return cs.join(' AND ');
|
2013-08-18 17:04:58 +00:00
|
|
|
}
|
|
|
|
|
2013-10-14 21:32:19 +00:00
|
|
|
function buildOrderBy(self, model, order) {
|
2014-02-13 00:57:06 +00:00
|
|
|
if (typeof order === 'string') {
|
|
|
|
order = [order];
|
|
|
|
}
|
|
|
|
return 'ORDER BY ' + order.map(function (o) {
|
|
|
|
var t = o.split(/[\s,]+/);
|
|
|
|
if (t.length === 1) {
|
|
|
|
return self.columnEscaped(model, o);
|
2013-08-18 17:04:58 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
return self.columnEscaped(model, t[0]) + ' ' + t[1];
|
|
|
|
}).join(', ');
|
2013-08-18 17:04:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function buildLimit(limit, offset) {
|
2014-05-30 22:15:27 +00:00
|
|
|
if (isNaN(limit)) {
|
|
|
|
limit = 0;
|
|
|
|
}
|
|
|
|
if (isNaN(offset)) {
|
|
|
|
offset = 0;
|
|
|
|
}
|
|
|
|
return 'LIMIT ' + (offset ? (offset + ',' + limit) : limit);
|
2013-07-21 05:37:59 +00:00
|
|
|
}
|
|
|
|
|
2013-10-03 21:50:38 +00:00
|
|
|
/**
|
|
|
|
* Find matching model instances by the filter
|
|
|
|
*
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} filter The filter
|
|
|
|
* @param {Function} [callback] The callback function
|
|
|
|
*/
|
2012-12-14 14:01:44 +00:00
|
|
|
MySQL.prototype.all = function all(model, filter, callback) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var self = this;
|
|
|
|
// Order by id if no order is specified
|
|
|
|
filter = filter || {};
|
|
|
|
if (!filter.order) {
|
|
|
|
var idNames = this.idNames(model);
|
|
|
|
if (idNames && idNames.length) {
|
|
|
|
filter.order = idNames;
|
2013-07-21 05:37:59 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
var sql = 'SELECT ' + this.getColumns(model, filter.fields) + ' FROM ' + this.tableEscaped(model);
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
if (filter) {
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
if (filter.where) {
|
2014-05-15 04:21:00 +00:00
|
|
|
sql += ' ' + self.buildWhere(model, filter.where);
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
if (filter.order) {
|
|
|
|
sql += ' ' + buildOrderBy(self, model, filter.order);
|
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
if (filter.limit) {
|
2014-05-30 22:15:27 +00:00
|
|
|
sql += ' ' + buildLimit(filter.limit, filter.skip || filter.offset || 0);
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
2012-12-16 17:57:39 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
this.query(sql, function (err, data) {
|
|
|
|
if (err) {
|
|
|
|
return callback(err, []);
|
|
|
|
}
|
|
|
|
|
|
|
|
var objs = data.map(function (obj) {
|
|
|
|
return self.fromDatabase(model, obj);
|
|
|
|
});
|
|
|
|
if (filter && filter.include) {
|
|
|
|
this._models[model].model.include(objs, filter.include, callback);
|
|
|
|
} else {
|
|
|
|
callback(null, objs);
|
|
|
|
}
|
|
|
|
}.bind(this));
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
return sql;
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2013-08-18 17:04:58 +00:00
|
|
|
};
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-05-30 22:15:27 +00:00
|
|
|
MySQL.prototype.count = function count(model, callback, where) {
|
|
|
|
|
|
|
|
this.query('SELECT count(*) as cnt FROM ' +
|
|
|
|
this.tableEscaped(model) + ' ' + this.buildWhere(model, where),
|
|
|
|
function (err, res) {
|
|
|
|
if (err) {
|
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
var c = (res && res[0] && res[0].cnt) || 0;
|
|
|
|
callback(err, c);
|
|
|
|
});
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
2013-08-18 17:04:58 +00:00
|
|
|
/**
|
|
|
|
* Delete instances for the given model
|
|
|
|
*
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} [where] The filter for where
|
|
|
|
* @param {Function} [callback] The callback function
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
MySQL.prototype.destroyAll = function destroyAll(model, where, callback) {
|
2014-02-13 00:57:06 +00:00
|
|
|
if (!callback && 'function' === typeof where) {
|
|
|
|
callback = where;
|
|
|
|
where = undefined;
|
|
|
|
}
|
2014-05-30 22:15:27 +00:00
|
|
|
this.query('DELETE FROM '
|
2014-05-25 16:46:55 +00:00
|
|
|
+ this.tableEscaped(model) + ' ' + this.buildWhere(model, where || {}),
|
2014-05-15 04:21:00 +00:00
|
|
|
function (err, data) {
|
|
|
|
callback && callback(err, data);
|
2014-05-25 16:46:55 +00:00
|
|
|
}.bind(this));
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
2013-10-03 21:50:38 +00:00
|
|
|
/**
|
|
|
|
* Perform autoupdate for the given models
|
|
|
|
* @param {String[]} [models] A model name or an array of model names. If not present, apply to all models
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
2013-08-08 15:35:29 +00:00
|
|
|
MySQL.prototype.autoupdate = function (models, cb) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var self = this;
|
|
|
|
var wait = 0;
|
|
|
|
if ((!cb) && ('function' === typeof models)) {
|
|
|
|
cb = models;
|
|
|
|
models = undefined;
|
|
|
|
}
|
|
|
|
// First argument is a model name
|
|
|
|
if ('string' === typeof models) {
|
|
|
|
models = [models];
|
|
|
|
}
|
|
|
|
|
|
|
|
models = models || Object.keys(this._models);
|
|
|
|
|
|
|
|
models.forEach(function (model) {
|
|
|
|
if (model in self._models) {
|
|
|
|
wait++;
|
|
|
|
self.query('SHOW FIELDS FROM ' + self.tableEscaped(model), function (err, fields) {
|
|
|
|
self.query('SHOW INDEXES FROM ' + self.tableEscaped(model), function (err, indexes) {
|
2014-06-16 10:32:29 +00:00
|
|
|
if (!err && fields && fields.length) {
|
2014-02-13 00:57:06 +00:00
|
|
|
self.alterTable(model, fields, indexes, done);
|
|
|
|
} else {
|
|
|
|
self.createTable(model, done);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
2013-08-08 15:35:29 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
});
|
2013-08-08 15:35:29 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
function done(err) {
|
|
|
|
if (err) {
|
|
|
|
console.error(err);
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
if (--wait === 0 && cb) {
|
|
|
|
cb();
|
|
|
|
}
|
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
2013-10-08 20:44:58 +00:00
|
|
|
/*!
|
|
|
|
* Create table
|
|
|
|
* @param model
|
|
|
|
* @param cb
|
|
|
|
*/
|
|
|
|
MySQL.prototype.createTable = function (model, cb) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var metadata = this._models[model].settings[this.name];
|
|
|
|
var engine = metadata && metadata.engine;
|
|
|
|
var sql = 'CREATE TABLE ' + this.tableEscaped(model) +
|
|
|
|
' (\n ' + this.propertiesSQL(model) + '\n)';
|
|
|
|
if (engine) {
|
|
|
|
sql += 'ENGINE=' + engine + '\n';
|
|
|
|
}
|
|
|
|
this.query(sql, cb);
|
2013-10-08 20:44:58 +00:00
|
|
|
};
|
|
|
|
|
2013-10-03 21:50:38 +00:00
|
|
|
/**
|
|
|
|
* Check if the models exist
|
|
|
|
* @param {String[]} [models] A model name or an array of model names. If not present, apply to all models
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
2012-12-14 14:01:44 +00:00
|
|
|
MySQL.prototype.isActual = function (cb) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var ok = false;
|
|
|
|
var self = this;
|
|
|
|
var wait = 0;
|
|
|
|
Object.keys(this._models).forEach(function (model) {
|
|
|
|
wait += 1;
|
|
|
|
self.query('SHOW FIELDS FROM ' + model, function (err, fields) {
|
|
|
|
self.query('SHOW INDEXES FROM ' + model, function (err, indexes) {
|
|
|
|
self.alterTable(model, fields, indexes, done, true);
|
|
|
|
});
|
2012-12-14 14:01:44 +00:00
|
|
|
});
|
2014-02-13 00:57:06 +00:00
|
|
|
});
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
function done(err, needAlter) {
|
|
|
|
if (err) {
|
2014-04-08 05:16:26 +00:00
|
|
|
debug(err);
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
ok = ok || needAlter;
|
|
|
|
if (--wait === 0 && cb) {
|
|
|
|
cb(null, !ok);
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
MySQL.prototype.alterTable = function (model, actualFields, actualIndexes, done, checkOnly) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var self = this;
|
|
|
|
var m = this._models[model];
|
|
|
|
var propNames = Object.keys(m.properties).filter(function (name) {
|
|
|
|
return !!m.properties[name];
|
|
|
|
});
|
|
|
|
var indexNames = m.settings.indexes ? Object.keys(m.settings.indexes).filter(function (name) {
|
|
|
|
return !!m.settings.indexes[name];
|
|
|
|
}) : [];
|
|
|
|
var sql = [];
|
|
|
|
var ai = {};
|
|
|
|
|
|
|
|
if (actualIndexes) {
|
|
|
|
actualIndexes.forEach(function (i) {
|
|
|
|
var name = i.Key_name;
|
|
|
|
if (!ai[name]) {
|
|
|
|
ai[name] = {
|
|
|
|
info: i,
|
|
|
|
columns: []
|
|
|
|
};
|
|
|
|
}
|
|
|
|
ai[name].columns[i.Seq_in_index - 1] = i.Column_name;
|
2012-12-14 14:01:44 +00:00
|
|
|
});
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
var aiNames = Object.keys(ai);
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
// change/add new fields
|
|
|
|
propNames.forEach(function (propName) {
|
|
|
|
if (m.properties[propName] && self.id(model, propName)) return;
|
|
|
|
var found;
|
2013-04-18 11:19:59 +00:00
|
|
|
if (actualFields) {
|
2014-02-13 00:57:06 +00:00
|
|
|
actualFields.forEach(function (f) {
|
|
|
|
if (f.Field === propName) {
|
|
|
|
found = f;
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
});
|
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
if (found) {
|
|
|
|
actualize(propName, found);
|
|
|
|
} else {
|
|
|
|
sql.push('ADD COLUMN `' + propName + '` ' + self.propertySettingsSQL(model, propName));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// drop columns
|
|
|
|
if (actualFields) {
|
|
|
|
actualFields.forEach(function (f) {
|
|
|
|
var notFound = !~propNames.indexOf(f.Field);
|
|
|
|
if (m.properties[f.Field] && self.id(model, f.Field)) return;
|
|
|
|
if (notFound || !m.properties[f.Field]) {
|
|
|
|
sql.push('DROP COLUMN `' + f.Field + '`');
|
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
});
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
// remove indexes
|
|
|
|
aiNames.forEach(function (indexName) {
|
|
|
|
if (indexName === 'PRIMARY' || (m.properties[indexName] && self.id(model, indexName))) return;
|
|
|
|
if (indexNames.indexOf(indexName) === -1 && !m.properties[indexName] || m.properties[indexName] && !m.properties[indexName].index) {
|
|
|
|
sql.push('DROP INDEX `' + indexName + '`');
|
2012-12-14 14:01:44 +00:00
|
|
|
} else {
|
2014-02-13 00:57:06 +00:00
|
|
|
// first: check single (only type and kind)
|
|
|
|
if (m.properties[indexName] && !m.properties[indexName].index) {
|
|
|
|
// TODO
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// second: check multiple indexes
|
|
|
|
var orderMatched = true;
|
|
|
|
if (indexNames.indexOf(indexName) !== -1) {
|
|
|
|
m.settings.indexes[indexName].columns.split(/,\s*/).forEach(function (columnName, i) {
|
|
|
|
if (ai[indexName].columns[i] !== columnName) orderMatched = false;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
if (!orderMatched) {
|
|
|
|
sql.push('DROP INDEX `' + indexName + '`');
|
|
|
|
delete ai[indexName];
|
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
});
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
// add single-column indexes
|
|
|
|
propNames.forEach(function (propName) {
|
|
|
|
var i = m.properties[propName].index;
|
|
|
|
if (!i) {
|
|
|
|
return;
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
var found = ai[propName] && ai[propName].info;
|
|
|
|
if (!found) {
|
|
|
|
var type = '';
|
|
|
|
var kind = '';
|
|
|
|
if (i.type) {
|
|
|
|
type = 'USING ' + i.type;
|
|
|
|
}
|
|
|
|
if (i.kind) {
|
|
|
|
// kind = i.kind;
|
|
|
|
}
|
|
|
|
if (kind && type) {
|
|
|
|
sql.push('ADD ' + kind + ' INDEX `' + propName + '` (`' + propName + '`) ' + type);
|
|
|
|
} else {
|
|
|
|
sql.push('ADD ' + kind + ' INDEX `' + propName + '` ' + type + ' (`' + propName + '`) ');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// add multi-column indexes
|
|
|
|
indexNames.forEach(function (indexName) {
|
|
|
|
var i = m.settings.indexes[indexName];
|
|
|
|
var found = ai[indexName] && ai[indexName].info;
|
|
|
|
if (!found) {
|
|
|
|
var type = '';
|
|
|
|
var kind = '';
|
|
|
|
if (i.type) {
|
|
|
|
type = 'USING ' + i.type;
|
|
|
|
}
|
|
|
|
if (i.kind) {
|
|
|
|
kind = i.kind;
|
|
|
|
}
|
|
|
|
if (kind && type) {
|
|
|
|
sql.push('ADD ' + kind + ' INDEX `' + indexName + '` (' + i.columns + ') ' + type);
|
|
|
|
} else {
|
|
|
|
sql.push('ADD ' + kind + ' INDEX ' + type + ' `' + indexName + '` (' + i.columns + ')');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
if (sql.length) {
|
|
|
|
var query = 'ALTER TABLE ' + self.tableEscaped(model) + ' ' + sql.join(',\n');
|
|
|
|
if (checkOnly) {
|
|
|
|
done(null, true, {statements: sql, query: query});
|
|
|
|
} else {
|
|
|
|
this.query(query, done);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
done();
|
|
|
|
}
|
|
|
|
|
|
|
|
function actualize(propName, oldSettings) {
|
|
|
|
var newSettings = m.properties[propName];
|
|
|
|
if (newSettings && changed(newSettings, oldSettings)) {
|
|
|
|
sql.push('CHANGE COLUMN `' + propName + '` `' + propName + '` ' + self.propertySettingsSQL(model, propName));
|
|
|
|
}
|
|
|
|
}
|
2013-11-27 01:40:31 +00:00
|
|
|
|
2014-02-13 00:57:06 +00:00
|
|
|
function changed(newSettings, oldSettings) {
|
|
|
|
if (oldSettings.Null === 'YES') { // Used to allow null and does not now.
|
|
|
|
if (newSettings.allowNull === false) return true;
|
|
|
|
if (newSettings.null === false) return true;
|
|
|
|
}
|
|
|
|
if (oldSettings.Null === 'NO') { // Did not allow null and now does.
|
|
|
|
if (newSettings.allowNull === true) return true;
|
|
|
|
if (newSettings.null === true) return true;
|
|
|
|
if (newSettings.null === undefined && newSettings.allowNull === undefined) return true;
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
|
|
|
|
if (oldSettings.Type.toUpperCase() !== datatype(newSettings).toUpperCase()) return true;
|
|
|
|
return false;
|
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
MySQL.prototype.propertiesSQL = function (model) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var self = this;
|
|
|
|
|
|
|
|
var pks = this.idNames(model).map(function (i) {
|
|
|
|
return self.columnEscaped(model, i);
|
|
|
|
});
|
|
|
|
|
|
|
|
var sql = [];
|
|
|
|
if (pks.length === 1) {
|
|
|
|
var idName = this.idName(model);
|
2014-04-08 05:16:26 +00:00
|
|
|
var idProp = this._models[model].properties[idName];
|
|
|
|
if(idProp.generated) {
|
|
|
|
sql.push(self.columnEscaped(model, idName) + ' INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY');
|
|
|
|
} else {
|
|
|
|
idProp.nullable = false;
|
|
|
|
sql.push(self.columnEscaped(model, idName) + ' ' + self.propertySettingsSQL(model, idName) + ' PRIMARY KEY');
|
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
Object.keys(this._models[model].properties).forEach(function (prop) {
|
|
|
|
if (self.id(model, prop) && pks.length === 1) {
|
|
|
|
return;
|
2013-10-14 21:32:19 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
var colName = self.columnEscaped(model, prop);
|
|
|
|
sql.push(colName + ' ' + self.propertySettingsSQL(model, prop));
|
|
|
|
});
|
|
|
|
if (pks.length > 1) {
|
|
|
|
sql.push('PRIMARY KEY(' + pks.join(',') + ')');
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
var sql = ['`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY'];
|
|
|
|
Object.keys(this._models[model].properties).forEach(function (prop) {
|
|
|
|
if (self.id(model, prop)) return;
|
|
|
|
sql.push('`' + prop + '` ' + self.propertySettingsSQL(model, prop));
|
|
|
|
});
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Declared in model index property indexes.
|
|
|
|
Object.keys(this._models[model].properties).forEach(function (prop) {
|
|
|
|
var i = self._models[model].properties[prop].index;
|
|
|
|
if (i) {
|
|
|
|
sql.push(self.singleIndexSettingsSQL(model, prop));
|
2013-10-14 21:32:19 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
});
|
|
|
|
// Settings might not have an indexes property.
|
|
|
|
var dxs = this._models[model].settings.indexes;
|
|
|
|
if (dxs) {
|
|
|
|
Object.keys(this._models[model].settings.indexes).forEach(function (prop) {
|
|
|
|
sql.push(self.indexSettingsSQL(model, prop));
|
2013-02-14 16:37:32 +00:00
|
|
|
});
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
return sql.join(',\n ');
|
2013-02-14 16:37:32 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
MySQL.prototype.singleIndexSettingsSQL = function (model, prop) {
|
2014-02-13 00:57:06 +00:00
|
|
|
// Recycled from alterTable single indexes above, more or less.
|
|
|
|
var i = this._models[model].properties[prop].index;
|
|
|
|
var type = '';
|
|
|
|
var kind = '';
|
|
|
|
if (i.type) {
|
|
|
|
type = 'USING ' + i.type;
|
|
|
|
}
|
|
|
|
if (i.kind) {
|
|
|
|
kind = i.kind;
|
|
|
|
}
|
|
|
|
var columnName = this.columnEscaped(model, prop);
|
|
|
|
if (kind && type) {
|
|
|
|
return (kind + ' INDEX ' + columnName + ' (' + columnName + ') ' + type);
|
|
|
|
} else {
|
|
|
|
return (kind + ' INDEX ' + columnName + ' ' + type + ' (' + columnName + ') ');
|
|
|
|
}
|
2013-02-14 16:52:00 +00:00
|
|
|
};
|
2012-12-14 14:01:44 +00:00
|
|
|
|
2013-02-14 16:37:32 +00:00
|
|
|
MySQL.prototype.indexSettingsSQL = function (model, prop) {
|
2014-02-13 00:57:06 +00:00
|
|
|
// Recycled from alterTable multi-column indexes above, more or less.
|
|
|
|
var i = this._models[model].settings.indexes[prop];
|
|
|
|
var type = '';
|
|
|
|
var kind = '';
|
|
|
|
if (i.type) {
|
|
|
|
type = 'USING ' + i.type;
|
|
|
|
}
|
|
|
|
if (i.kind) {
|
|
|
|
kind = i.kind;
|
|
|
|
}
|
|
|
|
var columnName = this.columnEscaped(model, prop);
|
|
|
|
if (kind && type) {
|
|
|
|
return (kind + ' INDEX ' + columnName + ' (' + i.columns + ') ' + type);
|
|
|
|
} else {
|
|
|
|
return (kind + ' INDEX ' + type + ' ' + columnName + ' (' + i.columns + ')');
|
|
|
|
}
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
MySQL.prototype.propertySettingsSQL = function (model, prop) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var p = this._models[model].properties[prop];
|
|
|
|
var line = this.columnDataType(model, prop) + ' ' +
|
|
|
|
(p.nullable === false || p.allowNull === false || p['null'] === false ? 'NOT NULL' : 'NULL');
|
|
|
|
return line;
|
2012-12-14 14:01:44 +00:00
|
|
|
};
|
|
|
|
|
2013-10-08 20:44:58 +00:00
|
|
|
MySQL.prototype.columnDataType = function (model, property) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var columnMetadata = this.columnMetadata(model, property);
|
|
|
|
var colType = columnMetadata && columnMetadata.dataType;
|
|
|
|
if (colType) {
|
|
|
|
colType = colType.toUpperCase();
|
|
|
|
}
|
|
|
|
var prop = this._models[model].properties[property];
|
|
|
|
if (!prop) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
var colLength = columnMetadata && columnMetadata.dataLength || prop.length;
|
|
|
|
if (colType) {
|
|
|
|
return colType + (colLength ? '(' + colLength + ')' : '');
|
|
|
|
}
|
|
|
|
return datatype(prop);
|
2013-10-08 20:44:58 +00:00
|
|
|
};
|
|
|
|
|
2012-12-14 14:01:44 +00:00
|
|
|
function datatype(p) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var dt = '';
|
|
|
|
switch (p.type.name) {
|
|
|
|
default:
|
|
|
|
case 'String':
|
|
|
|
dt = columnType(p, 'VARCHAR');
|
|
|
|
dt = stringOptionsByType(p, dt);
|
|
|
|
break;
|
2014-06-06 16:38:36 +00:00
|
|
|
case 'JSON':
|
|
|
|
case 'Object':
|
|
|
|
case 'Any':
|
2014-02-13 00:57:06 +00:00
|
|
|
case 'Text':
|
|
|
|
dt = columnType(p, 'TEXT');
|
|
|
|
dt = stringOptionsByType(p, dt);
|
|
|
|
break;
|
|
|
|
case 'Number':
|
|
|
|
dt = columnType(p, 'INT');
|
|
|
|
dt = numericOptionsByType(p, dt);
|
|
|
|
break;
|
|
|
|
case 'Date':
|
|
|
|
dt = columnType(p, 'DATETIME'); // Currently doesn't need options.
|
|
|
|
break;
|
|
|
|
case 'Boolean':
|
|
|
|
dt = 'TINYINT(1)';
|
|
|
|
break;
|
|
|
|
case 'Point':
|
|
|
|
case 'GeoPoint':
|
|
|
|
dt = 'POINT';
|
|
|
|
break;
|
|
|
|
case 'Enum':
|
|
|
|
dt = 'ENUM(' + p.type._string + ')';
|
|
|
|
dt = stringOptions(p, dt); // Enum columns can have charset/collation.
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
return dt;
|
2012-12-14 14:01:44 +00:00
|
|
|
}
|
|
|
|
|
2013-06-04 21:34:23 +00:00
|
|
|
function columnType(p, defaultType) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var dt = defaultType;
|
|
|
|
if (p.dataType) {
|
|
|
|
dt = String(p.dataType);
|
|
|
|
}
|
|
|
|
return dt;
|
2013-06-04 21:34:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function stringOptionsByType(p, dt) {
|
2014-02-13 00:57:06 +00:00
|
|
|
switch (dt.toLowerCase()) {
|
|
|
|
default:
|
|
|
|
case 'varchar':
|
2014-05-29 22:45:25 +00:00
|
|
|
// The maximum length for an ID column is 1000 bytes
|
2014-06-06 16:38:36 +00:00
|
|
|
// The maximum row size is 64K
|
2014-07-08 18:23:45 +00:00
|
|
|
var len = p.length || p.limit || ((p.type !== String) ? 4096 : p.id ? 255: 512);
|
2014-05-25 16:46:55 +00:00
|
|
|
dt += '(' + len + ')';
|
|
|
|
break;
|
2014-02-13 00:57:06 +00:00
|
|
|
case 'char':
|
2014-07-08 18:23:45 +00:00
|
|
|
len = p.length || p.limit || 255;
|
2014-05-25 16:46:55 +00:00
|
|
|
dt += '(' + len + ')';
|
2014-02-13 00:57:06 +00:00
|
|
|
break;
|
|
|
|
|
|
|
|
case 'text':
|
|
|
|
case 'tinytext':
|
|
|
|
case 'mediumtext':
|
|
|
|
case 'longtext':
|
|
|
|
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
dt = stringOptions(p, dt);
|
|
|
|
return dt;
|
2013-06-04 21:34:23 +00:00
|
|
|
}
|
|
|
|
|
2013-11-27 01:40:31 +00:00
|
|
|
function stringOptions(p, dt) {
|
2014-02-13 00:57:06 +00:00
|
|
|
if (p.charset) {
|
|
|
|
dt += " CHARACTER SET " + p.charset;
|
|
|
|
}
|
|
|
|
if (p.collation) {
|
|
|
|
dt += " COLLATE " + p.collation;
|
|
|
|
}
|
|
|
|
return dt;
|
2013-06-04 21:34:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function numericOptionsByType(p, dt) {
|
2014-02-13 00:57:06 +00:00
|
|
|
switch (dt.toLowerCase()) {
|
|
|
|
default:
|
|
|
|
case 'tinyint':
|
|
|
|
case 'smallint':
|
|
|
|
case 'mediumint':
|
|
|
|
case 'int':
|
|
|
|
case 'integer':
|
|
|
|
case 'bigint':
|
|
|
|
dt = integerOptions(p, dt);
|
|
|
|
break;
|
|
|
|
|
|
|
|
case 'decimal':
|
|
|
|
case 'numeric':
|
|
|
|
dt = fixedPointOptions(p, dt);
|
|
|
|
break;
|
|
|
|
|
|
|
|
case 'float':
|
|
|
|
case 'double':
|
|
|
|
dt = floatingPointOptions(p, dt);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
dt = unsigned(p, dt);
|
|
|
|
return dt;
|
2013-06-04 21:34:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function floatingPointOptions(p, dt) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var precision = 16;
|
|
|
|
var scale = 8;
|
|
|
|
if (p.precision) {
|
|
|
|
precision = Number(p.precision);
|
|
|
|
}
|
|
|
|
if (p.scale) {
|
|
|
|
scale = Number(p.scale);
|
|
|
|
}
|
|
|
|
if (p.precision && p.scale) {
|
|
|
|
dt += '(' + precision + ',' + scale + ')';
|
|
|
|
} else if (p.precision) {
|
|
|
|
dt += '(' + precision + ')';
|
|
|
|
}
|
|
|
|
return dt;
|
2013-06-04 21:34:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/* @TODO: Change fixed point to use an arbitrary precision arithmetic library. */
|
|
|
|
/* Currently fixed point will lose precision because it's turned to non-fixed in */
|
|
|
|
/* JS. Also, defaulting column to (9,2) and not allowing non-specified 'DECIMAL' */
|
|
|
|
/* declaration which would default to DECIMAL(10,0). Instead defaulting to (9,2). */
|
|
|
|
function fixedPointOptions(p, dt) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var precision = 9;
|
|
|
|
var scale = 2;
|
|
|
|
if (p.precision) {
|
|
|
|
precision = Number(p.precision);
|
|
|
|
}
|
|
|
|
if (p.scale) {
|
|
|
|
scale = Number(p.scale);
|
|
|
|
}
|
|
|
|
dt += '(' + precision + ',' + scale + ')';
|
|
|
|
return dt;
|
2013-06-04 21:34:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function integerOptions(p, dt) {
|
2014-02-13 00:57:06 +00:00
|
|
|
var tmp = 0;
|
|
|
|
if (p.display || p.limit) {
|
|
|
|
tmp = Number(p.display || p.limit);
|
|
|
|
}
|
|
|
|
if (tmp > 0) {
|
|
|
|
dt += '(' + tmp + ')';
|
|
|
|
} else if (p.unsigned) {
|
|
|
|
switch (dt.toLowerCase()) {
|
|
|
|
default:
|
|
|
|
case 'int':
|
|
|
|
dt += '(10)';
|
|
|
|
break;
|
|
|
|
case 'mediumint':
|
|
|
|
dt += '(8)';
|
|
|
|
break;
|
|
|
|
case 'smallint':
|
|
|
|
dt += '(5)';
|
|
|
|
break;
|
|
|
|
case 'tinyint':
|
|
|
|
dt += '(3)';
|
|
|
|
break;
|
|
|
|
case 'bigint':
|
|
|
|
dt += '(20)';
|
|
|
|
break;
|
2013-06-04 21:34:23 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
} else {
|
|
|
|
switch (dt.toLowerCase()) {
|
|
|
|
default:
|
|
|
|
case 'int':
|
|
|
|
dt += '(11)';
|
|
|
|
break;
|
|
|
|
case 'mediumint':
|
|
|
|
dt += '(9)';
|
|
|
|
break;
|
|
|
|
case 'smallint':
|
|
|
|
dt += '(6)';
|
|
|
|
break;
|
|
|
|
case 'tinyint':
|
|
|
|
dt += '(4)';
|
|
|
|
break;
|
|
|
|
case 'bigint':
|
|
|
|
dt += '(20)';
|
|
|
|
break;
|
2013-06-04 21:34:23 +00:00
|
|
|
}
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
return dt;
|
2013-06-04 21:34:23 +00:00
|
|
|
}
|
|
|
|
|
2013-11-27 01:40:31 +00:00
|
|
|
function unsigned(p, dt) {
|
2014-02-13 00:57:06 +00:00
|
|
|
if (p.unsigned) {
|
|
|
|
dt += ' UNSIGNED';
|
|
|
|
}
|
|
|
|
return dt;
|
2013-06-04 21:34:23 +00:00
|
|
|
}
|
2013-07-21 06:38:40 +00:00
|
|
|
|
2013-11-27 01:40:31 +00:00
|
|
|
/**
|
2013-11-27 16:42:40 +00:00
|
|
|
* Disconnect from MySQL
|
2013-11-27 01:40:31 +00:00
|
|
|
*/
|
|
|
|
MySQL.prototype.disconnect = function () {
|
2014-02-13 00:57:06 +00:00
|
|
|
if (this.debug) {
|
2014-04-08 05:16:26 +00:00
|
|
|
debug('disconnect');
|
2014-02-13 00:57:06 +00:00
|
|
|
}
|
|
|
|
if (this.client) {
|
|
|
|
this.client.end();
|
|
|
|
}
|
2013-11-27 01:40:31 +00:00
|
|
|
};
|
|
|
|
|
2013-07-21 17:36:26 +00:00
|
|
|
require('./discovery')(MySQL);
|
|
|
|
|