upgrade eslint deps

This commit is contained in:
biniam 2017-07-24 12:48:26 -04:00
parent 5eedce280e
commit 7a7a34e77f
14 changed files with 219 additions and 212 deletions

View File

@ -64,19 +64,19 @@ function mixinDiscovery(MySQL, mysql) {
sqlTables = paginateSQL('SELECT \'table\' AS "type",' + sqlTables = paginateSQL('SELECT \'table\' AS "type",' +
' table_name AS "name", table_schema AS "owner"' + ' table_name AS "name", table_schema AS "owner"' +
' FROM information_schema.tables', ' FROM information_schema.tables',
'table_schema, table_name', options); 'table_schema, table_name', options);
} else if (schema) { } else if (schema) {
sqlTables = paginateSQL('SELECT \'table\' AS "type",' + sqlTables = paginateSQL('SELECT \'table\' AS "type",' +
' table_name AS "name", table_schema AS "schema"' + ' table_name AS "name", table_schema AS "schema"' +
' FROM information_schema.tables' + ' FROM information_schema.tables' +
' WHERE table_schema=' + mysql.escape(schema), ' WHERE table_schema=' + mysql.escape(schema),
'table_schema, table_name', options); 'table_schema, table_name', options);
} else { } else {
sqlTables = paginateSQL('SELECT \'table\' AS "type",' + sqlTables = paginateSQL('SELECT \'table\' AS "type",' +
' table_name AS "name", ' + ' table_name AS "name", ' +
' table_schema AS "owner" FROM information_schema.tables' + ' table_schema AS "owner" FROM information_schema.tables' +
' WHERE table_schema=SUBSTRING_INDEX(USER(),\'@\',1)', ' WHERE table_schema=SUBSTRING_INDEX(USER(),\'@\',1)',
'table_name', options); 'table_name', options);
} }
return sqlTables; return sqlTables;
}; };
@ -96,20 +96,20 @@ function mixinDiscovery(MySQL, mysql) {
' table_name AS "name",' + ' table_name AS "name",' +
' table_schema AS "owner"' + ' table_schema AS "owner"' +
' FROM information_schema.views', ' FROM information_schema.views',
'table_schema, table_name', options); 'table_schema, table_name', options);
} else if (schema) { } else if (schema) {
sqlViews = paginateSQL('SELECT \'view\' AS "type",' + sqlViews = paginateSQL('SELECT \'view\' AS "type",' +
' table_name AS "name",' + ' table_name AS "name",' +
' table_schema AS "owner"' + ' table_schema AS "owner"' +
' FROM information_schema.views' + ' FROM information_schema.views' +
' WHERE table_schema=' + mysql.escape(schema), ' WHERE table_schema=' + mysql.escape(schema),
'table_schema, table_name', options); 'table_schema, table_name', options);
} else { } else {
sqlViews = paginateSQL('SELECT \'view\' AS "type",' + sqlViews = paginateSQL('SELECT \'view\' AS "type",' +
' table_name AS "name",' + ' table_name AS "name",' +
' table_schema AS "owner"' + ' table_schema AS "owner"' +
' FROM information_schema.views', ' FROM information_schema.views',
'table_name', options); 'table_name', options);
} }
} }
return sqlViews; return sqlViews;
@ -170,7 +170,7 @@ function mixinDiscovery(MySQL, mysql) {
' FROM information_schema.columns' + ' FROM information_schema.columns' +
' WHERE table_schema=' + mysql.escape(schema) + ' WHERE table_schema=' + mysql.escape(schema) +
(table ? ' AND table_name=' + mysql.escape(table) : ''), (table ? ' AND table_name=' + mysql.escape(table) : ''),
'table_name, ordinal_position', {}); 'table_name, ordinal_position', {});
} else { } else {
sql = paginateSQL('SELECT table_schema AS "owner",' + sql = paginateSQL('SELECT table_schema AS "owner",' +
' table_name AS "tableName",' + ' table_name AS "tableName",' +
@ -184,7 +184,7 @@ function mixinDiscovery(MySQL, mysql) {
' CASE WHEN extra LIKE \'%auto_increment%\' THEN 1 ELSE 0 END AS "generated"' + ' CASE WHEN extra LIKE \'%auto_increment%\' THEN 1 ELSE 0 END AS "generated"' +
' FROM information_schema.columns' + ' FROM information_schema.columns' +
(table ? ' WHERE table_name=' + mysql.escape(table) : ''), (table ? ' WHERE table_name=' + mysql.escape(table) : ''),
'table_name, ordinal_position', {}); 'table_name, ordinal_position', {});
} }
return sql; return sql;
}; };
@ -203,8 +203,8 @@ function mixinDiscovery(MySQL, mysql) {
* @param table * @param table
* @returns {string} * @returns {string}
*/ */
// http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html // http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html
// #getPrimaryKeys(java.lang.String, java.lang.String, java.lang.String) // #getPrimaryKeys(java.lang.String, java.lang.String, java.lang.String)
MySQL.prototype.buildQueryPrimaryKeys = function(schema, table) { MySQL.prototype.buildQueryPrimaryKeys = function(schema, table) {
var sql = 'SELECT table_schema AS "owner",' + var sql = 'SELECT table_schema AS "owner",' +
' table_name AS "tableName",' + ' table_name AS "tableName",' +

View File

@ -37,7 +37,7 @@ function mixinMigration(MySQL, mysql) {
}); });
}; };
/** /**
* Perform autoupdate for the given models * Perform autoupdate for the given models
* @param {String[]} [models] A model name or an array of model names. * @param {String[]} [models] A model name or an array of model names.
* If not present, apply to all models * If not present, apply to all models
@ -67,17 +67,18 @@ function mixinMigration(MySQL, mysql) {
self.getTableStatus(model, function(err, fields, indexes) { self.getTableStatus(model, function(err, fields, indexes) {
self.discoverForeignKeys(self.table(model), {}, function(err, foreignKeys) { self.discoverForeignKeys(self.table(model), {}, function(err, foreignKeys) {
if (err) console.log('Failed to discover "' + table + '" foreign keys', err); if (err) console.log('Failed to discover "' + self.table(model) +
'" foreign keys', err);
if (!err && fields && fields.length) { if (!err && fields && fields.length) {
//if we already have a definition, update this table // if we already have a definition, update this table
self.alterTable(model, fields, indexes, foreignKeys, function(err, result) { self.alterTable(model, fields, indexes, foreignKeys, function(err, result) {
if (!err) { if (!err) {
//foreignKeys is a list of EXISTING fkeys here, so you don't need to recreate them again // foreignKeys is a list of EXISTING fkeys here, so you don't need to recreate them again
//prepare fkSQL for new foreign keys // prepare fkSQL for new foreign keys
var fkSQL = self.getForeignKeySQL(model, var fkSQL = self.getForeignKeySQL(model,
self.getModelDefinition(model).settings.foreignKeys, self.getModelDefinition(model).settings.foreignKeys,
foreignKeys); foreignKeys);
self.addForeignKeys(model, fkSQL, function(err, result) { self.addForeignKeys(model, fkSQL, function(err, result) {
done(err); done(err);
}); });
@ -86,7 +87,7 @@ function mixinMigration(MySQL, mysql) {
} }
}); });
} else { } else {
//if there is not yet a definition, create this table // if there is not yet a definition, create this table
self.createTable(model, function(err) { self.createTable(model, function(err) {
if (!err) { if (!err) {
self.addForeignKeys(model, function(err, result) { self.addForeignKeys(model, function(err, result) {
@ -144,7 +145,8 @@ function mixinMigration(MySQL, mysql) {
async.eachSeries(models, function(model, done) { async.eachSeries(models, function(model, done) {
self.getTableStatus(model, function(err, fields, indexes) { self.getTableStatus(model, function(err, fields, indexes) {
self.discoverForeignKeys(self.table(model), {}, function(err, foreignKeys) { self.discoverForeignKeys(self.table(model), {}, function(err, foreignKeys) {
if (err) console.log('Failed to discover "' + table + '" foreign keys', err); if (err) console.log('Failed to discover "' + self.table(model) +
'" foreign keys', err);
self.alterTable(model, fields, indexes, foreignKeys, function(err, needAlter) { self.alterTable(model, fields, indexes, foreignKeys, function(err, needAlter) {
if (err) { if (err) {
@ -289,14 +291,14 @@ function mixinMigration(MySQL, mysql) {
// second: check multiple indexes // second: check multiple indexes
var orderMatched = true; var orderMatched = true;
if (indexNames.indexOf(indexName) !== -1) { if (indexNames.indexOf(indexName) !== -1) {
//check if indexes are configured as "columns" // check if indexes are configured as "columns"
if (m.settings.indexes[indexName].columns) { if (m.settings.indexes[indexName].columns) {
m.settings.indexes[indexName].columns.split(/,\s*/).forEach( m.settings.indexes[indexName].columns.split(/,\s*/).forEach(
function(columnName, i) { function(columnName, i) {
if (ai[indexName].columns[i] !== columnName) orderMatched = false; if (ai[indexName].columns[i] !== columnName) orderMatched = false;
}); });
} else if (m.settings.indexes[indexName].keys) { } else if (m.settings.indexes[indexName].keys) {
//if indexes are configured as "keys" // if indexes are configured as "keys"
var index = 0; var index = 0;
for (var key in m.settings.indexes[indexName].keys) { for (var key in m.settings.indexes[indexName].keys) {
var sortOrder = m.settings.indexes[indexName].keys[key]; var sortOrder = m.settings.indexes[indexName].keys[key];
@ -306,7 +308,7 @@ function mixinMigration(MySQL, mysql) {
} }
index++; index++;
} }
//if number of columns differ between new and old index // if number of columns differ between new and old index
if (index !== ai[indexName].columns.length) { if (index !== ai[indexName].columns.length) {
orderMatched = false; orderMatched = false;
} }
@ -361,13 +363,13 @@ function mixinMigration(MySQL, mysql) {
if (i.kind) { if (i.kind) {
kind = i.kind; kind = i.kind;
} else if (i.options && i.options.unique && i.options.unique == true) { } else if (i.options && i.options.unique && i.options.unique == true) {
//if index unique indicator is configured // if index unique indicator is configured
kind = 'UNIQUE'; kind = 'UNIQUE';
} }
var indexedColumns = []; var indexedColumns = [];
var columns = ''; var columns = '';
//if indexes are configured as "keys" // if indexes are configured as "keys"
if (i.keys) { if (i.keys) {
for (var key in i.keys) { for (var key in i.keys) {
if (i.keys[key] !== -1) { if (i.keys[key] !== -1) {
@ -380,7 +382,7 @@ function mixinMigration(MySQL, mysql) {
if (indexedColumns.length > 0) { if (indexedColumns.length > 0) {
columns = indexedColumns.join(','); columns = indexedColumns.join(',');
} else if (i.columns) { } else if (i.columns) {
//if indexes are configured as "columns" // if indexes are configured as "columns"
columns = i.columns; columns = i.columns;
} }
if (kind && type) { if (kind && type) {
@ -404,8 +406,8 @@ function mixinMigration(MySQL, mysql) {
if (actualFks) { if (actualFks) {
var keys = Object.keys(actualFks); var keys = Object.keys(actualFks);
for (var i = 0; i < keys.length; i++) { for (var i = 0; i < keys.length; i++) {
//all existing fks are already checked in MySQL.prototype.dropForeignKeys // all existing fks are already checked in MySQL.prototype.dropForeignKeys
//so we need check only names - skip if found // so we need check only names - skip if found
if (existingFks.filter(function(fk) { if (existingFks.filter(function(fk) {
return fk.fkName === keys[i]; return fk.fkName === keys[i];
}).length > 0) continue; }).length > 0) continue;
@ -450,7 +452,7 @@ function mixinMigration(MySQL, mysql) {
var sql = []; var sql = [];
var correctFks = m.settings.foreignKeys || {}; var correctFks = m.settings.foreignKeys || {};
//drop foreign keys for removed fields // drop foreign keys for removed fields
if (fks && fks.length) { if (fks && fks.length) {
var removedFks = []; var removedFks = [];
fks.forEach(function(fk) { fks.forEach(function(fk) {
@ -471,11 +473,11 @@ function mixinMigration(MySQL, mysql) {
if (needsToDrop) { if (needsToDrop) {
sql.push('DROP FOREIGN KEY ' + fk.fkName); sql.push('DROP FOREIGN KEY ' + fk.fkName);
removedFks.push(fk); //keep track that we removed these removedFks.push(fk); // keep track that we removed these
} }
}); });
//update out list of existing keys by removing dropped keys // update out list of existing keys by removing dropped keys
removedFks.forEach(function(k) { removedFks.forEach(function(k) {
var index = actualFks.indexOf(k); var index = actualFks.indexOf(k);
if (index !== -1) actualFks.splice(index, 1); if (index !== -1) actualFks.splice(index, 1);
@ -491,7 +493,7 @@ function mixinMigration(MySQL, mysql) {
}; };
MySQL.prototype.alterTable = function(model, actualFields, actualIndexes, actualFks, done, checkOnly) { MySQL.prototype.alterTable = function(model, actualFields, actualIndexes, actualFks, done, checkOnly) {
//if this is using an old signature, then grab the correct callback and check boolean // if this is using an old signature, then grab the correct callback and check boolean
if ('function' == typeof actualFks && typeof done !== 'function') { if ('function' == typeof actualFks && typeof done !== 'function') {
checkOnly = done || false; checkOnly = done || false;
done = actualFks; done = actualFks;
@ -520,25 +522,25 @@ function mixinMigration(MySQL, mysql) {
], function(err, result) { ], function(err, result) {
if (err) done(err); if (err) done(err);
//determine if there are column, index, or foreign keys changes (all require update) // determine if there are column, index, or foreign keys changes (all require update)
if (statements.length) { if (statements.length) {
//get the required alter statements // get the required alter statements
var alterStmt = self.getAlterStatement(model, statements); var alterStmt = self.getAlterStatement(model, statements);
var stmtList = [alterStmt]; var stmtList = [alterStmt];
//set up an object to pass back all changes, changes that have been run, // set up an object to pass back all changes, changes that have been run,
//and foreign key statements that haven't been run // and foreign key statements that haven't been run
var retValues = { var retValues = {
statements: stmtList, statements: stmtList,
query: stmtList.join(';'), query: stmtList.join(';'),
}; };
//if we're running in read only mode OR if the only changes are foreign keys additions, // if we're running in read only mode OR if the only changes are foreign keys additions,
//then just return the object directly // then just return the object directly
if (checkOnly) { if (checkOnly) {
done(null, true, retValues); done(null, true, retValues);
} else { } else {
//if there are changes in the alter statement, then execute them and return the object // if there are changes in the alter statement, then execute them and return the object
self.execute(alterStmt, function(err) { self.execute(alterStmt, function(err) {
done(err, true, retValues); done(err, true, retValues);
}); });
@ -554,10 +556,10 @@ function mixinMigration(MySQL, mysql) {
var fk = definition.settings.foreignKeys[keyName]; var fk = definition.settings.foreignKeys[keyName];
if (fk) { if (fk) {
//get the definition of the referenced object // get the definition of the referenced object
var fkEntityName = (typeof fk.entity === 'object') ? fk.entity.name : fk.entity; var fkEntityName = (typeof fk.entity === 'object') ? fk.entity.name : fk.entity;
//verify that the other model in the same DB // verify that the other model in the same DB
if (this._models[fkEntityName]) { if (this._models[fkEntityName]) {
return ' CONSTRAINT ' + this.client.escapeId(fk.name) + return ' CONSTRAINT ' + this.client.escapeId(fk.name) +
' FOREIGN KEY (`' + expectedColNameForModel(fk.foreignKey, definition) + '`)' + ' FOREIGN KEY (`' + expectedColNameForModel(fk.foreignKey, definition) + '`)' +
@ -648,24 +650,24 @@ function mixinMigration(MySQL, mysql) {
type = 'USING ' + i.type; type = 'USING ' + i.type;
} }
if (i.kind) { if (i.kind) {
//if index uniqueness is configured as "kind" // if index uniqueness is configured as "kind"
kind = i.kind; kind = i.kind;
} else if (i.options && i.options.unique && i.options.unique == true) { } else if (i.options && i.options.unique && i.options.unique == true) {
//if index unique indicator is configured // if index unique indicator is configured
kind = 'UNIQUE'; kind = 'UNIQUE';
} }
var indexedColumns = []; var indexedColumns = [];
var indexName = this.escapeName(index); var indexName = this.escapeName(index);
var columns = ''; var columns = '';
//if indexes are configured as "keys" // if indexes are configured as "keys"
if (i.keys) { if (i.keys) {
//for each field in "keys" object // for each field in "keys" object
for (var key in i.keys) { for (var key in i.keys) {
if (i.keys[key] !== -1) { if (i.keys[key] !== -1) {
indexedColumns.push(this.escapeName(key)); indexedColumns.push(this.escapeName(key));
} else { } else {
//mysql does not support index sorting Currently // mysql does not support index sorting Currently
//but mysql has added DESC keyword for future support // but mysql has added DESC keyword for future support
indexedColumns.push(this.escapeName(key) + ' DESC '); indexedColumns.push(this.escapeName(key) + ' DESC ');
} }
} }

View File

@ -281,10 +281,10 @@ MySQL.prototype._modifyOrCreate = function(model, data, options, fields, cb) {
} }
var meta = {}; var meta = {};
if (info) { if (info) {
// When using the INSERT ... ON DUPLICATE KEY UPDATE statement, // When using the INSERT ... ON DUPLICATE KEY UPDATE statement,
// the returned value is as follows: // the returned value is as follows:
// 1 for each successful INSERT. // 1 for each successful INSERT.
// 2 for each successful UPDATE. // 2 for each successful UPDATE.
meta.isNewInstance = (info.affectedRows === 1); meta.isNewInstance = (info.affectedRows === 1);
} }
cb(err, data, meta); cb(err, data, meta);
@ -345,8 +345,8 @@ MySQL.prototype.toColumnValue = function(prop, val) {
} }
return castNull; return castNull;
} catch (err) { } catch (err) {
//if we can't coerce null to a certain type, // if we can't coerce null to a certain type,
//we just return it // we just return it
return 'null'; return 'null';
} }
} }
@ -541,7 +541,7 @@ MySQL.prototype.ping = function(cb) {
}; };
MySQL.prototype.buildExpression = function(columnName, operator, operatorValue, MySQL.prototype.buildExpression = function(columnName, operator, operatorValue,
propertyDefinition) { propertyDefinition) {
if (operator === 'regexp') { if (operator === 'regexp') {
var clause = columnName + ' REGEXP ?'; var clause = columnName + ' REGEXP ?';
// By default, MySQL regexp is not case sensitive. (https://dev.mysql.com/doc/refman/5.7/en/regexp.html) // By default, MySQL regexp is not case sensitive. (https://dev.mysql.com/doc/refman/5.7/en/regexp.html)
@ -560,12 +560,12 @@ MySQL.prototype.buildExpression = function(columnName, operator, operatorValue,
g.warn('{{MySQL}} {{regex}} syntax does not respect the {{`m`}} flag'); g.warn('{{MySQL}} {{regex}} syntax does not respect the {{`m`}} flag');
return new ParameterizedSQL(clause, return new ParameterizedSQL(clause,
[operatorValue.source]); [operatorValue.source]);
} }
// invoke the base implementation of `buildExpression` // invoke the base implementation of `buildExpression`
return this.invokeSuper('buildExpression', columnName, operator, return this.invokeSuper('buildExpression', columnName, operator,
operatorValue, propertyDefinition); operatorValue, propertyDefinition);
}; };
require('./migration')(MySQL, mysql); require('./migration')(MySQL, mysql);

View File

@ -22,8 +22,8 @@
}, },
"devDependencies": { "devDependencies": {
"bluebird": "~2.9.10", "bluebird": "~2.9.10",
"eslint": "^2.13.1", "eslint": "^4.3.0",
"eslint-config-loopback": "^4.0.0", "eslint-config-loopback": "^8.0.0",
"loopback-datasource-juggler": "^3.0.0", "loopback-datasource-juggler": "^3.0.0",
"mocha": "^2.1.0", "mocha": "^2.1.0",
"rc": "^1.0.0", "rc": "^1.0.0",

View File

@ -19,7 +19,8 @@ describe('connections', function() {
config = global.getConfig(); config = global.getConfig();
odb = getDataSource({collation: 'utf8_general_ci', createDatabase: true}); odb = global.getDataSource({collation: 'utf8_general_ci',
createDatabase: true});
db = odb; db = odb;
}); });
@ -53,7 +54,7 @@ describe('connections', function() {
it('should disconnect first db', function(done) { it('should disconnect first db', function(done) {
db.disconnect(function() { db.disconnect(function() {
odb = getDataSource(); odb = global.getDataSource();
done(); done();
}); });
}); });
@ -112,7 +113,8 @@ function charsetTest(test_set, test_collo, test_set_str, test_set_collo, done) {
query('DROP DATABASE IF EXISTS ' + odb.settings.database, function(err) { query('DROP DATABASE IF EXISTS ' + odb.settings.database, function(err) {
assert.ok(!err); assert.ok(!err);
odb.disconnect(function() { odb.disconnect(function() {
db = getDataSource({collation: test_set_collo, createDatabase: true}); db = global.getDataSource({collation: test_set_collo,
createDatabase: true});
DummyModel = db.define('DummyModel', {string: String}); DummyModel = db.define('DummyModel', {string: String});
db.automigrate(function() { db.automigrate(function() {
var q = 'SELECT DEFAULT_COLLATION_NAME' + var q = 'SELECT DEFAULT_COLLATION_NAME' +

View File

@ -33,7 +33,7 @@ describe('MySQL specific datatypes', function() {
]; ];
before(function(done) { before(function(done) {
require('./init.js'); require('./init.js');
db = getSchema(); db = global.getSchema();
Account = db.define('Account', { Account = db.define('Account', {
type: {type: String}, type: {type: String},
amount: { amount: {
@ -233,7 +233,7 @@ describe('MySQL specific datatypes', function() {
function setup(done) { function setup(done) {
require('./init.js'); require('./init.js');
db = getSchema(); db = global.getSchema();
ANIMAL_ENUM = db.EnumFactory('dog', 'cat', 'mouse'); ANIMAL_ENUM = db.EnumFactory('dog', 'cat', 'mouse');

View File

@ -28,7 +28,7 @@ describe('MySQL datetime handling', function() {
}); });
} }
before(function(done) { before(function(done) {
db = getSchema({ db = global.getSchema({
dateStrings: true, dateStrings: true,
}); });
Person = db.define('Person', personDefinition, {forceId: true, strict: true}); Person = db.define('Person', personDefinition, {forceId: true, strict: true});

View File

@ -30,7 +30,7 @@ global.getConfig = function(options) {
}; };
global.getDataSource = global.getSchema = function(options) { global.getDataSource = global.getSchema = function(options) {
var db = new DataSource(require('../'), getConfig(options)); var db = new DataSource(require('../'), global.getConfig(options));
return db; return db;
}; };

View File

@ -357,7 +357,7 @@ describe('migrations', function() {
next(); next();
}); });
}, function(next) { }, function(next) {
//Minimum value for unsigned mediumInt is 0 // Minimum value for unsigned mediumInt is 0
NumberData.create({number: 1.1234567, mediumInt: -8388608}, function(err, obj) { NumberData.create({number: 1.1234567, mediumInt: -8388608}, function(err, obj) {
assert(err); assert(err);
assert.equal(err.code, 'ER_WARN_DATA_OUT_OF_RANGE'); assert.equal(err.code, 'ER_WARN_DATA_OUT_OF_RANGE');
@ -403,16 +403,16 @@ describe('migrations', function() {
query('INSERT INTO `DateData` ' + query('INSERT INTO `DateData` ' +
'(`dateTime`, `timestamp`) ' + '(`dateTime`, `timestamp`) ' +
'VALUES("0000-00-00 00:00:00", "0000-00-00 00:00:00") ', 'VALUES("0000-00-00 00:00:00", "0000-00-00 00:00:00") ',
function(err, ret) { function(err, ret) {
should.not.exists(err); should.not.exists(err);
DateData.findById(ret.insertId, function(err, dateData) { DateData.findById(ret.insertId, function(err, dateData) {
should(dateData.dateTime) should(dateData.dateTime)
.be.null(); .be.null();
should(dateData.timestamp) should(dateData.timestamp)
.be.null(); .be.null();
done(); done();
});
}); });
});
}); });
it('rejects out of range datetime', function(done) { it('rejects out of range datetime', function(done) {
@ -468,7 +468,7 @@ describe('migrations', function() {
function setup(done) { function setup(done) {
require('./init.js'); require('./init.js');
db = getSchema(); db = global.getSchema();
UserData = db.define('UserData', { UserData = db.define('UserData', {
email: {type: String, null: false, index: true}, email: {type: String, null: false, index: true},

View File

@ -9,7 +9,7 @@ require('./init');
var ds; var ds;
before(function() { before(function() {
ds = getDataSource(); ds = global.getDataSource();
}); });
describe('MySQL connector', function() { describe('MySQL connector', function() {
@ -18,7 +18,7 @@ describe('MySQL connector', function() {
}); });
describe('escape index names upon automigrate', function() { describe('escape index names upon automigrate', function() {
before (function(done) { before(function(done) {
var messageSchema = { var messageSchema = {
'name': 'Message', 'name': 'Message',
'options': { 'options': {
@ -260,7 +260,7 @@ describe('MySQL connector', function() {
assert.equal(updatedindexes[1].Key_name, 'customer_code'); assert.equal(updatedindexes[1].Key_name, 'customer_code');
assert.equal(updatedindexes[2].Key_name, 'updated_name_index'); assert.equal(updatedindexes[2].Key_name, 'updated_name_index');
assert.equal(updatedindexes[3].Key_name, 'updated_name_index'); assert.equal(updatedindexes[3].Key_name, 'updated_name_index');
//Mysql supports only index sorting in ascending; DESC is ignored // Mysql supports only index sorting in ascending; DESC is ignored
assert.equal(updatedindexes[1].Collation, 'A'); assert.equal(updatedindexes[1].Collation, 'A');
assert.equal(updatedindexes[2].Collation, 'A'); assert.equal(updatedindexes[2].Collation, 'A');
assert.equal(updatedindexes[3].Collation, 'A'); assert.equal(updatedindexes[3].Collation, 'A');
@ -453,17 +453,17 @@ describe('MySQL connector', function() {
ds.createModel(customer3_schema.name, customer3_schema.properties, customer3_schema.options); ds.createModel(customer3_schema.name, customer3_schema.properties, customer3_schema.options);
ds.createModel(schema_v1.name, schema_v1.properties, schema_v1.options); ds.createModel(schema_v1.name, schema_v1.properties, schema_v1.options);
//do initial update/creation of table // do initial update/creation of table
ds.autoupdate(function(err) { ds.autoupdate(function(err) {
assert(!err, err); assert(!err, err);
ds.discoverModelProperties('order_test', function(err, props) { ds.discoverModelProperties('order_test', function(err, props) {
//validate that we have the correct number of properties // validate that we have the correct number of properties
assert.equal(props.length, 3); assert.equal(props.length, 3);
//get the foreign keys for this table // get the foreign keys for this table
ds.connector.execute(foreignKeySelect, function(err, foreignKeys) { ds.connector.execute(foreignKeySelect, function(err, foreignKeys) {
if (err) return done(err); if (err) return done(err);
//validate that the foreign key exists and points to the right column // validate that the foreign key exists and points to the right column
assert(foreignKeys); assert(foreignKeys);
assert(foreignKeys.length.should.be.equal(1)); assert(foreignKeys.length.should.be.equal(1));
assert.equal(foreignKeys[0].REFERENCED_TABLE_NAME, 'customer_test3'); assert.equal(foreignKeys[0].REFERENCED_TABLE_NAME, 'customer_test3');
@ -471,26 +471,26 @@ describe('MySQL connector', function() {
assert.equal(foreignKeys[0].CONSTRAINT_NAME, 'fk_ordertest_customerId'); assert.equal(foreignKeys[0].CONSTRAINT_NAME, 'fk_ordertest_customerId');
assert.equal(foreignKeys[0].REFERENCED_COLUMN_NAME, 'id'); assert.equal(foreignKeys[0].REFERENCED_COLUMN_NAME, 'id');
//update our model (move foreign key) and run autoupdate to migrate // update our model (move foreign key) and run autoupdate to migrate
ds.createModel(schema_v2.name, schema_v2.properties, schema_v2.options); ds.createModel(schema_v2.name, schema_v2.properties, schema_v2.options);
ds.autoupdate(function(err, result) { ds.autoupdate(function(err, result) {
if (err) return done(err); if (err) return done(err);
//should be actual after autoupdate // should be actual after autoupdate
ds.isActual(function(err, isEqual) { ds.isActual(function(err, isEqual) {
if (err) return done(err); if (err) return done(err);
assert(!isEqual); assert(!isEqual);
//get and validate the properties on this model // get and validate the properties on this model
ds.discoverModelProperties('order_test', function(err, props) { ds.discoverModelProperties('order_test', function(err, props) {
if (err) return done(err); if (err) return done(err);
assert.equal(props.length, 3); assert.equal(props.length, 3);
//get the foreign keys that exist after the migration // get the foreign keys that exist after the migration
ds.connector.execute(foreignKeySelect, function(err, updatedForeignKeys) { ds.connector.execute(foreignKeySelect, function(err, updatedForeignKeys) {
if (err) return done(err); if (err) return done(err);
//validate that the foreign keys was moved to the new column // validate that the foreign keys was moved to the new column
assert(updatedForeignKeys); assert(updatedForeignKeys);
assert(updatedForeignKeys.length.should.be.equal(1)); assert(updatedForeignKeys.length.should.be.equal(1));
assert.equal(updatedForeignKeys[0].REFERENCED_TABLE_NAME, 'customer_test2'); assert.equal(updatedForeignKeys[0].REFERENCED_TABLE_NAME, 'customer_test2');
@ -498,17 +498,17 @@ describe('MySQL connector', function() {
assert.equal(updatedForeignKeys[0].CONSTRAINT_NAME, 'fk_ordertest_customerId'); assert.equal(updatedForeignKeys[0].CONSTRAINT_NAME, 'fk_ordertest_customerId');
assert.equal(updatedForeignKeys[0].REFERENCED_COLUMN_NAME, 'id'); assert.equal(updatedForeignKeys[0].REFERENCED_COLUMN_NAME, 'id');
//update model (to drop foreign key) and autoupdate // update model (to drop foreign key) and autoupdate
ds.createModel(schema_v3.name, schema_v3.properties, schema_v3.options); ds.createModel(schema_v3.name, schema_v3.properties, schema_v3.options);
ds.autoupdate(function(err, result) { ds.autoupdate(function(err, result) {
if (err) return done(err); if (err) return done(err);
//validate the properties // validate the properties
ds.discoverModelProperties('order_test', function(err, props) { ds.discoverModelProperties('order_test', function(err, props) {
if (err) return done(err); if (err) return done(err);
assert.equal(props.length, 3); assert.equal(props.length, 3);
//get the foreign keys and validate the foreign key has been dropped // get the foreign keys and validate the foreign key has been dropped
ds.connector.execute(foreignKeySelect, function(err, thirdForeignKeys) { ds.connector.execute(foreignKeySelect, function(err, thirdForeignKeys) {
if (err) return done(err); if (err) return done(err);
assert(thirdForeignKeys); assert(thirdForeignKeys);

View File

@ -5,7 +5,7 @@
'use strict'; 'use strict';
process.env.NODE_ENV = 'test'; process.env.NODE_ENV = 'test';
require('should'); var should = require('should');
var assert = require('assert'); var assert = require('assert');
var DataSource = require('loopback-datasource-juggler').DataSource; var DataSource = require('loopback-datasource-juggler').DataSource;
@ -13,7 +13,7 @@ var db, config;
before(function(done) { before(function(done) {
require('./init'); require('./init');
config = getConfig(); config = global.getConfig();
config.database = 'STRONGLOOP'; config.database = 'STRONGLOOP';
db = new DataSource(require('../'), config); db = new DataSource(require('../'), config);
db.once('connected', done); db.once('connected', done);
@ -43,7 +43,7 @@ describe('discoverModels', function() {
done(err); done(err);
} else { } else {
var views = false; var views = false;
should.assert(models.length > 0, 'some models returned'); assert(models.length > 0, 'some models returned');
models.forEach(function(m) { models.forEach(function(m) {
if (m.type === 'view') { if (m.type === 'view') {
views = true; views = true;
@ -67,7 +67,7 @@ describe('discoverModels', function() {
done(err); done(err);
} else { } else {
var views = false; var views = false;
should.assert(models.length > 0, 'some models returned'); assert(models.length > 0, 'some models returned');
models.forEach(function(m) { models.forEach(function(m) {
assert.equal(m.schema.toLowerCase(), config.database.toLowerCase()); assert.equal(m.schema.toLowerCase(), config.database.toLowerCase());
}); });
@ -88,9 +88,9 @@ describe('discoverModels', function() {
console.error(err); console.error(err);
done(err); done(err);
} else { } else {
should.assert(models.length > 0, 'some models returned'); assert(models.length > 0, 'some models returned');
models.forEach(function(m) { models.forEach(function(m) {
should.not.equal(m.type, 'view', 'model type should not be a view'); should.notEqual(m.type, 'view', 'model type should not be a view');
}); });
done(null, models); done(null, models);
} }
@ -259,10 +259,10 @@ describe('Discover and build models', function() {
var models; var models;
before(function(done) { before(function(done) {
db.discoverAndBuildModels('INVENTORY', {owner: 'STRONGLOOP', visited: {}, associations: true}, db.discoverAndBuildModels('INVENTORY', {owner: 'STRONGLOOP', visited: {}, associations: true},
function(err, models_) { function(err, models_) {
models = models_; models = models_;
done(err); done(err);
}); });
}); });
it('should discover and build models', function() { it('should discover and build models', function() {
assert(models.Inventory, 'Inventory model should be discovered and built'); assert(models.Inventory, 'Inventory model should be discovered and built');

View File

@ -5,6 +5,7 @@
'use strict'; 'use strict';
var should = require('./init.js'); var should = require('./init.js');
var sinon = require('sinon');
var Post, PostWithStringId, PostWithUniqueTitle, PostWithNumId, db; var Post, PostWithStringId, PostWithUniqueTitle, PostWithNumId, db;
@ -23,7 +24,7 @@ ObjectID.prototype.toJSON = function() {
describe('mysql', function() { describe('mysql', function() {
before(function(done) { before(function(done) {
db = getDataSource(); db = global.getDataSource();
Post = db.define('PostWithDefaultId', { Post = db.define('PostWithDefaultId', {
title: {type: String, length: 255, index: true}, title: {type: String, length: 255, index: true},
@ -257,25 +258,25 @@ describe('mysql', function() {
}); });
}); });
it('save should update the instance without removing existing properties', function(done) { it('save should update the instance without removing existing properties',
Post.create({title: 'a', content: 'AAA'}, function(err, post) { function(done) {
delete post.title; Post.create({title: 'a', content: 'AAA'}, function(err, post) {
post.save(function(err, p) { delete post.title;
should.not.exist(err); post.save(function(err, p) {
p.id.should.be.equal(post.id); should.not.exist(err);
p.content.should.be.equal(post.content);
Post.findById(post.id, function(err, p) {
p.id.should.be.equal(post.id); p.id.should.be.equal(post.id);
p.content.should.be.equal(post.content); p.content.should.be.equal(post.content);
p.title.should.be.equal('a');
done(); Post.findById(post.id, function(err, p) {
p.id.should.be.equal(post.id);
p.content.should.be.equal(post.content);
p.title.should.be.equal('a');
done();
});
}); });
}); });
}); });
});
it('save should create a new instance if it does not exist', function(done) { it('save should create a new instance if it does not exist', function(done) {
var post = new Post({id: 123, title: 'a', content: 'AAA'}); var post = new Post({id: 123, title: 'a', content: 'AAA'});
@ -504,14 +505,14 @@ describe('mysql', function() {
should.not.exist(err); should.not.exist(err);
post.id.should.equal(defaultPost.id); post.id.should.equal(defaultPost.id);
PostWithNumId.find({where: {and: [ PostWithNumId.find({where: {and: [
{id: {nin: [null]}}, {id: {nin: [null]}},
{title: {nin: [null]}}, {title: {nin: [null]}},
{content: {nin: [null]}}, {content: {nin: [null]}},
{buffProp: {nin: [null]}}, {buffProp: {nin: [null]}},
{objProp: {nin: [null]}}, {objProp: {nin: [null]}},
{arrProp: {nin: [null]}}, {arrProp: {nin: [null]}},
{dateProp: {nin: [null]}}, {dateProp: {nin: [null]}},
{pointProp: {nin: [null]}}, {pointProp: {nin: [null]}},
]}}, function(err, posts) { ]}}, function(err, posts) {
should.not.exist(err); should.not.exist(err);
posts.length.should.equal(1); posts.length.should.equal(1);
@ -707,28 +708,28 @@ describe('mysql', function() {
}); });
it('should print a warning when the ignore flag is set', it('should print a warning when the ignore flag is set',
function(done) { function(done) {
Post.find({where: {content: {regexp: '^a/i'}}}, function(err, posts) { Post.find({where: {content: {regexp: '^a/i'}}}, function(err, posts) {
console.warn.calledOnce.should.be.ok; console.warn.calledOnce.should.be.ok;
done(); done();
});
}); });
});
it('should print a warning when the global flag is set', it('should print a warning when the global flag is set',
function(done) { function(done) {
Post.find({where: {content: {regexp: '^a/g'}}}, function(err, posts) { Post.find({where: {content: {regexp: '^a/g'}}}, function(err, posts) {
console.warn.calledOnce.should.be.ok; console.warn.calledOnce.should.be.ok;
done(); done();
});
}); });
});
it('should print a warning when the multiline flag is set', it('should print a warning when the multiline flag is set',
function(done) { function(done) {
Post.find({where: {content: {regexp: '^a/m'}}}, function(err, posts) { Post.find({where: {content: {regexp: '^a/m'}}}, function(err, posts) {
console.warn.calledOnce.should.be.ok; console.warn.calledOnce.should.be.ok;
done(); done();
});
}); });
});
}); });
it('filter with case sensitive regex string', function(done) { it('filter with case sensitive regex string', function(done) {
@ -771,28 +772,28 @@ describe('mysql', function() {
}); });
it('should print a warning when the ignore flag is set', it('should print a warning when the ignore flag is set',
function(done) { function(done) {
Post.find({where: {content: {regexp: /^a/i}}}, function(err, posts) { Post.find({where: {content: {regexp: /^a/i}}}, function(err, posts) {
console.warn.calledOnce.should.be.ok; console.warn.calledOnce.should.be.ok;
done(); done();
});
}); });
});
it('should print a warning when the global flag is set', it('should print a warning when the global flag is set',
function(done) { function(done) {
Post.find({where: {content: {regexp: /^a/g}}}, function(err, posts) { Post.find({where: {content: {regexp: /^a/g}}}, function(err, posts) {
console.warn.calledOnce.should.be.ok; console.warn.calledOnce.should.be.ok;
done(); done();
});
}); });
});
it('should print a warning when the multiline flag is set', it('should print a warning when the multiline flag is set',
function(done) { function(done) {
Post.find({where: {content: {regexp: /^a/m}}}, function(err, posts) { Post.find({where: {content: {regexp: /^a/m}}}, function(err, posts) {
console.warn.calledOnce.should.be.ok; console.warn.calledOnce.should.be.ok;
done(); done();
});
}); });
});
}); });
it('filter with case sensitive regex literal', function(done) { it('filter with case sensitive regex literal', function(done) {
@ -817,51 +818,51 @@ describe('mysql', function() {
context('using no flags', function() { context('using no flags', function() {
it('should work', function(done) { it('should work', function(done) {
Post.find({where: {content: {regexp: new RegExp(/^A/)}}}, Post.find({where: {content: {regexp: new RegExp(/^A/)}}},
function(err, posts) { function(err, posts) {
should.not.exist(err); should.not.exist(err);
posts.length.should.equal(1); posts.length.should.equal(1);
posts[0].content.should.equal('AAA'); posts[0].content.should.equal('AAA');
done(); done();
}); });
}); });
}); });
context('using flags', function() { context('using flags', function() {
it('should work', function(done) { it('should work', function(done) {
Post.find({where: {content: {regexp: new RegExp(/^a/i)}}}, Post.find({where: {content: {regexp: new RegExp(/^a/i)}}},
function(err, posts) { function(err, posts) {
should.not.exist(err); should.not.exist(err);
posts.length.should.equal(1); posts.length.should.equal(1);
posts[0].content.should.equal('AAA'); posts[0].content.should.equal('AAA');
done(); done();
}); });
}); });
it('should print a warning when the ignore flag is set', it('should print a warning when the ignore flag is set',
function(done) { function(done) {
Post.find({where: {content: {regexp: new RegExp(/^a/i)}}}, Post.find({where: {content: {regexp: new RegExp(/^a/i)}}},
function(err, posts) { function(err, posts) {
console.warn.calledOnce.should.be.ok; console.warn.calledOnce.should.be.ok;
done(); done();
}); });
}); });
it('should print a warning when the global flag is set', it('should print a warning when the global flag is set',
function(done) { function(done) {
Post.find({where: {content: {regexp: new RegExp(/^a/g)}}}, Post.find({where: {content: {regexp: new RegExp(/^a/g)}}},
function(err, posts) { function(err, posts) {
console.warn.calledOnce.should.be.ok; console.warn.calledOnce.should.be.ok;
done(); done();
}); });
}); });
it('should print a warning when the multiline flag is set', it('should print a warning when the multiline flag is set',
function(done) { function(done) {
Post.find({where: {content: {regexp: new RegExp(/^a/m)}}}, Post.find({where: {content: {regexp: new RegExp(/^a/m)}}},
function(err, posts) { function(err, posts) {
console.warn.calledOnce.should.be.ok; console.warn.calledOnce.should.be.ok;
done(); done();
}); });
}); });
it('filter with case sensitive regex object', function(done) { it('filter with case sensitive regex object', function(done) {
Post.find({where: {content: {regexp: new RegExp(/^a/)}}}, function(err, posts) { Post.find({where: {content: {regexp: new RegExp(/^a/)}}}, function(err, posts) {

View File

@ -15,7 +15,8 @@ var db, Post, Review;
describe('transactions with promise', function() { describe('transactions with promise', function() {
before(function(done) { before(function(done) {
db = getDataSource({collation: 'utf8_general_ci', createDatabase: true}); db = global.getDataSource({collation: 'utf8_general_ci',
createDatabase: true});
db.once('connected', function() { db.once('connected', function() {
Post = db.define('PostTX', { Post = db.define('PostTX', {
title: {type: String, length: 255, index: true}, title: {type: String, length: 255, index: true},
@ -82,8 +83,8 @@ describe('transactions with promise', function() {
}; };
} }
// Return an async function to find matching posts and assert number of // Return an async function to find matching posts and assert number of
// records to equal to the count // records to equal to the count
function expectToFindPosts(where, count, inTx) { function expectToFindPosts(where, count, inTx) {
return function(done) { return function(done) {
var options = {}; var options = {};

View File

@ -12,7 +12,8 @@ var db, Post, Review;
describe('transactions', function() { describe('transactions', function() {
before(function(done) { before(function(done) {
db = getDataSource({collation: 'utf8_general_ci', createDatabase: true}); db = global.getDataSource({collation: 'utf8_general_ci',
createDatabase: true});
db.once('connected', function() { db.once('connected', function() {
Post = db.define('PostTX', { Post = db.define('PostTX', {
title: {type: String, length: 255, index: true}, title: {type: String, length: 255, index: true},
@ -37,42 +38,42 @@ describe('transactions', function() {
isolationLevel: Transaction.READ_COMMITTED, isolationLevel: Transaction.READ_COMMITTED,
timeout: timeout, timeout: timeout,
}, },
function(err, tx) { function(err, tx) {
if (err) return done(err); if (err) return done(err);
(typeof tx.id).should.be.eql('string'); (typeof tx.id).should.be.eql('string');
hooks = []; hooks = [];
tx.observe('before commit', function(context, next) { tx.observe('before commit', function(context, next) {
hooks.push('before commit'); hooks.push('before commit');
next(); next();
});
tx.observe('after commit', function(context, next) {
hooks.push('after commit');
next();
});
tx.observe('before rollback', function(context, next) {
hooks.push('before rollback');
next();
});
tx.observe('after rollback', function(context, next) {
hooks.push('after rollback');
next();
});
currentTx = tx;
Post.create(post, {transaction: tx},
function(err, p) {
if (err) {
done(err);
} else {
p.reviews.create({
author: 'John',
content: 'Review for ' + p.title,
}, {transaction: tx},
function(err, c) {
done(err);
});
}
});
}); });
tx.observe('after commit', function(context, next) {
hooks.push('after commit');
next();
});
tx.observe('before rollback', function(context, next) {
hooks.push('before rollback');
next();
});
tx.observe('after rollback', function(context, next) {
hooks.push('after rollback');
next();
});
currentTx = tx;
Post.create(post, {transaction: tx},
function(err, p) {
if (err) {
done(err);
} else {
p.reviews.create({
author: 'John',
content: 'Review for ' + p.title,
}, {transaction: tx},
function(err, c) {
done(err);
});
}
});
});
}; };
} }