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

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';
var Utils = require('./utils')
, _ = require('lodash')
, DataTypes = require('./data-types')
, SQLiteQueryInterface = require('./dialects/sqlite/query-interface')
, MSSSQLQueryInterface = require('./dialects/mssql/query-interface')
, MySQLQueryInterface = require('./dialects/mysql/query-interface')
, Transaction = require('./transaction')
, Promise = require('./promise')
, QueryTypes = require('./query-types');
/*
const Utils = require('./utils');
const _ = require('lodash');
const DataTypes = require('./data-types');
const SQLiteQueryInterface = require('./dialects/sqlite/query-interface');
const MSSSQLQueryInterface = require('./dialects/mssql/query-interface');
const MySQLQueryInterface = require('./dialects/mysql/query-interface');
const Transaction = require('./transaction');
const Promise = require('./promise');
const QueryTypes = require('./query-types');
/**
* The interface that Sequelize uses to talk to all databases
* @class QueryInterface
**/
var QueryInterface = function(sequelize) {
this.sequelize = sequelize;
this.QueryGenerator = this.sequelize.dialect.QueryGenerator;
};
QueryInterface.prototype.createSchema = function(schema, options) {
options = options || {};
var sql = this.QueryGenerator.createSchema(schema);
return this.sequelize.query(sql, options);
};
QueryInterface.prototype.dropSchema = function(schema, options) {
options = options || {};
var sql = this.QueryGenerator.dropSchema(schema);
return this.sequelize.query(sql, options);
};
QueryInterface.prototype.dropAllSchemas = function(options) {
options = options || {};
var self = this;
if (!this.QueryGenerator._dialect.supports.schemas) {
return this.sequelize.drop(options);
} else {
return this.showAllSchemas(options).map(function(schemaName) {
return self.dropSchema(schemaName, options);
});
*/
class QueryInterface {
constructor(sequelize) {
this.sequelize = sequelize;
this.QueryGenerator = this.sequelize.dialect.QueryGenerator;
}
createSchema(schema, options) {
options = options || {};
const sql = this.QueryGenerator.createSchema(schema);
return this.sequelize.query(sql, options);
}
dropSchema(schema, options) {
options = options || {};
const sql = this.QueryGenerator.dropSchema(schema);
return this.sequelize.query(sql, options);
}
dropAllSchemas(options) {
options = options || {};
if (!this.QueryGenerator._dialect.supports.schemas) {
return this.sequelize.drop(options);
} else {
return this.showAllSchemas(options).map(schemaName => this.dropSchema(schemaName, options));
}
}
};
QueryInterface.prototype.showAllSchemas = function(options) {
var self = this;
showAllSchemas(options) {
options = _.assign({}, options, {
raw: true,
type: this.sequelize.QueryTypes.SELECT
});
options = _.assign({}, options, {
raw: true,
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 Utils._.flatten(
Utils._.map(schemaNames, function(value) {
return (!!value.schema_name ? value.schema_name : value);
})
return this.sequelize.query(showSchemasSql, options).then(schemaNames => Utils._.flatten(
Utils._.map(schemaNames, value => (!!value.schema_name ? value.schema_name : value))
));
}
databaseVersion(options) {
return this.sequelize.query(
this.QueryGenerator.versionQuery(),
_.assign({}, options, { type: QueryTypes.VERSION })
);
});
};
QueryInterface.prototype.databaseVersion = function(options) {
return this.sequelize.query(
this.QueryGenerator.versionQuery(),
_.assign({}, options, { type: QueryTypes.VERSION })
);
};
QueryInterface.prototype.createTable = function(tableName, attributes, options, model) {
var keys = Object.keys(attributes)
, keyLen = keys.length
, 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 })
));
}
createTable(tableName, attributes, options, model) {
const keys = Object.keys(attributes);
const keyLen = keys.length;
let sql = '';
let i = 0;
options = _.clone(options) || {};
attributes = Utils._.mapValues(attributes, attribute => {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute, allowNull: true };
}
}
return Promise.all(promises).then(function(results) {
var promises = []
, enumIdx = 0;
attribute = this.sequelize.normalizeAttribute(attribute);
return attribute;
});
// Postgres requires a special SQL command for enums
if (this.sequelize.options.dialect === 'postgres') {
const promises = [];
for (i = 0; i < keyLen; i++) {
if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
// If the enum type doesn't exist then create it
if (!results[enumIdx]) {
sql = self.QueryGenerator.pgEnum(tableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options);
promises.push(self.sequelize.query(
sql,
_.assign({}, options, { raw: true })
));
} else if (!!results[enumIdx] && !!model) {
var enumVals = self.QueryGenerator.fromArray(results[enumIdx].enum_value)
, vals = model.rawAttributes[keys[i]].values;
vals.forEach(function(value, idx) {
// reset out after/before options since it's for every enum value
var 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];
sql = this.QueryGenerator.pgListEnums(tableName, attributes[keys[i]].field || keys[i], options);
promises.push(this.sequelize.query(
sql,
_.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT })
));
}
}
return Promise.all(promises).then(results => {
const promises = [];
let enumIdx = 0;
for (i = 0; i < keyLen; i++) {
if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
// If the enum type doesn't exist then create it
if (!results[enumIdx]) {
sql = this.QueryGenerator.pgEnum(tableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options);
promises.push(this.sequelize.query(
sql,
_.assign({}, options, { raw: true })
));
} else if (!!results[enumIdx] && !!model) {
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 &&
(options.schema || (!!model && model.$schema))) {
tableName = self.QueryGenerator.addSchema({
tableName: tableName,
tableName = this.QueryGenerator.addSchema({
tableName,
$schema: (!!model && model.$schema) || options.schema
});
}
attributes = self.QueryGenerator.attributesToSQL(attributes, {
attributes = this.QueryGenerator.attributesToSQL(attributes, {
context: 'createTable'
});
sql = self.QueryGenerator.createTableQuery(tableName, attributes, options);
sql = this.QueryGenerator.createTableQuery(tableName, attributes, options);
return Promise.all(promises).then(function() {
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
});
return this.sequelize.query(sql, options);
}
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) {
// if we're forcing we should be cascading unless explicitly stated otherwise
options = _.clone(options) || {};
options.cascade = options.cascade || options.force || false;
dropTable(tableName, options) {
// if we're forcing we should be cascading unless explicitly stated otherwise
options = _.clone(options) || {};
options.cascade = options.cascade || options.force || false;
var sql = this.QueryGenerator.dropTableQuery(tableName, options)
, self = this;
let sql = this.QueryGenerator.dropTableQuery(tableName, options);
return this.sequelize.query(sql, options).then(function() {
var promises = [];
return this.sequelize.query(sql, options).then(() => {
const promises = [];
// Since postgres has a special case for enums, we should drop the related
// enum type within the table and attribute
if (self.sequelize.options.dialect === 'postgres') {
var instanceTable = self.sequelize.modelManager.getModel(tableName, { attribute: 'tableName' });
// Since postgres has a special case for enums, we should drop the related
// enum type within the table and attribute
if (this.sequelize.options.dialect === 'postgres') {
const instanceTable = this.sequelize.modelManager.getModel(tableName, { attribute: 'tableName' });
if (!!instanceTable) {
var getTableName = (!options || !options.schema || options.schema === 'public' ? '' : options.schema + '_') + tableName;
if (!!instanceTable) {
const getTableName = (!options || !options.schema || options.schema === 'public' ? '' : options.schema + '_') + tableName;
var keys = Object.keys(instanceTable.rawAttributes)
, keyLen = keys.length
, i = 0;
const keys = Object.keys(instanceTable.rawAttributes);
const keyLen = keys.length;
for (i = 0; i < keyLen; i++) {
if (instanceTable.rawAttributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = self.QueryGenerator.pgEnumDrop(getTableName, keys[i]);
options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true })));
for (let i = 0; i < keyLen; i++) {
if (instanceTable.rawAttributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = this.QueryGenerator.pgEnumDrop(getTableName, keys[i]);
options.supportsSearchPath = false;
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) {
var self = this
, skip;
dropAllTables(options) {
options = options || {};
skip = options.skip || [];
options = options || {};
const skip = options.skip || [];
var dropAllTables = function(tableNames) {
return Promise.each(tableNames, function(tableName) {
const dropAllTables = tableNames => Promise.each(tableNames, tableName => {
// if tableName is not in the Array of tables names then dont drop it
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) {
if (self.sequelize.options.dialect === 'sqlite') {
return self.sequelize.query('PRAGMA foreign_keys;', options).then(function(result) {
var foreignKeysAreEnabled = result.foreign_keys === 1;
if (foreignKeysAreEnabled) {
return self.sequelize.query('PRAGMA foreign_keys = OFF', options).then(function() {
return dropAllTables(tableNames).then(function() {
return self.sequelize.query('PRAGMA foreign_keys = ON', options);
return this.showAllTables(options).then(tableNames => {
if (this.sequelize.options.dialect === 'sqlite') {
return this.sequelize.query('PRAGMA foreign_keys;', options).then(result => {
const foreignKeysAreEnabled = result.foreign_keys === 1;
if (foreignKeysAreEnabled) {
return this.sequelize.query('PRAGMA foreign_keys = OFF', options)
.then(() => dropAllTables(tableNames))
.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) {
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(() => dropAllTables(tableNames));
});
}
});
}
return Promise.all(promises).then(function() {
return dropAllTables(tableNames);
});
});
dropAllEnums(options) {
if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve();
}
});
};
QueryInterface.prototype.dropAllEnums = function(options) {
if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve();
}
options = options || {};
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) {
return self.sequelize.query(
self.QueryGenerator.pgEnumDrop(null, null, self.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
_.assign({}, options, { raw: true })
);
});
};
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);
renameTable(before, after, options) {
options = options || {};
const sql = this.QueryGenerator.renameTableQuery(before, after);
return this.sequelize.query(sql, options);
}
};
QueryInterface.prototype.changeColumn = function(tableName, attributeName, dataTypeOrOptions, options) {
var attributes = {};
options = options || {};
showAllTables(options) {
options = _.assign({}, options, {
raw: true,
type: QueryTypes.SHOWTABLES
});
if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) {
attributes[attributeName] = { type: dataTypeOrOptions, allowNull: true };
} else {
attributes[attributeName] = dataTypeOrOptions;
const showTablesSql = this.QueryGenerator.showTablesQuery();
return this.sequelize.query(showTablesSql, options).then(tableNames => Utils._.flatten(tableNames));
}
attributes[attributeName].type = this.sequelize.normalizeDataType(attributes[attributeName].type);
describeTable(tableName, options) {
let schema = null;
let schemaDelimiter = null;
if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot change a column
return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options);
} else {
var query = this.QueryGenerator.attributesToSQL(attributes)
, sql = this.QueryGenerator.changeColumnQuery(tableName, query);
if (typeof options === 'string') {
schema = options;
} else if (typeof options === 'object' && options !== null) {
schema = options.schema || null;
schemaDelimiter = options.schemaDelimiter || null;
}
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) {
options = options || {};
return this.describeTable(tableName, options).then(function(data) {
data = data[attrNameBefore] || {};
addColumn(table, key, attribute, options) {
if (!table || !key || !attribute) {
throw new Error('addColumn takes atleast 3 arguments (table, attribute name, attribute definition)');
}
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] = {
attribute: attrNameAfter,
type: data.type,
allowNull: data.allowNull,
defaultValue: data.defaultValue
};
changeColumn(tableName, attributeName, dataTypeOrOptions, options) {
const attributes = {};
options = options || {};
// fix: a not-null column cannot have null as default value
if (data.defaultValue === null && !data.allowNull) {
delete _options[attrNameAfter].defaultValue;
if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) {
attributes[attributeName] = { type: dataTypeOrOptions, allowNull: true };
} else {
attributes[attributeName] = dataTypeOrOptions;
}
attributes[attributeName].type = this.sequelize.normalizeDataType(attributes[attributeName].type);
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);
// sqlite needs some special treatment as it cannot change a column
return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options);
} else {
var sql = this.QueryGenerator.renameColumnQuery(
tableName,
attrNameBefore,
this.QueryGenerator.attributesToSQL(_options)
);
const query = this.QueryGenerator.attributesToSQL(attributes);
const sql = this.QueryGenerator.changeColumnQuery(tableName, query);
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) {
// Map for backwards compat
rawTablename = tableName;
renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
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);
options.fields = attributes;
var sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false }));
};
addIndex(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
QueryInterface.prototype.showIndex = function(tableName, options) {
var sql = this.QueryGenerator.showIndexesQuery(tableName, options);
return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
};
if (!rawTablename) {
// Map for backwards compat
rawTablename = tableName;
}
QueryInterface.prototype.nameIndexes = function(indexes, rawTablename) {
return this.QueryGenerator.nameIndexes(indexes, rawTablename);
};
options = Utils.cloneDeep(options);
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) {
var self = this;
options = options || {};
showIndex(tableName, options) {
const sql = this.QueryGenerator.showIndexesQuery(tableName, options);
return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
}
if (tableNames.length === 0) {
return Promise.resolve({});
nameIndexes(indexes, rawTablename) {
return this.QueryGenerator.nameIndexes(indexes, rawTablename);
}
return Promise.map(tableNames, function(tableName) {
return self.sequelize.query(self.QueryGenerator.getForeignKeysQuery(tableName, self.sequelize.config.database), options).get(0);
}).then(function(results) {
var result = {};
getForeignKeysForTables(tableNames, options) {
options = options || {};
tableNames.forEach(function(tableName, i) {
if (Utils._.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
if (tableNames.length === 0) {
return Promise.resolve({});
}
result[tableName] = Utils._.compact(results[i]).map(function(r) {
return r.constraint_name;
});
});
return Promise.map(tableNames, tableName =>
this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options).get(0)
).then(results => {
const result = {};
return result;
});
};
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;
tableNames.forEach((tableName, i) => {
if (Utils._.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
return field;
});
indexes.push(indexFields);
}
});
indexes.forEach(function (index) {
if (Utils._.intersection(attributes, index).length === index.length) {
where = {};
index.forEach(function (field) {
where[field] = valuesByField[field];
result[tableName] = Utils._.compact(results[i]).map(r => r.constraint_name);
});
wheres.push(where);
}
});
where = { $or: wheres };
return result;
});
}
options.type = QueryTypes.UPSERT;
options.raw = true;
removeIndex(tableName, indexNameOrAttributes, options) {
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);
return this.sequelize.query(sql, options).then(function (rowCount) {
if (rowCount === undefined) {
return rowCount;
}
insert(instance, tableName, values, options) {
options = Utils.cloneDeep(options);
options.hasTrigger = instance && instance.constructor.options.hasTrigger;
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) {
options = _.clone(options) || {};
options.type = QueryTypes.INSERT;
var sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes);
return this.sequelize.query(sql, options);
};
upsert(tableName, valuesByField, updateValues, where, model, options) {
const wheres = [];
const attributes = Object.keys(valuesByField);
let indexes = [];
let indexFields;
QueryInterface.prototype.update = function(instance, tableName, values, identifier, options) {
options = _.clone(options || {});
options.hasTrigger = !!(instance && instance.$modelOptions && instance.$modelOptions.hasTrigger);
options = _.clone(options);
if (!Utils._.isEmpty(where)) {
wheres.push(where);
}
var self = this
, restrict = false
, sql = self.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes);
// Lets combine uniquekeys and indexes into one
indexes = Utils._.map(model.options.uniqueKeys, value => {
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
if (instance.constructor && instance.constructor.associations) {
var keys = Object.keys(instance.constructor.associations)
, length = keys.length;
options.type = QueryTypes.UPSERT;
options.raw = true;
for (var 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') {
restrict = true;
const sql = this.QueryGenerator.upsertQuery(tableName, valuesByField, updateValues, where, model.rawAttributes, options);
return this.sequelize.query(sql, options).then(rowCount => {
if (rowCount === undefined) {
return rowCount;
}
}
}
options.instance = instance;
return this.sequelize.query(sql, 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
QueryInterface.prototype.bulkUpdate = function(tableName, values, identifier, options, attributes) {
options = Utils.cloneDeep(options);
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
return rowCount === 1;
});
}
var sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, attributes)
, table = Utils._.isObject(tableName) ? tableName : { tableName: tableName }
, model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName });
bulkInsert(tableName, records, options, attributes) {
options = _.clone(options) || {};
options.type = QueryTypes.INSERT;
const sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes);
return this.sequelize.query(sql, options);
}
options.model = model;
return this.sequelize.query(sql, options);
};
update(instance, tableName, values, identifier, 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
if (!!instance.constructor && !!instance.constructor.associations) {
var keys = Object.keys(instance.constructor.associations)
, length = keys.length
, association;
options.type = QueryTypes.UPDATE;
for (var i = 0; i < length; i++) {
association = instance.constructor.associations[keys[i]];
if (association.options && association.options.onDelete &&
association.options.onDelete.toLowerCase() === 'cascade' &&
association.options.useHooks === true) {
cascades.push(association.accessors.get);
}
}
}
// Check for a restrict field
if (instance.constructor && instance.constructor.associations) {
const keys = Object.keys(instance.constructor.associations);
const length = keys.length;
return Promise.each(cascades, function (cascade) {
return instance[cascade](options).then(function (instances) {
// Check for hasOne relationship with non-existing associate ("has zero")
if (!instances) {
return Promise.resolve();
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') {
restrict = true;
}
}
}
if (!Array.isArray(instances)) instances = [instances];
return Promise.each(instances, function (instance) {
return instance.destroy(options);
});
});
}).then(function () {
options.instance = instance;
return self.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
});
return this.sequelize.query(sql, options);
}
options = Utils.cloneDeep(options);
options = _.defaults(options, {
raw: true,
plain: true,
type: QueryTypes.SELECT
});
bulkUpdate(tableName, values, identifier, options, attributes) {
options = Utils.cloneDeep(options);
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
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) {
throw new Error('Please pass an attribute selector!');
options.model = model;
return this.sequelize.query(sql, options);
}
return this.sequelize.query(sql, options).then(function(data) {
if (!options.plain) {
return data;
}
delete(instance, tableName, identifier, options) {
const cascades = [];
const sql = this.QueryGenerator.deleteQuery(tableName, identifier, null, instance.constructor);
var result = data ? data[attributeSelector] : null;
options = _.clone(options) || {};
if (options && options.dataType) {
var dataType = options.dataType;
// Check for a restrict field
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) {
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);
for (let i = 0; i < length; i++) {
association = instance.constructor.associations[keys[i]];
if (association.options && association.options.onDelete &&
association.options.onDelete.toLowerCase() === 'cascade' &&
association.options.useHooks === true) {
cascades.push(association.accessors.get);
}
} 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) {
var 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();
if (!Array.isArray(instances)) instances = [instances];
return Promise.each(instances, instance => instance.destroy(options));
});
}).then(() => {
options.instance = instance;
return this.sequelize.query(sql, options);
});
}
};
QueryInterface.prototype.dropTrigger = function(tableName, triggerName, options) {
var sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
options = options || {};
bulkDelete(tableName, identifier, options, model) {
options = Utils.cloneDeep(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);
} else {
return Promise.resolve();
}
};
QueryInterface.prototype.renameTrigger = function(tableName, oldTriggerName, newTriggerName, options) {
var sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName);
options = options || {};
select(model, tableName, options) {
options = Utils.cloneDeep(options);
options.type = QueryTypes.SELECT;
options.model = model;
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
return this.sequelize.query(
this.QueryGenerator.selectQuery(tableName, options, model),
options
);
}
};
QueryInterface.prototype.createFunction = function(functionName, params, returnType, language, body, options) {
var sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options);
options = options || {};
increment(instance, tableName, values, identifier, options) {
const sql = this.QueryGenerator.incrementQuery(tableName, values, identifier, options.attributes);
options = _.clone(options) || {};
if (sql) {
options.type = QueryTypes.UPDATE;
options.instance = instance;
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
};
QueryInterface.prototype.dropFunction = function(functionName, params, options) {
var sql = this.QueryGenerator.dropFunction(functionName, params);
options = options || {};
rawSelect(tableName, options, attributeSelector, Model) {
if (options.schema) {
tableName = this.QueryGenerator.addSchema({
tableName,
$schema: options.schema
});
}
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
};
options = Utils.cloneDeep(options);
options = _.defaults(options, {
raw: true,
plain: true,
type: QueryTypes.SELECT
});
QueryInterface.prototype.renameFunction = function(oldFunctionName, params, newFunctionName, options) {
var sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
options = options || {};
const sql = this.QueryGenerator.selectQuery(tableName, options, Model);
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
if (attributeSelector === undefined) {
throw new Error('Please pass an attribute selector!');
}
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();
}
}
/**
* 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.
*/
QueryInterface.prototype.quoteIdentifier = function(identifier, force) {
return this.QueryGenerator.quoteIdentifier(identifier, force);
};
dropTrigger(tableName, triggerName, options) {
const sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
options = options || {};
QueryInterface.prototype.quoteTable = function(identifier) {
return this.QueryGenerator.quoteTable(identifier);
};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
/**
* Split an identifier into .-separated tokens and quote each part.
* If force is true, the identifier will be quoted even if the
* `quoteIdentifiers` option is false.
*/
QueryInterface.prototype.quoteIdentifiers = function(identifiers, force) {
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
};
renameTrigger(tableName, oldTriggerName, newTriggerName, options) {
const sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName);
options = options || {};
/**
* Escape a value (e.g. a string, number or date)
*/
QueryInterface.prototype.escape = function(value) {
return this.QueryGenerator.escape(value);
};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
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 (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set autocommit for a transaction without transaction object!');
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
if (transaction.parent) {
// Not possible to set a seperate isolation level for savepoints
return Promise.resolve();
dropFunction(functionName, params, options) {
const sql = this.QueryGenerator.dropFunction(functionName, params);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
renameFunction(oldFunctionName, params, newFunctionName, options) {
const sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
options = options || {};
var sql = this.QueryGenerator.setAutocommitQuery(value, {
parent: transaction.parent
});
if (sql) {
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) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set isolation level for a transaction without transaction object!');
quoteTable(identifier) {
return this.QueryGenerator.quoteTable(identifier);
}
if (transaction.parent || !value) {
// Not possible to set a seperate isolation level for savepoints
return Promise.resolve();
/**
* Split an identifier into .-separated tokens and quote each part.
* 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, {
parent: transaction.parent
});
options = _.assign({}, options, {
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) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to start a transaction without transaction object!');
return this.sequelize.query(sql, options);
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
setIsolationLevel(transaction, value, options) {
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) {
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
const sql = this.QueryGenerator.setIsolationLevelQuery(value, {
parent: transaction.parent
});
var sql = this.QueryGenerator.deferConstraintsQuery(options);
if (!sql) return Promise.resolve();
if (sql) {
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) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to commit a transaction without transaction object!');
return this.sequelize.query(sql, options);
}
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();
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction,
supportsSearchPath: false
});
commitTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
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);
var promise = this.sequelize.query(sql, options);
options = _.assign({}, 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) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to rollback a transaction without transaction object!');
return promise;
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction,
supportsSearchPath: false
});
rollbackTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to rollback a transaction without transaction object!');
}
var sql = this.QueryGenerator.rollbackTransactionQuery(transaction);
var promise = this.sequelize.query(sql, options);
options = _.assign({}, 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 = 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!