不要怂,就是干,撸起袖子干!

Commit 797720d9 by Felix Becker Committed by Jan Aagaard Meier

ES6 refactor: QueryInterface (#6041)

* Make QueryInterface an ES6 class

* ES6 refactor of QueryInterface

let, const, arrow functions, for..of, export default, property shorthands
1 parent 194ff2c7
Showing with 269 additions and 300 deletions
'use strict'; 'use strict';
var Utils = require('./utils') const Utils = require('./utils');
, _ = require('lodash') const _ = require('lodash');
, DataTypes = require('./data-types') const DataTypes = require('./data-types');
, SQLiteQueryInterface = require('./dialects/sqlite/query-interface') const SQLiteQueryInterface = require('./dialects/sqlite/query-interface');
, MSSSQLQueryInterface = require('./dialects/mssql/query-interface') const MSSSQLQueryInterface = require('./dialects/mssql/query-interface');
, MySQLQueryInterface = require('./dialects/mysql/query-interface') const MySQLQueryInterface = require('./dialects/mysql/query-interface');
, Transaction = require('./transaction') const Transaction = require('./transaction');
, Promise = require('./promise') const Promise = require('./promise');
, QueryTypes = require('./query-types'); const QueryTypes = require('./query-types');
/* /**
* The interface that Sequelize uses to talk to all databases * The interface that Sequelize uses to talk to all databases
* @class QueryInterface * @class QueryInterface
**/ */
var QueryInterface = function(sequelize) { class QueryInterface {
constructor(sequelize) {
this.sequelize = sequelize; this.sequelize = sequelize;
this.QueryGenerator = this.sequelize.dialect.QueryGenerator; this.QueryGenerator = this.sequelize.dialect.QueryGenerator;
}; }
QueryInterface.prototype.createSchema = function(schema, options) { createSchema(schema, options) {
options = options || {}; options = options || {};
var sql = this.QueryGenerator.createSchema(schema); const sql = this.QueryGenerator.createSchema(schema);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.dropSchema = function(schema, options) { dropSchema(schema, options) {
options = options || {}; options = options || {};
var sql = this.QueryGenerator.dropSchema(schema); const sql = this.QueryGenerator.dropSchema(schema);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.dropAllSchemas = function(options) { dropAllSchemas(options) {
options = options || {}; options = options || {};
var self = this;
if (!this.QueryGenerator._dialect.supports.schemas) { if (!this.QueryGenerator._dialect.supports.schemas) {
return this.sequelize.drop(options); return this.sequelize.drop(options);
} else { } else {
return this.showAllSchemas(options).map(function(schemaName) { return this.showAllSchemas(options).map(schemaName => this.dropSchema(schemaName, options));
return self.dropSchema(schemaName, options); }
});
} }
};
QueryInterface.prototype.showAllSchemas = function(options) { showAllSchemas(options) {
var self = this;
options = _.assign({}, options, { options = _.assign({}, options, {
raw: true, raw: true,
type: this.sequelize.QueryTypes.SELECT type: this.sequelize.QueryTypes.SELECT
}); });
var showSchemasSql = self.QueryGenerator.showSchemasQuery(); const showSchemasSql = this.QueryGenerator.showSchemasQuery();
return this.sequelize.query(showSchemasSql, options).then(function(schemaNames) { return this.sequelize.query(showSchemasSql, options).then(schemaNames => Utils._.flatten(
return Utils._.flatten( Utils._.map(schemaNames, value => (!!value.schema_name ? value.schema_name : value))
Utils._.map(schemaNames, function(value) { ));
return (!!value.schema_name ? value.schema_name : value); }
})
);
});
};
QueryInterface.prototype.databaseVersion = function(options) { databaseVersion(options) {
return this.sequelize.query( return this.sequelize.query(
this.QueryGenerator.versionQuery(), this.QueryGenerator.versionQuery(),
_.assign({}, options, { type: QueryTypes.VERSION }) _.assign({}, options, { type: QueryTypes.VERSION })
); );
}; }
QueryInterface.prototype.createTable = function(tableName, attributes, options, model) { createTable(tableName, attributes, options, model) {
var keys = Object.keys(attributes) const keys = Object.keys(attributes);
, keyLen = keys.length const keyLen = keys.length;
, self = this let sql = '';
, sql = '' let i = 0;
, i = 0;
options = _.clone(options) || {}; options = _.clone(options) || {};
attributes = Utils._.mapValues(attributes, function(attribute) { attributes = Utils._.mapValues(attributes, attribute => {
if (!Utils._.isPlainObject(attribute)) { if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute, allowNull: true }; attribute = { type: attribute, allowNull: true };
} }
attribute = self.sequelize.normalizeAttribute(attribute); attribute = this.sequelize.normalizeAttribute(attribute);
return attribute; return attribute;
}); });
// Postgres requires a special SQL command for enums // Postgres requires a special SQL command for enums
if (self.sequelize.options.dialect === 'postgres') { if (this.sequelize.options.dialect === 'postgres') {
var promises = []; const promises = [];
for (i = 0; i < keyLen; i++) { for (i = 0; i < keyLen; i++) {
if (attributes[keys[i]].type instanceof DataTypes.ENUM) { if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = self.QueryGenerator.pgListEnums(tableName, attributes[keys[i]].field || keys[i], options); sql = this.QueryGenerator.pgListEnums(tableName, attributes[keys[i]].field || keys[i], options);
promises.push(self.sequelize.query( promises.push(this.sequelize.query(
sql, sql,
_.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT }) _.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT })
)); ));
} }
} }
return Promise.all(promises).then(function(results) { return Promise.all(promises).then(results => {
var promises = [] const promises = [];
, enumIdx = 0; let enumIdx = 0;
for (i = 0; i < keyLen; i++) { for (i = 0; i < keyLen; i++) {
if (attributes[keys[i]].type instanceof DataTypes.ENUM) { if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
// If the enum type doesn't exist then create it // If the enum type doesn't exist then create it
if (!results[enumIdx]) { if (!results[enumIdx]) {
sql = self.QueryGenerator.pgEnum(tableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options); sql = this.QueryGenerator.pgEnum(tableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options);
promises.push(self.sequelize.query( promises.push(this.sequelize.query(
sql, sql,
_.assign({}, options, { raw: true }) _.assign({}, options, { raw: true })
)); ));
} else if (!!results[enumIdx] && !!model) { } else if (!!results[enumIdx] && !!model) {
var enumVals = self.QueryGenerator.fromArray(results[enumIdx].enum_value) const enumVals = this.QueryGenerator.fromArray(results[enumIdx].enum_value);
, vals = model.rawAttributes[keys[i]].values; const vals = model.rawAttributes[keys[i]].values;
vals.forEach(function(value, idx) { vals.forEach((value, idx) => {
// reset out after/before options since it's for every enum value // reset out after/before options since it's for every enum value
var valueOptions = _.clone(options); const valueOptions = _.clone(options);
valueOptions.before = null; valueOptions.before = null;
valueOptions.after = null; valueOptions.after = null;
...@@ -134,7 +126,7 @@ QueryInterface.prototype.createTable = function(tableName, attributes, options, ...@@ -134,7 +126,7 @@ QueryInterface.prototype.createTable = function(tableName, attributes, options,
valueOptions.after = vals[idx - 1]; valueOptions.after = vals[idx - 1];
} }
valueOptions.supportsSearchPath = false; valueOptions.supportsSearchPath = false;
promises.push(self.sequelize.query(self.QueryGenerator.pgEnumAdd(tableName, keys[i], value, valueOptions), valueOptions)); promises.push(this.sequelize.query(this.QueryGenerator.pgEnumAdd(tableName, keys[i], value, valueOptions), valueOptions));
} }
}); });
enumIdx++; enumIdx++;
...@@ -144,67 +136,65 @@ QueryInterface.prototype.createTable = function(tableName, attributes, options, ...@@ -144,67 +136,65 @@ QueryInterface.prototype.createTable = function(tableName, attributes, options,
if (!tableName.schema && if (!tableName.schema &&
(options.schema || (!!model && model.$schema))) { (options.schema || (!!model && model.$schema))) {
tableName = self.QueryGenerator.addSchema({ tableName = this.QueryGenerator.addSchema({
tableName: tableName, tableName,
$schema: (!!model && model.$schema) || options.schema $schema: (!!model && model.$schema) || options.schema
}); });
} }
attributes = self.QueryGenerator.attributesToSQL(attributes, { attributes = this.QueryGenerator.attributesToSQL(attributes, {
context: 'createTable' context: 'createTable'
}); });
sql = self.QueryGenerator.createTableQuery(tableName, attributes, options); sql = this.QueryGenerator.createTableQuery(tableName, attributes, options);
return Promise.all(promises).then(function() { return Promise.all(promises).then(() => {
return self.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}); });
}); });
} else { } else {
if (!tableName.schema && if (!tableName.schema &&
(options.schema || (!!model && model.$schema))) { (options.schema || (!!model && model.$schema))) {
tableName = self.QueryGenerator.addSchema({ tableName = this.QueryGenerator.addSchema({
tableName: tableName, tableName,
$schema: (!!model && model.$schema) || options.schema $schema: (!!model && model.$schema) || options.schema
}); });
} }
attributes = self.QueryGenerator.attributesToSQL(attributes, { attributes = this.QueryGenerator.attributesToSQL(attributes, {
context: 'createTable' context: 'createTable'
}); });
sql = self.QueryGenerator.createTableQuery(tableName, attributes, options); sql = this.QueryGenerator.createTableQuery(tableName, attributes, options);
return self.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}
} }
};
QueryInterface.prototype.dropTable = function(tableName, options) { dropTable(tableName, options) {
// if we're forcing we should be cascading unless explicitly stated otherwise // if we're forcing we should be cascading unless explicitly stated otherwise
options = _.clone(options) || {}; options = _.clone(options) || {};
options.cascade = options.cascade || options.force || false; options.cascade = options.cascade || options.force || false;
var sql = this.QueryGenerator.dropTableQuery(tableName, options) let sql = this.QueryGenerator.dropTableQuery(tableName, options);
, self = this;
return this.sequelize.query(sql, options).then(function() { return this.sequelize.query(sql, options).then(() => {
var promises = []; const promises = [];
// Since postgres has a special case for enums, we should drop the related // Since postgres has a special case for enums, we should drop the related
// enum type within the table and attribute // enum type within the table and attribute
if (self.sequelize.options.dialect === 'postgres') { if (this.sequelize.options.dialect === 'postgres') {
var instanceTable = self.sequelize.modelManager.getModel(tableName, { attribute: 'tableName' }); const instanceTable = this.sequelize.modelManager.getModel(tableName, { attribute: 'tableName' });
if (!!instanceTable) { if (!!instanceTable) {
var getTableName = (!options || !options.schema || options.schema === 'public' ? '' : options.schema + '_') + tableName; const getTableName = (!options || !options.schema || options.schema === 'public' ? '' : options.schema + '_') + tableName;
var keys = Object.keys(instanceTable.rawAttributes) const keys = Object.keys(instanceTable.rawAttributes);
, keyLen = keys.length const keyLen = keys.length;
, i = 0;
for (i = 0; i < keyLen; i++) { for (let i = 0; i < keyLen; i++) {
if (instanceTable.rawAttributes[keys[i]].type instanceof DataTypes.ENUM) { if (instanceTable.rawAttributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = self.QueryGenerator.pgEnumDrop(getTableName, keys[i]); sql = this.QueryGenerator.pgEnumDrop(getTableName, keys[i]);
options.supportsSearchPath = false; options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true }))); promises.push(this.sequelize.query(sql, _.assign({}, options, { raw: true })));
} }
} }
} }
...@@ -212,108 +202,93 @@ QueryInterface.prototype.dropTable = function(tableName, options) { ...@@ -212,108 +202,93 @@ QueryInterface.prototype.dropTable = function(tableName, options) {
return Promise.all(promises).get(0); return Promise.all(promises).get(0);
}); });
}; }
QueryInterface.prototype.dropAllTables = function(options) { dropAllTables(options) {
var self = this
, skip;
options = options || {}; options = options || {};
skip = options.skip || []; const skip = options.skip || [];
var dropAllTables = function(tableNames) { const dropAllTables = tableNames => Promise.each(tableNames, tableName => {
return Promise.each(tableNames, function(tableName) {
// if tableName is not in the Array of tables names then dont drop it // if tableName is not in the Array of tables names then dont drop it
if (skip.indexOf(tableName.tableName || tableName) === -1) { if (skip.indexOf(tableName.tableName || tableName) === -1) {
return self.dropTable(tableName, _.assign({}, options, { cascade: true }) ); return this.dropTable(tableName, _.assign({}, options, { cascade: true }) );
} }
}); });
};
return self.showAllTables(options).then(function(tableNames) { return this.showAllTables(options).then(tableNames => {
if (self.sequelize.options.dialect === 'sqlite') { if (this.sequelize.options.dialect === 'sqlite') {
return self.sequelize.query('PRAGMA foreign_keys;', options).then(function(result) { return this.sequelize.query('PRAGMA foreign_keys;', options).then(result => {
var foreignKeysAreEnabled = result.foreign_keys === 1; const foreignKeysAreEnabled = result.foreign_keys === 1;
if (foreignKeysAreEnabled) { if (foreignKeysAreEnabled) {
return self.sequelize.query('PRAGMA foreign_keys = OFF', options).then(function() { return this.sequelize.query('PRAGMA foreign_keys = OFF', options)
return dropAllTables(tableNames).then(function() { .then(() => dropAllTables(tableNames))
return self.sequelize.query('PRAGMA foreign_keys = ON', options); .then(() => this.sequelize.query('PRAGMA foreign_keys = ON', options));
});
});
} else { } else {
return dropAllTables(tableNames); return dropAllTables(tableNames);
} }
}); });
} else { } else {
return self.getForeignKeysForTables(tableNames, options).then(function(foreignKeys) { return this.getForeignKeysForTables(tableNames, options).then(foreignKeys => {
var promises = []; const promises = [];
tableNames.forEach(function(tableName) { tableNames.forEach(tableName => {
var normalizedTableName = tableName; let normalizedTableName = tableName;
if (Utils._.isObject(tableName)) { if (Utils._.isObject(tableName)) {
normalizedTableName = tableName.schema + '.' + tableName.tableName; normalizedTableName = tableName.schema + '.' + tableName.tableName;
} }
foreignKeys[normalizedTableName].forEach(function(foreignKey) { foreignKeys[normalizedTableName].forEach(foreignKey => {
var sql = self.QueryGenerator.dropForeignKeyQuery(tableName, foreignKey); const sql = this.QueryGenerator.dropForeignKeyQuery(tableName, foreignKey);
promises.push(self.sequelize.query(sql, options)); promises.push(this.sequelize.query(sql, options));
}); });
}); });
return Promise.all(promises).then(function() { return Promise.all(promises).then(() => dropAllTables(tableNames));
return dropAllTables(tableNames);
});
}); });
} }
}); });
}; }
QueryInterface.prototype.dropAllEnums = function(options) { dropAllEnums(options) {
if (this.sequelize.getDialect() !== 'postgres') { if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve(); return Promise.resolve();
} }
options = options || {}; options = options || {};
var self = this; return this.pgListEnums(null, options).map(result => this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
return this.pgListEnums(null, options).map(function(result) {
return self.sequelize.query(
self.QueryGenerator.pgEnumDrop(null, null, self.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
_.assign({}, options, { raw: true }) _.assign({}, options, { raw: true })
); ));
}); }
};
QueryInterface.prototype.pgListEnums = function (tableName, options) { pgListEnums(tableName, options) {
options = options || {}; options = options || {};
var sql = this.QueryGenerator.pgListEnums(tableName); const sql = this.QueryGenerator.pgListEnums(tableName);
return this.sequelize.query(sql, _.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT })); return this.sequelize.query(sql, _.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT }));
}; }
QueryInterface.prototype.renameTable = function(before, after, options) { renameTable(before, after, options) {
options = options || {}; options = options || {};
var sql = this.QueryGenerator.renameTableQuery(before, after); const sql = this.QueryGenerator.renameTableQuery(before, after);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.showAllTables = function(options) { showAllTables(options) {
var self = this;
options = _.assign({}, options, { options = _.assign({}, options, {
raw: true, raw: true,
type: QueryTypes.SHOWTABLES type: QueryTypes.SHOWTABLES
}); });
var showTablesSql = self.QueryGenerator.showTablesQuery(); const showTablesSql = this.QueryGenerator.showTablesQuery();
return self.sequelize.query(showTablesSql, options).then(function(tableNames) { return this.sequelize.query(showTablesSql, options).then(tableNames => Utils._.flatten(tableNames));
return Utils._.flatten(tableNames); }
});
};
QueryInterface.prototype.describeTable = function(tableName, options) { describeTable(tableName, options) {
var schema = null let schema = null;
, schemaDelimiter = null; let schemaDelimiter = null;
if (typeof options === 'string') { if (typeof options === 'string') {
schema = options; schema = options;
...@@ -327,12 +302,12 @@ QueryInterface.prototype.describeTable = function(tableName, options) { ...@@ -327,12 +302,12 @@ QueryInterface.prototype.describeTable = function(tableName, options) {
tableName = tableName.tableName; tableName = tableName.tableName;
} }
var sql = this.QueryGenerator.describeTableQuery(tableName, schema, schemaDelimiter); const sql = this.QueryGenerator.describeTableQuery(tableName, schema, schemaDelimiter);
return this.sequelize.query( return this.sequelize.query(
sql, sql,
_.assign({}, options, { type: QueryTypes.DESCRIBE }) _.assign({}, options, { type: QueryTypes.DESCRIBE })
).then(function(data) { ).then(data => {
// If no data is returned from the query, then the table name may be wrong. // If no data is returned from the query, then the table name may be wrong.
// Query generators that use information_schema for retrieving table info will just return an empty result set, // Query generators that use information_schema for retrieving table info will just return an empty result set,
// it will not throw an error like built-ins do (e.g. DESCRIBE on MySql). // it will not throw an error like built-ins do (e.g. DESCRIBE on MySql).
...@@ -342,9 +317,9 @@ QueryInterface.prototype.describeTable = function(tableName, options) { ...@@ -342,9 +317,9 @@ QueryInterface.prototype.describeTable = function(tableName, options) {
return Promise.resolve(data); return Promise.resolve(data);
} }
}); });
}; }
QueryInterface.prototype.addColumn = function(table, key, attribute, options) { addColumn(table, key, attribute, options) {
if (!table || !key || !attribute) { if (!table || !key || !attribute) {
throw new Error('addColumn takes atleast 3 arguments (table, attribute name, attribute definition)'); throw new Error('addColumn takes atleast 3 arguments (table, attribute name, attribute definition)');
} }
...@@ -352,9 +327,9 @@ QueryInterface.prototype.addColumn = function(table, key, attribute, options) { ...@@ -352,9 +327,9 @@ QueryInterface.prototype.addColumn = function(table, key, attribute, options) {
options = options || {}; options = options || {};
attribute = this.sequelize.normalizeAttribute(attribute); attribute = this.sequelize.normalizeAttribute(attribute);
return this.sequelize.query(this.QueryGenerator.addColumnQuery(table, key, attribute), options); return this.sequelize.query(this.QueryGenerator.addColumnQuery(table, key, attribute), options);
}; }
QueryInterface.prototype.removeColumn = function(tableName, attributeName, options) { removeColumn(tableName, attributeName, options) {
options = options || {}; options = options || {};
switch (this.sequelize.options.dialect) { switch (this.sequelize.options.dialect) {
case 'sqlite': case 'sqlite':
...@@ -367,13 +342,12 @@ QueryInterface.prototype.removeColumn = function(tableName, attributeName, optio ...@@ -367,13 +342,12 @@ QueryInterface.prototype.removeColumn = function(tableName, attributeName, optio
// mysql needs special treatment as it cannot drop a column with a foreign key constraint // mysql needs special treatment as it cannot drop a column with a foreign key constraint
return MySQLQueryInterface.removeColumn.call(this, tableName, attributeName, options); return MySQLQueryInterface.removeColumn.call(this, tableName, attributeName, options);
default: default:
var sql = this.QueryGenerator.removeColumnQuery(tableName, attributeName); return this.sequelize.query(this.QueryGenerator.removeColumnQuery(tableName, attributeName), options);
return this.sequelize.query(sql, options); }
} }
};
QueryInterface.prototype.changeColumn = function(tableName, attributeName, dataTypeOrOptions, options) { changeColumn(tableName, attributeName, dataTypeOrOptions, options) {
var attributes = {}; const attributes = {};
options = options || {}; options = options || {};
if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) { if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) {
...@@ -388,19 +362,19 @@ QueryInterface.prototype.changeColumn = function(tableName, attributeName, dataT ...@@ -388,19 +362,19 @@ QueryInterface.prototype.changeColumn = function(tableName, attributeName, dataT
// sqlite needs some special treatment as it cannot change a column // sqlite needs some special treatment as it cannot change a column
return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options); return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options);
} else { } else {
var query = this.QueryGenerator.attributesToSQL(attributes) const query = this.QueryGenerator.attributesToSQL(attributes);
, sql = this.QueryGenerator.changeColumnQuery(tableName, query); const sql = this.QueryGenerator.changeColumnQuery(tableName, query);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} }
}; }
QueryInterface.prototype.renameColumn = function(tableName, attrNameBefore, attrNameAfter, options) { renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {}; options = options || {};
return this.describeTable(tableName, options).then(function(data) { return this.describeTable(tableName, options).then(data => {
data = data[attrNameBefore] || {}; data = data[attrNameBefore] || {};
var _options = {}; const _options = {};
_options[attrNameAfter] = { _options[attrNameAfter] = {
attribute: attrNameAfter, attribute: attrNameAfter,
...@@ -418,17 +392,17 @@ QueryInterface.prototype.renameColumn = function(tableName, attrNameBefore, attr ...@@ -418,17 +392,17 @@ QueryInterface.prototype.renameColumn = function(tableName, attrNameBefore, attr
// sqlite needs some special treatment as it cannot rename a column // sqlite needs some special treatment as it cannot rename a column
return SQLiteQueryInterface.renameColumn.call(this, tableName, attrNameBefore, attrNameAfter, options); return SQLiteQueryInterface.renameColumn.call(this, tableName, attrNameBefore, attrNameAfter, options);
} else { } else {
var sql = this.QueryGenerator.renameColumnQuery( const sql = this.QueryGenerator.renameColumnQuery(
tableName, tableName,
attrNameBefore, attrNameBefore,
this.QueryGenerator.attributesToSQL(_options) this.QueryGenerator.attributesToSQL(_options)
); );
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} }
}.bind(this)); });
}; }
QueryInterface.prototype.addIndex = function(tableName, attributes, options, rawTablename) { addIndex(tableName, attributes, options, rawTablename) {
// Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes) // Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes)
if (!Array.isArray(attributes)) { if (!Array.isArray(attributes)) {
rawTablename = options; rawTablename = options;
...@@ -444,71 +418,68 @@ QueryInterface.prototype.addIndex = function(tableName, attributes, options, raw ...@@ -444,71 +418,68 @@ QueryInterface.prototype.addIndex = function(tableName, attributes, options, raw
options = Utils.cloneDeep(options); options = Utils.cloneDeep(options);
options.fields = attributes; options.fields = attributes;
var sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename); const sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false })); return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false }));
}; }
QueryInterface.prototype.showIndex = function(tableName, options) { showIndex(tableName, options) {
var sql = this.QueryGenerator.showIndexesQuery(tableName, options); const sql = this.QueryGenerator.showIndexesQuery(tableName, options);
return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES })); return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
}; }
QueryInterface.prototype.nameIndexes = function(indexes, rawTablename) { nameIndexes(indexes, rawTablename) {
return this.QueryGenerator.nameIndexes(indexes, rawTablename); return this.QueryGenerator.nameIndexes(indexes, rawTablename);
}; }
QueryInterface.prototype.getForeignKeysForTables = function(tableNames, options) { getForeignKeysForTables(tableNames, options) {
var self = this;
options = options || {}; options = options || {};
if (tableNames.length === 0) { if (tableNames.length === 0) {
return Promise.resolve({}); return Promise.resolve({});
} }
return Promise.map(tableNames, function(tableName) { return Promise.map(tableNames, tableName =>
return self.sequelize.query(self.QueryGenerator.getForeignKeysQuery(tableName, self.sequelize.config.database), options).get(0); this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options).get(0)
}).then(function(results) { ).then(results => {
var result = {}; const result = {};
tableNames.forEach(function(tableName, i) { tableNames.forEach((tableName, i) => {
if (Utils._.isObject(tableName)) { if (Utils._.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName; tableName = tableName.schema + '.' + tableName.tableName;
} }
result[tableName] = Utils._.compact(results[i]).map(function(r) { result[tableName] = Utils._.compact(results[i]).map(r => r.constraint_name);
return r.constraint_name;
});
}); });
return result; return result;
}); });
}; }
QueryInterface.prototype.removeIndex = function(tableName, indexNameOrAttributes, options) { removeIndex(tableName, indexNameOrAttributes, options) {
options = options || {}; options = options || {};
var sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes); const sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.insert = function(instance, tableName, values, options) { insert(instance, tableName, values, options) {
options = Utils.cloneDeep(options); options = Utils.cloneDeep(options);
options.hasTrigger = instance && instance.constructor.options.hasTrigger; options.hasTrigger = instance && instance.constructor.options.hasTrigger;
var sql = this.QueryGenerator.insertQuery(tableName, values, instance && instance.constructor.rawAttributes, options); const sql = this.QueryGenerator.insertQuery(tableName, values, instance && instance.constructor.rawAttributes, options);
options.type = QueryTypes.INSERT; options.type = QueryTypes.INSERT;
options.instance = instance; options.instance = instance;
return this.sequelize.query(sql, options).then(function(result) { return this.sequelize.query(sql, options).then(result => {
if (instance) result.isNewRecord = false; if (instance) result.isNewRecord = false;
return result; return result;
}); });
}; }
QueryInterface.prototype.upsert = function(tableName, valuesByField, updateValues, where, model, options) { upsert(tableName, valuesByField, updateValues, where, model, options) {
var wheres = [] const wheres = [];
, indexFields const attributes = Object.keys(valuesByField);
, indexes = [] let indexes = [];
, attributes = Object.keys(valuesByField); let indexFields;
options = _.clone(options); options = _.clone(options);
...@@ -517,14 +488,14 @@ QueryInterface.prototype.upsert = function(tableName, valuesByField, updateValue ...@@ -517,14 +488,14 @@ QueryInterface.prototype.upsert = function(tableName, valuesByField, updateValue
} }
// Lets combine uniquekeys and indexes into one // Lets combine uniquekeys and indexes into one
indexes = Utils._.map(model.options.uniqueKeys, function (value) { indexes = Utils._.map(model.options.uniqueKeys, value => {
return value.fields; return value.fields;
}); });
Utils._.each(model.options.indexes, function (value) { Utils._.each(model.options.indexes, value => {
if (value.unique === true) { if (value.unique === true) {
// fields in the index may both the strings or objects with an attribute property - lets sanitize that // fields in the index may both the strings or objects with an attribute property - lets sanitize that
indexFields = Utils._.map(value.fields, function (field) { indexFields = Utils._.map(value.fields, field => {
if (Utils._.isPlainObject(field)) { if (Utils._.isPlainObject(field)) {
return field.attribute; return field.attribute;
} }
...@@ -534,23 +505,23 @@ QueryInterface.prototype.upsert = function(tableName, valuesByField, updateValue ...@@ -534,23 +505,23 @@ QueryInterface.prototype.upsert = function(tableName, valuesByField, updateValue
} }
}); });
indexes.forEach(function (index) { for (const index of indexes) {
if (Utils._.intersection(attributes, index).length === index.length) { if (Utils._.intersection(attributes, index).length === index.length) {
where = {}; where = {};
index.forEach(function (field) { for (const field of index) {
where[field] = valuesByField[field]; where[field] = valuesByField[field];
}); }
wheres.push(where); wheres.push(where);
} }
}); }
where = { $or: wheres }; where = { $or: wheres };
options.type = QueryTypes.UPSERT; options.type = QueryTypes.UPSERT;
options.raw = true; options.raw = true;
var sql = this.QueryGenerator.upsertQuery(tableName, valuesByField, updateValues, where, model.rawAttributes, options); const sql = this.QueryGenerator.upsertQuery(tableName, valuesByField, updateValues, where, model.rawAttributes, options);
return this.sequelize.query(sql, options).then(function (rowCount) { return this.sequelize.query(sql, options).then(rowCount => {
if (rowCount === undefined) { if (rowCount === undefined) {
return rowCount; return rowCount;
} }
...@@ -559,33 +530,31 @@ QueryInterface.prototype.upsert = function(tableName, valuesByField, updateValue ...@@ -559,33 +530,31 @@ QueryInterface.prototype.upsert = function(tableName, valuesByField, updateValue
return rowCount === 1; return rowCount === 1;
}); });
}; }
QueryInterface.prototype.bulkInsert = function(tableName, records, options, attributes) { bulkInsert(tableName, records, options, attributes) {
options = _.clone(options) || {}; options = _.clone(options) || {};
options.type = QueryTypes.INSERT; options.type = QueryTypes.INSERT;
var sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes); const sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.update = function(instance, tableName, values, identifier, options) { update(instance, tableName, values, identifier, options) {
options = _.clone(options || {}); options = _.clone(options || {});
options.hasTrigger = !!(instance && instance.$modelOptions && instance.$modelOptions.hasTrigger); options.hasTrigger = !!(instance && instance.$modelOptions && instance.$modelOptions.hasTrigger);
var self = this const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes);
, restrict = false let restrict = false;
, sql = self.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes);
options.type = QueryTypes.UPDATE; options.type = QueryTypes.UPDATE;
// Check for a restrict field // Check for a restrict field
if (instance.constructor && instance.constructor.associations) { if (instance.constructor && instance.constructor.associations) {
var keys = Object.keys(instance.constructor.associations) const keys = Object.keys(instance.constructor.associations);
, length = keys.length; const length = keys.length;
for (var i = 0; i < length; i++) { for (let i = 0; i < length; i++) {
if (instance.constructor.associations[keys[i]].options && instance.constructor.associations[keys[i]].options.onUpdate && instance.constructor.associations[keys[i]].options.onUpdate === 'restrict') { if (instance.constructor.associations[keys[i]].options && instance.constructor.associations[keys[i]].options.onUpdate && instance.constructor.associations[keys[i]].options.onUpdate === 'restrict') {
restrict = true; restrict = true;
} }
...@@ -594,34 +563,33 @@ QueryInterface.prototype.update = function(instance, tableName, values, identifi ...@@ -594,34 +563,33 @@ QueryInterface.prototype.update = function(instance, tableName, values, identifi
options.instance = instance; options.instance = instance;
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.bulkUpdate = function(tableName, values, identifier, options, attributes) { bulkUpdate(tableName, values, identifier, options, attributes) {
options = Utils.cloneDeep(options); options = Utils.cloneDeep(options);
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier); if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
var sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, attributes) const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, attributes);
, table = Utils._.isObject(tableName) ? tableName : { tableName: tableName } const table = Utils._.isObject(tableName) ? tableName : { tableName };
, model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName }); const model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName });
options.model = model; options.model = model;
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.delete = function(instance, tableName, identifier, options) { delete(instance, tableName, identifier, options) {
var self = this const cascades = [];
, cascades = [] const sql = this.QueryGenerator.deleteQuery(tableName, identifier, null, instance.constructor);
, sql = self.QueryGenerator.deleteQuery(tableName, identifier, null, instance.constructor);
options = _.clone(options) || {}; options = _.clone(options) || {};
// Check for a restrict field // Check for a restrict field
if (!!instance.constructor && !!instance.constructor.associations) { if (!!instance.constructor && !!instance.constructor.associations) {
var keys = Object.keys(instance.constructor.associations) const keys = Object.keys(instance.constructor.associations);
, length = keys.length const length = keys.length;
, association; let association;
for (var i = 0; i < length; i++) { for (let i = 0; i < length; i++) {
association = instance.constructor.associations[keys[i]]; association = instance.constructor.associations[keys[i]];
if (association.options && association.options.onDelete && if (association.options && association.options.onDelete &&
association.options.onDelete.toLowerCase() === 'cascade' && association.options.onDelete.toLowerCase() === 'cascade' &&
...@@ -631,8 +599,8 @@ QueryInterface.prototype.delete = function(instance, tableName, identifier, opti ...@@ -631,8 +599,8 @@ QueryInterface.prototype.delete = function(instance, tableName, identifier, opti
} }
} }
return Promise.each(cascades, function (cascade) { return Promise.each(cascades, cascade => {
return instance[cascade](options).then(function (instances) { return instance[cascade](options).then(instances => {
// Check for hasOne relationship with non-existing associate ("has zero") // Check for hasOne relationship with non-existing associate ("has zero")
if (!instances) { if (!instances) {
return Promise.resolve(); return Promise.resolve();
...@@ -640,26 +608,24 @@ QueryInterface.prototype.delete = function(instance, tableName, identifier, opti ...@@ -640,26 +608,24 @@ QueryInterface.prototype.delete = function(instance, tableName, identifier, opti
if (!Array.isArray(instances)) instances = [instances]; if (!Array.isArray(instances)) instances = [instances];
return Promise.each(instances, function (instance) { return Promise.each(instances, instance => instance.destroy(options));
return instance.destroy(options);
}); });
}); }).then(() => {
}).then(function () {
options.instance = instance; options.instance = instance;
return self.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}); });
}; }
QueryInterface.prototype.bulkDelete = function(tableName, identifier, options, model) { bulkDelete(tableName, identifier, options, model) {
options = Utils.cloneDeep(options); options = Utils.cloneDeep(options);
options = _.defaults(options, {limit: null}); options = _.defaults(options, {limit: null});
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier); if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
var sql = this.QueryGenerator.deleteQuery(tableName, identifier, options, model); const sql = this.QueryGenerator.deleteQuery(tableName, identifier, options, model);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.select = function(model, tableName, options) { select(model, tableName, options) {
options = Utils.cloneDeep(options); options = Utils.cloneDeep(options);
options.type = QueryTypes.SELECT; options.type = QueryTypes.SELECT;
options.model = model; options.model = model;
...@@ -668,22 +634,22 @@ QueryInterface.prototype.select = function(model, tableName, options) { ...@@ -668,22 +634,22 @@ QueryInterface.prototype.select = function(model, tableName, options) {
this.QueryGenerator.selectQuery(tableName, options, model), this.QueryGenerator.selectQuery(tableName, options, model),
options options
); );
}; }
QueryInterface.prototype.increment = function(instance, tableName, values, identifier, options) { increment(instance, tableName, values, identifier, options) {
var sql = this.QueryGenerator.incrementQuery(tableName, values, identifier, options.attributes); const sql = this.QueryGenerator.incrementQuery(tableName, values, identifier, options.attributes);
options = _.clone(options) || {}; options = _.clone(options) || {};
options.type = QueryTypes.UPDATE; options.type = QueryTypes.UPDATE;
options.instance = instance; options.instance = instance;
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.rawSelect = function(tableName, options, attributeSelector, Model) { rawSelect(tableName, options, attributeSelector, Model) {
if (options.schema) { if (options.schema) {
tableName = this.QueryGenerator.addSchema({ tableName = this.QueryGenerator.addSchema({
tableName: tableName, tableName,
$schema: options.schema $schema: options.schema
}); });
} }
...@@ -695,21 +661,21 @@ QueryInterface.prototype.rawSelect = function(tableName, options, attributeSelec ...@@ -695,21 +661,21 @@ QueryInterface.prototype.rawSelect = function(tableName, options, attributeSelec
type: QueryTypes.SELECT type: QueryTypes.SELECT
}); });
var sql = this.QueryGenerator.selectQuery(tableName, options, Model); const sql = this.QueryGenerator.selectQuery(tableName, options, Model);
if (attributeSelector === undefined) { if (attributeSelector === undefined) {
throw new Error('Please pass an attribute selector!'); throw new Error('Please pass an attribute selector!');
} }
return this.sequelize.query(sql, options).then(function(data) { return this.sequelize.query(sql, options).then(data => {
if (!options.plain) { if (!options.plain) {
return data; return data;
} }
var result = data ? data[attributeSelector] : null; let result = data ? data[attributeSelector] : null;
if (options && options.dataType) { if (options && options.dataType) {
var dataType = options.dataType; const dataType = options.dataType;
if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) { if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
result = parseFloat(result); result = parseFloat(result);
...@@ -726,20 +692,20 @@ QueryInterface.prototype.rawSelect = function(tableName, options, attributeSelec ...@@ -726,20 +692,20 @@ QueryInterface.prototype.rawSelect = function(tableName, options, attributeSelec
return result; return result;
}); });
}; }
QueryInterface.prototype.createTrigger = function(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray, options) { createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray, options) {
var sql = this.QueryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray); const sql = this.QueryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray);
options = options || {}; options = options || {};
if (sql) { if (sql) {
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; }
QueryInterface.prototype.dropTrigger = function(tableName, triggerName, options) { dropTrigger(tableName, triggerName, options) {
var sql = this.QueryGenerator.dropTrigger(tableName, triggerName); const sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
options = options || {}; options = options || {};
if (sql) { if (sql) {
...@@ -747,10 +713,10 @@ QueryInterface.prototype.dropTrigger = function(tableName, triggerName, options) ...@@ -747,10 +713,10 @@ QueryInterface.prototype.dropTrigger = function(tableName, triggerName, options)
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; }
QueryInterface.prototype.renameTrigger = function(tableName, oldTriggerName, newTriggerName, options) { renameTrigger(tableName, oldTriggerName, newTriggerName, options) {
var sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName); const sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName);
options = options || {}; options = options || {};
if (sql) { if (sql) {
...@@ -758,10 +724,10 @@ QueryInterface.prototype.renameTrigger = function(tableName, oldTriggerName, new ...@@ -758,10 +724,10 @@ QueryInterface.prototype.renameTrigger = function(tableName, oldTriggerName, new
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; }
QueryInterface.prototype.createFunction = function(functionName, params, returnType, language, body, options) { createFunction(functionName, params, returnType, language, body, options) {
var sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options); const sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options);
options = options || {}; options = options || {};
if (sql) { if (sql) {
...@@ -769,10 +735,10 @@ QueryInterface.prototype.createFunction = function(functionName, params, returnT ...@@ -769,10 +735,10 @@ QueryInterface.prototype.createFunction = function(functionName, params, returnT
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; }
QueryInterface.prototype.dropFunction = function(functionName, params, options) { dropFunction(functionName, params, options) {
var sql = this.QueryGenerator.dropFunction(functionName, params); const sql = this.QueryGenerator.dropFunction(functionName, params);
options = options || {}; options = options || {};
if (sql) { if (sql) {
...@@ -780,10 +746,10 @@ QueryInterface.prototype.dropFunction = function(functionName, params, options) ...@@ -780,10 +746,10 @@ QueryInterface.prototype.dropFunction = function(functionName, params, options)
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; }
QueryInterface.prototype.renameFunction = function(oldFunctionName, params, newFunctionName, options) { renameFunction(oldFunctionName, params, newFunctionName, options) {
var sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName); const sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
options = options || {}; options = options || {};
if (sql) { if (sql) {
...@@ -791,40 +757,40 @@ QueryInterface.prototype.renameFunction = function(oldFunctionName, params, newF ...@@ -791,40 +757,40 @@ QueryInterface.prototype.renameFunction = function(oldFunctionName, params, newF
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; }
// Helper methods useful for querying // Helper methods useful for querying
/** /**
* Escape an identifier (e.g. a table or attribute name). If force is true, * Escape an identifier (e.g. a table or attribute name). If force is true,
* the identifier will be quoted even if the `quoteIdentifiers` option is * the identifier will be quoted even if the `quoteIdentifiers` option is
* false. * false.
*/ */
QueryInterface.prototype.quoteIdentifier = function(identifier, force) { quoteIdentifier(identifier, force) {
return this.QueryGenerator.quoteIdentifier(identifier, force); return this.QueryGenerator.quoteIdentifier(identifier, force);
}; }
QueryInterface.prototype.quoteTable = function(identifier) { quoteTable(identifier) {
return this.QueryGenerator.quoteTable(identifier); return this.QueryGenerator.quoteTable(identifier);
}; }
/** /**
* Split an identifier into .-separated tokens and quote each part. * Split an identifier into .-separated tokens and quote each part.
* If force is true, the identifier will be quoted even if the * If force is true, the identifier will be quoted even if the
* `quoteIdentifiers` option is false. * `quoteIdentifiers` option is false.
*/ */
QueryInterface.prototype.quoteIdentifiers = function(identifiers, force) { quoteIdentifiers(identifiers, force) {
return this.QueryGenerator.quoteIdentifiers(identifiers, force); return this.QueryGenerator.quoteIdentifiers(identifiers, force);
}; }
/** /**
* Escape a value (e.g. a string, number or date) * Escape a value (e.g. a string, number or date)
*/ */
QueryInterface.prototype.escape = function(value) { escape(value) {
return this.QueryGenerator.escape(value); return this.QueryGenerator.escape(value);
}; }
QueryInterface.prototype.setAutocommit = function(transaction, value, options) { setAutocommit(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set autocommit for a transaction without transaction object!'); throw new Error('Unable to set autocommit for a transaction without transaction object!');
} }
...@@ -837,16 +803,16 @@ QueryInterface.prototype.setAutocommit = function(transaction, value, options) { ...@@ -837,16 +803,16 @@ QueryInterface.prototype.setAutocommit = function(transaction, value, options) {
transaction: transaction.parent || transaction transaction: transaction.parent || transaction
}); });
var sql = this.QueryGenerator.setAutocommitQuery(value, { const sql = this.QueryGenerator.setAutocommitQuery(value, {
parent: transaction.parent parent: transaction.parent
}); });
if (!sql) return Promise.resolve(); if (!sql) return Promise.resolve();
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.setIsolationLevel = function(transaction, value, options) { setIsolationLevel(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set isolation level for a transaction without transaction object!'); throw new Error('Unable to set isolation level for a transaction without transaction object!');
} }
...@@ -860,16 +826,16 @@ QueryInterface.prototype.setIsolationLevel = function(transaction, value, option ...@@ -860,16 +826,16 @@ QueryInterface.prototype.setIsolationLevel = function(transaction, value, option
transaction: transaction.parent || transaction transaction: transaction.parent || transaction
}); });
var sql = this.QueryGenerator.setIsolationLevelQuery(value, { const sql = this.QueryGenerator.setIsolationLevelQuery(value, {
parent: transaction.parent parent: transaction.parent
}); });
if (!sql) return Promise.resolve(); if (!sql) return Promise.resolve();
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.startTransaction = function(transaction, options) { startTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to start a transaction without transaction object!'); throw new Error('Unable to start a transaction without transaction object!');
} }
...@@ -878,26 +844,26 @@ QueryInterface.prototype.startTransaction = function(transaction, options) { ...@@ -878,26 +844,26 @@ QueryInterface.prototype.startTransaction = function(transaction, options) {
transaction: transaction.parent || transaction transaction: transaction.parent || transaction
}); });
var sql = this.QueryGenerator.startTransactionQuery(transaction); const sql = this.QueryGenerator.startTransactionQuery(transaction);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; }
QueryInterface.prototype.deferConstraints = function (transaction, options) { deferConstraints(transaction, options) {
options = _.assign({}, options, { options = _.assign({}, options, {
transaction: transaction.parent || transaction transaction: transaction.parent || transaction
}); });
var sql = this.QueryGenerator.deferConstraintsQuery(options); const sql = this.QueryGenerator.deferConstraintsQuery(options);
if (sql) { if (sql) {
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} }
return Promise.resolve(); return Promise.resolve();
}; }
QueryInterface.prototype.commitTransaction = function(transaction, options) { commitTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to commit a transaction without transaction object!'); throw new Error('Unable to commit a transaction without transaction object!');
} }
...@@ -911,15 +877,15 @@ QueryInterface.prototype.commitTransaction = function(transaction, options) { ...@@ -911,15 +877,15 @@ QueryInterface.prototype.commitTransaction = function(transaction, options) {
supportsSearchPath: false supportsSearchPath: false
}); });
var sql = this.QueryGenerator.commitTransactionQuery(transaction); const sql = this.QueryGenerator.commitTransactionQuery(transaction);
var promise = this.sequelize.query(sql, options); const promise = this.sequelize.query(sql, options);
transaction.finished = 'commit'; transaction.finished = 'commit';
return promise; return promise;
}; }
QueryInterface.prototype.rollbackTransaction = function(transaction, options) { rollbackTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to rollback a transaction without transaction object!'); throw new Error('Unable to rollback a transaction without transaction object!');
} }
...@@ -929,12 +895,15 @@ QueryInterface.prototype.rollbackTransaction = function(transaction, options) { ...@@ -929,12 +895,15 @@ QueryInterface.prototype.rollbackTransaction = function(transaction, options) {
supportsSearchPath: false supportsSearchPath: false
}); });
var sql = this.QueryGenerator.rollbackTransactionQuery(transaction); const sql = this.QueryGenerator.rollbackTransactionQuery(transaction);
var promise = this.sequelize.query(sql, options); const promise = this.sequelize.query(sql, options);
transaction.finished = 'rollback'; transaction.finished = 'rollback';
return promise; return promise;
}; }
}
module.exports = QueryInterface; module.exports = QueryInterface;
module.exports.QueryInterface = QueryInterface;
module.exports.default = QueryInterface;
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!