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

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 712 additions and 743 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 {
this.sequelize = sequelize; constructor(sequelize) {
this.QueryGenerator = this.sequelize.dialect.QueryGenerator; this.sequelize = sequelize;
}; this.QueryGenerator = this.sequelize.dialect.QueryGenerator;
}
QueryInterface.prototype.createSchema = function(schema, options) {
options = options || {}; createSchema(schema, options) {
var sql = this.QueryGenerator.createSchema(schema); options = options || {};
return this.sequelize.query(sql, options); const sql = this.QueryGenerator.createSchema(schema);
}; return this.sequelize.query(sql, options);
}
QueryInterface.prototype.dropSchema = function(schema, options) {
options = options || {}; dropSchema(schema, options) {
var sql = this.QueryGenerator.dropSchema(schema); options = options || {};
return this.sequelize.query(sql, options); const sql = this.QueryGenerator.dropSchema(schema);
}; return this.sequelize.query(sql, options);
}
QueryInterface.prototype.dropAllSchemas = function(options) {
options = options || {}; dropAllSchemas(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); }
})
databaseVersion(options) {
return this.sequelize.query(
this.QueryGenerator.versionQuery(),
_.assign({}, options, { type: QueryTypes.VERSION })
); );
}); }
};
createTable(tableName, attributes, options, model) {
QueryInterface.prototype.databaseVersion = function(options) { const keys = Object.keys(attributes);
return this.sequelize.query( const keyLen = keys.length;
this.QueryGenerator.versionQuery(), let sql = '';
_.assign({}, options, { type: QueryTypes.VERSION }) let i = 0;
);
}; options = _.clone(options) || {};
QueryInterface.prototype.createTable = function(tableName, attributes, options, model) { attributes = Utils._.mapValues(attributes, attribute => {
var keys = Object.keys(attributes) if (!Utils._.isPlainObject(attribute)) {
, keyLen = keys.length attribute = { type: attribute, allowNull: true };
, self = this
, sql = ''
, i = 0;
options = _.clone(options) || {};
attributes = Utils._.mapValues(attributes, function(attribute) {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute, allowNull: true };
}
attribute = self.sequelize.normalizeAttribute(attribute);
return attribute;
});
// Postgres requires a special SQL command for enums
if (self.sequelize.options.dialect === 'postgres') {
var promises = [];
for (i = 0; i < keyLen; i++) {
if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = self.QueryGenerator.pgListEnums(tableName, attributes[keys[i]].field || keys[i], options);
promises.push(self.sequelize.query(
sql,
_.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT })
));
} }
}
return Promise.all(promises).then(function(results) { attribute = this.sequelize.normalizeAttribute(attribute);
var promises = []
, enumIdx = 0; return attribute;
});
// Postgres requires a special SQL command for enums
if (this.sequelize.options.dialect === 'postgres') {
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) {
// If the enum type doesn't exist then create it sql = this.QueryGenerator.pgListEnums(tableName, attributes[keys[i]].field || keys[i], options);
if (!results[enumIdx]) { promises.push(this.sequelize.query(
sql = self.QueryGenerator.pgEnum(tableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options); sql,
promises.push(self.sequelize.query( _.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT })
sql, ));
_.assign({}, options, { raw: true }) }
)); }
} else if (!!results[enumIdx] && !!model) {
var enumVals = self.QueryGenerator.fromArray(results[enumIdx].enum_value) return Promise.all(promises).then(results => {
, vals = model.rawAttributes[keys[i]].values; const promises = [];
let enumIdx = 0;
vals.forEach(function(value, idx) {
// reset out after/before options since it's for every enum value for (i = 0; i < keyLen; i++) {
var valueOptions = _.clone(options); if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
valueOptions.before = null; // If the enum type doesn't exist then create it
valueOptions.after = null; if (!results[enumIdx]) {
sql = this.QueryGenerator.pgEnum(tableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options);
if (enumVals.indexOf(value) === -1) { promises.push(this.sequelize.query(
if (!!vals[idx + 1]) { sql,
valueOptions.before = vals[idx + 1]; _.assign({}, options, { raw: true })
} ));
else if (!!vals[idx - 1]) { } else if (!!results[enumIdx] && !!model) {
valueOptions.after = vals[idx - 1]; const enumVals = this.QueryGenerator.fromArray(results[enumIdx].enum_value);
const vals = model.rawAttributes[keys[i]].values;
vals.forEach((value, idx) => {
// reset out after/before options since it's for every enum value
const valueOptions = _.clone(options);
valueOptions.before = null;
valueOptions.after = null;
if (enumVals.indexOf(value) === -1) {
if (!!vals[idx + 1]) {
valueOptions.before = vals[idx + 1];
}
else if (!!vals[idx - 1]) {
valueOptions.after = vals[idx - 1];
}
valueOptions.supportsSearchPath = false;
promises.push(this.sequelize.query(this.QueryGenerator.pgEnumAdd(tableName, keys[i], value, valueOptions), valueOptions));
} }
valueOptions.supportsSearchPath = false; });
promises.push(self.sequelize.query(self.QueryGenerator.pgEnumAdd(tableName, keys[i], value, valueOptions), valueOptions)); enumIdx++;
} }
});
enumIdx++;
} }
} }
}
if (!tableName.schema &&
(options.schema || (!!model && model.$schema))) {
tableName = this.QueryGenerator.addSchema({
tableName,
$schema: (!!model && model.$schema) || options.schema
});
}
attributes = this.QueryGenerator.attributesToSQL(attributes, {
context: 'createTable'
});
sql = this.QueryGenerator.createTableQuery(tableName, attributes, options);
return Promise.all(promises).then(() => {
return this.sequelize.query(sql, options);
});
});
} 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 Promise.all(promises).then(function() { return this.sequelize.query(sql, options);
return self.sequelize.query(sql, options);
});
});
} else {
if (!tableName.schema &&
(options.schema || (!!model && model.$schema))) {
tableName = self.QueryGenerator.addSchema({
tableName: tableName,
$schema: (!!model && model.$schema) || options.schema
});
} }
attributes = self.QueryGenerator.attributesToSQL(attributes, {
context: 'createTable'
});
sql = self.QueryGenerator.createTableQuery(tableName, attributes, options);
return self.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 })));
}
} }
} }
} }
}
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 {
return dropAllTables(tableNames);
}
});
} else {
return this.getForeignKeysForTables(tableNames, options).then(foreignKeys => {
const promises = [];
tableNames.forEach(tableName => {
let normalizedTableName = tableName;
if (Utils._.isObject(tableName)) {
normalizedTableName = tableName.schema + '.' + tableName.tableName;
}
foreignKeys[normalizedTableName].forEach(foreignKey => {
const sql = this.QueryGenerator.dropForeignKeyQuery(tableName, foreignKey);
promises.push(this.sequelize.query(sql, options));
}); });
}); });
} else {
return dropAllTables(tableNames);
}
});
} else {
return self.getForeignKeysForTables(tableNames, options).then(function(foreignKeys) {
var promises = [];
tableNames.forEach(function(tableName) { return Promise.all(promises).then(() => dropAllTables(tableNames));
var normalizedTableName = tableName;
if (Utils._.isObject(tableName)) {
normalizedTableName = tableName.schema + '.' + tableName.tableName;
}
foreignKeys[normalizedTableName].forEach(function(foreignKey) {
var sql = self.QueryGenerator.dropForeignKeyQuery(tableName, foreignKey);
promises.push(self.sequelize.query(sql, options));
});
}); });
}
});
}
return Promise.all(promises).then(function() { dropAllEnums(options) {
return dropAllTables(tableNames); if (this.sequelize.getDialect() !== 'postgres') {
}); return Promise.resolve();
});
} }
});
};
QueryInterface.prototype.dropAllEnums = function(options) { options = options || {};
if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve();
}
options = options || {}; return this.pgListEnums(null, options).map(result => this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
_.assign({}, options, { raw: true })
));
}
var self = this; pgListEnums(tableName, options) {
options = options || {};
const sql = this.QueryGenerator.pgListEnums(tableName);
return this.sequelize.query(sql, _.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT }));
}
return this.pgListEnums(null, options).map(function(result) { renameTable(before, after, options) {
return self.sequelize.query( options = options || {};
self.QueryGenerator.pgEnumDrop(null, null, self.QueryGenerator.pgEscapeAndQuote(result.enum_name)), const sql = this.QueryGenerator.renameTableQuery(before, after);
_.assign({}, options, { raw: true }) return this.sequelize.query(sql, options);
);
});
};
QueryInterface.prototype.pgListEnums = function (tableName, options) {
options = options || {};
var sql = this.QueryGenerator.pgListEnums(tableName);
return this.sequelize.query(sql, _.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT }));
};
QueryInterface.prototype.renameTable = function(before, after, options) {
options = options || {};
var sql = this.QueryGenerator.renameTableQuery(before, after);
return this.sequelize.query(sql, options);
};
QueryInterface.prototype.showAllTables = function(options) {
var self = this;
options = _.assign({}, options, {
raw: true,
type: QueryTypes.SHOWTABLES
});
var showTablesSql = self.QueryGenerator.showTablesQuery();
return self.sequelize.query(showTablesSql, options).then(function(tableNames) {
return Utils._.flatten(tableNames);
});
};
QueryInterface.prototype.describeTable = function(tableName, options) {
var schema = null
, schemaDelimiter = null;
if (typeof options === 'string') {
schema = options;
} else if (typeof options === 'object' && options !== null) {
schema = options.schema || null;
schemaDelimiter = options.schemaDelimiter || null;
}
if (typeof tableName === 'object' && tableName !== null) {
schema = tableName.schema;
tableName = tableName.tableName;
}
var sql = this.QueryGenerator.describeTableQuery(tableName, schema, schemaDelimiter);
return this.sequelize.query(
sql,
_.assign({}, options, { type: QueryTypes.DESCRIBE })
).then(function(data) {
// 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,
// it will not throw an error like built-ins do (e.g. DESCRIBE on MySql).
if (Utils._.isEmpty(data)) {
return Promise.reject('No description found for "' + tableName + '" table. Check the table name and schema; remember, they _are_ case sensitive.');
} else {
return Promise.resolve(data);
}
});
};
QueryInterface.prototype.addColumn = function(table, key, attribute, options) {
if (!table || !key || !attribute) {
throw new Error('addColumn takes atleast 3 arguments (table, attribute name, attribute definition)');
}
options = options || {};
attribute = this.sequelize.normalizeAttribute(attribute);
return this.sequelize.query(this.QueryGenerator.addColumnQuery(table, key, attribute), options);
};
QueryInterface.prototype.removeColumn = function(tableName, attributeName, options) {
options = options || {};
switch (this.sequelize.options.dialect) {
case 'sqlite':
// sqlite needs some special treatment as it cannot drop a column
return SQLiteQueryInterface.removeColumn.call(this, tableName, attributeName, options);
case 'mssql':
// mssql needs special treatment as it cannot drop a column with a default or foreign key constraint
return MSSSQLQueryInterface.removeColumn.call(this, tableName, attributeName, options);
case 'mysql':
// mysql needs special treatment as it cannot drop a column with a foreign key constraint
return MySQLQueryInterface.removeColumn.call(this, tableName, attributeName, options);
default:
var sql = this.QueryGenerator.removeColumnQuery(tableName, attributeName);
return this.sequelize.query(sql, options);
} }
};
QueryInterface.prototype.changeColumn = function(tableName, attributeName, dataTypeOrOptions, options) { showAllTables(options) {
var attributes = {}; options = _.assign({}, options, {
options = options || {}; raw: true,
type: QueryTypes.SHOWTABLES
});
if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) { const showTablesSql = this.QueryGenerator.showTablesQuery();
attributes[attributeName] = { type: dataTypeOrOptions, allowNull: true }; return this.sequelize.query(showTablesSql, options).then(tableNames => Utils._.flatten(tableNames));
} else {
attributes[attributeName] = dataTypeOrOptions;
} }
attributes[attributeName].type = this.sequelize.normalizeDataType(attributes[attributeName].type); describeTable(tableName, options) {
let schema = null;
let schemaDelimiter = null;
if (this.sequelize.options.dialect === 'sqlite') { if (typeof options === 'string') {
// sqlite needs some special treatment as it cannot change a column schema = options;
return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options); } else if (typeof options === 'object' && options !== null) {
} else { schema = options.schema || null;
var query = this.QueryGenerator.attributesToSQL(attributes) schemaDelimiter = options.schemaDelimiter || null;
, sql = this.QueryGenerator.changeColumnQuery(tableName, query); }
return this.sequelize.query(sql, options); if (typeof tableName === 'object' && tableName !== null) {
schema = tableName.schema;
tableName = tableName.tableName;
}
const sql = this.QueryGenerator.describeTableQuery(tableName, schema, schemaDelimiter);
return this.sequelize.query(
sql,
_.assign({}, options, { type: QueryTypes.DESCRIBE })
).then(data => {
// 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,
// it will not throw an error like built-ins do (e.g. DESCRIBE on MySql).
if (Utils._.isEmpty(data)) {
return Promise.reject('No description found for "' + tableName + '" table. Check the table name and schema; remember, they _are_ case sensitive.');
} else {
return Promise.resolve(data);
}
});
} }
};
QueryInterface.prototype.renameColumn = function(tableName, attrNameBefore, attrNameAfter, options) { addColumn(table, key, attribute, options) {
options = options || {}; if (!table || !key || !attribute) {
return this.describeTable(tableName, options).then(function(data) { throw new Error('addColumn takes atleast 3 arguments (table, attribute name, attribute definition)');
data = data[attrNameBefore] || {}; }
var _options = {}; options = options || {};
attribute = this.sequelize.normalizeAttribute(attribute);
return this.sequelize.query(this.QueryGenerator.addColumnQuery(table, key, attribute), options);
}
removeColumn(tableName, attributeName, options) {
options = options || {};
switch (this.sequelize.options.dialect) {
case 'sqlite':
// sqlite needs some special treatment as it cannot drop a column
return SQLiteQueryInterface.removeColumn.call(this, tableName, attributeName, options);
case 'mssql':
// mssql needs special treatment as it cannot drop a column with a default or foreign key constraint
return MSSSQLQueryInterface.removeColumn.call(this, tableName, attributeName, options);
case 'mysql':
// mysql needs special treatment as it cannot drop a column with a foreign key constraint
return MySQLQueryInterface.removeColumn.call(this, tableName, attributeName, options);
default:
return this.sequelize.query(this.QueryGenerator.removeColumnQuery(tableName, attributeName), options);
}
}
_options[attrNameAfter] = { changeColumn(tableName, attributeName, dataTypeOrOptions, options) {
attribute: attrNameAfter, const attributes = {};
type: data.type, options = options || {};
allowNull: data.allowNull,
defaultValue: data.defaultValue
};
// fix: a not-null column cannot have null as default value if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) {
if (data.defaultValue === null && !data.allowNull) { attributes[attributeName] = { type: dataTypeOrOptions, allowNull: true };
delete _options[attrNameAfter].defaultValue; } else {
attributes[attributeName] = dataTypeOrOptions;
} }
attributes[attributeName].type = this.sequelize.normalizeDataType(attributes[attributeName].type);
if (this.sequelize.options.dialect === 'sqlite') { if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot rename a column // sqlite needs some special treatment as it cannot change a column
return SQLiteQueryInterface.renameColumn.call(this, tableName, attrNameBefore, attrNameAfter, options); return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options);
} else { } else {
var sql = this.QueryGenerator.renameColumnQuery( const query = this.QueryGenerator.attributesToSQL(attributes);
tableName, const sql = this.QueryGenerator.changeColumnQuery(tableName, query);
attrNameBefore,
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) {
// Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes)
if (!Array.isArray(attributes)) {
rawTablename = options;
options = attributes;
attributes = options.fields;
} }
// testhint argsConform.end
if (!rawTablename) { renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
// Map for backwards compat options = options || {};
rawTablename = tableName; return this.describeTable(tableName, options).then(data => {
data = data[attrNameBefore] || {};
const _options = {};
_options[attrNameAfter] = {
attribute: attrNameAfter,
type: data.type,
allowNull: data.allowNull,
defaultValue: data.defaultValue
};
// fix: a not-null column cannot have null as default value
if (data.defaultValue === null && !data.allowNull) {
delete _options[attrNameAfter].defaultValue;
}
if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot rename a column
return SQLiteQueryInterface.renameColumn.call(this, tableName, attrNameBefore, attrNameAfter, options);
} else {
const sql = this.QueryGenerator.renameColumnQuery(
tableName,
attrNameBefore,
this.QueryGenerator.attributesToSQL(_options)
);
return this.sequelize.query(sql, options);
}
});
} }
options = Utils.cloneDeep(options); addIndex(tableName, attributes, options, rawTablename) {
options.fields = attributes; // Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes)
var sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename); if (!Array.isArray(attributes)) {
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false })); rawTablename = options;
}; options = attributes;
attributes = options.fields;
}
// testhint argsConform.end
QueryInterface.prototype.showIndex = function(tableName, options) { if (!rawTablename) {
var sql = this.QueryGenerator.showIndexesQuery(tableName, options); // Map for backwards compat
return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES })); rawTablename = tableName;
}; }
QueryInterface.prototype.nameIndexes = function(indexes, rawTablename) { options = Utils.cloneDeep(options);
return this.QueryGenerator.nameIndexes(indexes, rawTablename); options.fields = attributes;
}; const sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false }));
}
QueryInterface.prototype.getForeignKeysForTables = function(tableNames, options) { showIndex(tableName, options) {
var self = this; const sql = this.QueryGenerator.showIndexesQuery(tableName, options);
options = options || {}; return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
}
if (tableNames.length === 0) { nameIndexes(indexes, rawTablename) {
return Promise.resolve({}); return this.QueryGenerator.nameIndexes(indexes, rawTablename);
} }
return Promise.map(tableNames, function(tableName) { getForeignKeysForTables(tableNames, options) {
return self.sequelize.query(self.QueryGenerator.getForeignKeysQuery(tableName, self.sequelize.config.database), options).get(0); options = options || {};
}).then(function(results) {
var result = {};
tableNames.forEach(function(tableName, i) { if (tableNames.length === 0) {
if (Utils._.isObject(tableName)) { return Promise.resolve({});
tableName = tableName.schema + '.' + tableName.tableName; }
}
result[tableName] = Utils._.compact(results[i]).map(function(r) { return Promise.map(tableNames, tableName =>
return r.constraint_name; this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options).get(0)
}); ).then(results => {
}); const result = {};
return result; tableNames.forEach((tableName, i) => {
}); if (Utils._.isObject(tableName)) {
}; tableName = tableName.schema + '.' + tableName.tableName;
QueryInterface.prototype.removeIndex = function(tableName, indexNameOrAttributes, options) {
options = options || {};
var sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes);
return this.sequelize.query(sql, options);
};
QueryInterface.prototype.insert = function(instance, tableName, values, options) {
options = Utils.cloneDeep(options);
options.hasTrigger = instance && instance.constructor.options.hasTrigger;
var sql = this.QueryGenerator.insertQuery(tableName, values, instance && instance.constructor.rawAttributes, options);
options.type = QueryTypes.INSERT;
options.instance = instance;
return this.sequelize.query(sql, options).then(function(result) {
if (instance) result.isNewRecord = false;
return result;
});
};
QueryInterface.prototype.upsert = function(tableName, valuesByField, updateValues, where, model, options) {
var wheres = []
, indexFields
, indexes = []
, attributes = Object.keys(valuesByField);
options = _.clone(options);
if (!Utils._.isEmpty(where)) {
wheres.push(where);
}
// Lets combine uniquekeys and indexes into one
indexes = Utils._.map(model.options.uniqueKeys, function (value) {
return value.fields;
});
Utils._.each(model.options.indexes, function (value) {
if (value.unique === true) {
// fields in the index may both the strings or objects with an attribute property - lets sanitize that
indexFields = Utils._.map(value.fields, function (field) {
if (Utils._.isPlainObject(field)) {
return field.attribute;
} }
return field;
});
indexes.push(indexFields);
}
});
indexes.forEach(function (index) { result[tableName] = Utils._.compact(results[i]).map(r => r.constraint_name);
if (Utils._.intersection(attributes, index).length === index.length) {
where = {};
index.forEach(function (field) {
where[field] = valuesByField[field];
}); });
wheres.push(where);
}
});
where = { $or: wheres }; return result;
});
}
options.type = QueryTypes.UPSERT; removeIndex(tableName, indexNameOrAttributes, options) {
options.raw = true; options = options || {};
const sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes);
return this.sequelize.query(sql, options);
}
var sql = this.QueryGenerator.upsertQuery(tableName, valuesByField, updateValues, where, model.rawAttributes, options); insert(instance, tableName, values, options) {
return this.sequelize.query(sql, options).then(function (rowCount) { options = Utils.cloneDeep(options);
if (rowCount === undefined) { options.hasTrigger = instance && instance.constructor.options.hasTrigger;
return rowCount; const sql = this.QueryGenerator.insertQuery(tableName, values, instance && instance.constructor.rawAttributes, options);
}
// MySQL returns 1 for inserted, 2 for updated http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html. Postgres has been modded to do the same options.type = QueryTypes.INSERT;
options.instance = instance;
return rowCount === 1; return this.sequelize.query(sql, options).then(result => {
}); if (instance) result.isNewRecord = false;
}; return result;
});
}
QueryInterface.prototype.bulkInsert = function(tableName, records, options, attributes) { upsert(tableName, valuesByField, updateValues, where, model, options) {
options = _.clone(options) || {}; const wheres = [];
options.type = QueryTypes.INSERT; const attributes = Object.keys(valuesByField);
var sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes); let indexes = [];
return this.sequelize.query(sql, options); let indexFields;
};
QueryInterface.prototype.update = function(instance, tableName, values, identifier, options) { options = _.clone(options);
options = _.clone(options || {});
options.hasTrigger = !!(instance && instance.$modelOptions && instance.$modelOptions.hasTrigger);
if (!Utils._.isEmpty(where)) {
wheres.push(where);
}
var self = this // Lets combine uniquekeys and indexes into one
, restrict = false indexes = Utils._.map(model.options.uniqueKeys, value => {
, sql = self.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes); return value.fields;
});
Utils._.each(model.options.indexes, value => {
if (value.unique === true) {
// fields in the index may both the strings or objects with an attribute property - lets sanitize that
indexFields = Utils._.map(value.fields, field => {
if (Utils._.isPlainObject(field)) {
return field.attribute;
}
return field;
});
indexes.push(indexFields);
}
});
for (const index of indexes) {
if (Utils._.intersection(attributes, index).length === index.length) {
where = {};
for (const field of index) {
where[field] = valuesByField[field];
}
wheres.push(where);
}
}
options.type = QueryTypes.UPDATE; where = { $or: wheres };
// Check for a restrict field options.type = QueryTypes.UPSERT;
if (instance.constructor && instance.constructor.associations) { options.raw = true;
var keys = Object.keys(instance.constructor.associations)
, length = keys.length;
for (var i = 0; i < length; i++) { const sql = this.QueryGenerator.upsertQuery(tableName, valuesByField, updateValues, where, model.rawAttributes, options);
if (instance.constructor.associations[keys[i]].options && instance.constructor.associations[keys[i]].options.onUpdate && instance.constructor.associations[keys[i]].options.onUpdate === 'restrict') { return this.sequelize.query(sql, options).then(rowCount => {
restrict = true; if (rowCount === undefined) {
return rowCount;
} }
}
}
options.instance = instance; // MySQL returns 1 for inserted, 2 for updated http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html. Postgres has been modded to do the same
return this.sequelize.query(sql, options);
};
QueryInterface.prototype.bulkUpdate = function(tableName, values, identifier, options, attributes) { return rowCount === 1;
options = Utils.cloneDeep(options); });
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier); }
var sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, attributes) bulkInsert(tableName, records, options, attributes) {
, table = Utils._.isObject(tableName) ? tableName : { tableName: tableName } options = _.clone(options) || {};
, model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName }); options.type = QueryTypes.INSERT;
const sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes);
return this.sequelize.query(sql, options);
}
options.model = model; update(instance, tableName, values, identifier, options) {
return this.sequelize.query(sql, options); options = _.clone(options || {});
}; options.hasTrigger = !!(instance && instance.$modelOptions && instance.$modelOptions.hasTrigger);
QueryInterface.prototype.delete = function(instance, tableName, identifier, options) {
var self = this
, cascades = []
, sql = self.QueryGenerator.deleteQuery(tableName, identifier, null, instance.constructor);
options = _.clone(options) || {}; const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes);
let restrict = false;
// Check for a restrict field options.type = QueryTypes.UPDATE;
if (!!instance.constructor && !!instance.constructor.associations) {
var keys = Object.keys(instance.constructor.associations)
, length = keys.length
, association;
for (var i = 0; i < length; i++) { // Check for a restrict field
association = instance.constructor.associations[keys[i]]; if (instance.constructor && instance.constructor.associations) {
if (association.options && association.options.onDelete && const keys = Object.keys(instance.constructor.associations);
association.options.onDelete.toLowerCase() === 'cascade' && const length = keys.length;
association.options.useHooks === true) {
cascades.push(association.accessors.get);
}
}
}
return Promise.each(cascades, function (cascade) { for (let i = 0; i < length; i++) {
return instance[cascade](options).then(function (instances) { if (instance.constructor.associations[keys[i]].options && instance.constructor.associations[keys[i]].options.onUpdate && instance.constructor.associations[keys[i]].options.onUpdate === 'restrict') {
// Check for hasOne relationship with non-existing associate ("has zero") restrict = true;
if (!instances) { }
return Promise.resolve();
} }
}
if (!Array.isArray(instances)) instances = [instances];
return Promise.each(instances, function (instance) {
return instance.destroy(options);
});
});
}).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) {
options = Utils.cloneDeep(options);
options = _.defaults(options, {limit: null});
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
var sql = this.QueryGenerator.deleteQuery(tableName, identifier, options, model);
return this.sequelize.query(sql, options);
};
QueryInterface.prototype.select = function(model, tableName, options) {
options = Utils.cloneDeep(options);
options.type = QueryTypes.SELECT;
options.model = model;
return this.sequelize.query(
this.QueryGenerator.selectQuery(tableName, options, model),
options
);
};
QueryInterface.prototype.increment = function(instance, tableName, values, identifier, options) {
var sql = this.QueryGenerator.incrementQuery(tableName, values, identifier, options.attributes);
options = _.clone(options) || {};
options.type = QueryTypes.UPDATE;
options.instance = instance;
return this.sequelize.query(sql, options);
};
QueryInterface.prototype.rawSelect = function(tableName, options, attributeSelector, Model) {
if (options.schema) {
tableName = this.QueryGenerator.addSchema({
tableName: tableName,
$schema: options.schema
});
} }
options = Utils.cloneDeep(options); bulkUpdate(tableName, values, identifier, options, attributes) {
options = _.defaults(options, { options = Utils.cloneDeep(options);
raw: true, if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
plain: true,
type: QueryTypes.SELECT
});
var sql = this.QueryGenerator.selectQuery(tableName, options, Model); const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, attributes);
const table = Utils._.isObject(tableName) ? tableName : { tableName };
const model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName });
if (attributeSelector === undefined) { options.model = model;
throw new Error('Please pass an attribute selector!'); return this.sequelize.query(sql, options);
} }
return this.sequelize.query(sql, options).then(function(data) { delete(instance, tableName, identifier, options) {
if (!options.plain) { const cascades = [];
return data; const sql = this.QueryGenerator.deleteQuery(tableName, identifier, null, instance.constructor);
}
var result = data ? data[attributeSelector] : null; options = _.clone(options) || {};
if (options && options.dataType) { // Check for a restrict field
var dataType = options.dataType; if (!!instance.constructor && !!instance.constructor.associations) {
const keys = Object.keys(instance.constructor.associations);
const length = keys.length;
let association;
if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) { for (let i = 0; i < length; i++) {
result = parseFloat(result); association = instance.constructor.associations[keys[i]];
} else if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) { if (association.options && association.options.onDelete &&
result = parseInt(result, 10); association.options.onDelete.toLowerCase() === 'cascade' &&
} else if (dataType instanceof DataTypes.DATE) { association.options.useHooks === true) {
if (!Utils._.isNull(result) && !Utils._.isDate(result)) { cascades.push(association.accessors.get);
result = new Date(result);
} }
} else if (dataType instanceof DataTypes.STRING) {
// Nothing to do, result is already a string.
} }
} }
return result; return Promise.each(cascades, cascade => {
}); return instance[cascade](options).then(instances => {
}; // Check for hasOne relationship with non-existing associate ("has zero")
if (!instances) {
return Promise.resolve();
}
QueryInterface.prototype.createTrigger = function(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray, options) { if (!Array.isArray(instances)) instances = [instances];
var sql = this.QueryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray);
options = options || {}; return Promise.each(instances, instance => instance.destroy(options));
if (sql) { });
return this.sequelize.query(sql, options); }).then(() => {
} else { options.instance = instance;
return Promise.resolve(); return this.sequelize.query(sql, options);
});
} }
};
QueryInterface.prototype.dropTrigger = function(tableName, triggerName, options) { bulkDelete(tableName, identifier, options, model) {
var sql = this.QueryGenerator.dropTrigger(tableName, triggerName); options = Utils.cloneDeep(options);
options = options || {}; options = _.defaults(options, {limit: null});
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
if (sql) { const sql = this.QueryGenerator.deleteQuery(tableName, identifier, options, model);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
} }
};
QueryInterface.prototype.renameTrigger = function(tableName, oldTriggerName, newTriggerName, options) { select(model, tableName, options) {
var sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName); options = Utils.cloneDeep(options);
options = options || {}; options.type = QueryTypes.SELECT;
options.model = model;
if (sql) { return this.sequelize.query(
return this.sequelize.query(sql, options); this.QueryGenerator.selectQuery(tableName, options, model),
} else { options
return Promise.resolve(); );
} }
};
QueryInterface.prototype.createFunction = function(functionName, params, returnType, language, body, options) { increment(instance, tableName, values, identifier, options) {
var sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options); const sql = this.QueryGenerator.incrementQuery(tableName, values, identifier, options.attributes);
options = options || {};
options = _.clone(options) || {};
if (sql) { options.type = QueryTypes.UPDATE;
options.instance = instance;
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
} }
};
QueryInterface.prototype.dropFunction = function(functionName, params, options) { rawSelect(tableName, options, attributeSelector, Model) {
var sql = this.QueryGenerator.dropFunction(functionName, params); if (options.schema) {
options = options || {}; tableName = this.QueryGenerator.addSchema({
tableName,
$schema: options.schema
});
}
if (sql) { options = Utils.cloneDeep(options);
return this.sequelize.query(sql, options); options = _.defaults(options, {
} else { raw: true,
return Promise.resolve(); plain: true,
} type: QueryTypes.SELECT
}; });
QueryInterface.prototype.renameFunction = function(oldFunctionName, params, newFunctionName, options) { const sql = this.QueryGenerator.selectQuery(tableName, options, Model);
var sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
options = options || {};
if (sql) { if (attributeSelector === undefined) {
return this.sequelize.query(sql, options); throw new Error('Please pass an attribute selector!');
} else { }
return Promise.resolve();
return this.sequelize.query(sql, options).then(data => {
if (!options.plain) {
return data;
}
let result = data ? data[attributeSelector] : null;
if (options && options.dataType) {
const dataType = options.dataType;
if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
result = parseFloat(result);
} else if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
result = parseInt(result, 10);
} else if (dataType instanceof DataTypes.DATE) {
if (!Utils._.isNull(result) && !Utils._.isDate(result)) {
result = new Date(result);
}
} else if (dataType instanceof DataTypes.STRING) {
// Nothing to do, result is already a string.
}
}
return result;
});
} }
};
// Helper methods useful for querying createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray, options) {
const sql = this.QueryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
/** dropTrigger(tableName, triggerName, options) {
* Escape an identifier (e.g. a table or attribute name). If force is true, const sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
* the identifier will be quoted even if the `quoteIdentifiers` option is options = options || {};
* false.
*/
QueryInterface.prototype.quoteIdentifier = function(identifier, force) {
return this.QueryGenerator.quoteIdentifier(identifier, force);
};
QueryInterface.prototype.quoteTable = function(identifier) { if (sql) {
return this.QueryGenerator.quoteTable(identifier); return this.sequelize.query(sql, options);
}; } else {
return Promise.resolve();
}
}
/** renameTrigger(tableName, oldTriggerName, newTriggerName, options) {
* Split an identifier into .-separated tokens and quote each part. const sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName);
* If force is true, the identifier will be quoted even if the options = options || {};
* `quoteIdentifiers` option is false.
*/
QueryInterface.prototype.quoteIdentifiers = function(identifiers, force) {
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
};
/** if (sql) {
* Escape a value (e.g. a string, number or date) return this.sequelize.query(sql, options);
*/ } else {
QueryInterface.prototype.escape = function(value) { return Promise.resolve();
return this.QueryGenerator.escape(value); }
}; }
createFunction(functionName, params, returnType, language, body, options) {
const sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options);
options = options || {};
QueryInterface.prototype.setAutocommit = function(transaction, value, options) { if (sql) {
if (!transaction || !(transaction instanceof Transaction)) { return this.sequelize.query(sql, options);
throw new Error('Unable to set autocommit for a transaction without transaction object!'); } else {
return Promise.resolve();
}
} }
if (transaction.parent) {
// Not possible to set a seperate isolation level for savepoints dropFunction(functionName, params, options) {
return Promise.resolve(); const sql = this.QueryGenerator.dropFunction(functionName, params);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
} }
options = _.assign({}, options, { renameFunction(oldFunctionName, params, newFunctionName, options) {
transaction: transaction.parent || transaction const sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
}); options = options || {};
var sql = this.QueryGenerator.setAutocommitQuery(value, { if (sql) {
parent: transaction.parent return this.sequelize.query(sql, options);
}); } else {
return Promise.resolve();
}
}
if (!sql) return Promise.resolve(); // Helper methods useful for querying
return this.sequelize.query(sql, options); /**
}; * 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
* false.
*/
quoteIdentifier(identifier, force) {
return this.QueryGenerator.quoteIdentifier(identifier, force);
}
QueryInterface.prototype.setIsolationLevel = function(transaction, value, options) { quoteTable(identifier) {
if (!transaction || !(transaction instanceof Transaction)) { return this.QueryGenerator.quoteTable(identifier);
throw new Error('Unable to set isolation level for a transaction without transaction object!');
} }
if (transaction.parent || !value) { /**
// Not possible to set a seperate isolation level for savepoints * Split an identifier into .-separated tokens and quote each part.
return Promise.resolve(); * If force is true, the identifier will be quoted even if the
* `quoteIdentifiers` option is false.
*/
quoteIdentifiers(identifiers, force) {
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
} }
options = _.assign({}, options, { /**
transaction: transaction.parent || transaction * Escape a value (e.g. a string, number or date)
}); */
escape(value) {
return this.QueryGenerator.escape(value);
}
setAutocommit(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set autocommit for a transaction without transaction object!');
}
if (transaction.parent) {
// Not possible to set a seperate isolation level for savepoints
return Promise.resolve();
}
var sql = this.QueryGenerator.setIsolationLevelQuery(value, { options = _.assign({}, options, {
parent: transaction.parent transaction: transaction.parent || transaction
}); });
if (!sql) return Promise.resolve(); const sql = this.QueryGenerator.setAutocommitQuery(value, {
parent: transaction.parent
});
return this.sequelize.query(sql, options); if (!sql) return Promise.resolve();
};
QueryInterface.prototype.startTransaction = function(transaction, options) { return this.sequelize.query(sql, options);
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to start a transaction without transaction object!');
} }
options = _.assign({}, options, { setIsolationLevel(transaction, value, options) {
transaction: transaction.parent || transaction if (!transaction || !(transaction instanceof Transaction)) {
}); throw new Error('Unable to set isolation level for a transaction without transaction object!');
}
var sql = this.QueryGenerator.startTransactionQuery(transaction); if (transaction.parent || !value) {
// Not possible to set a seperate isolation level for savepoints
return Promise.resolve();
}
return this.sequelize.query(sql, options); options = _.assign({}, options, {
}; transaction: transaction.parent || transaction
});
QueryInterface.prototype.deferConstraints = function (transaction, options) { const sql = this.QueryGenerator.setIsolationLevelQuery(value, {
options = _.assign({}, options, { parent: transaction.parent
transaction: transaction.parent || transaction });
});
var sql = this.QueryGenerator.deferConstraintsQuery(options); if (!sql) return Promise.resolve();
if (sql) {
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} }
return Promise.resolve(); startTransaction(transaction, options) {
}; if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to start a transaction without transaction object!');
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
const sql = this.QueryGenerator.startTransactionQuery(transaction);
QueryInterface.prototype.commitTransaction = function(transaction, options) { return this.sequelize.query(sql, options);
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to commit a transaction without transaction object!');
} }
if (transaction.parent) {
// Savepoints cannot be committed deferConstraints(transaction, options) {
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
const sql = this.QueryGenerator.deferConstraintsQuery(options);
if (sql) {
return this.sequelize.query(sql, options);
}
return Promise.resolve(); return Promise.resolve();
} }
options = _.assign({}, options, { commitTransaction(transaction, options) {
transaction: transaction.parent || transaction, if (!transaction || !(transaction instanceof Transaction)) {
supportsSearchPath: false throw new Error('Unable to commit a transaction without transaction object!');
}); }
if (transaction.parent) {
// Savepoints cannot be committed
return Promise.resolve();
}
var sql = this.QueryGenerator.commitTransactionQuery(transaction); options = _.assign({}, options, {
var promise = this.sequelize.query(sql, options); transaction: transaction.parent || transaction,
supportsSearchPath: false
});
transaction.finished = 'commit'; const sql = this.QueryGenerator.commitTransactionQuery(transaction);
const promise = this.sequelize.query(sql, options);
return promise; transaction.finished = 'commit';
};
QueryInterface.prototype.rollbackTransaction = function(transaction, options) { return promise;
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to rollback a transaction without transaction object!');
} }
options = _.assign({}, options, { rollbackTransaction(transaction, options) {
transaction: transaction.parent || transaction, if (!transaction || !(transaction instanceof Transaction)) {
supportsSearchPath: false throw new Error('Unable to rollback a transaction without transaction object!');
}); }
var sql = this.QueryGenerator.rollbackTransactionQuery(transaction); options = _.assign({}, options, {
var promise = this.sequelize.query(sql, options); transaction: transaction.parent || transaction,
supportsSearchPath: false
});
const sql = this.QueryGenerator.rollbackTransactionQuery(transaction);
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!