sequelize = function (database, username, password, options) {
var config;
if (arguments.length === 1 && typeof database === 'object') {
// new Sequelize({ ... options })
options = database;
config = _.pick(options, 'host', 'port', 'database', 'username', 'password');
} else if ((arguments.length === 1 && typeof database === 'string') || (arguments.length === 2 && typeof username === 'object')) {
// new Sequelize(URI, { ... options })
config = {};
options = username || {};
var urlParts = url.parse(arguments[0]);
// SQLite don't have DB in connection url
if (urlParts.pathname) {
config.database = urlParts.pathname.replace(/^\//, '');
}
options.dialect = urlParts.protocol.replace(/:$/, '');
options.host = urlParts.hostname;
if (urlParts.port) {
options.port = urlParts.port;
}
if (urlParts.auth) {
config.username = urlParts.auth.split(':')[0];
config.password = urlParts.auth.split(':')[1];
}
} else {
// new Sequelize(database, username, password, { ... options })
options = options || {};
config = {database: database, username: username, password: password};
}
Sequelize.runHooks('beforeInit', config, options);
this.options = Utils._.extend({
dialect: 'mysql',
dialectModulePath: null,
host: 'localhost',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone:'+00:00',
logging: console.log,
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: {max: 5, match: ['SQLITE_BUSY: database is locked']},
transactionType: Transaction.TYPES.DEFERRED,
isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
databaseVersion: 0,
typeValidation: false,
benchmark: false
}, options || {});
if (this.options.dialect === 'postgresql') {
this.options.dialect = 'postgres';
}
if (this.options.dialect === 'sqlite' && this.options.timezone !== '+00:00') {
throw new Error('Setting a custom timezone is not supported by SQLite, dates are always returned as UTC. Please remove the custom
timezone parameter.');
}
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
this.options.hooks = this.replaceHookAliases(this.options.hooks);
if ((['', null, false].indexOf(config.password) > -1) || (typeof config.password === 'undefined')) {
config.password = null;
}
this.config = {
database: config.database,
username: config.username,
password: config.password,
host: config.host || this.options.host,
port: config.port || this.options.port,
pool: this.options.pool,
protocol: this.options.protocol,
native: this.options.native,
ssl: this.options.ssl,
replication: this.options.replication,
dialectModulePath: this.options.dialectModulePath,
keepDefaultTimezone: this.options.keepDefaultTimezone,
dialectOptions: this.options.dialectOptions
};
var Dialect;
// Requiring the dialect in a switch-case to keep the
// require calls static. (Browserify fix)
switch (this.getDialect()){
case 'mariadb':
Dialect = require('./dialects/mariadb');
break;
case 'mssql':
Dialect = require('./dialects/mssql');
break;
case 'mysql':
Dialect = require('./dialects/mysql');
break;
case 'postgres':
Dialect = require('./dialects/postgres');
break;
case 'sqlite':
Dialect = require('./dialects/sqlite');
break;
default:
throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mariadb, mssql, mysql, postgres
, and sqlite.');
}
this.dialect = new Dialect(this);
this.dialect.QueryGenerator.typeValidation = options.typeValidation;
/**
* Models are stored here under the name given to `sequelize.define`
* @property models
*/
this.models = {};
this.mod ...n/a
ABSTRACT = function (options) {
}n/a
ARRAY = function (type) {
var options = _.isPlainObject(type) ? type : {
type: type
};
if (!(this instanceof ARRAY)) return new ARRAY(options);
this.type = typeof options.type === 'function' ? new options.type() : options.type;
}n/a
AccessDeniedError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeAccessDeniedError';
}n/a
Association = function () {}n/a
Association.BelongsTo = function (source, target, options) {
Association.call(this);
this.associationType = 'BelongsTo';
this.source = source;
this.target = target;
this.options = options;
this.scope = options.scope;
this.isSingleAssociation = true;
this.isSelfAssociation = (this.source === this.target);
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.as) {
this.isAliased = true;
this.options.name = {
singular: this.as
};
} else {
this.as = this.target.options.name.singular;
this.options.name = this.target.options.name;
}
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(this.as, this.source.options.underscored),
this.target.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
this.identifier = this.foreignKey;
if (this.source.rawAttributes[this.identifier]) {
this.identifierField = this.source.rawAttributes[this.identifier].field || this.identifier;
}
this.targetKey = this.options.targetKey || this.target.primaryKeyAttribute;
this.targetKeyField = this.target.rawAttributes[this.targetKey].field || this.targetKey;
this.targetKeyIsPrimary = this.targetKey === this.target.primaryKeyAttribute;
this.targetIdentifier = this.targetKey;
this.associationAccessor = this.as;
this.options.useHooks = options.useHooks;
// Get singular name, trying to uppercase the first letter, unless the model forbids it
var singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Instance>}
* @method getAssociation
*/
get: 'get' + singular,
/**
* Set the associated model.
*
* @param {Instance|String|Number} [newAssociation] An persisted instance or the primary key of an instance to associate with
this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to `this.save`
* @param {Boolean} [options.save=true] Skip saving this after setting the foreign key if false.
* @return {Promise}
* @method setAssociation
*/
set: 'set' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @return {Promise}
* @method createAssociation
*/
create: 'create' + singular
};
}n/a
Association.BelongsToMany = function (source, target, options) {
Association.call(this);
options = options || {};
if (options.through === undefined || options.through === true || options.through === null) {
throw new Error('belongsToMany must be given a through option, either a string or a model');
}
if (!options.through.model) {
options.through = {
model: options.through
};
}
this.associationType = 'BelongsToMany';
this.source = source;
this.target = target;
this.targetAssociation = null;
this.options = options;
this.sequelize = source.modelManager.sequelize;
this.through = _.assign({}, options.through);
this.scope = options.scope;
this.isMultiAssociation = true;
this.isSelfAssociation = this.source === this.target;
this.doubleLinked = false;
this.as = this.options.as;
if (!this.as && this.isSelfAssociation) {
throw new Error('\'as\' must be defined for many-to-many self-associations');
}
if (this.as) {
this.isAliased = true;
if (Utils._.isPlainObject(this.as)) {
this.options.name = this.as;
this.as = this.as.plural;
} else {
this.options.name = {
plural: this.as,
singular: Utils.singularize(this.as)
};
}
} else {
this.as = this.target.options.name.plural;
this.options.name = this.target.options.name;
}
this.combinedTableName = Utils.combineTableNames(
this.source.tableName,
this.isSelfAssociation ? (this.as || this.target.tableName) : this.target.tableName
);
/*
* If self association, this is the target association - Unless we find a pairing association
*/
if (this.isSelfAssociation) {
this.targetAssociation = this;
}
/*
* Default/generated foreign/other keys
*/
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else {
if (!this.options.foreignKey) {
this.foreignKeyDefault = true;
}
this.foreignKeyAttribute = {};
this.foreignKey = this.options.foreignKey || Utils.camelizeIf(
[
Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
if (_.isObject(this.options.otherKey)) {
this.otherKeyAttribute = this.options.otherKey;
this.otherKey = this.otherKeyAttribute.name || this.otherKeyAttribute.fieldName;
} else {
if (!this.options.otherKey) {
this.otherKeyDefault = true;
}
this.otherKeyAttribute = {};
this.otherKey = this.options.otherKey || Utils.camelizeIf(
[
Utils.underscoredIf(
this.isSelfAssociation ?
Utils.singularize(this.as) :
this.target.options.name.singular,
this.target.options.underscored
),
this.target.primaryKeyAttribute
].join('_'),
!this.target.options.underscored
);
}
/*
* Find paired association (if exists)
*/
_.each(this.target.associations, function(association) {
if (association.associationType !== 'BelongsToMany') return;
if (association.target !== this.source) return;
if (this.options.through.model === association.options.through.model) {
this.paired = association;
association.paired = this;
}
}.bind(this));
if (typeof this.through.model === 'string') {
if (!this.sequelize.isDefined(this.through.model)) {
this.through.model = this.sequelize.define(this.through.model, {}, _.extend(this.options, {
tableName: this.through.model,
indexes: [], //we don't want indexes here (as referenced in #2416)
paranoid: false, // A paranoid join table does not make sense
validate: {} // Don't propagate model-level validations
}));
} else {
this.through.model = this.sequelize.model(this.through.model);
}
}
this.options = _.assign(this.options, _.pick(this.through.model.options, [
'timestamps', 'createdAt', 'updatedAt ...n/a
Association.HasMany = function (source, target, options) {
Association.call(this);
this.associationType = 'HasMany';
this.source = source;
this.target = target;
this.targetAssociation = null;
this.options = options || {};
this.sequelize = source.modelManager.sequelize;
this.through = options.through;
this.scope = options.scope;
this.isMultiAssociation = true;
this.isSelfAssociation = this.source === this.target;
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.options.through) {
throw new Error('N:M associations are not supported with hasMany. Use belongsToMany instead');
}
/*
* If self association, this is the target association
*/
if (this.isSelfAssociation) {
this.targetAssociation = this;
}
if (this.as) {
this.isAliased = true;
if (_.isPlainObject(this.as)) {
this.options.name = this.as;
this.as = this.as.plural;
} else {
this.options.name = {
plural: this.as,
singular: Utils.singularize(this.as)
};
}
} else {
this.as = this.target.options.name.plural;
this.options.name = this.target.options.name;
}
/*
* Foreign key setup
*/
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
if (this.target.rawAttributes[this.foreignKey]) {
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
}
this.sourceKey = this.options.sourceKey || this.source.primaryKeyAttribute;
if (this.target.rawAttributes[this.sourceKey]) {
this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;
} else {
this.sourceKeyField = this.sourceKey;
}
if (this.source.fieldRawAttributesMap[this.sourceKey]) {
this.sourceKeyAttribute = this.source.fieldRawAttributesMap[this.sourceKey].fieldName;
} else {
this.sourceKeyAttribute = this.source.primaryKeyAttribute;
}
this.sourceIdentifier = this.sourceKey;
this.associationAccessor = this.as;
// Get singular and plural names, trying to uppercase the first letter, unless the model forbids it
var plural = Utils.uppercaseFirst(this.options.name.plural)
, singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Array<Instance>>}
* @method getAssociations
*/
get: 'get' + plural,
/**
* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the
passed array will be un-associated
*
* @param {Array<Instance|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate
with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model
* @return {Promise}
* @method setAssociations
*/
set: 'set' + plural,
/**
* Associate several persisted instances with this.
*
* @param {Array<In ...n/a
Association.HasOne = function (srcModel, targetModel, options) {
Association.call(this);
this.associationType = 'HasOne';
this.source = srcModel;
this.target = targetModel;
this.options = options;
this.scope = options.scope;
this.isSingleAssociation = true;
this.isSelfAssociation = (this.source === this.target);
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.as) {
this.isAliased = true;
this.options.name = {
singular: this.as
};
} else {
this.as = this.target.options.name.singular;
this.options.name = this.target.options.name;
}
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(Utils.singularize(this.source.name), this.target.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
this.sourceIdentifier = this.source.primaryKeyAttribute;
this.sourceKey = this.source.primaryKeyAttribute;
this.sourceKeyIsPrimary = this.sourceKey === this.source.primaryKeyAttribute;
this.associationAccessor = this.as;
this.options.useHooks = options.useHooks;
if (this.target.rawAttributes[this.foreignKey]) {
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
}
// Get singular name, trying to uppercase the first letter, unless the model forbids it
var singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Instance>}
* @method getAssociation
*/
get: 'get' + singular,
/**
* Set the associated model.
*
* @param {Instance|String|Number} [newAssociation] An persisted instance or the primary key of a persisted instance to associate
with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to getAssociation and `target.save`
* @return {Promise}
* @method setAssociation
*/
set: 'set' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @return {Promise}
* @method createAssociation
*/
create: 'create' + singular
};
}n/a
BIGINT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BIGINT)) return new BIGINT(options);
NUMBER.call(this, options);
}n/a
BLOB = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BLOB)) return new BLOB(options);
this.options = options;
this._length = options.length || '';
}n/a
BOOLEAN = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
CHAR = function (length, binary) {
var options = typeof length === 'object' && length || {
length: length,
binary: binary
};
if (!(this instanceof CHAR)) return new CHAR(options);
STRING.apply(this, arguments);
}n/a
ConnectionError = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
ConnectionRefusedError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeConnectionRefusedError';
}n/a
ConnectionTimedOutError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeConnectionTimedOutError';
}n/a
DATE = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof DATE)) return new DATE(options);
this.options = options;
this._length = options.length || '';
}n/a
DATEONLY = function () {
if (!(this instanceof DATEONLY)) return new DATEONLY();
ABSTRACT.apply(this, arguments);
}n/a
DECIMAL = function (precision, scale) {
var options = typeof precision === 'object' && precision || {
precision: precision,
scale: scale
};
if (!(this instanceof DECIMAL)) return new DECIMAL(options);
NUMBER.call(this, options);
}n/a
DOUBLE = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof DOUBLE)) return new DOUBLE(options);
NUMBER.call(this, options);
}n/a
DatabaseError = function (parent) {
error.BaseError.apply(this, [parent.message]);
this.name = 'SequelizeDatabaseError';
/**
* The database specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
/**
* The SQL that triggered the error
* @member sql
*/
this.sql = parent.sql;
/**
* The message from the DB.
* @member message
* @name message
*/
/**
* The fields of the unique constraint
* @member fields
* @name fields
*/
/**
* The value(s) which triggered the error
* @member value
* @name value
*/
/**
* The name of the index that triggered the error
* @member index
* @name index
*/
}n/a
DEFERRABLE INITIALLY DEFERRED
n/a
DEFERRABLE INITIALLY IMMEDIATE
n/a
NOT DEFERRABLE
n/a
n/a
n/a
n/a
n/a
ENUM = function (value) {
var options = typeof value === 'object' && !Array.isArray(value) && value || {
values: Array.prototype.slice.call(arguments).reduce(function(result, element) {
return result.concat(Array.isArray(element) ? element : [element]);
}, [])
};
if (!(this instanceof ENUM)) return new ENUM(options);
this.values = options.values;
this.options = options;
}n/a
EmptyResultError = function (message) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeEmptyResultError';
this.message = message;
}n/a
Error = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
function Error() { [native code] }n/a
ExclusionConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
error.DatabaseError.call(this, options.parent);
this.name = 'SequelizeExclusionConstraintError';
this.message = options.message || options.parent.message;
this.constraint = options.constraint;
this.fields = options.fields;
this.table = options.table;
}n/a
FLOAT = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof FLOAT)) return new FLOAT(options);
NUMBER.call(this, options);
}n/a
ForeignKeyConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
error.DatabaseError.call(this, options.parent);
this.name = 'SequelizeForeignKeyConstraintError';
this.message = options.message || options.parent.message || 'Database Error';
this.fields = options.fields;
this.table = options.table;
this.value = options.value;
this.index = options.index;
}n/a
GEOGRAPHY = function (type, srid) {
var options = _.isPlainObject(type) ? type : {
type: type,
srid: srid
};
if (!(this instanceof GEOGRAPHY)) return new GEOGRAPHY(options);
this.options = options;
this.type = options.type;
this.srid = options.srid;
}n/a
GEOMETRY = function (type, srid) {
var options = _.isPlainObject(type) ? type : {
type: type,
srid: srid
};
if (!(this instanceof GEOMETRY)) return new GEOMETRY(options);
this.options = options;
this.type = options.type;
this.srid = options.srid;
}n/a
HSTORE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
HostNotFoundError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeHostNotFoundError';
}n/a
HostNotReachableError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeHostNotReachableError';
}n/a
INTEGER = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof INTEGER)) return new INTEGER(options);
NUMBER.call(this, options);
}n/a
Instance = function (values, options) {
this.dataValues = {};
this._previousDataValues = {};
this._changed = {};
this.$modelOptions = this.Model.options;
this.$options = options || {};
this.hasPrimaryKeys = this.Model.options.hasPrimaryKeys;
this.__eagerlyLoadedAssociations = [];
/**
* Returns true if this instance has not yet been persisted to the database
* @property isNewRecord
* @return {Boolean}
*/
this.isNewRecord = options.isNewRecord;
/**
* Returns the Model the instance was created from.
* @see {Model}
* @property Model
* @return {Model}
*/
initValues.call(this, values, options);
}n/a
InstanceError = function (message) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeInstanceError';
this.message = message;
}n/a
InvalidConnectionError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeInvalidConnectionError';
}n/a
JSON = function () {
if (!(this instanceof JSONTYPE)) return new JSONTYPE();
ABSTRACT.apply(this, arguments);
}n/a
JSONB = function () {
if (!(this instanceof JSONB)) return new JSONB();
JSONTYPE.apply(this, arguments);
}n/a
Model = function (name, attributes, options) {
this.options = Utils._.extend({
timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: []
}, options || {});
this.associations = {};
this.modelManager = null;
this.name = name;
this.options.hooks = _.mapValues(this.replaceHookAliases(this.options.hooks), function (hooks) {
if (!Array.isArray(hooks)) hooks = [hooks];
return hooks;
});
this.sequelize = options.sequelize;
this.underscored = this.underscored || this.underscoredAll;
if (!this.options.tableName) {
this.tableName = this.options.freezeTableName ? name : Utils.underscoredIf(Utils.pluralize(name), this.options.underscoredAll
);
} else {
this.tableName = this.options.tableName;
}
this.$schema = this.options.schema;
this.$schemaDelimiter = this.options.schemaDelimiter;
// error check options
_.each(options.validate, function(validator, validatorType) {
if (_.includes(Utils._.keys(attributes), validatorType)) {
throw new Error('A model validator function must not have the same name as a field. Model: ' + name + ', field/validation
name: ' + validatorType);
}
if (!_.isFunction(validator)) {
throw new Error('Members of the validate option must be functions. Model: ' + name + ', error with validate member ' + validatorType
);
}
});
this.attributes = this.rawAttributes = _.mapValues(attributes, function(attribute, name) {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute };
}
attribute = this.sequelize.normalizeAttribute(attribute);
if (attribute.references) {
attribute = Utils.formatReferences(attribute);
if (attribute.references.model instanceof Model) {
attribute.references.model = attribute.references.model.tableName;
}
}
if (attribute.type === undefined) {
throw new Error('Unrecognized data type for field ' + name);
}
return attribute;
}.bind(this));
}n/a
NONE = function (ReturnType, fields) {
if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields);
if (typeof ReturnType === 'function') ReturnType = new ReturnType();
this.returnType = ReturnType;
this.fields = fields;
}n/a
NOW = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
NUMBER = function (options) {
this.options = options;
this._length = options.length;
this._zerofill = options.zerofill;
this._decimals = options.decimals;
this._precision = options.precision;
this._scale = options.scale;
this._unsigned = options.unsigned;
}n/a
NUMERIC = function (precision, scale) {
var options = typeof precision === 'object' && precision || {
precision: precision,
scale: scale
};
if (!(this instanceof DECIMAL)) return new DECIMAL(options);
NUMBER.call(this, options);
}n/a
function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}n/a
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed()
? promise._settledValue() : undefined;
}
else {
this._bitField = 0;
this._settledValueField = undefined;
}
}n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}n/a
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
var ret = spawn.promise();
spawn._generator = generator;
spawn._promiseFulfilled(undefined);
return ret;
};
}n/a
Promise.each = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.filter = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.join = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.map = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.mapSeries = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.catch = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.done = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.each = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.error = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.filter = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.finally = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.map = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.mapSeries = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.nodeify = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.reduce = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.spread = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.tap = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.prototype.then = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
Promise.reduce = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
RANGE = function (subtype) {
var options = _.isPlainObject(subtype) ? subtype : { subtype: subtype };
if (!options.subtype) options.subtype = new INTEGER();
if (_.isFunction(options.subtype)) {
options.subtype = new options.subtype();
}
if (!(this instanceof RANGE)) return new RANGE(options);
ABSTRACT.apply(this, arguments);
this._subtype = options.subtype.key;
this.options = options;
}n/a
REAL = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof REAL)) return new REAL(options);
NUMBER.call(this, options);
}n/a
STRING = function (length, binary) {
var options = typeof length === 'object' && length || {
length: length,
binary: binary
};
if (!(this instanceof STRING)) return new STRING(options);
this.options = options;
this._binary = options.binary;
this._length = options.length || 255;
}n/a
Sequelize = function (database, username, password, options) {
var config;
if (arguments.length === 1 && typeof database === 'object') {
// new Sequelize({ ... options })
options = database;
config = _.pick(options, 'host', 'port', 'database', 'username', 'password');
} else if ((arguments.length === 1 && typeof database === 'string') || (arguments.length === 2 && typeof username === 'object')) {
// new Sequelize(URI, { ... options })
config = {};
options = username || {};
var urlParts = url.parse(arguments[0]);
// SQLite don't have DB in connection url
if (urlParts.pathname) {
config.database = urlParts.pathname.replace(/^\//, '');
}
options.dialect = urlParts.protocol.replace(/:$/, '');
options.host = urlParts.hostname;
if (urlParts.port) {
options.port = urlParts.port;
}
if (urlParts.auth) {
config.username = urlParts.auth.split(':')[0];
config.password = urlParts.auth.split(':')[1];
}
} else {
// new Sequelize(database, username, password, { ... options })
options = options || {};
config = {database: database, username: username, password: password};
}
Sequelize.runHooks('beforeInit', config, options);
this.options = Utils._.extend({
dialect: 'mysql',
dialectModulePath: null,
host: 'localhost',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone:'+00:00',
logging: console.log,
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: {max: 5, match: ['SQLITE_BUSY: database is locked']},
transactionType: Transaction.TYPES.DEFERRED,
isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
databaseVersion: 0,
typeValidation: false,
benchmark: false
}, options || {});
if (this.options.dialect === 'postgresql') {
this.options.dialect = 'postgres';
}
if (this.options.dialect === 'sqlite' && this.options.timezone !== '+00:00') {
throw new Error('Setting a custom timezone is not supported by SQLite, dates are always returned as UTC. Please remove the custom
timezone parameter.');
}
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
this.options.hooks = this.replaceHookAliases(this.options.hooks);
if ((['', null, false].indexOf(config.password) > -1) || (typeof config.password === 'undefined')) {
config.password = null;
}
this.config = {
database: config.database,
username: config.username,
password: config.password,
host: config.host || this.options.host,
port: config.port || this.options.port,
pool: this.options.pool,
protocol: this.options.protocol,
native: this.options.native,
ssl: this.options.ssl,
replication: this.options.replication,
dialectModulePath: this.options.dialectModulePath,
keepDefaultTimezone: this.options.keepDefaultTimezone,
dialectOptions: this.options.dialectOptions
};
var Dialect;
// Requiring the dialect in a switch-case to keep the
// require calls static. (Browserify fix)
switch (this.getDialect()){
case 'mariadb':
Dialect = require('./dialects/mariadb');
break;
case 'mssql':
Dialect = require('./dialects/mssql');
break;
case 'mysql':
Dialect = require('./dialects/mysql');
break;
case 'postgres':
Dialect = require('./dialects/postgres');
break;
case 'sqlite':
Dialect = require('./dialects/sqlite');
break;
default:
throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mariadb, mssql, mysql, postgres
, and sqlite.');
}
this.dialect = new Dialect(this);
this.dialect.QueryGenerator.typeValidation = options.typeValidation;
/**
* Models are stored here under the name given to `sequelize.define`
* @property models
*/
this.models = {};
this.mod ...n/a
TEXT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof TEXT)) return new TEXT(options);
this.options = options;
this._length = options.length || '';
}n/a
TIME = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
TimeoutError = function (parent) {
error.DatabaseError.call(this, parent);
this.name = 'SequelizeTimeoutError';
}n/a
function Transaction(sequelize, options) {
this.sequelize = sequelize;
this.savepoints = [];
var generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;
this.options = Utils._.extend({
autocommit: true,
type: sequelize.options.transactionType,
isolationLevel: sequelize.options.isolationLevel,
readOnly: false
}, options || {});
this.parent = this.options.transaction;
this.id = this.parent ? this.parent.id : generateTransactionId();
if (this.parent) {
this.id = this.parent.id;
this.parent.savepoints.push(this);
this.name = this.id + '-savepoint-' + this.parent.savepoints.length;
} else {
this.id = this.name = generateTransactionId();
}
delete this.options.transaction;
}n/a
UUID = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
UUIDV1 = function () {
if (!(this instanceof UUIDV1)) return new UUIDV1();
ABSTRACT.apply(this, arguments);
}n/a
UUIDV4 = function () {
if (!(this instanceof UUIDV4)) return new UUIDV4();
ABSTRACT.apply(this, arguments);
}n/a
UniqueConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
options.message = options.message || options.parent.message || 'Validation Error';
options.errors = options.errors || {};
error.ValidationError.call(this, options.message, options.errors);
this.name = 'SequelizeUniqueConstraintError';
this.message = options.message;
this.errors = options.errors;
this.fields = options.fields;
this.parent = options.parent;
this.original = options.parent;
this.sql = options.parent.sql;
}n/a
n/a
n/a
Utils.fn = function (fn, args) {
this.fn = fn;
this.args = args;
}n/a
VIRTUAL = function (ReturnType, fields) {
if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields);
if (typeof ReturnType === 'function') ReturnType = new ReturnType();
this.returnType = ReturnType;
this.fields = fields;
}n/a
ValidationError = function (message, errors) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeValidationError';
this.message = 'Validation Error';
/**
* An array of ValidationErrorItems
* @member errors
*/
this.errors = errors || [];
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
}...
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
} else {
return null;
}
});
};
/**
...ValidationErrorItem = function (message, type, path, value) {
this.message = message || '';
this.type = type || null;
this.path = path || null;
this.value = value || null;
}...
* @param {*} value anything.
* @private
*/
InstanceValidator.prototype._validateSchema = function(rawAttribute, field, value) {
var error;
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be null',
x27;notNull Violation', field, value);
this.errors.push(error);
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes.TEXT
|| rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || (_.isObject(value) && !value._isSequelizeMethod) && !Buffer.isBuffer(value)) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be an array or an object', 'string violation
x27;, field, value);
this.errors.push(error);
...addHook = function (hookType, name, fn) {
if (typeof name === 'function') {
fn = name;
name = null;
}
hookType = hookAliases[hookType] || hookType;
this.options.hooks[hookType] = this.options.hooks[hookType] || [];
this.options.hooks[hookType].push(!!name ? {name: name, fn: fn} : fn);
return this;
}...
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
});
}
};
...and = function () {
return { $and: Utils.sliceArgs(arguments) };
}n/a
asIs = function (val) {
return new Utils.literal(val);
}n/a
cast = function (val, type) {
return new Utils.cast(val, type);
}n/a
col = function (col) {
return new Utils.col(col);
}n/a
condition = function (attr, comparator, logic) {
return new Utils.where(attr, comparator, logic);
}n/a
default = function (database, username, password, options) {
var config;
if (arguments.length === 1 && typeof database === 'object') {
// new Sequelize({ ... options })
options = database;
config = _.pick(options, 'host', 'port', 'database', 'username', 'password');
} else if ((arguments.length === 1 && typeof database === 'string') || (arguments.length === 2 && typeof username === 'object')) {
// new Sequelize(URI, { ... options })
config = {};
options = username || {};
var urlParts = url.parse(arguments[0]);
// SQLite don't have DB in connection url
if (urlParts.pathname) {
config.database = urlParts.pathname.replace(/^\//, '');
}
options.dialect = urlParts.protocol.replace(/:$/, '');
options.host = urlParts.hostname;
if (urlParts.port) {
options.port = urlParts.port;
}
if (urlParts.auth) {
config.username = urlParts.auth.split(':')[0];
config.password = urlParts.auth.split(':')[1];
}
} else {
// new Sequelize(database, username, password, { ... options })
options = options || {};
config = {database: database, username: username, password: password};
}
Sequelize.runHooks('beforeInit', config, options);
this.options = Utils._.extend({
dialect: 'mysql',
dialectModulePath: null,
host: 'localhost',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone:'+00:00',
logging: console.log,
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: {max: 5, match: ['SQLITE_BUSY: database is locked']},
transactionType: Transaction.TYPES.DEFERRED,
isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
databaseVersion: 0,
typeValidation: false,
benchmark: false
}, options || {});
if (this.options.dialect === 'postgresql') {
this.options.dialect = 'postgres';
}
if (this.options.dialect === 'sqlite' && this.options.timezone !== '+00:00') {
throw new Error('Setting a custom timezone is not supported by SQLite, dates are always returned as UTC. Please remove the custom
timezone parameter.');
}
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
this.options.hooks = this.replaceHookAliases(this.options.hooks);
if ((['', null, false].indexOf(config.password) > -1) || (typeof config.password === 'undefined')) {
config.password = null;
}
this.config = {
database: config.database,
username: config.username,
password: config.password,
host: config.host || this.options.host,
port: config.port || this.options.port,
pool: this.options.pool,
protocol: this.options.protocol,
native: this.options.native,
ssl: this.options.ssl,
replication: this.options.replication,
dialectModulePath: this.options.dialectModulePath,
keepDefaultTimezone: this.options.keepDefaultTimezone,
dialectOptions: this.options.dialectOptions
};
var Dialect;
// Requiring the dialect in a switch-case to keep the
// require calls static. (Browserify fix)
switch (this.getDialect()){
case 'mariadb':
Dialect = require('./dialects/mariadb');
break;
case 'mssql':
Dialect = require('./dialects/mssql');
break;
case 'mysql':
Dialect = require('./dialects/mysql');
break;
case 'postgres':
Dialect = require('./dialects/postgres');
break;
case 'sqlite':
Dialect = require('./dialects/sqlite');
break;
default:
throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mariadb, mssql, mysql, postgres
, and sqlite.');
}
this.dialect = new Dialect(this);
this.dialect.QueryGenerator.typeValidation = options.typeValidation;
/**
* Models are stored here under the name given to `sequelize.define`
* @property models
*/
this.models = {};
this.mod ...n/a
fn = function (fn) {
return new Utils.fn(fn, Utils.sliceArgs(arguments, 1));
}n/a
hasHook = function (hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
}...
*
* @param {String} hookType
* @param {String} name
*/
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
...hasHooks = function (hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
}n/a
hook = function () {
return Hooks.addHook.apply(this, arguments);
}...
* function () {},
* function() {} // Or an array of several
* ]
* }
* })
*
* // Method 2
* Model.hook('afterDestroy', function () {})
*
* // Method 3
* Model.afterBulkUpdate(function () {})
* ```
*
* @see {Sequelize#define}
* @mixin Hooks
...function InstanceValidator(modelInstance, options) {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
skip: []
});
this.modelInstance = modelInstance;
/**
* Exposes a reference to validator.js. This allows you to add custom validations using `validator.extend`
* @name validator
*/
this.validator = validator;
/**
* All errors will be stored here from the validations.
*
* @type {Array} Will contain keys that correspond to attributes which will
* be Arrays of Errors.
*/
this.errors = [];
/** @type {boolean} Indicates if validations are in progress */
this.inProgress = false;
extendModelValidations(modelInstance);
}n/a
json = function (conditionsOrPath, value) {
return new Utils.json(conditionsOrPath, value);
}n/a
literal = function (val) {
return new Utils.literal(val);
}...
return sequelize.sync({
force: true,
logging: console.log
})
.then(() => {
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount'
;]]
}
});
})
.then(console.log)
.finally(() => {
sequelize.close();
});
...model_manager = function (sequelize) {
this.models = [];
this.sequelize = sequelize;
}n/a
mssql.BIGINT = function () {
if (!(this instanceof BIGINT)) return new BIGINT();
BaseTypes.BIGINT.apply(this, arguments);
// MSSQL does not support any options for bigint
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('MSSQL does not support BIGINT with options. Plain `BIGINT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
mssql.BLOB = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
mssql.BOOLEAN = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
mssql.DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
mssql.ENUM = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
mssql.FLOAT = function () {
if (!(this instanceof FLOAT)) return new FLOAT();
BaseTypes.FLOAT.apply(this, arguments);
// MSSQL does only support lengths as option.
// Values between 1-24 result in 7 digits precision (4 bytes storage size)
// Values between 25-53 result in 15 digits precision (8 bytes storage size)
// If decimals are provided remove these and print a warning
if (this._decimals) {
warn('MSSQL does not support Float with decimals. Plain `FLOAT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
}
if (this._unsigned) {
warn('MSSQL does not support Float unsigned. `UNSIGNED` was removed.');
this._unsigned = undefined;
}
if (this._zerofill) {
warn('MSSQL does not support Float zerofill. `ZEROFILL` was removed.');
this._zerofill = undefined;
}
}n/a
mssql.INTEGER = function () {
if (!(this instanceof INTEGER)) return new INTEGER();
BaseTypes.INTEGER.apply(this, arguments);
// MSSQL does not support any options for integer
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('MSSQL does not support INTEGER with options. Plain `INTEGER` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
mssql.NOW = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
mssql.REAL = function () {
if (!(this instanceof REAL)) return new REAL();
BaseTypes.REAL.apply(this, arguments);
// MSSQL does not support any options for real
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('MSSQL does not support REAL with options. Plain `REAL` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
mssql.STRING = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
mssql.TEXT = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
mssql.UUID = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
mysql.DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
mysql.ENUM = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
mysql.GEOMETRY = function () {
if (!(this instanceof GEOMETRY)) return new GEOMETRY();
BaseTypes.GEOMETRY.apply(this, arguments);
if (_.isEmpty(this.type)) {
this.sqlType = this.key;
} else if (_.includes(SUPPORTED_GEOMETRY_TYPES, this.type)) {
this.sqlType = this.type;
} else {
throw new Error('Supported geometry types are: ' + SUPPORTED_GEOMETRY_TYPES.join(', '));
}
}n/a
mysql.UUID = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
or = function () {
return { $or: Utils.sliceArgs(arguments) };
}n/a
postgres.BIGINT = function () {
if (!(this instanceof BIGINT)) return new BIGINT();
BaseTypes.BIGINT.apply(this, arguments);
// POSTGRES does not support any parameters for bigint
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('PostgreSQL does not support BIGINT with options. Plain `BIGINT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
postgres.BLOB = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
postgres.BOOLEAN = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
postgres.CHAR = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
postgres.DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
postgres.DECIMAL = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
postgres.FLOAT = function () {
if (!(this instanceof FLOAT)) return new FLOAT();
BaseTypes.FLOAT.apply(this, arguments);
// POSTGRES does only support lengths as parameter.
// Values between 1-24 result in REAL
// Values between 25-53 result in DOUBLE PRECISION
// If decimals are provided remove these and print a warning
if (this._decimals) {
warn('PostgreSQL does not support FLOAT with decimals. Plain `FLOAT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._decimals = undefined;
}
if (this._unsigned) {
warn('PostgreSQL does not support FLOAT unsigned. `UNSIGNED` was removed.');
this._unsigned = undefined;
}
if (this._zerofill) {
warn('PostgreSQL does not support FLOAT zerofill. `ZEROFILL` was removed.');
this._zerofill = undefined;
}
}n/a
postgres.GEOGRAPHY = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
postgres.GEOMETRY = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
postgres.HSTORE = function () {
if (!(this instanceof HSTORE)) return new HSTORE();
BaseTypes.HSTORE.apply(this, arguments);
if (!hstore) {
// All datatype files are loaded at import - make sure we don't load the hstore parser before a hstore is instantiated
hstore = require('./hstore');
}
}n/a
postgres.INTEGER = function () {
if (!(this instanceof INTEGER)) return new INTEGER();
BaseTypes.INTEGER.apply(this, arguments);
// POSTGRES does not support any parameters for integer
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('PostgreSQL does not support INTEGER with options. Plain `INTEGER` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
postgres.RANGE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
postgres.REAL = function () {
if (!(this instanceof REAL)) return new REAL();
BaseTypes.REAL.apply(this, arguments);
// POSTGRES does not support any parameters for real
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('PostgreSQL does not support REAL with options. Plain `REAL` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
postgres.STRING = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
postgres.TEXT = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
query_interface = function (sequelize) {
this.sequelize = sequelize;
this.QueryGenerator = this.sequelize.dialect.QueryGenerator;
}n/a
removeHook = function (hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
return this;
}n/a
replaceHookAliases = function (hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
}
});
return hooks;
}n/a
runHooks = function (hooks) {
var self = this
, fn
, fnArgs = Utils.sliceArgs(arguments, 1)
, hookType;
if (typeof fnArgs[fnArgs.length - 1] === 'function') {
fn = fnArgs.pop();
}
if (typeof hooks === 'string') {
hookType = hooks;
hooks = this.options.hooks[hookType] || [];
if (!Array.isArray(hooks)) hooks = hooks === undefined ? [] : [hooks];
if (this.sequelize) hooks = hooks.concat(this.sequelize.options.hooks[hookType] || []);
}
if (!Array.isArray(hooks)) {
hooks = hooks === undefined ? [] : [hooks];
}
// run hooks as sync functions if flagged as sync
if (hookTypes[hookType] && hookTypes[hookType].sync) {
hooks.forEach(function(hook) {
if (typeof hook === 'object') hook = hook.fn;
return hook.apply(self, fnArgs);
});
return;
}
// run hooks async
var promise = Promise.each(hooks, function (hook) {
if (typeof hook === 'object') {
hook = hook.fn;
}
if (hookType && hook.length > hookTypes[hookType].params) {
hook = Promise.promisify(hook, self);
}
return hook.apply(self, fnArgs);
}).return();
if (fn) {
return promise.nodeify(fn);
}
return promise;
}...
* - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance
, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
...sqlite.BIGINT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BIGINT)) return new BIGINT(options);
BaseTypes.BIGINT.call(this, options);
}n/a
sqlite.CHAR = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
sqlite.DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
sqlite.ENUM = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
sqlite.FLOAT = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof FLOAT)) return new FLOAT(options);
BaseTypes.FLOAT.call(this, options);
}n/a
sqlite.INTEGER = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof INTEGER)) return new INTEGER(options);
BaseTypes.INTEGER.call(this, options);
}n/a
sqlite.NUMBER = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
sqlite.REAL = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof REAL)) return new REAL(options);
BaseTypes.REAL.call(this, options);
}n/a
sqlite.STRING = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
sqlite.TEXT = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
where = function (attr, comparator, logic) {
return new Utils.where(attr, comparator, logic);
}n/a
ABSTRACT = function (options) {
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
stringify = function (value, options) {
if (this.$stringify) {
return this.$stringify(value, options);
}
return value;
}...
// In mssql, prepend N to all quoted vals which are originally a string (for
// unicode compatibility)
prependN = dialect === 'mssql';
break;
}
if (val instanceof Date) {
val = dataTypes[dialect].DATE.prototype.stringify(val, { timezone: timeZone });
}
if (Buffer.isBuffer(val)) {
if (dataTypes[dialect].BLOB) {
return dataTypes[dialect].BLOB.prototype.stringify(val);
}
...toSql = function () {
return this.key;
}n/a
toString = function (options) {
return this.toSql(options);
}n/a
ARRAY = function (type) {
var options = _.isPlainObject(type) ? type : {
type: type
};
if (!(this instanceof ARRAY)) return new ARRAY(options);
this.type = typeof options.type === 'function' ? new options.type() : options.type;
}n/a
is = function (obj, type) {
return obj instanceof ARRAY && obj.type instanceof type;
}n/a
super_ = function (options) {
}n/a
toSql = function () {
return this.type.toSql() + '[]';
}n/a
validate = function (value) {
if (!_.isArray(value)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid array', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...AccessDeniedError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeAccessDeniedError';
}n/a
super_ = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
Association = function () {}n/a
BelongsTo = function (source, target, options) {
Association.call(this);
this.associationType = 'BelongsTo';
this.source = source;
this.target = target;
this.options = options;
this.scope = options.scope;
this.isSingleAssociation = true;
this.isSelfAssociation = (this.source === this.target);
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.as) {
this.isAliased = true;
this.options.name = {
singular: this.as
};
} else {
this.as = this.target.options.name.singular;
this.options.name = this.target.options.name;
}
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(this.as, this.source.options.underscored),
this.target.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
this.identifier = this.foreignKey;
if (this.source.rawAttributes[this.identifier]) {
this.identifierField = this.source.rawAttributes[this.identifier].field || this.identifier;
}
this.targetKey = this.options.targetKey || this.target.primaryKeyAttribute;
this.targetKeyField = this.target.rawAttributes[this.targetKey].field || this.targetKey;
this.targetKeyIsPrimary = this.targetKey === this.target.primaryKeyAttribute;
this.targetIdentifier = this.targetKey;
this.associationAccessor = this.as;
this.options.useHooks = options.useHooks;
// Get singular name, trying to uppercase the first letter, unless the model forbids it
var singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Instance>}
* @method getAssociation
*/
get: 'get' + singular,
/**
* Set the associated model.
*
* @param {Instance|String|Number} [newAssociation] An persisted instance or the primary key of an instance to associate with
this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to `this.save`
* @param {Boolean} [options.save=true] Skip saving this after setting the foreign key if false.
* @return {Promise}
* @method setAssociation
*/
set: 'set' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @return {Promise}
* @method createAssociation
*/
create: 'create' + singular
};
}n/a
BelongsToMany = function (source, target, options) {
Association.call(this);
options = options || {};
if (options.through === undefined || options.through === true || options.through === null) {
throw new Error('belongsToMany must be given a through option, either a string or a model');
}
if (!options.through.model) {
options.through = {
model: options.through
};
}
this.associationType = 'BelongsToMany';
this.source = source;
this.target = target;
this.targetAssociation = null;
this.options = options;
this.sequelize = source.modelManager.sequelize;
this.through = _.assign({}, options.through);
this.scope = options.scope;
this.isMultiAssociation = true;
this.isSelfAssociation = this.source === this.target;
this.doubleLinked = false;
this.as = this.options.as;
if (!this.as && this.isSelfAssociation) {
throw new Error('\'as\' must be defined for many-to-many self-associations');
}
if (this.as) {
this.isAliased = true;
if (Utils._.isPlainObject(this.as)) {
this.options.name = this.as;
this.as = this.as.plural;
} else {
this.options.name = {
plural: this.as,
singular: Utils.singularize(this.as)
};
}
} else {
this.as = this.target.options.name.plural;
this.options.name = this.target.options.name;
}
this.combinedTableName = Utils.combineTableNames(
this.source.tableName,
this.isSelfAssociation ? (this.as || this.target.tableName) : this.target.tableName
);
/*
* If self association, this is the target association - Unless we find a pairing association
*/
if (this.isSelfAssociation) {
this.targetAssociation = this;
}
/*
* Default/generated foreign/other keys
*/
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else {
if (!this.options.foreignKey) {
this.foreignKeyDefault = true;
}
this.foreignKeyAttribute = {};
this.foreignKey = this.options.foreignKey || Utils.camelizeIf(
[
Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
if (_.isObject(this.options.otherKey)) {
this.otherKeyAttribute = this.options.otherKey;
this.otherKey = this.otherKeyAttribute.name || this.otherKeyAttribute.fieldName;
} else {
if (!this.options.otherKey) {
this.otherKeyDefault = true;
}
this.otherKeyAttribute = {};
this.otherKey = this.options.otherKey || Utils.camelizeIf(
[
Utils.underscoredIf(
this.isSelfAssociation ?
Utils.singularize(this.as) :
this.target.options.name.singular,
this.target.options.underscored
),
this.target.primaryKeyAttribute
].join('_'),
!this.target.options.underscored
);
}
/*
* Find paired association (if exists)
*/
_.each(this.target.associations, function(association) {
if (association.associationType !== 'BelongsToMany') return;
if (association.target !== this.source) return;
if (this.options.through.model === association.options.through.model) {
this.paired = association;
association.paired = this;
}
}.bind(this));
if (typeof this.through.model === 'string') {
if (!this.sequelize.isDefined(this.through.model)) {
this.through.model = this.sequelize.define(this.through.model, {}, _.extend(this.options, {
tableName: this.through.model,
indexes: [], //we don't want indexes here (as referenced in #2416)
paranoid: false, // A paranoid join table does not make sense
validate: {} // Don't propagate model-level validations
}));
} else {
this.through.model = this.sequelize.model(this.through.model);
}
}
this.options = _.assign(this.options, _.pick(this.through.model.options, [
'timestamps', 'createdAt', 'updatedAt ...n/a
HasMany = function (source, target, options) {
Association.call(this);
this.associationType = 'HasMany';
this.source = source;
this.target = target;
this.targetAssociation = null;
this.options = options || {};
this.sequelize = source.modelManager.sequelize;
this.through = options.through;
this.scope = options.scope;
this.isMultiAssociation = true;
this.isSelfAssociation = this.source === this.target;
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.options.through) {
throw new Error('N:M associations are not supported with hasMany. Use belongsToMany instead');
}
/*
* If self association, this is the target association
*/
if (this.isSelfAssociation) {
this.targetAssociation = this;
}
if (this.as) {
this.isAliased = true;
if (_.isPlainObject(this.as)) {
this.options.name = this.as;
this.as = this.as.plural;
} else {
this.options.name = {
plural: this.as,
singular: Utils.singularize(this.as)
};
}
} else {
this.as = this.target.options.name.plural;
this.options.name = this.target.options.name;
}
/*
* Foreign key setup
*/
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
if (this.target.rawAttributes[this.foreignKey]) {
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
}
this.sourceKey = this.options.sourceKey || this.source.primaryKeyAttribute;
if (this.target.rawAttributes[this.sourceKey]) {
this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;
} else {
this.sourceKeyField = this.sourceKey;
}
if (this.source.fieldRawAttributesMap[this.sourceKey]) {
this.sourceKeyAttribute = this.source.fieldRawAttributesMap[this.sourceKey].fieldName;
} else {
this.sourceKeyAttribute = this.source.primaryKeyAttribute;
}
this.sourceIdentifier = this.sourceKey;
this.associationAccessor = this.as;
// Get singular and plural names, trying to uppercase the first letter, unless the model forbids it
var plural = Utils.uppercaseFirst(this.options.name.plural)
, singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Array<Instance>>}
* @method getAssociations
*/
get: 'get' + plural,
/**
* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the
passed array will be un-associated
*
* @param {Array<Instance|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate
with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model
* @return {Promise}
* @method setAssociations
*/
set: 'set' + plural,
/**
* Associate several persisted instances with this.
*
* @param {Array<In ...n/a
HasOne = function (srcModel, targetModel, options) {
Association.call(this);
this.associationType = 'HasOne';
this.source = srcModel;
this.target = targetModel;
this.options = options;
this.scope = options.scope;
this.isSingleAssociation = true;
this.isSelfAssociation = (this.source === this.target);
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.as) {
this.isAliased = true;
this.options.name = {
singular: this.as
};
} else {
this.as = this.target.options.name.singular;
this.options.name = this.target.options.name;
}
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(Utils.singularize(this.source.name), this.target.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
this.sourceIdentifier = this.source.primaryKeyAttribute;
this.sourceKey = this.source.primaryKeyAttribute;
this.sourceKeyIsPrimary = this.sourceKey === this.source.primaryKeyAttribute;
this.associationAccessor = this.as;
this.options.useHooks = options.useHooks;
if (this.target.rawAttributes[this.foreignKey]) {
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
}
// Get singular name, trying to uppercase the first letter, unless the model forbids it
var singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Instance>}
* @method getAssociation
*/
get: 'get' + singular,
/**
* Set the associated model.
*
* @param {Instance|String|Number} [newAssociation] An persisted instance or the primary key of a persisted instance to associate
with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to getAssociation and `target.save`
* @return {Promise}
* @method setAssociation
*/
set: 'set' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @return {Promise}
* @method createAssociation
*/
create: 'create' + singular
};
}n/a
default = function () {}n/a
BelongsTo = function (source, target, options) {
Association.call(this);
this.associationType = 'BelongsTo';
this.source = source;
this.target = target;
this.options = options;
this.scope = options.scope;
this.isSingleAssociation = true;
this.isSelfAssociation = (this.source === this.target);
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.as) {
this.isAliased = true;
this.options.name = {
singular: this.as
};
} else {
this.as = this.target.options.name.singular;
this.options.name = this.target.options.name;
}
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(this.as, this.source.options.underscored),
this.target.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
this.identifier = this.foreignKey;
if (this.source.rawAttributes[this.identifier]) {
this.identifierField = this.source.rawAttributes[this.identifier].field || this.identifier;
}
this.targetKey = this.options.targetKey || this.target.primaryKeyAttribute;
this.targetKeyField = this.target.rawAttributes[this.targetKey].field || this.targetKey;
this.targetKeyIsPrimary = this.targetKey === this.target.primaryKeyAttribute;
this.targetIdentifier = this.targetKey;
this.associationAccessor = this.as;
this.options.useHooks = options.useHooks;
// Get singular name, trying to uppercase the first letter, unless the model forbids it
var singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Instance>}
* @method getAssociation
*/
get: 'get' + singular,
/**
* Set the associated model.
*
* @param {Instance|String|Number} [newAssociation] An persisted instance or the primary key of an instance to associate with
this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to `this.save`
* @param {Boolean} [options.save=true] Skip saving this after setting the foreign key if false.
* @return {Promise}
* @method setAssociation
*/
set: 'set' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @return {Promise}
* @method createAssociation
*/
create: 'create' + singular
};
}n/a
default = function (source, target, options) {
Association.call(this);
this.associationType = 'BelongsTo';
this.source = source;
this.target = target;
this.options = options;
this.scope = options.scope;
this.isSingleAssociation = true;
this.isSelfAssociation = (this.source === this.target);
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.as) {
this.isAliased = true;
this.options.name = {
singular: this.as
};
} else {
this.as = this.target.options.name.singular;
this.options.name = this.target.options.name;
}
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(this.as, this.source.options.underscored),
this.target.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
this.identifier = this.foreignKey;
if (this.source.rawAttributes[this.identifier]) {
this.identifierField = this.source.rawAttributes[this.identifier].field || this.identifier;
}
this.targetKey = this.options.targetKey || this.target.primaryKeyAttribute;
this.targetKeyField = this.target.rawAttributes[this.targetKey].field || this.targetKey;
this.targetKeyIsPrimary = this.targetKey === this.target.primaryKeyAttribute;
this.targetIdentifier = this.targetKey;
this.associationAccessor = this.as;
this.options.useHooks = options.useHooks;
// Get singular name, trying to uppercase the first letter, unless the model forbids it
var singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Instance>}
* @method getAssociation
*/
get: 'get' + singular,
/**
* Set the associated model.
*
* @param {Instance|String|Number} [newAssociation] An persisted instance or the primary key of an instance to associate with
this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to `this.save`
* @param {Boolean} [options.save=true] Skip saving this after setting the foreign key if false.
* @return {Promise}
* @method setAssociation
*/
set: 'set' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @return {Promise}
* @method createAssociation
*/
create: 'create' + singular
};
}n/a
super_ = function () {}n/a
get = function (instances, options) {
var association = this
, Target = association.target
, instance
, where = {};
options = Utils.cloneDeep(options);
if (options.hasOwnProperty('scope')) {
if (!options.scope) {
Target = Target.unscoped();
} else {
Target = Target.scope(options.scope);
}
}
if (options.hasOwnProperty('schema')) {
Target = Target.schema(options.schema, options.schemaDelimiter);
}
if (!Array.isArray(instances)) {
instance = instances;
instances = undefined;
}
if (instances) {
where[association.targetKey] = {
$in: instances.map(function (instance) {
return instance.get(association.foreignKey);
})
};
} else {
if (association.targetKeyIsPrimary && !options.where) {
return Target.findById(instance.get(association.foreignKey), options);
} else {
where[association.targetKey] = instance.get(association.foreignKey);
options.limit = null;
}
}
options.where = options.where ?
{$and: [where, options.where]} :
where;
if (instances) {
return Target.findAll(options).then(function (results) {
var result = {};
instances.forEach(function (instance) {
result[instance.get(association.foreignKey, {raw: true})] = null;
});
results.forEach(function (instance) {
result[instance.get(association.targetKey, {raw: true})] = instance;
});
return result;
});
}
return Target.findOne(options);
}...
options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
};
QueryInterface.prototype.dropAllTables = function(options) {
var self = this
, skip;
...injectAttributes = function () {
var newAttributes = {};
newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, {
type: this.options.keyType || this.target.rawAttributes[this.targetKey].type,
allowNull : true
});
if (this.options.constraints !== false) {
var source = this.source.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];
this.options.onDelete = this.options.onDelete || (source.allowNull ? 'SET NULL' : 'NO ACTION');
this.options.onUpdate = this.options.onUpdate || 'CASCADE';
}
Helpers.addForeignKeyConstraints(newAttributes[this.foreignKey], this.target, this.source, this.options, this.targetKeyField);
Utils.mergeDefaults(this.source.rawAttributes, newAttributes);
this.identifierField = this.source.rawAttributes[this.foreignKey].field || this.foreignKey;
this.source.refreshAttributes();
Helpers.checkNamingCollision(this);
return this;
}n/a
injectCreator = function (instancePrototype) {
var association = this;
instancePrototype[this.accessors.create] = function(values, fieldsOrOptions) {
var instance = this
, options = {};
if ((fieldsOrOptions || {}).transaction instanceof Transaction) {
options.transaction = fieldsOrOptions.transaction;
}
options.logging = (fieldsOrOptions || {}).logging;
return association.target.create(values, fieldsOrOptions).then(function(newAssociatedObject) {
return instance[association.accessors.set](newAssociatedObject, options);
});
};
return this;
}n/a
injectSetter = function (instancePrototype) {
var association = this;
instancePrototype[this.accessors.set] = function(associatedInstance, options) {
options = options || {};
var value = associatedInstance;
if (associatedInstance instanceof association.target.Instance) {
value = associatedInstance[association.targetKey];
}
this.set(association.foreignKey, value);
if (options.save === false) return;
options = _.extend({
fields: [association.foreignKey],
allowNull: [association.foreignKey],
association: true
}, options);
// passes the changed field to save, so only that field get updated.
return this.save(options);
};
return this;
}n/a
mixin = function (obj) {
var association = this;
obj[this.accessors.get] = function(options) {
return association.get(this, options);
};
association.injectSetter(obj);
association.injectCreator(obj);
}...
*/
module.exports = {
hooks: hookTypes,
hookAliases: hookAliases,
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
...BelongsToMany = function (source, target, options) {
Association.call(this);
options = options || {};
if (options.through === undefined || options.through === true || options.through === null) {
throw new Error('belongsToMany must be given a through option, either a string or a model');
}
if (!options.through.model) {
options.through = {
model: options.through
};
}
this.associationType = 'BelongsToMany';
this.source = source;
this.target = target;
this.targetAssociation = null;
this.options = options;
this.sequelize = source.modelManager.sequelize;
this.through = _.assign({}, options.through);
this.scope = options.scope;
this.isMultiAssociation = true;
this.isSelfAssociation = this.source === this.target;
this.doubleLinked = false;
this.as = this.options.as;
if (!this.as && this.isSelfAssociation) {
throw new Error('\'as\' must be defined for many-to-many self-associations');
}
if (this.as) {
this.isAliased = true;
if (Utils._.isPlainObject(this.as)) {
this.options.name = this.as;
this.as = this.as.plural;
} else {
this.options.name = {
plural: this.as,
singular: Utils.singularize(this.as)
};
}
} else {
this.as = this.target.options.name.plural;
this.options.name = this.target.options.name;
}
this.combinedTableName = Utils.combineTableNames(
this.source.tableName,
this.isSelfAssociation ? (this.as || this.target.tableName) : this.target.tableName
);
/*
* If self association, this is the target association - Unless we find a pairing association
*/
if (this.isSelfAssociation) {
this.targetAssociation = this;
}
/*
* Default/generated foreign/other keys
*/
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else {
if (!this.options.foreignKey) {
this.foreignKeyDefault = true;
}
this.foreignKeyAttribute = {};
this.foreignKey = this.options.foreignKey || Utils.camelizeIf(
[
Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
if (_.isObject(this.options.otherKey)) {
this.otherKeyAttribute = this.options.otherKey;
this.otherKey = this.otherKeyAttribute.name || this.otherKeyAttribute.fieldName;
} else {
if (!this.options.otherKey) {
this.otherKeyDefault = true;
}
this.otherKeyAttribute = {};
this.otherKey = this.options.otherKey || Utils.camelizeIf(
[
Utils.underscoredIf(
this.isSelfAssociation ?
Utils.singularize(this.as) :
this.target.options.name.singular,
this.target.options.underscored
),
this.target.primaryKeyAttribute
].join('_'),
!this.target.options.underscored
);
}
/*
* Find paired association (if exists)
*/
_.each(this.target.associations, function(association) {
if (association.associationType !== 'BelongsToMany') return;
if (association.target !== this.source) return;
if (this.options.through.model === association.options.through.model) {
this.paired = association;
association.paired = this;
}
}.bind(this));
if (typeof this.through.model === 'string') {
if (!this.sequelize.isDefined(this.through.model)) {
this.through.model = this.sequelize.define(this.through.model, {}, _.extend(this.options, {
tableName: this.through.model,
indexes: [], //we don't want indexes here (as referenced in #2416)
paranoid: false, // A paranoid join table does not make sense
validate: {} // Don't propagate model-level validations
}));
} else {
this.through.model = this.sequelize.model(this.through.model);
}
}
this.options = _.assign(this.options, _.pick(this.through.model.options, [
'timestamps', 'createdAt', 'updatedAt ...n/a
default = function (source, target, options) {
Association.call(this);
options = options || {};
if (options.through === undefined || options.through === true || options.through === null) {
throw new Error('belongsToMany must be given a through option, either a string or a model');
}
if (!options.through.model) {
options.through = {
model: options.through
};
}
this.associationType = 'BelongsToMany';
this.source = source;
this.target = target;
this.targetAssociation = null;
this.options = options;
this.sequelize = source.modelManager.sequelize;
this.through = _.assign({}, options.through);
this.scope = options.scope;
this.isMultiAssociation = true;
this.isSelfAssociation = this.source === this.target;
this.doubleLinked = false;
this.as = this.options.as;
if (!this.as && this.isSelfAssociation) {
throw new Error('\'as\' must be defined for many-to-many self-associations');
}
if (this.as) {
this.isAliased = true;
if (Utils._.isPlainObject(this.as)) {
this.options.name = this.as;
this.as = this.as.plural;
} else {
this.options.name = {
plural: this.as,
singular: Utils.singularize(this.as)
};
}
} else {
this.as = this.target.options.name.plural;
this.options.name = this.target.options.name;
}
this.combinedTableName = Utils.combineTableNames(
this.source.tableName,
this.isSelfAssociation ? (this.as || this.target.tableName) : this.target.tableName
);
/*
* If self association, this is the target association - Unless we find a pairing association
*/
if (this.isSelfAssociation) {
this.targetAssociation = this;
}
/*
* Default/generated foreign/other keys
*/
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else {
if (!this.options.foreignKey) {
this.foreignKeyDefault = true;
}
this.foreignKeyAttribute = {};
this.foreignKey = this.options.foreignKey || Utils.camelizeIf(
[
Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
if (_.isObject(this.options.otherKey)) {
this.otherKeyAttribute = this.options.otherKey;
this.otherKey = this.otherKeyAttribute.name || this.otherKeyAttribute.fieldName;
} else {
if (!this.options.otherKey) {
this.otherKeyDefault = true;
}
this.otherKeyAttribute = {};
this.otherKey = this.options.otherKey || Utils.camelizeIf(
[
Utils.underscoredIf(
this.isSelfAssociation ?
Utils.singularize(this.as) :
this.target.options.name.singular,
this.target.options.underscored
),
this.target.primaryKeyAttribute
].join('_'),
!this.target.options.underscored
);
}
/*
* Find paired association (if exists)
*/
_.each(this.target.associations, function(association) {
if (association.associationType !== 'BelongsToMany') return;
if (association.target !== this.source) return;
if (this.options.through.model === association.options.through.model) {
this.paired = association;
association.paired = this;
}
}.bind(this));
if (typeof this.through.model === 'string') {
if (!this.sequelize.isDefined(this.through.model)) {
this.through.model = this.sequelize.define(this.through.model, {}, _.extend(this.options, {
tableName: this.through.model,
indexes: [], //we don't want indexes here (as referenced in #2416)
paranoid: false, // A paranoid join table does not make sense
validate: {} // Don't propagate model-level validations
}));
} else {
this.through.model = this.sequelize.model(this.through.model);
}
}
this.options = _.assign(this.options, _.pick(this.through.model.options, [
'timestamps', 'createdAt', 'updatedAt ...n/a
super_ = function () {}n/a
get = function (instance, options) {
options = Utils.cloneDeep(options) || {};
var association = this
, through = association.through
, scopeWhere
, throughWhere;
if (association.scope) {
scopeWhere = _.clone(association.scope);
}
options.where = {
$and: [
scopeWhere,
options.where
]
};
if (Object(through.model) === through.model) {
throughWhere = {};
throughWhere[association.foreignKey] = instance.get(association.source.primaryKeyAttribute);
if (through.scope) {
_.assign(throughWhere, through.scope);
}
//If a user pass a where on the options through options, make an "and" with the current throughWhere
if (options.through && options.through.where) {
throughWhere = {
$and: [throughWhere, options.through.where]
};
}
options.include = options.include || [];
options.include.push({
association: association.oneFromTarget,
attributes: options.joinTableAttributes,
required: true,
where: throughWhere
});
}
var model = association.target;
if (options.hasOwnProperty('scope')) {
if (!options.scope) {
model = model.unscoped();
} else {
model = model.scope(options.scope);
}
}
if (options.hasOwnProperty('schema')) {
model = model.schema(options.schema, options.schemaDelimiter);
}
return model.findAll(options);
}...
options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
};
QueryInterface.prototype.dropAllTables = function(options) {
var self = this
, skip;
...injectAttributes = function () {
var self = this;
this.identifier = this.foreignKey;
this.foreignIdentifier = this.otherKey;
// remove any PKs previously defined by sequelize
// but ignore any keys that are part of this association (#5865)
_.each(this.through.model.rawAttributes, function(attribute, attributeName) {
if (attribute.primaryKey === true && attribute._autoGenerated === true) {
if (attributeName === self.foreignKey || attributeName === self.otherKey) {
// this key is still needed as it's part of the association
// so just set primaryKey to false
attribute.primaryKey = false;
}
else {
delete self.through.model.rawAttributes[attributeName];
}
self.primaryKeyDeleted = true;
}
});
var sourceKey = this.source.rawAttributes[this.source.primaryKeyAttribute]
, sourceKeyType = sourceKey.type
, sourceKeyField = sourceKey.field || this.source.primaryKeyAttribute
, targetKey = this.target.rawAttributes[this.target.primaryKeyAttribute]
, targetKeyType = targetKey.type
, targetKeyField = targetKey.field || this.target.primaryKeyAttribute
, sourceAttribute = _.defaults({}, this.foreignKeyAttribute, { type: sourceKeyType })
, targetAttribute = _.defaults({}, this.otherKeyAttribute, { type: targetKeyType });
if (this.primaryKeyDeleted === true) {
targetAttribute.primaryKey = sourceAttribute.primaryKey = true;
} else if (this.through.unique !== false) {
var uniqueKey = [this.through.model.tableName, this.foreignKey, this.otherKey, 'unique'].join('_');
targetAttribute.unique = sourceAttribute.unique = uniqueKey;
}
if (!this.through.model.rawAttributes[this.foreignKey]) {
this.through.model.rawAttributes[this.foreignKey] = {
_autoGenerated: true
};
}
if (!this.through.model.rawAttributes[this.otherKey]) {
this.through.model.rawAttributes[this.otherKey] = {
_autoGenerated: true
};
}
if (this.options.constraints !== false) {
sourceAttribute.references = {
model: this.source.getTableName(),
key: sourceKeyField
};
// For the source attribute the passed option is the priority
sourceAttribute.onDelete = this.options.onDelete || this.through.model.rawAttributes[this.foreignKey].onDelete;
sourceAttribute.onUpdate = this.options.onUpdate || this.through.model.rawAttributes[this.foreignKey].onUpdate;
if (!sourceAttribute.onDelete) sourceAttribute.onDelete = 'CASCADE';
if (!sourceAttribute.onUpdate) sourceAttribute.onUpdate = 'CASCADE';
targetAttribute.references = {
model: this.target.getTableName(),
key: targetKeyField
};
// But the for target attribute the previously defined option is the priority (since it could've been set by another belongsToMany
call)
targetAttribute.onDelete = this.through.model.rawAttributes[this.otherKey].onDelete || this.options.onDelete;
targetAttribute.onUpdate = this.through.model.rawAttributes[this.otherKey].onUpdate || this.options.onUpdate;
if (!targetAttribute.onDelete) targetAttribute.onDelete = 'CASCADE';
if (!targetAttribute.onUpdate) targetAttribute.onUpdate = 'CASCADE';
}
this.through.model.rawAttributes[this.foreignKey] = _.extend(this.through.model.rawAttributes[this.foreignKey], sourceAttribute
);
this.through.model.rawAttributes[this.otherKey] = _.extend(this.through.model.rawAttributes[this.otherKey], targetAttribute);
this.identifierField = this.through.model.rawAttributes[this.foreignKey].field || this.foreignKey;
this.foreignIdentifierField = this.through.model.rawAttributes[this.otherKey].field || this.otherKey;
if (this.paired && !this.paired.foreignIdentifierField) {
this.paired.foreignIdentifierField = this.through.model.rawAttributes[this.paired.otherKey].field || this.paired.otherKey;
}
this.through.model.refreshAttributes();
this.toSource = new BelongsTo(this.through.model, this.source, {
foreignKey: this.foreignKey
});
this.manyFromSource = new HasMany(this.source, this.through.model, {
foreignKey: this.fo ...n/a
injectCreator = function (obj) {
var association = this;
obj[this.accessors.create] = function(values, options) {
var instance = this;
options = options || {};
values = values || {};
if (Array.isArray(options)) {
options = {
fields: options
};
}
if (association.scope) {
_.assign(values, association.scope);
if (options.fields) {
options.fields = options.fields.concat(Object.keys(association.scope));
}
}
// Create the related model instance
return association.target.create(values, options).then(function(newAssociatedObject) {
return instance[association.accessors.add](newAssociatedObject, _.omit(options, ['fields'])).return(newAssociatedObject);
});
};
return this;
}n/a
injectGetter = function (obj) {
var association = this;
obj[this.accessors.get] = function(options) {
return association.get(this, options);
};
obj[this.accessors.count] = function(options) {
var model = association.target
, sequelize = model.sequelize;
options = Utils.cloneDeep(options);
options.attributes = [
[sequelize.fn('COUNT', sequelize.col([association.target.name, model.primaryKeyAttribute].join('.'))), 'count']
];
options.joinTableAttributes = [];
options.raw = true;
options.plain = true;
return obj[association.accessors.get].call(this, options).then(function (result) {
return parseInt(result.count, 10);
});
};
obj[this.accessors.hasSingle] = obj[this.accessors.hasAll] = function(instances, options) {
var where = {};
if (!Array.isArray(instances)) {
instances = [instances];
}
options = _.assign({
raw: true
}, options, {
scope: false
});
where.$or = instances.map(function (instance) {
if (instance instanceof association.target.Instance) {
return instance.where();
} else {
var $where = {};
$where[association.target.primaryKeyAttribute] = instance;
return $where;
}
});
options.where = {
$and: [
where,
options.where
]
};
return this[association.accessors.get](options).then(function(associatedObjects) {
return associatedObjects.length === instances.length;
});
};
return this;
}n/a
injectSetter = function (obj) {
var association = this;
obj[this.accessors.set] = function(newAssociatedObjects, options) {
options = options || {};
var instance = this
, sourceKey = association.source.primaryKeyAttribute
, targetKey = association.target.primaryKeyAttribute
, identifier = association.identifier
, foreignIdentifier = association.foreignIdentifier
, where = {};
if (newAssociatedObjects === null) {
newAssociatedObjects = [];
} else {
newAssociatedObjects = association.toInstanceArray(newAssociatedObjects);
}
where[identifier] = this.get(sourceKey);
_.assign(where, association.through.scope);
return association.through.model.findAll(_.defaults({
where: where,
raw: true,
}, options)).then(function (currentRows) {
var obsoleteAssociations = []
, defaultAttributes = options
, promises = []
, unassociatedObjects;
// Don't try to insert the transaction as an attribute in the through table
defaultAttributes = _.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', '
fields', 'logging']);
unassociatedObjects = newAssociatedObjects.filter(function(obj) {
return !_.find(currentRows, function(currentRow) {
return currentRow[foreignIdentifier] === obj.get(targetKey);
});
});
currentRows.forEach(function(currentRow) {
var newObj = _.find(newAssociatedObjects, function(obj) {
return currentRow[foreignIdentifier] === obj.get(targetKey);
});
if (!newObj) {
obsoleteAssociations.push(currentRow);
} else {
var throughAttributes = newObj[association.through.model.name];
// Quick-fix for subtle bug when using existing objects that might have the through model attached (not as an attribute
object)
if (throughAttributes instanceof association.through.model.Instance) {
throughAttributes = {};
}
var where = {}
, attributes = _.defaults({}, throughAttributes, defaultAttributes);
where[identifier] = instance.get(sourceKey);
where[foreignIdentifier] = newObj.get(targetKey);
if (Object.keys(attributes).length) {
promises.push(association.through.model.update(attributes, _.extend(options, {
where: where
})));
}
}
});
if (obsoleteAssociations.length > 0) {
var where = {};
where[identifier] = instance.get(sourceKey);
where[foreignIdentifier] = obsoleteAssociations.map(function(obsoleteAssociation) {
return obsoleteAssociation[foreignIdentifier];
});
promises.push(association.through.model.destroy(_.defaults({
where: where
}, options)));
}
if (unassociatedObjects.length > 0) {
var bulk = unassociatedObjects.map(function(unassociatedObject) {
var attributes = {};
attributes[identifier] = instance.get(sourceKey);
attributes[foreignIdentifier] = unassociatedObject.get(targetKey);
attributes = _.defaults(attributes, unassociatedObject[association.through.model.name], defaultAttributes);
_.assign(attributes, association.through.scope);
return attributes;
}.bind(this));
promises.push(association.through.model.bulkCreate(bulk, _.assign({ validate: true }, options)));
}
return Utils.Promise.all(promises);
});
};
obj[this.accessors.addMultiple] = obj[this.accessors.add] = function(newInstances, additionalAttributes) {
// If newInstances is null or undefined, no-op
if (!newInstances) return Utils.Promise.resolve();
additionalAttributes = _.clone(additionalAttributes) || {};
var instance = this
, defaultAttributes = _.omit(additionalAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate
', 'fields', 'logging'])
, sourceKey = association.source.primaryKeyAttr ...n/a
HasMany = function (source, target, options) {
Association.call(this);
this.associationType = 'HasMany';
this.source = source;
this.target = target;
this.targetAssociation = null;
this.options = options || {};
this.sequelize = source.modelManager.sequelize;
this.through = options.through;
this.scope = options.scope;
this.isMultiAssociation = true;
this.isSelfAssociation = this.source === this.target;
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.options.through) {
throw new Error('N:M associations are not supported with hasMany. Use belongsToMany instead');
}
/*
* If self association, this is the target association
*/
if (this.isSelfAssociation) {
this.targetAssociation = this;
}
if (this.as) {
this.isAliased = true;
if (_.isPlainObject(this.as)) {
this.options.name = this.as;
this.as = this.as.plural;
} else {
this.options.name = {
plural: this.as,
singular: Utils.singularize(this.as)
};
}
} else {
this.as = this.target.options.name.plural;
this.options.name = this.target.options.name;
}
/*
* Foreign key setup
*/
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
if (this.target.rawAttributes[this.foreignKey]) {
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
}
this.sourceKey = this.options.sourceKey || this.source.primaryKeyAttribute;
if (this.target.rawAttributes[this.sourceKey]) {
this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;
} else {
this.sourceKeyField = this.sourceKey;
}
if (this.source.fieldRawAttributesMap[this.sourceKey]) {
this.sourceKeyAttribute = this.source.fieldRawAttributesMap[this.sourceKey].fieldName;
} else {
this.sourceKeyAttribute = this.source.primaryKeyAttribute;
}
this.sourceIdentifier = this.sourceKey;
this.associationAccessor = this.as;
// Get singular and plural names, trying to uppercase the first letter, unless the model forbids it
var plural = Utils.uppercaseFirst(this.options.name.plural)
, singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Array<Instance>>}
* @method getAssociations
*/
get: 'get' + plural,
/**
* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the
passed array will be un-associated
*
* @param {Array<Instance|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate
with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model
* @return {Promise}
* @method setAssociations
*/
set: 'set' + plural,
/**
* Associate several persisted instances with this.
*
* @param {Array<In ...n/a
default = function (source, target, options) {
Association.call(this);
this.associationType = 'HasMany';
this.source = source;
this.target = target;
this.targetAssociation = null;
this.options = options || {};
this.sequelize = source.modelManager.sequelize;
this.through = options.through;
this.scope = options.scope;
this.isMultiAssociation = true;
this.isSelfAssociation = this.source === this.target;
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.options.through) {
throw new Error('N:M associations are not supported with hasMany. Use belongsToMany instead');
}
/*
* If self association, this is the target association
*/
if (this.isSelfAssociation) {
this.targetAssociation = this;
}
if (this.as) {
this.isAliased = true;
if (_.isPlainObject(this.as)) {
this.options.name = this.as;
this.as = this.as.plural;
} else {
this.options.name = {
plural: this.as,
singular: Utils.singularize(this.as)
};
}
} else {
this.as = this.target.options.name.plural;
this.options.name = this.target.options.name;
}
/*
* Foreign key setup
*/
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
if (this.target.rawAttributes[this.foreignKey]) {
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
}
this.sourceKey = this.options.sourceKey || this.source.primaryKeyAttribute;
if (this.target.rawAttributes[this.sourceKey]) {
this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;
} else {
this.sourceKeyField = this.sourceKey;
}
if (this.source.fieldRawAttributesMap[this.sourceKey]) {
this.sourceKeyAttribute = this.source.fieldRawAttributesMap[this.sourceKey].fieldName;
} else {
this.sourceKeyAttribute = this.source.primaryKeyAttribute;
}
this.sourceIdentifier = this.sourceKey;
this.associationAccessor = this.as;
// Get singular and plural names, trying to uppercase the first letter, unless the model forbids it
var plural = Utils.uppercaseFirst(this.options.name.plural)
, singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Array<Instance>>}
* @method getAssociations
*/
get: 'get' + plural,
/**
* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the
passed array will be un-associated
*
* @param {Array<Instance|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate
with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model
* @return {Promise}
* @method setAssociations
*/
set: 'set' + plural,
/**
* Associate several persisted instances with this.
*
* @param {Array<In ...n/a
super_ = function () {}n/a
add = function (sourceInstance, targetInstances, options) {
if (!targetInstances) return Utils.Promise.resolve();
var association = this
, update = {}
, where = {};
options = options || {};
targetInstances = association.toInstanceArray(targetInstances);
update[association.foreignKey] = sourceInstance.get(association.sourceKey);
_.assign(update, association.scope);
where[association.target.primaryKeyAttribute] = targetInstances.map(function (unassociatedObject) {
return unassociatedObject.get(association.target.primaryKeyAttribute);
});
return association.target.unscoped().update(
update,
_.defaults({
where: where
}, options)
).return(sourceInstance);
}...
}
}
deps = deps.filter(function(dep) {
return tableName !== dep;
});
sorter.add(tableName, deps);
});
sorted = sorter.sort();
if (options.reverse) {
sorted = sorted.reverse();
}
sorted.forEach(function(name) {
...count = function (instance, options) {
var association = this
, model = association.target
, sequelize = model.sequelize;
options = Utils.cloneDeep(options);
options.attributes = [
[sequelize.fn('COUNT', sequelize.col(model.primaryKeyField)), 'count']
];
options.raw = true;
options.plain = true;
return this.get(instance, options).then(function (result) {
return parseInt(result.count, 10);
});
}n/a
create = function (sourceInstance, values, options) {
var association = this;
options = options || {};
if (Array.isArray(options)) {
options = {
fields: options
};
}
if (values === undefined) {
values = {};
}
if (association.scope) {
Object.keys(association.scope).forEach(function (attribute) {
values[attribute] = association.scope[attribute];
if (options.fields) options.fields.push(attribute);
});
}
values[association.foreignKey] = sourceInstance.get(association.sourceKey);
if (options.fields) options.fields.push(association.foreignKey);
return association.target.create(values, options);
}n/a
get = function (instances, options) {
var association = this
, where = {}
, Model = association.target
, instance
, values;
if (!Array.isArray(instances)) {
instance = instances;
instances = undefined;
}
options = Utils.cloneDeep(options) || {};
if (association.scope) {
_.assign(where, association.scope);
}
if (instances) {
values = instances.map(function (instance) {
return instance.get(association.sourceKey, {raw: true});
});
if (options.limit && instances.length > 1) {
options.groupedLimit = {
limit: options.limit,
on: association.foreignKeyField,
values: values
};
delete options.limit;
} else {
where[association.foreignKey] = {
$in: values
};
delete options.groupedLimit;
}
} else {
where[association.foreignKey] = instance.get(association.sourceKey, {raw: true});
}
options.where = options.where ?
{$and: [where, options.where]} :
where;
if (options.hasOwnProperty('scope')) {
if (!options.scope) {
Model = Model.unscoped();
} else {
Model = Model.scope(options.scope);
}
}
if (options.hasOwnProperty('schema')) {
Model = Model.schema(options.schema, options.schemaDelimiter);
}
return Model.findAll(options).then(function (results) {
if (instance) return results;
var result = {};
instances.forEach(function (instance) {
result[instance.get(association.sourceKey, {raw: true})] = [];
});
results.forEach(function (instance) {
result[instance.get(association.foreignKey, {raw: true})].push(instance);
});
return result;
});
}...
options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
};
QueryInterface.prototype.dropAllTables = function(options) {
var self = this
, skip;
...has = function (sourceInstance, targetInstances, options) {
var association = this
, where = {};
if (!Array.isArray(targetInstances)) {
targetInstances = [targetInstances];
}
options = _.assign({}, options, {
scope: false,
raw: true
});
where.$or = targetInstances.map(function (instance) {
if (instance instanceof association.target.Instance) {
return instance.where();
} else {
var _where = {};
_where[association.target.primaryKeyAttribute] = instance;
return _where;
}
});
options.where = {
$and: [
where,
options.where
]
};
return this.get(
sourceInstance,
options
).then(function(associatedObjects) {
return associatedObjects.length === targetInstances.length;
});
}n/a
injectAttributes = function () {
var newAttributes = {};
var constraintOptions = _.clone(this.options); // Create a new options object for use with addForeignKeyConstraints, to avoid
polluting this.options in case it is later used for a n:m
newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, {
type: this.options.keyType || this.source.rawAttributes[this.sourceKeyAttribute].type,
allowNull : true
});
if (this.options.constraints !== false) {
var target = this.target.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];
constraintOptions.onDelete = constraintOptions.onDelete || (target.allowNull ? 'SET NULL' : 'CASCADE');
constraintOptions.onUpdate = constraintOptions.onUpdate || 'CASCADE';
}
Helpers.addForeignKeyConstraints(newAttributes[this.foreignKey], this.source, this.target, constraintOptions, this.sourceKeyField
);
Utils.mergeDefaults(this.target.rawAttributes, newAttributes);
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
this.target.refreshAttributes();
this.source.refreshAttributes();
Helpers.checkNamingCollision(this);
return this;
}n/a
mixin = function (obj) {
var association = this;
obj[this.accessors.get] = function(options) {
return association.get(this, options);
};
if (this.accessors.count) {
obj[this.accessors.count] = function(options) {
return association.count(this, options);
};
}
obj[this.accessors.hasSingle] = obj[this.accessors.hasAll] = function(instances, options) {
return association.has(this, instances, options);
};
obj[this.accessors.set] = function(instances, options) {
return association.set(this, instances, options);
};
obj[this.accessors.add] = obj[this.accessors.addMultiple] = function(instances, options) {
return association.add(this, instances, options);
};
obj[this.accessors.remove] = obj[this.accessors.removeMultiple] = function(instances, options) {
return association.remove(this, instances, options);
};
obj[this.accessors.create] = function(values, options) {
return association.create(this, values, options);
};
}...
*/
module.exports = {
hooks: hookTypes,
hookAliases: hookAliases,
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
...remove = function (sourceInstance, targetInstances, options) {
var association = this
, update = {}
, where = {};
options = options || {};
targetInstances = association.toInstanceArray(targetInstances);
update[association.foreignKey] = null;
where[association.foreignKey] = sourceInstance.get(association.sourceKey);
where[association.target.primaryKeyAttribute] = targetInstances.map(function (targetInstance) {
return targetInstance.get(association.target.primaryKeyAttribute);
});
return association.target.unscoped().update(
update,
_.defaults({
where: where
}, options)
).return(this);
}n/a
set = function (sourceInstance, targetInstances, options) {
var association = this;
if (targetInstances === null) {
targetInstances = [];
} else {
targetInstances = association.toInstanceArray(targetInstances);
}
return association.get(sourceInstance, _.defaults({
scope: false,
raw: true
}, options)).then(function(oldAssociations) {
var promises = []
, obsoleteAssociations = oldAssociations.filter(function(old) {
return !_.find(targetInstances, function(obj) {
return obj[association.target.primaryKeyAttribute] === old[association.target.primaryKeyAttribute];
});
})
, unassociatedObjects = targetInstances.filter(function(obj) {
return !_.find(oldAssociations, function(old) {
return obj[association.target.primaryKeyAttribute] === old[association.target.primaryKeyAttribute];
});
})
, updateWhere
, update;
if (obsoleteAssociations.length > 0) {
update = {};
update[association.foreignKey] = null;
updateWhere = {};
updateWhere[association.target.primaryKeyAttribute] = obsoleteAssociations.map(function(associatedObject) {
return associatedObject[association.target.primaryKeyAttribute];
});
promises.push(association.target.unscoped().update(
update,
_.defaults({
where: updateWhere
}, options)
));
}
if (unassociatedObjects.length > 0) {
updateWhere = {};
update = {};
update[association.foreignKey] = sourceInstance.get(association.sourceKey);
_.assign(update, association.scope);
updateWhere[association.target.primaryKeyAttribute] = unassociatedObjects.map(function(unassociatedObject) {
return unassociatedObject[association.target.primaryKeyAttribute];
});
promises.push(association.target.unscoped().update(
update,
_.defaults({
where: updateWhere
}, options)
));
}
return Utils.Promise.all(promises).return(sourceInstance);
});
}n/a
HasOne = function (srcModel, targetModel, options) {
Association.call(this);
this.associationType = 'HasOne';
this.source = srcModel;
this.target = targetModel;
this.options = options;
this.scope = options.scope;
this.isSingleAssociation = true;
this.isSelfAssociation = (this.source === this.target);
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.as) {
this.isAliased = true;
this.options.name = {
singular: this.as
};
} else {
this.as = this.target.options.name.singular;
this.options.name = this.target.options.name;
}
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(Utils.singularize(this.source.name), this.target.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
this.sourceIdentifier = this.source.primaryKeyAttribute;
this.sourceKey = this.source.primaryKeyAttribute;
this.sourceKeyIsPrimary = this.sourceKey === this.source.primaryKeyAttribute;
this.associationAccessor = this.as;
this.options.useHooks = options.useHooks;
if (this.target.rawAttributes[this.foreignKey]) {
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
}
// Get singular name, trying to uppercase the first letter, unless the model forbids it
var singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Instance>}
* @method getAssociation
*/
get: 'get' + singular,
/**
* Set the associated model.
*
* @param {Instance|String|Number} [newAssociation] An persisted instance or the primary key of a persisted instance to associate
with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to getAssociation and `target.save`
* @return {Promise}
* @method setAssociation
*/
set: 'set' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @return {Promise}
* @method createAssociation
*/
create: 'create' + singular
};
}n/a
default = function (srcModel, targetModel, options) {
Association.call(this);
this.associationType = 'HasOne';
this.source = srcModel;
this.target = targetModel;
this.options = options;
this.scope = options.scope;
this.isSingleAssociation = true;
this.isSelfAssociation = (this.source === this.target);
this.as = this.options.as;
this.foreignKeyAttribute = {};
if (this.as) {
this.isAliased = true;
this.options.name = {
singular: this.as
};
} else {
this.as = this.target.options.name.singular;
this.options.name = this.target.options.name;
}
if (_.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else if (this.options.foreignKey) {
this.foreignKey = this.options.foreignKey;
}
if (!this.foreignKey) {
this.foreignKey = Utils.camelizeIf(
[
Utils.underscoredIf(Utils.singularize(this.source.name), this.target.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
this.sourceIdentifier = this.source.primaryKeyAttribute;
this.sourceKey = this.source.primaryKeyAttribute;
this.sourceKeyIsPrimary = this.sourceKey === this.source.primaryKeyAttribute;
this.associationAccessor = this.as;
this.options.useHooks = options.useHooks;
if (this.target.rawAttributes[this.foreignKey]) {
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
}
// Get singular name, trying to uppercase the first letter, unless the model forbids it
var singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @return {Promise<Instance>}
* @method getAssociation
*/
get: 'get' + singular,
/**
* Set the associated model.
*
* @param {Instance|String|Number} [newAssociation] An persisted instance or the primary key of a persisted instance to associate
with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to getAssociation and `target.save`
* @return {Promise}
* @method setAssociation
*/
set: 'set' + singular,
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @return {Promise}
* @method createAssociation
*/
create: 'create' + singular
};
}n/a
super_ = function () {}n/a
get = function (instances, options) {
var association = this
, Target = association.target
, instance
, where = {};
options = Utils.cloneDeep(options);
if (options.hasOwnProperty('scope')) {
if (!options.scope) {
Target = Target.unscoped();
} else {
Target = Target.scope(options.scope);
}
}
if (options.hasOwnProperty('schema')) {
Target = Target.schema(options.schema, options.schemaDelimiter);
}
if (!Array.isArray(instances)) {
instance = instances;
instances = undefined;
}
if (instances) {
where[association.foreignKey] = {
$in: instances.map(function (instance) {
return instance.get(association.sourceKey);
})
};
} else {
where[association.foreignKey] = instance.get(association.sourceKey);
}
if (association.scope) {
_.assign(where, association.scope);
}
options.where = options.where ?
{$and: [where, options.where]} :
where;
if (instances) {
return Target.findAll(options).then(function (results) {
var result = {};
instances.forEach(function (instance) {
result[instance.get(association.sourceKey, {raw: true})] = null;
});
results.forEach(function (instance) {
result[instance.get(association.foreignKey, {raw: true})] = instance;
});
return result;
});
}
return Target.findOne(options);
}...
options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
};
QueryInterface.prototype.dropAllTables = function(options) {
var self = this
, skip;
...injectAttributes = function () {
var newAttributes = {}
, keyType = this.source.rawAttributes[this.source.primaryKeyAttribute].type;
newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, {
type: this.options.keyType || keyType,
allowNull : true
});
Utils.mergeDefaults(this.target.rawAttributes, newAttributes);
this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
if (this.options.constraints !== false) {
var target = this.target.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];
this.options.onDelete = this.options.onDelete || (target.allowNull ? 'SET NULL' : 'CASCADE');
this.options.onUpdate = this.options.onUpdate || 'CASCADE';
}
Helpers.addForeignKeyConstraints(this.target.rawAttributes[this.foreignKey], this.source, this.target, this.options);
// Sync attributes and setters/getters to Model prototype
this.target.refreshAttributes();
Helpers.checkNamingCollision(this);
return this;
}n/a
injectCreator = function (instancePrototype) {
var association = this;
instancePrototype[this.accessors.create] = function(values, options) {
var instance = this;
values = values || {};
options = options || {};
if (association.scope) {
Object.keys(association.scope).forEach(function (attribute) {
values[attribute] = association.scope[attribute];
if (options.fields) options.fields.push(attribute);
});
}
values[association.foreignKey] = instance.get(association.sourceIdentifier);
if (options.fields) options.fields.push(association.foreignKey);
return association.target.create(values, options);
};
return this;
}n/a
injectSetter = function (instancePrototype) {
var association = this;
instancePrototype[this.accessors.set] = function(associatedInstance, options) {
var instance = this,
alreadyAssociated;
options = _.assign({}, options, {
scope: false
});
return instance[association.accessors.get](options).then(function(oldInstance) {
// TODO Use equals method once #5605 is resolved
alreadyAssociated = oldInstance && associatedInstance && _.every(association.target.primaryKeyAttributes, function(attribute
) {
return oldInstance.get(attribute, {raw: true}) === associatedInstance.get(attribute, {raw: true});
});
if (oldInstance && !alreadyAssociated) {
oldInstance[association.foreignKey] = null;
return oldInstance.save(_.extend({}, options, {
fields: [association.foreignKey],
allowNull: [association.foreignKey],
association: true
}));
}
}).then(function() {
if (associatedInstance && !alreadyAssociated) {
if (!(associatedInstance instanceof association.target.Instance)) {
var tmpInstance = {};
tmpInstance[association.target.primaryKeyAttribute] = associatedInstance;
associatedInstance = association.target.build(tmpInstance, {
isNewRecord: false
});
}
_.assign(associatedInstance, association.scope);
associatedInstance.set(association.foreignKey, instance.get(association.sourceIdentifier));
return associatedInstance.save(options);
}
return null;
});
};
return this;
}n/a
mixin = function (obj) {
var association = this;
obj[this.accessors.get] = function(options) {
return association.get(this, options);
};
association.injectSetter(obj);
association.injectCreator(obj);
}...
*/
module.exports = {
hooks: hookTypes,
hookAliases: hookAliases,
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
...inspect = function () {
return this.as;
}n/a
toInstanceArray = function (objs) {
if (!Array.isArray(objs)) {
objs = [objs];
}
return objs.map(function(obj) {
if (!(obj instanceof this.target.Instance)) {
var tmpInstance = {};
tmpInstance[this.target.primaryKeyAttribute] = obj;
return this.target.build(tmpInstance, {
isNewRecord: false
});
}
return obj;
}, this);
}n/a
BIGINT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BIGINT)) return new BIGINT(options);
NUMBER.call(this, options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
validate = function (value) {
if (!Validator.isInt(String(value))) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid bigint', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...BLOB = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BLOB)) return new BLOB(options);
this.options = options;
this._length = options.length || '';
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
switch (this._length.toLowerCase()) {
case 'tiny':
return 'TINYBLOB';
case 'medium':
return 'MEDIUMBLOB';
case 'long':
return 'LONGBLOB';
default:
return this.key;
}
}n/a
validate = function (value) {
if (!_.isString(value) && !Buffer.isBuffer(value)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid blob', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...BOOLEAN = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'TINYINT(1)';
}n/a
validate = function (value) {
if (!Validator.isBoolean(String(value))) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid boolean', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...CHAR = function (length, binary) {
var options = typeof length === 'object' && length || {
length: length,
binary: binary
};
if (!(this instanceof CHAR)) return new CHAR(options);
STRING.apply(this, arguments);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'CHAR(' + this._length + ')' + ((this._binary) ? ' BINARY' : '');
}n/a
ConnectionError = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
super_ = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
ConnectionRefusedError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeConnectionRefusedError';
}n/a
super_ = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
ConnectionTimedOutError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeConnectionTimedOutError';
}n/a
super_ = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
DATE = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof DATE)) return new DATE(options);
this.options = options;
this._length = options.length || '';
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'DATETIME';
}n/a
validate = function (value) {
if (!Validator.isDate(String(value))) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid date', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...DATEONLY = function () {
if (!(this instanceof DATEONLY)) return new DATEONLY();
ABSTRACT.apply(this, arguments);
}n/a
super_ = function (options) {
}n/a
toSql = function () {
return 'DATE';
}n/a
DECIMAL = function (precision, scale) {
var options = typeof precision === 'object' && precision || {
precision: precision,
scale: scale
};
if (!(this instanceof DECIMAL)) return new DECIMAL(options);
NUMBER.call(this, options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
if (this._precision || this._scale) {
return 'DECIMAL(' + [this._precision, this._scale].filter(_.identity).join(',') + ')';
}
return 'DECIMAL';
}n/a
validate = function (value) {
if (!Validator.isDecimal(String(value))) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid decimal', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...DOUBLE = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof DOUBLE)) return new DOUBLE(options);
NUMBER.call(this, options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
ABSTRACT = function (options) {
}n/a
ARRAY = function (type) {
var options = _.isPlainObject(type) ? type : {
type: type
};
if (!(this instanceof ARRAY)) return new ARRAY(options);
this.type = typeof options.type === 'function' ? new options.type() : options.type;
}n/a
BIGINT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BIGINT)) return new BIGINT(options);
NUMBER.call(this, options);
}n/a
BLOB = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BLOB)) return new BLOB(options);
this.options = options;
this._length = options.length || '';
}n/a
BOOLEAN = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
CHAR = function (length, binary) {
var options = typeof length === 'object' && length || {
length: length,
binary: binary
};
if (!(this instanceof CHAR)) return new CHAR(options);
STRING.apply(this, arguments);
}n/a
DATE = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof DATE)) return new DATE(options);
this.options = options;
this._length = options.length || '';
}n/a
DATEONLY = function () {
if (!(this instanceof DATEONLY)) return new DATEONLY();
ABSTRACT.apply(this, arguments);
}n/a
DECIMAL = function (precision, scale) {
var options = typeof precision === 'object' && precision || {
precision: precision,
scale: scale
};
if (!(this instanceof DECIMAL)) return new DECIMAL(options);
NUMBER.call(this, options);
}n/a
DOUBLE = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof DOUBLE)) return new DOUBLE(options);
NUMBER.call(this, options);
}n/a
ENUM = function (value) {
var options = typeof value === 'object' && !Array.isArray(value) && value || {
values: Array.prototype.slice.call(arguments).reduce(function(result, element) {
return result.concat(Array.isArray(element) ? element : [element]);
}, [])
};
if (!(this instanceof ENUM)) return new ENUM(options);
this.values = options.values;
this.options = options;
}n/a
FLOAT = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof FLOAT)) return new FLOAT(options);
NUMBER.call(this, options);
}n/a
GEOGRAPHY = function (type, srid) {
var options = _.isPlainObject(type) ? type : {
type: type,
srid: srid
};
if (!(this instanceof GEOGRAPHY)) return new GEOGRAPHY(options);
this.options = options;
this.type = options.type;
this.srid = options.srid;
}n/a
GEOMETRY = function (type, srid) {
var options = _.isPlainObject(type) ? type : {
type: type,
srid: srid
};
if (!(this instanceof GEOMETRY)) return new GEOMETRY(options);
this.options = options;
this.type = options.type;
this.srid = options.srid;
}n/a
HSTORE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
INTEGER = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof INTEGER)) return new INTEGER(options);
NUMBER.call(this, options);
}n/a
JSON = function () {
if (!(this instanceof JSONTYPE)) return new JSONTYPE();
ABSTRACT.apply(this, arguments);
}n/a
JSONB = function () {
if (!(this instanceof JSONB)) return new JSONB();
JSONTYPE.apply(this, arguments);
}n/a
NONE = function (ReturnType, fields) {
if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields);
if (typeof ReturnType === 'function') ReturnType = new ReturnType();
this.returnType = ReturnType;
this.fields = fields;
}n/a
NOW = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
NUMBER = function (options) {
this.options = options;
this._length = options.length;
this._zerofill = options.zerofill;
this._decimals = options.decimals;
this._precision = options.precision;
this._scale = options.scale;
this._unsigned = options.unsigned;
}n/a
NUMERIC = function (precision, scale) {
var options = typeof precision === 'object' && precision || {
precision: precision,
scale: scale
};
if (!(this instanceof DECIMAL)) return new DECIMAL(options);
NUMBER.call(this, options);
}n/a
RANGE = function (subtype) {
var options = _.isPlainObject(subtype) ? subtype : { subtype: subtype };
if (!options.subtype) options.subtype = new INTEGER();
if (_.isFunction(options.subtype)) {
options.subtype = new options.subtype();
}
if (!(this instanceof RANGE)) return new RANGE(options);
ABSTRACT.apply(this, arguments);
this._subtype = options.subtype.key;
this.options = options;
}n/a
REAL = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof REAL)) return new REAL(options);
NUMBER.call(this, options);
}n/a
STRING = function (length, binary) {
var options = typeof length === 'object' && length || {
length: length,
binary: binary
};
if (!(this instanceof STRING)) return new STRING(options);
this.options = options;
this._binary = options.binary;
this._length = options.length || 255;
}n/a
TEXT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof TEXT)) return new TEXT(options);
this.options = options;
this._length = options.length || '';
}n/a
TIME = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
UUID = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
UUIDV1 = function () {
if (!(this instanceof UUIDV1)) return new UUIDV1();
ABSTRACT.apply(this, arguments);
}n/a
UUIDV4 = function () {
if (!(this instanceof UUIDV4)) return new UUIDV4();
ABSTRACT.apply(this, arguments);
}n/a
VIRTUAL = function (ReturnType, fields) {
if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields);
if (typeof ReturnType === 'function') ReturnType = new ReturnType();
this.returnType = ReturnType;
this.fields = fields;
}n/a
DatabaseError = function (parent) {
error.BaseError.apply(this, [parent.message]);
this.name = 'SequelizeDatabaseError';
/**
* The database specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
/**
* The SQL that triggered the error
* @member sql
*/
this.sql = parent.sql;
/**
* The message from the DB.
* @member message
* @name message
*/
/**
* The fields of the unique constraint
* @member fields
* @name fields
*/
/**
* The value(s) which triggered the error
* @member value
* @name value
*/
/**
* The name of the index that triggered the error
* @member index
* @name index
*/
}n/a
super_ = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
DEFERRABLE INITIALLY DEFERRED
n/a
DEFERRABLE INITIALLY IMMEDIATE
n/a
NOT DEFERRABLE
n/a
n/a
n/a
n/a
n/a
DEFERRABLE INITIALLY DEFERRED
n/a
function ABSTRACT() {}n/a
toString = function () {
var instance = new DeferrableType();
return instance.toString.apply(instance, arguments);
}n/a
toSql = function () {
return 'DEFERRABLE INITIALLY DEFERRED';
}n/a
toString = function () {
return this.toSql.apply(this, arguments);
}n/a
DEFERRABLE INITIALLY IMMEDIATE
n/a
function ABSTRACT() {}n/a
toString = function () {
var instance = new DeferrableType();
return instance.toString.apply(instance, arguments);
}n/a
toSql = function () {
return 'DEFERRABLE INITIALLY IMMEDIATE';
}n/a
NOT DEFERRABLE
n/a
function ABSTRACT() {}n/a
toString = function () {
var instance = new DeferrableType();
return instance.toString.apply(instance, arguments);
}n/a
toSql = function () {
return 'NOT DEFERRABLE';
}n/a
n/a
n/a
function ABSTRACT() {}n/a
toString = function () {
var instance = new DeferrableType();
return instance.toString.apply(instance, arguments);
}n/a
toSql = function (queryGenerator) {
return queryGenerator.setDeferredQuery(this.constraints);
}n/a
n/a
n/a
function ABSTRACT() {}n/a
toString = function () {
var instance = new DeferrableType();
return instance.toString.apply(instance, arguments);
}n/a
toSql = function (queryGenerator) {
return queryGenerator.setImmediateQuery(this.constraints);
}n/a
ENUM = function (value) {
var options = typeof value === 'object' && !Array.isArray(value) && value || {
values: Array.prototype.slice.call(arguments).reduce(function(result, element) {
return result.concat(Array.isArray(element) ? element : [element]);
}, [])
};
if (!(this instanceof ENUM)) return new ENUM(options);
this.values = options.values;
this.options = options;
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
validate = function (value) {
if (!_.includes(this.values, value)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid choice in %j', value, this.values));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...EmptyResultError = function (message) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeEmptyResultError';
this.message = message;
}n/a
super_ = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
Error = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
function Error() { [native code] }n/a
function Error() { [native code] }n/a
function captureStackTrace() { [native code] }...
*/
error.BaseError = function() {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
...ExclusionConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
error.DatabaseError.call(this, options.parent);
this.name = 'SequelizeExclusionConstraintError';
this.message = options.message || options.parent.message;
this.constraint = options.constraint;
this.fields = options.fields;
this.table = options.table;
}n/a
super_ = function (parent) {
error.BaseError.apply(this, [parent.message]);
this.name = 'SequelizeDatabaseError';
/**
* The database specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
/**
* The SQL that triggered the error
* @member sql
*/
this.sql = parent.sql;
/**
* The message from the DB.
* @member message
* @name message
*/
/**
* The fields of the unique constraint
* @member fields
* @name fields
*/
/**
* The value(s) which triggered the error
* @member value
* @name value
*/
/**
* The name of the index that triggered the error
* @member index
* @name index
*/
}n/a
FLOAT = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof FLOAT)) return new FLOAT(options);
NUMBER.call(this, options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
validate = function (value) {
if (!Validator.isFloat(String(value))) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid float', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...ForeignKeyConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
error.DatabaseError.call(this, options.parent);
this.name = 'SequelizeForeignKeyConstraintError';
this.message = options.message || options.parent.message || 'Database Error';
this.fields = options.fields;
this.table = options.table;
this.value = options.value;
this.index = options.index;
}n/a
super_ = function (parent) {
error.BaseError.apply(this, [parent.message]);
this.name = 'SequelizeDatabaseError';
/**
* The database specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
/**
* The SQL that triggered the error
* @member sql
*/
this.sql = parent.sql;
/**
* The message from the DB.
* @member message
* @name message
*/
/**
* The fields of the unique constraint
* @member fields
* @name fields
*/
/**
* The value(s) which triggered the error
* @member value
* @name value
*/
/**
* The name of the index that triggered the error
* @member index
* @name index
*/
}n/a
GEOGRAPHY = function (type, srid) {
var options = _.isPlainObject(type) ? type : {
type: type,
srid: srid
};
if (!(this instanceof GEOGRAPHY)) return new GEOGRAPHY(options);
this.options = options;
this.type = options.type;
this.srid = options.srid;
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
GEOMETRY = function (type, srid) {
var options = _.isPlainObject(type) ? type : {
type: type,
srid: srid
};
if (!(this instanceof GEOMETRY)) return new GEOMETRY(options);
this.options = options;
this.type = options.type;
this.srid = options.srid;
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
HSTORE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
validate = function (value) {
if (!_.isPlainObject(value)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid hstore', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...HostNotFoundError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeHostNotFoundError';
}n/a
super_ = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
HostNotReachableError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeHostNotReachableError';
}n/a
super_ = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
INTEGER = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof INTEGER)) return new INTEGER(options);
NUMBER.call(this, options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
validate = function (value) {
if (!Validator.isInt(String(value))) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid integer', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...Instance = function (values, options) {
this.dataValues = {};
this._previousDataValues = {};
this._changed = {};
this.$modelOptions = this.Model.options;
this.$options = options || {};
this.hasPrimaryKeys = this.Model.options.hasPrimaryKeys;
this.__eagerlyLoadedAssociations = [];
/**
* Returns true if this instance has not yet been persisted to the database
* @property isNewRecord
* @return {Boolean}
*/
this.isNewRecord = options.isNewRecord;
/**
* Returns the Model the instance was created from.
* @see {Model}
* @property Model
* @return {Model}
*/
initValues.call(this, values, options);
}n/a
default = function (values, options) {
this.dataValues = {};
this._previousDataValues = {};
this._changed = {};
this.$modelOptions = this.Model.options;
this.$options = options || {};
this.hasPrimaryKeys = this.Model.options.hasPrimaryKeys;
this.__eagerlyLoadedAssociations = [];
/**
* Returns true if this instance has not yet been persisted to the database
* @property isNewRecord
* @return {Boolean}
*/
this.isNewRecord = options.isNewRecord;
/**
* Returns the Model the instance was created from.
* @see {Model}
* @property Model
* @return {Model}
*/
initValues.call(this, values, options);
}n/a
_setInclude = function (key, value, options) {
if (!Array.isArray(value)) value = [value];
if (value[0] instanceof Instance) {
value = value.map(function(instance) {
return instance.dataValues;
});
}
var include = this.$options.includeMap[key]
, association = include.association
, self = this
, accessor = key
, childOptions
, primaryKeyAttribute = include.model.primaryKeyAttribute
, isEmpty;
if (!isEmpty) {
childOptions = {
isNewRecord: this.isNewRecord,
include: include.include,
includeNames: include.includeNames,
includeMap: include.includeMap,
includeValidated: true,
raw: options.raw,
attributes: include.originalAttributes
};
}
if (include.originalAttributes === undefined || include.originalAttributes.length) {
if (association.isSingleAssociation) {
if (Array.isArray(value)) {
value = value[0];
}
isEmpty = (value && value[primaryKeyAttribute] === null) || (value === null);
self[accessor] = self.dataValues[accessor] = isEmpty ? null : include.model.build(value, childOptions);
} else {
isEmpty = value[0] && value[0][primaryKeyAttribute] === null;
self[accessor] = self.dataValues[accessor] = isEmpty ? [] : include.model.bulkBuild(value, childOptions);
}
}
}n/a
changed = function (key, value) {
if (key) {
if (value !== undefined) {
this._changed[key] = value;
return this;
}
return this._changed[key] || false;
}
var changed = Object.keys(this.dataValues).filter(function(key) {
return this.changed(key);
}.bind(this));
return changed.length ? changed : false;
}n/a
decrement = function (fields, options) {
options = _.defaults({}, options, {
by: 1
});
if (!Utils._.isString(fields) && !Utils._.isArray(fields)) { // Assume fields is key-value pairs
Utils._.each(fields, function(value, field) {
fields[field] = -value;
});
}
options.by = 0 - options.by;
return this.increment(fields, options);
}n/a
destroy = function (options) {
options = Utils._.extend({
hooks: true,
force: false
}, options);
return Promise.bind(this).then(function() {
// Run before hook
if (options.hooks) {
return this.Model.runHooks('beforeDestroy', this, options);
}
}).then(function() {
var where = this.where();
if (this.Model._timestampAttributes.deletedAt && options.force === false) {
var attribute = this.Model.rawAttributes[this.Model._timestampAttributes.deletedAt]
, field = attribute.field || this.Model._timestampAttributes.deletedAt
, values = {};
values[field] = new Date();
where[field] = attribute.hasOwnProperty('defaultValue') ? attribute.defaultValue : null;
this.setDataValue(field, values[field]);
return this.sequelize.getQueryInterface().update(this, this.$Model.getTableName(options), values, where, _.defaults({ hooks
: false }, options));
} else {
return this.sequelize.getQueryInterface().delete(this, this.$Model.getTableName(options), where, _.assign({ type: QueryTypes
.DELETE, limit: null }, options));
}
}).tap(function() {
// Run after hook
if (options.hooks) {
return this.Model.runHooks('afterDestroy', this, options);
}
}).then(function(result) {
return result;
});
}...
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;
return self.sequelize.query(sql, options);
});
};
...equals = function (other) {
var result = true;
if (!other || !other.dataValues) {
return false;
}
Utils._.each(this.dataValues, function(value, key) {
if (Utils._.isDate(value) && Utils._.isDate(other.dataValues[key])) {
result = result && (value.getTime() === other.dataValues[key].getTime());
} else {
result = result && (value === other.dataValues[key]);
}
});
return result;
}n/a
equalsOneOf = function (others) {
var self = this;
return _.some(others, function(other) {
return self.equals(other);
});
}n/a
get = function (key, options) { // testhint options:none
if (options === undefined && typeof key === 'object') {
options = key;
key = undefined;
}
if (key) {
if (this._customGetters[key]) {
return this._customGetters[key].call(this, key);
}
if (options && options.plain && this.$options.include && this.$options.includeNames.indexOf(key) !== -1) {
if (Array.isArray(this.dataValues[key])) {
return this.dataValues[key].map(function (instance) {
return instance.get({plain: options.plain});
});
} else if (this.dataValues[key] instanceof Instance) {
return this.dataValues[key].get({plain: options.plain});
} else {
return this.dataValues[key];
}
}
return this.dataValues[key];
}
if (this._hasCustomGetters || (options && options.plain && this.$options.include) || (options && options.clone)) {
var values = {}
, _key;
if (this._hasCustomGetters) {
for (_key in this._customGetters) {
if (this._customGetters.hasOwnProperty(_key)) {
values[_key] = this.get(_key, options);
}
}
}
for (_key in this.dataValues) {
if (!values.hasOwnProperty(_key) && this.dataValues.hasOwnProperty(_key)) {
values[_key] = this.get(_key, options);
}
}
return values;
}
return this.dataValues;
}...
options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
};
QueryInterface.prototype.dropAllTables = function(options) {
var self = this
, skip;
...getDataValue = function (key) {
return this.dataValues[key];
}n/a
hookValidate = function (options) {
return new InstanceValidator(this, options).hookValidate();
}n/a
increment = function (fields, options) {
var identifier = this.where()
, updatedAtAttr = this.Model._timestampAttributes.updatedAt
, values = {}
, where;
options = _.defaults({}, options, {
by: 1,
attributes: {},
where: {}
});
where = _.extend({}, options.where, identifier);
if (Utils._.isString(fields)) {
values[fields] = options.by;
} else if (Utils._.isArray(fields)) {
Utils._.each(fields, function(field) {
values[field] = options.by;
});
} else { // Assume fields is key-value pairs
values = fields;
}
if (!options.silent && updatedAtAttr && !values[updatedAtAttr]) {
options.attributes[updatedAtAttr] = this.Model.$getDefaultTimestamp(updatedAtAttr) || Utils.now(this.sequelize.options.dialect
);
}
Object.keys(values).forEach(function(attr) {
// Field name mapping
if (this.Model.rawAttributes[attr] && this.Model.rawAttributes[attr].field && this.Model.rawAttributes[attr].field !== attr) {
values[this.Model.rawAttributes[attr].field] = values[attr];
delete values[attr];
}
}, this);
return this.sequelize.getQueryInterface().increment(this, this.$Model.getTableName(options), values, where, options).return(this
);
}n/a
previous = function (key) {
if (key) {
return this._previousDataValues[key];
}
return _.pickBy(this._previousDataValues, function(value, key) {
return this.changed(key);
}.bind(this));
}n/a
reload = function (options) {
options = _.defaults({}, options, {
where: this.where(),
include: this.$options.include || null
});
return this.Model.findOne(options).bind(this)
.tap(function (reload) {
if (!reload) {
throw new sequelizeErrors.InstanceError(
'Instance could not be reloaded because it does not exist anymore (find call returned null)'
);
}
})
.then(function(reload) {
// update the internal options of the instance
this.$options = reload.$options;
// re-set instance values
this.set(reload.dataValues, {
raw: true,
reset: true && !options.attributes
});
}).return(this);
}n/a
restore = function (options) {
if (!this.Model._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = Utils._.extend({
hooks: true,
force: false
}, options);
return Promise.bind(this).then(function() {
// Run before hook
if (options.hooks) {
return this.Model.runHooks('beforeRestore', this, options);
}
}).then(function() {
var deletedAtCol = this.Model._timestampAttributes.deletedAt
, deletedAtAttribute = this.Model.rawAttributes[deletedAtCol]
, deletedAtDefaultValue = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null;
this.setDataValue(deletedAtCol, deletedAtDefaultValue);
return this.save(_.extend({}, options, {hooks : false, omitNull : false}));
}).tap(function() {
// Run after hook
if (options.hooks) {
return this.Model.runHooks('afterRestore', this, options);
}
});
}n/a
save = function (options) {
if (arguments.length > 1) {
throw new Error('The second argument was removed in favor of the options object.');
}
options = Utils.cloneDeep(options);
options = _.defaults(options, {
hooks: true,
validate: true
});
if (!options.fields) {
if (this.isNewRecord) {
options.fields = Object.keys(this.Model.attributes);
} else {
options.fields = _.intersection(this.changed(), Object.keys(this.Model.attributes));
}
options.defaultFields = options.fields;
}
if (options.returning === undefined) {
if (options.association) {
options.returning = false;
} else if (this.isNewRecord) {
options.returning = true;
}
}
var self = this
, primaryKeyName = this.Model.primaryKeyAttribute
, primaryKeyAttribute = primaryKeyName && this.Model.rawAttributes[primaryKeyName]
, updatedAtAttr = this.Model._timestampAttributes.updatedAt
, createdAtAttr = this.Model._timestampAttributes.createdAt
, hook = self.isNewRecord ? 'Create' : 'Update'
, wasNewRecord = this.isNewRecord
, now = Utils.now(this.sequelize.options.dialect);
if (updatedAtAttr && options.fields.length >= 1 && options.fields.indexOf(updatedAtAttr) === -1) {
options.fields.push(updatedAtAttr);
}
if (options.silent === true && !(this.isNewRecord && this.get(updatedAtAttr, {raw: true}))) {
// UpdateAtAttr might have been added as a result of Object.keys(Model.attributes). In that case we have to remove it again
Utils._.remove(options.fields, function(val) {
return val === updatedAtAttr;
});
updatedAtAttr = false;
}
if (this.isNewRecord === true) {
if (createdAtAttr && options.fields.indexOf(createdAtAttr) === -1) {
options.fields.push(createdAtAttr);
}
if (primaryKeyAttribute && primaryKeyAttribute.defaultValue && options.fields.indexOf(primaryKeyName) < 0) {
options.fields.unshift(primaryKeyName);
}
}
if (this.isNewRecord === false) {
if (primaryKeyName && this.get(primaryKeyName, {raw: true}) === undefined) {
throw new Error('You attempted to save an instance with no primary key, this is not allowed since it would result in a global
update');
}
}
if (updatedAtAttr && !options.silent && options.fields.indexOf(updatedAtAttr) !== -1) {
this.dataValues[updatedAtAttr] = this.Model.$getDefaultTimestamp(updatedAtAttr) || now;
}
if (this.isNewRecord && createdAtAttr && !this.dataValues[createdAtAttr]) {
this.dataValues[createdAtAttr] = this.Model.$getDefaultTimestamp(createdAtAttr) || now;
}
return Promise.bind(this).then(function() {
// Validate
if (options.validate) {
return Promise.bind(this).then(function () {
// hookValidate rejects with errors, validate returns with errors
if (options.hooks) return this.hookValidate(options);
return this.validate(options).then(function (err) {
if (err) throw err;
});
});
}
}).then(function() {
return Promise.bind(this).then(function() {
// Run before hook
if (options.hooks) {
var beforeHookValues = _.pick(this.dataValues, options.fields)
, afterHookValues
, hookChanged
, ignoreChanged = _.difference(this.changed(), options.fields); // In case of update where it's only supposed to update
the passed values and the hook values
if (updatedAtAttr && options.fields.indexOf(updatedAtAttr) !== -1) {
ignoreChanged = _.without(ignoreChanged, updatedAtAttr);
}
return this.Model.runHooks('before' + hook, this, options).bind(this).then(function() {
if (options.defaultFields && !this.isNewRecord) {
afterHookValues = _.pick(this.dataValues, _.difference(this.changed(), ignoreChanged));
hookChanged = [];
Object.keys(afterHookValues).forEach(function (key) {
if (afterHookValues[key] !== beforeHookValues[key]) {
hookChanged.push(key);
}
});
options.fields = _.u ...n/a
set = function (key, value, options) { // testhint options:none
var values
, originalValue
, keys
, i
, length;
if (typeof key === 'object' && key !== null) {
values = key;
options = value || {};
if (options.reset) {
this.dataValues = {};
}
// If raw, and we're not dealing with includes or special attributes, just set it straight on the dataValues object
if (options.raw && !(this.$options && this.$options.include) && !(options && options.attributes) && !this.Model._hasBooleanAttributes
&& !this.Model._hasDateAttributes) {
if (Object.keys(this.dataValues).length) {
this.dataValues = _.extend(this.dataValues, values);
} else {
this.dataValues = values;
}
// If raw, .changed() shouldn't be true
this._previousDataValues = _.clone(this.dataValues);
} else {
// Loop and call set
if (options.attributes) {
keys = options.attributes;
if (this.Model._hasVirtualAttributes) {
keys = keys.concat(this.Model._virtualAttributes);
}
if (this.$options.includeNames) {
keys = keys.concat(this.$options.includeNames);
}
for (i = 0, length = keys.length; i < length; i++) {
if (values[keys[i]] !== undefined) {
this.set(keys[i], values[keys[i]], options);
}
}
} else {
for (key in values) {
this.set(key, values[key], options);
}
}
if (options.raw) {
// If raw, .changed() shouldn't be true
this._previousDataValues = _.clone(this.dataValues);
}
}
} else {
if (!options)
options = {};
if (!options.raw) {
originalValue = this.dataValues[key];
}
// If not raw, and there's a customer setter
if (!options.raw && this._customSetters[key]) {
this._customSetters[key].call(this, value, key);
if (!Utils.isPrimitive(value) && value !== null || value !== originalValue) {
this._previousDataValues[key] = originalValue;
this.changed(key, true);
}
} else {
// Check if we have included models, and if this key matches the include model names/aliases
if (this.$options && this.$options.include && this.$options.includeNames.indexOf(key) !== -1) {
// Pass it on to the include handler
this._setInclude(key, value, options);
return this;
} else {
// Bunch of stuff we won't do when its raw
if (!options.raw) {
// If attribute is not in model definition, return
if (!this._isAttribute(key)) {
if (key.indexOf('.') > -1 && this.Model._isJsonAttribute(key.split('.')[0])) {
var previousDottieValue = Dottie.get(this.dataValues, key);
if (!_.isEqual(previousDottieValue, value)) {
Dottie.set(this.dataValues, key, value);
this.changed(key.split('.')[0], true);
}
}
return this;
}
// If attempting to set primary key and primary key is already defined, return
if (this.Model._hasPrimaryKeys && originalValue && this.Model._isPrimaryKey(key)) {
return this;
}
// If attempting to set read only attributes, return
if (!this.isNewRecord && this.Model._hasReadOnlyAttributes && this.Model._isReadOnlyAttribute(key)) {
return this;
}
// Convert date fields to real date objects
if (this.Model._hasDateAttributes && this.Model._isDateAttribute(key) && !!value && !value._isSequelizeMethod) {
if (!(value instanceof Date)) {
value = new Date(value);
}
if (originalValue) {
if (!(originalValue instanceof Date)) {
originalValue = new Date(originalValue);
}
if (value.getTime() === originalValue.getTime()) {
return this;
}
}
}
}
// Convert boolean-ish values to booleans
i ...n/a
setAttributes = function (updates) {
return this.set(updates);
}n/a
setDataValue = function (key, value) {
var originalValue = this._previousDataValues[key];
if (!Utils.isPrimitive(value) || value !== originalValue) {
this.changed(key, true);
}
this.dataValues[key] = value;
}n/a
setValidators = function (attribute, validators) {
this.validators[attribute] = validators;
}n/a
toJSON = function () {
return this.get({
plain: true
});
}n/a
toString = function () {
return '[object SequelizeInstance:'+this.Model.name+']';
}n/a
update = function (values, options) {
var changedBefore = this.changed() || []
, sideEffects
, fields
, setOptions;
options = options || {};
if (Array.isArray(options)) options = {fields: options};
options = Utils.cloneDeep(options);
setOptions = Utils.cloneDeep(options);
setOptions.attributes = options.fields;
this.set(values, setOptions);
// Now we need to figure out which fields were actually affected by the setter.
sideEffects = _.without.apply(this, [this.changed() || []].concat(changedBefore));
fields = _.union(Object.keys(values), sideEffects);
if (!options.fields) {
options.fields = _.intersection(fields, this.changed());
options.defaultFields = options.fields;
}
return this.save(options);
}n/a
updateAttributes = function (values, options) {
var changedBefore = this.changed() || []
, sideEffects
, fields
, setOptions;
options = options || {};
if (Array.isArray(options)) options = {fields: options};
options = Utils.cloneDeep(options);
setOptions = Utils.cloneDeep(options);
setOptions.attributes = options.fields;
this.set(values, setOptions);
// Now we need to figure out which fields were actually affected by the setter.
sideEffects = _.without.apply(this, [this.changed() || []].concat(changedBefore));
fields = _.union(Object.keys(values), sideEffects);
if (!options.fields) {
options.fields = _.intersection(fields, this.changed());
options.defaultFields = options.fields;
}
return this.save(options);
}n/a
validate = function (options) {
return new InstanceValidator(this, options).validate();
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...where = function () {
var where;
where = this.Model.primaryKeyAttributes.reduce(function (result, attribute) {
result[attribute] = this.get(attribute, {raw: true});
return result;
}.bind(this), {});
if (_.size(where) === 0) {
return this.$modelOptions.whereCollection;
}
return Utils.mapWhereFieldNames(where, this.$Model);
}n/a
InstanceError = function (message) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeInstanceError';
this.message = message;
}n/a
super_ = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
InvalidConnectionError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeInvalidConnectionError';
}n/a
super_ = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
JSON = function () {
if (!(this instanceof JSONTYPE)) return new JSONTYPE();
ABSTRACT.apply(this, arguments);
}n/a
super_ = function (options) {
}n/a
validate = function (value) {
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...JSONB = function () {
if (!(this instanceof JSONB)) return new JSONB();
JSONTYPE.apply(this, arguments);
}n/a
super_ = function () {
if (!(this instanceof JSONTYPE)) return new JSONTYPE();
ABSTRACT.apply(this, arguments);
}n/a
Model = function (name, attributes, options) {
this.options = Utils._.extend({
timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: []
}, options || {});
this.associations = {};
this.modelManager = null;
this.name = name;
this.options.hooks = _.mapValues(this.replaceHookAliases(this.options.hooks), function (hooks) {
if (!Array.isArray(hooks)) hooks = [hooks];
return hooks;
});
this.sequelize = options.sequelize;
this.underscored = this.underscored || this.underscoredAll;
if (!this.options.tableName) {
this.tableName = this.options.freezeTableName ? name : Utils.underscoredIf(Utils.pluralize(name), this.options.underscoredAll
);
} else {
this.tableName = this.options.tableName;
}
this.$schema = this.options.schema;
this.$schemaDelimiter = this.options.schemaDelimiter;
// error check options
_.each(options.validate, function(validator, validatorType) {
if (_.includes(Utils._.keys(attributes), validatorType)) {
throw new Error('A model validator function must not have the same name as a field. Model: ' + name + ', field/validation
name: ' + validatorType);
}
if (!_.isFunction(validator)) {
throw new Error('Members of the validate option must be functions. Model: ' + name + ', error with validate member ' + validatorType
);
}
});
this.attributes = this.rawAttributes = _.mapValues(attributes, function(attribute, name) {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute };
}
attribute = this.sequelize.normalizeAttribute(attribute);
if (attribute.references) {
attribute = Utils.formatReferences(attribute);
if (attribute.references.model instanceof Model) {
attribute.references.model = attribute.references.model.tableName;
}
}
if (attribute.type === undefined) {
throw new Error('Unrecognized data type for field ' + name);
}
return attribute;
}.bind(this));
}n/a
addHook = function (hookType, name, fn) {
if (typeof name === 'function') {
fn = name;
name = null;
}
hookType = hookAliases[hookType] || hookType;
this.options.hooks[hookType] = this.options.hooks[hookType] || [];
this.options.hooks[hookType].push(!!name ? {name: name, fn: fn} : fn);
return this;
}...
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
});
}
};
...default = function (name, attributes, options) {
this.options = Utils._.extend({
timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: []
}, options || {});
this.associations = {};
this.modelManager = null;
this.name = name;
this.options.hooks = _.mapValues(this.replaceHookAliases(this.options.hooks), function (hooks) {
if (!Array.isArray(hooks)) hooks = [hooks];
return hooks;
});
this.sequelize = options.sequelize;
this.underscored = this.underscored || this.underscoredAll;
if (!this.options.tableName) {
this.tableName = this.options.freezeTableName ? name : Utils.underscoredIf(Utils.pluralize(name), this.options.underscoredAll
);
} else {
this.tableName = this.options.tableName;
}
this.$schema = this.options.schema;
this.$schemaDelimiter = this.options.schemaDelimiter;
// error check options
_.each(options.validate, function(validator, validatorType) {
if (_.includes(Utils._.keys(attributes), validatorType)) {
throw new Error('A model validator function must not have the same name as a field. Model: ' + name + ', field/validation
name: ' + validatorType);
}
if (!_.isFunction(validator)) {
throw new Error('Members of the validate option must be functions. Model: ' + name + ', error with validate member ' + validatorType
);
}
});
this.attributes = this.rawAttributes = _.mapValues(attributes, function(attribute, name) {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute };
}
attribute = this.sequelize.normalizeAttribute(attribute);
if (attribute.references) {
attribute = Utils.formatReferences(attribute);
if (attribute.references.model instanceof Model) {
attribute.references.model = attribute.references.model.tableName;
}
}
if (attribute.type === undefined) {
throw new Error('Unrecognized data type for field ' + name);
}
return attribute;
}.bind(this));
}n/a
hasHook = function (hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
}...
*
* @param {String} hookType
* @param {String} name
*/
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
...hasHooks = function (hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
}n/a
hook = function () {
return Hooks.addHook.apply(this, arguments);
}...
* function () {},
* function() {} // Or an array of several
* ]
* }
* })
*
* // Method 2
* Model.hook('afterDestroy', function () {})
*
* // Method 3
* Model.afterBulkUpdate(function () {})
* ```
*
* @see {Sequelize#define}
* @mixin Hooks
...removeHook = function (hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
return this;
}n/a
replaceHookAliases = function (hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
}
});
return hooks;
}n/a
runHooks = function (hooks) {
var self = this
, fn
, fnArgs = Utils.sliceArgs(arguments, 1)
, hookType;
if (typeof fnArgs[fnArgs.length - 1] === 'function') {
fn = fnArgs.pop();
}
if (typeof hooks === 'string') {
hookType = hooks;
hooks = this.options.hooks[hookType] || [];
if (!Array.isArray(hooks)) hooks = hooks === undefined ? [] : [hooks];
if (this.sequelize) hooks = hooks.concat(this.sequelize.options.hooks[hookType] || []);
}
if (!Array.isArray(hooks)) {
hooks = hooks === undefined ? [] : [hooks];
}
// run hooks as sync functions if flagged as sync
if (hookTypes[hookType] && hookTypes[hookType].sync) {
hooks.forEach(function(hook) {
if (typeof hook === 'object') hook = hook.fn;
return hook.apply(self, fnArgs);
});
return;
}
// run hooks async
var promise = Promise.each(hooks, function (hook) {
if (typeof hook === 'object') {
hook = hook.fn;
}
if (hookType && hook.length > hookTypes[hookType].params) {
hook = Promise.promisify(hook, self);
}
return hook.apply(self, fnArgs);
}).return();
if (fn) {
return promise.nodeify(fn);
}
return promise;
}...
* - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance
, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
...addHook = function (hookType, name, fn) {
if (typeof name === 'function') {
fn = name;
name = null;
}
hookType = hookAliases[hookType] || hookType;
this.options.hooks[hookType] = this.options.hooks[hookType] || [];
this.options.hooks[hookType].push(!!name ? {name: name, fn: fn} : fn);
return this;
}...
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
});
}
};
...addScope = function (name, scope, options) {
options = _.assign({
override: false
}, options);
if ((name === 'defaultScope' || name in this.options.scopes) && options.override === false) {
throw new Error('The scope ' + name + ' already exists. Pass { override: true } as options to silence this error');
}
conformOptions(scope, this);
if (name === 'defaultScope') {
this.options.defaultScope = this.$scope = scope;
} else {
this.options.scopes[name] = scope;
}
}n/a
afterBulkCreate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterBulkDelete = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterBulkDestroy = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterBulkRestore = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterBulkSync = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterBulkUpdate = function (name, callback) {
return this.addHook(hook, name, callback);
}...
* }
* })
*
* // Method 2
* Model.hook('afterDestroy', function () {})
*
* // Method 3
* Model.afterBulkUpdate(function () {})
* ```
*
* @see {Sequelize#define}
* @mixin Hooks
* @name Hooks
*/
...afterConnect = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterCreate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterDefine = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterDelete = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterDestroy = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterFind = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterInit = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterRestore = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterSync = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterUpdate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterValidate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
aggregate = function (attribute, aggregateFunction, options) {
options = Utils.cloneDeep(options);
options = _.defaults(options, { attributes: [] });
conformOptions(options, this);
this.$injectScope(options);
if (options.include) {
expandIncludeAll.call(this, options);
validateIncludedElements.call(this, options);
}
var attrOptions = this.rawAttributes[attribute]
, field = attrOptions && attrOptions.field || attribute
, aggregateColumn = this.sequelize.col(field);
if (options.distinct) {
aggregateColumn = this.sequelize.fn('DISTINCT', aggregateColumn);
}
options.attributes.push([this.sequelize.fn(aggregateFunction, aggregateColumn), aggregateFunction]);
if (!options.dataType) {
if (attrOptions) {
options.dataType = attrOptions.type;
} else {
// Use FLOAT as fallback
options.dataType = new DataTypes.FLOAT();
}
} else {
options.dataType = this.sequelize.normalizeDataType(options.dataType);
}
Utils.mapOptionFieldNames(options, this);
options = paranoidClause(this, options);
return this.QueryInterface.rawSelect(this.getTableName(options), options, aggregateFunction, this);
}n/a
all = function (options) {
return this.findAll(options);
}...
InstanceValidator.prototype.validate = function() {
if (this.inProgress) {
throw new Error('Validations already in progress.');
}
this.inProgress = true;
var self = this;
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
...beforeBulkCreate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeBulkDelete = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeBulkDestroy = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeBulkRestore = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeBulkSync = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeBulkUpdate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeConnect = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeConnection = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeCount = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeCreate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeDefine = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeDelete = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeDestroy = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeFind = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeFindAfterExpandIncludeAll = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeFindAfterOptions = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeInit = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeRestore = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeSync = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeUpdate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeValidate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
belongsTo = function (target, options) { // testhint options:none
if (!(target instanceof this.sequelize.Model)) {
throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not an instance of
Sequelize.Model');
}
var source = this;
// Since this is a mixin, we'll need a unique variable name for hooks (since Model will override our hooks option)
options = options || {};
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks);
options.useHooks = options.hooks;
// the id is in the foreign table
var association = new Type(source, target, _.extend(options, source.options));
source.associations[association.associationAccessor] = association.injectAttributes();
if (association.mixin) {
association.mixin(source.Instance.prototype);
} else {
association.injectGetter(source.Instance.prototype);
association.injectSetter(source.Instance.prototype);
association.injectCreator(source.Instance.prototype);
}
return association;
}n/a
belongsToMany = function (targetModel, options) { // testhint options:none
if (!(targetModel instanceof this.sequelize.Model)) {
throw new Error(this.name + '.belongsToMany called with something that\'s not an instance of Sequelize.Model');
}
var sourceModel = this;
// Since this is a mixin, we'll need a unique variable name for hooks (since Model will override our hooks option)
options = options || {};
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks);
options.useHooks = options.hooks;
options.timestamps = options.timestamps === undefined ? this.sequelize.options.timestamps : options.timestamps;
options = _.extend(options, _.omit(sourceModel.options, ['hooks', 'timestamps', 'scopes', 'defaultScope']));
// the id is in the foreign table or in a connecting table
var association = new BelongsToMany(sourceModel, targetModel, options);
sourceModel.associations[association.associationAccessor] = association.injectAttributes();
association.injectGetter(sourceModel.Instance.prototype);
association.injectSetter(sourceModel.Instance.prototype);
association.injectCreator(sourceModel.Instance.prototype);
return association;
}n/a
build = function (values, options) { // testhint options:none
if (Array.isArray(values)) {
return this.bulkBuild(values, options);
}
options = _.extend({
isNewRecord: true,
$schema: this.$schema,
$schemaDelimiter: this.$schemaDelimiter
}, options || {});
if (options.attributes) {
options.attributes = options.attributes.map(function(attribute) {
return Array.isArray(attribute) ? attribute[1] : attribute;
});
}
if (!options.includeValidated) {
conformOptions(options, this);
if (options.include) {
expandIncludeAll.call(this, options);
validateIncludedElements.call(this, options);
}
}
return new this.Instance(values, options);
}n/a
bulkBuild = function (valueSets, options) { // testhint options:none
options = _.extend({
isNewRecord: true
}, options || {});
if (!options.includeValidated) {
conformOptions(options, this);
if (options.include) {
expandIncludeAll.call(this, options);
validateIncludedElements.call(this, options);
}
}
if (options.attributes) {
options.attributes = options.attributes.map(function(attribute) {
return Array.isArray(attribute) ? attribute[1] : attribute;
});
}
return valueSets.map(function(values) {
return this.build(values, options);
}.bind(this));
}n/a
bulkCreate = function (records, options) {
if (!records.length) {
return Promise.resolve([]);
}
options = Utils._.extend({
validate: false,
hooks: true,
individualHooks: false,
ignoreDuplicates: false
}, options || {});
options.fields = options.fields || Object.keys(this.tableAttributes);
// Expose model to global hooks
options.model = this;
var dialect = this.sequelize.options.dialect;
if (options.ignoreDuplicates && ['postgres', 'mssql'].indexOf(dialect) !== -1) {
return Promise.reject(new Error(dialect + ' does not support the \'ignoreDuplicates\' option.'));
}
if (options.updateOnDuplicate && ['mysql', 'mariadb'].indexOf(dialect) === -1) {
return Promise.reject(new Error(dialect + ' does not support the \'updateOnDuplicate\' option.'));
}
if (options.updateOnDuplicate) {
// By default, all attributes except 'createdAt' can be updated
var updatableFields = Utils._.pull(Object.keys(this.tableAttributes), 'createdAt');
if (Utils._.isArray(options.updateOnDuplicate) && !Utils._.isEmpty(options.updateOnDuplicate)) {
updatableFields = Utils._.intersection(updatableFields, options.updateOnDuplicate);
}
options.updateOnDuplicate = updatableFields;
}
var self = this
, createdAtAttr = this._timestampAttributes.createdAt
, updatedAtAttr = this._timestampAttributes.updatedAt
, now = Utils.now(self.modelManager.sequelize.options.dialect);
var instances = records.map(function(values) {
return self.build(values, {isNewRecord: true});
});
return Promise.try(function() {
// Run before hook
if (options.hooks) {
return self.runHooks('beforeBulkCreate', instances, options);
}
}).then(function() {
// Validate
if (options.validate) {
var errors = [];
return Promise.map(instances, function(instance) {
// hookValidate rejects with errors, validate returns with errors
if (options.individualHooks) {
return instance.hookValidate(options).catch(function (err) {
if (err) {
errors.push({record: instance, errors: err});
}
});
} else {
return instance.validate(options).then(function (err) {
if (err) {
errors.push({record: instance, errors: err});
}
});
}
}).then(function() {
delete options.skip;
if (errors.length) {
return Promise.reject(errors);
}
});
}
}).then(function() {
instances.forEach(function(instance) {
var values = Utils.mapValueFieldNames(instance.dataValues, options.fields, self);
// set createdAt/updatedAt attributes
if (createdAtAttr && !values[createdAtAttr]) {
values[createdAtAttr] = now;
}
if (updatedAtAttr && !values[updatedAtAttr]) {
values[updatedAtAttr] = now;
}
instance.dataValues = values;
});
if (options.individualHooks) {
// Create each instance individually
return Promise.map(instances, function(instance) {
var individualOptions = Utils._.clone(options);
delete individualOptions.fields;
delete individualOptions.individualHooks;
delete individualOptions.ignoreDuplicates;
individualOptions.validate = false;
individualOptions.hooks = true;
return instance.save(individualOptions);
}).then(function(_instances) {
instances = _instances;
});
} else {
// Create all in one query
// Recreate records from instances to represent any changes made in hooks or validation
records = instances.map(function(instance) {
return Utils._.omit(instance.dataValues, self._virtualAttributes);
});
// Map attributes for serial identification
var attributes = {};
for (var attr in self.tableAttributes) {
attributes[attr] = self.rawAttributes[attr];
if (self.rawAttributes[attr].field) {
attributes[self.rawAttributes[attr].field] = self.rawAttributes[attr];
}
} ...n/a
count = function (options) {
return Promise.bind(this).then(function() {
options = _.defaults(Utils.cloneDeep(options), { hooks: true });
if (options.hooks) {
return this.runHooks('beforeCount', options);
}
}).then(function() {
var col = options.include ? this.name + '.' + this.primaryKeyField : '*';
options.plain = !options.group;
options.dataType = new DataTypes.INTEGER();
options.includeIgnoreAttributes = false;
// No limit, offset, order or attributes for the options max be given to count()
// Set them to null to prevent scopes setting those values
options.limit = null;
options.offset = null;
options.order = null;
return this.aggregate(col, 'count', options);
});
}n/a
create = function (values, options) {
options = Utils.cloneDeep(options || {});
return this.build(values, {
isNewRecord: true,
attributes: options.fields,
include: options.include,
raw: options.raw,
silent: options.silent
}).save(options);
}n/a
describe = function (schema, options) {
return this.QueryInterface.describeTable(this.tableName, _.assign({schema: schema || this.$schema || undefined}, options));
}n/a
destroy = function (options) {
var self = this
, instances;
if (!options || !(options.where || options.truncate)) {
throw new Error('Missing where or truncate attribute in the options parameter of model.destroy.');
}
if (!options.truncate && !_.isPlainObject(options.where) && !_.isArray(options.where) && options.where._isSequelizeMethod !==
true) {
throw new Error('Expected plain object, array or sequelize method in the options.where parameter of model.destroy.');
}
options = Utils.cloneDeep(options);
options = _.defaults(options, {
hooks: true,
individualHooks: false,
force: false,
cascade: false,
restartIdentity: false
});
options.type = QueryTypes.BULKDELETE;
this.$injectScope(options);
Utils.mapOptionFieldNames(options, this);
options.model = self;
return Promise.try(function() {
// Run before hook
if (options.hooks) {
return self.runHooks('beforeBulkDestroy', options);
}
}).then(function() {
// Get daos and run beforeDestroy hook on each record individually
if (options.individualHooks) {
return self.findAll({where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.
benchmark}).map(function(instance) {
return self.runHooks('beforeDestroy', instance, options).then(function() {
return instance;
});
}).then(function(_instances) {
instances = _instances;
});
}
}).then(function() {
// Run delete query (or update if paranoid)
if (self._timestampAttributes.deletedAt && !options.force) {
// Set query type appropriately when running soft delete
options.type = QueryTypes.BULKUPDATE;
var attrValueHash = {}
, deletedAtAttribute = self.rawAttributes[self._timestampAttributes.deletedAt]
, field = self.rawAttributes[self._timestampAttributes.deletedAt].field
, where = {};
where[field] = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null;
attrValueHash[field] = Utils.now(self.modelManager.sequelize.options.dialect);
return self.QueryInterface.bulkUpdate(self.getTableName(options), attrValueHash, _.defaults(where, options.where), options
, self.rawAttributes);
} else {
return self.QueryInterface.bulkDelete(self.getTableName(options), options.where, options, self);
}
}).tap(function() {
// Run afterDestroy hook on each record individually
if (options.individualHooks) {
return Promise.map(instances, function(instance) {
return self.runHooks('afterDestroy', instance, options);
});
}
}).tap(function() {
// Run after hook
if (options.hooks) {
return self.runHooks('afterBulkDestroy', options);
}
}).then(function(affectedRows) {
return affectedRows;
});
}...
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;
return self.sequelize.query(sql, options);
});
};
...drop = function (options) {
return this.QueryInterface.dropTable(this.getTableName(options), 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);
});
}
};
...dropSchema = function (schema) {
return this.QueryInterface.dropSchema(schema);
}...
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;
...find = function (options) {
if (options !== undefined && !_.isPlainObject(options)) {
throw new Error('The argument passed to findOne must be an options object, use findById if you wish to pass a single primary
key value');
}
options = Utils.cloneDeep(options);
if (options.limit === undefined) {
var pkVal = options.where && options.where[this.primaryKeyAttribute];
// Don't add limit if querying directly on the pk
if (!options.where || !(Utils.isPrimitive(pkVal) || Buffer.isBuffer(pkVal))) {
options.limit = 1;
}
}
// Bypass a possible overloaded findAll.
return Model.prototype.findAll.call(this, _.defaults(options, {
plain: true,
rejectOnEmpty: false
}));
}...
QueryInterface.prototype.bulkUpdate = function(tableName, values, identifier, options, attributes) {
options = Utils.cloneDeep(options);
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
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
});
options.model = model;
return this.sequelize.query(sql, options);
};
QueryInterface.prototype.delete = function(instance, tableName, identifier, options) {
var self = this
...findAll = function (options) {
if (options !== undefined && !_.isPlainObject(options)) {
throw new Error('The argument passed to findAll must be an options object, use findById if you wish to pass a single primary
key value');
}
// TODO: Remove this in the next major version (4.0)
if (arguments.length > 1) {
throw new Error('Please note that find* was refactored and uses only one options object from now on.');
}
var tableNames = {}
, originalOptions;
tableNames[this.getTableName(options)] = true;
options = Utils.cloneDeep(options);
_.defaults(options, { hooks: true, rejectOnEmpty: this.options.rejectOnEmpty });
//set rejectOnEmpty option from model config
options.rejectOnEmpty = options.rejectOnEmpty || this.options.rejectOnEmpty;
return Promise.bind(this).then(function() {
conformOptions(options, this);
this.$injectScope(options);
if (options.hooks) {
return this.runHooks('beforeFind', options);
}
}).then(function() {
expandIncludeAll.call(this, options);
if (options.hooks) {
return this.runHooks('beforeFindAfterExpandIncludeAll', options);
}
}).then(function() {
if (options.include) {
options.hasJoin = true;
validateIncludedElements.call(this, options, tableNames);
// If we're not raw, we have to make sure we include the primary key for deduplication
if (options.attributes && !options.raw && this.primaryKeyAttribute && options.attributes.indexOf(this.primaryKeyAttribute
) === -1) {
options.originalAttributes = options.attributes;
options.attributes = [this.primaryKeyAttribute].concat(options.attributes);
}
}
if (!options.attributes) {
options.attributes = Object.keys(this.tableAttributes);
}
// whereCollection is used for non-primary key updates
this.options.whereCollection = options.where || null;
Utils.mapFinderOptions(options, this);
options = paranoidClause(this, options);
if (options.hooks) {
return this.runHooks('beforeFindAfterOptions', options);
}
}).then(function() {
originalOptions = Utils.cloneDeep(options);
options.tableNames = Object.keys(tableNames);
return this.QueryInterface.select(this, this.getTableName(options), options);
}).tap(function(results) {
if (options.hooks) {
return this.runHooks('afterFind', results, options);
}
}).then(function (results) {
//rejectOnEmpty mode
if (_.isEmpty(results) && options.rejectOnEmpty) {
if (typeof options.rejectOnEmpty === 'function') {
throw new options.rejectOnEmpty();
} else if (typeof options.rejectOnEmpty === 'object') {
throw options.rejectOnEmpty;
} else {
throw new sequelizeErrors.EmptyResultError();
}
}
return Model.$findSeparate(results, originalOptions);
});
}...
return sequelize.sync({
force: true,
logging: console.log
})
.then(() => {
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount']]
}
});
})
.then(console.log)
.finally(() => {
...findAndCount = function (options) {
if (options !== undefined && !_.isPlainObject(options)) {
throw new Error('The argument passed to findAndCount must be an options object, use findById if you wish to pass a single primary
key value');
}
var self = this;
var countOptions = Utils.cloneDeep(options);
if (countOptions.attributes) {
countOptions.attributes = undefined;
}
return self.count(countOptions).then(function(count) {
if (count === 0) {
return {
count: count || 0,
rows: []
};
}
return self.findAll(options).then(function(results) {
return {
count: count || 0,
rows: results
};
});
});
}n/a
findAndCountAll = function (options) {
if (options !== undefined && !_.isPlainObject(options)) {
throw new Error('The argument passed to findAndCount must be an options object, use findById if you wish to pass a single primary
key value');
}
var self = this;
var countOptions = Utils.cloneDeep(options);
if (countOptions.attributes) {
countOptions.attributes = undefined;
}
return self.count(countOptions).then(function(count) {
if (count === 0) {
return {
count: count || 0,
rows: []
};
}
return self.findAll(options).then(function(results) {
return {
count: count || 0,
rows: results
};
});
});
}n/a
findById = function (param, options) {
// return Promise resolved with null if no arguments are passed
if ([null, undefined].indexOf(param) !== -1) {
return Promise.resolve(null);
}
options = Utils.cloneDeep(options) || {};
if (typeof param === 'number' || typeof param === 'string' || Buffer.isBuffer(param)) {
options.where = {};
options.where[this.primaryKeyAttribute] = param;
} else {
throw new Error('Argument passed to findById is invalid: '+param);
}
// Bypass a possible overloaded findOne
return Model.prototype.findOne.call(this, options);
}n/a
findByPrimary = function (param, options) {
// return Promise resolved with null if no arguments are passed
if ([null, undefined].indexOf(param) !== -1) {
return Promise.resolve(null);
}
options = Utils.cloneDeep(options) || {};
if (typeof param === 'number' || typeof param === 'string' || Buffer.isBuffer(param)) {
options.where = {};
options.where[this.primaryKeyAttribute] = param;
} else {
throw new Error('Argument passed to findById is invalid: '+param);
}
// Bypass a possible overloaded findOne
return Model.prototype.findOne.call(this, options);
}n/a
findCreateFind = function (options) {
if (!options || !options.where) {
throw new Error(
'Missing where attribute in the options parameter passed to findOrCreate.'
);
}
var values = Utils._.clone(options.defaults) || {};
if (Utils._.isPlainObject(options.where)) {
values = _.defaults(values, options.where);
}
return this.findOne(options).bind(this).then(function (result) {
if (result) return [result, false];
return this.create(values, options).bind(this).then(function (result) {
return [result, true];
}).catch(this.sequelize.UniqueConstraintError, function (err) {
return this.findOne(options).then(function (result) {
return [result, false];
});
});
});
}n/a
findOne = function (options) {
if (options !== undefined && !_.isPlainObject(options)) {
throw new Error('The argument passed to findOne must be an options object, use findById if you wish to pass a single primary
key value');
}
options = Utils.cloneDeep(options);
if (options.limit === undefined) {
var pkVal = options.where && options.where[this.primaryKeyAttribute];
// Don't add limit if querying directly on the pk
if (!options.where || !(Utils.isPrimitive(pkVal) || Buffer.isBuffer(pkVal))) {
options.limit = 1;
}
}
// Bypass a possible overloaded findAll.
return Model.prototype.findAll.call(this, _.defaults(options, {
plain: true,
rejectOnEmpty: false
}));
}n/a
findOrBuild = function (options) {
if (!options || !options.where || arguments.length > 1) {
throw new Error(
'Missing where attribute in the options parameter passed to findOrInitialize. ' +
'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)'
);
}
var self = this
, values;
return self.find(options).then(function(instance) {
if (instance === null) {
values = Utils._.clone(options.defaults) || {};
if (Utils._.isPlainObject(options.where)) {
values = Utils._.defaults(values, options.where);
}
instance = self.build(values);
return Promise.resolve([instance, true]);
}
return Promise.resolve([instance, false]);
});
}n/a
findOrCreate = function (options) {
if (!options || !options.where || arguments.length > 1) {
throw new Error(
'Missing where attribute in the options parameter passed to findOrCreate. '+
'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)'
);
}
options = _.assign({}, options);
if (options.transaction === undefined && this.sequelize.constructor.cls) {
var t = this.sequelize.constructor.cls.get('transaction');
if (t) {
options.transaction = t;
}
}
var self = this
, internalTransaction = !options.transaction
, values
, whereFields = Object.keys(options.where)
, defaultFields
, transaction;
if (options.defaults) defaultFields = Object.keys(options.defaults);
// Create a transaction or a savepoint, depending on whether a transaction was passed in
return self.sequelize.transaction(options).bind({}).then(function (t) {
transaction = t;
options.transaction = t;
return self.findOne(_.defaults({
transaction: transaction
}, options));
}).then(function(instance) {
if (instance !== null) {
return [instance, false];
}
values = Utils._.clone(options.defaults) || {};
if (Utils._.isPlainObject(options.where)) {
values = _.defaults(values, options.where);
}
options.exception = true;
return self.create(values, options).bind(this).then(function(instance) {
if (instance.get(self.primaryKeyAttribute, { raw: true }) === null) {
// If the query returned an empty result for the primary key, we know that this was actually a unique constraint violation
throw new self.sequelize.UniqueConstraintError();
}
return [instance, true];
}).catch(self.sequelize.UniqueConstraintError, function (err) {
if (defaultFields) {
if (!_.intersection(err.fields, whereFields).length && _.intersection(err.fields, defaultFields).length) {
throw err;
}
}
// Someone must have created a matching instance inside the same transaction since we last did a find. Let's find it!
return self.findOne(_.defaults({
transaction: internalTransaction ? null : transaction
}, options)).then(function(instance) {
// Sanity check, ideally we caught this at the defaultFeilds/err.fields check
// But if we didn't and instance is null, we will throw
if (instance === null) throw err;
return [instance, false];
});
});
}).finally(function () {
if (internalTransaction && transaction) {
// If we created a transaction internally (and not just a savepoint), we should clean it up
return transaction.commit();
}
});
}n/a
findOrInitialize = function (options) {
if (!options || !options.where || arguments.length > 1) {
throw new Error(
'Missing where attribute in the options parameter passed to findOrInitialize. ' +
'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)'
);
}
var self = this
, values;
return self.find(options).then(function(instance) {
if (instance === null) {
values = Utils._.clone(options.defaults) || {};
if (Utils._.isPlainObject(options.where)) {
values = Utils._.defaults(values, options.where);
}
instance = self.build(values);
return Promise.resolve([instance, true]);
}
return Promise.resolve([instance, false]);
});
}n/a
getAssociation = function (target, alias) {
for (var associationName in this.associations) {
if (this.associations.hasOwnProperty(associationName)) {
var association = this.associations[associationName];
if (association.target.name === target.name && (alias === undefined ? !association.isAliased : association.as === alias)) {
return association;
}
}
}
return null;
}n/a
getTableName = function (options) { // testhint options:none
return this.QueryGenerator.addSchema(this);
}...
options = _.defaults(options || {}, {
reverse: true
});
this.models.forEach(function(model) {
var deps = []
, tableName = model.getTableName();
if (_.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
models[tableName] = model;
...hasHook = function (hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
}...
*
* @param {String} hookType
* @param {String} name
*/
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
...hasHooks = function (hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
}n/a
hasMany = function (target, options) { // testhint options:none
if (!(target instanceof this.sequelize.Model)) {
throw new Error(this.name + '.hasMany called with something that\'s not an instance of Sequelize.Model');
}
var source = this;
// Since this is a mixin, we'll need a unique variable name for hooks (since Model will override our hooks option)
options = options || {};
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks);
options.useHooks = options.hooks;
options = _.extend(options, _.omit(source.options, ['hooks']));
// the id is in the foreign table or in a connecting table
var association = new HasMany(source, target, options);
source.associations[association.associationAccessor] = association;
association.injectAttributes();
association.mixin(source.Instance.prototype);
return association;
}n/a
hasOne = function (target, options) { // testhint options:none
if (!(target instanceof this.sequelize.Model)) {
throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not an instance of
Sequelize.Model');
}
var source = this;
// Since this is a mixin, we'll need a unique variable name for hooks (since Model will override our hooks option)
options = options || {};
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks);
options.useHooks = options.hooks;
// the id is in the foreign table
var association = new Type(source, target, _.extend(options, source.options));
source.associations[association.associationAccessor] = association.injectAttributes();
if (association.mixin) {
association.mixin(source.Instance.prototype);
} else {
association.injectGetter(source.Instance.prototype);
association.injectSetter(source.Instance.prototype);
association.injectCreator(source.Instance.prototype);
}
return association;
}n/a
hook = function () {
return Hooks.addHook.apply(this, arguments);
}...
* function () {},
* function() {} // Or an array of several
* ]
* }
* })
*
* // Method 2
* Model.hook('afterDestroy', function () {})
*
* // Method 3
* Model.afterBulkUpdate(function () {})
* ```
*
* @see {Sequelize#define}
* @mixin Hooks
...init = function (modelManager) {
var self = this;
this.modelManager = modelManager;
this.primaryKeys = {};
// Setup names of timestamp attributes
this._timestampAttributes = {};
if (this.options.timestamps) {
if (this.options.createdAt !== false) {
this._timestampAttributes.createdAt = this.options.createdAt || Utils.underscoredIf('createdAt', this.options.underscored);
}
if (this.options.updatedAt !== false) {
this._timestampAttributes.updatedAt = this.options.updatedAt || Utils.underscoredIf('updatedAt', this.options.underscored);
}
if (this.options.paranoid && this.options.deletedAt !== false) {
this._timestampAttributes.deletedAt = this.options.deletedAt || Utils.underscoredIf('deletedAt', this.options.underscored);
}
}
// Add head and tail default attributes (id, timestamps)
addOptionalClassMethods.call(this);
// Instance prototype
this.Instance = function() {
Instance.apply(this, arguments);
};
Util.inherits(this.Instance, Instance);
this._readOnlyAttributes = Utils._.values(this._timestampAttributes);
this._hasReadOnlyAttributes = this._readOnlyAttributes && this._readOnlyAttributes.length;
this._isReadOnlyAttribute = Utils._.memoize(function(key) {
return self._hasReadOnlyAttributes && self._readOnlyAttributes.indexOf(key) !== -1;
});
if (this.options.instanceMethods) {
Utils._.each(this.options.instanceMethods, function(fct, name) {
self.Instance.prototype[name] = fct;
});
}
addDefaultAttributes.call(this);
this.refreshAttributes();
findAutoIncrementField.call(this);
this.$scope = this.options.defaultScope;
if (_.isPlainObject(this.$scope)) {
conformOptions(this.$scope, this);
}
_.each(this.options.scopes, function (scope) {
if (_.isPlainObject(scope)) {
conformOptions(scope, this);
}
}.bind(this));
this.options.indexes = this.options.indexes.map(this.$conformIndex);
this.Instance.prototype.$Model =
this.Instance.prototype.Model = this;
return this;
}n/a
insertOrUpdate = function (values, options) {
options = Utils.cloneDeep(options) || {};
if (!options.fields) {
options.fields = Object.keys(this.attributes);
}
var createdAtAttr = this._timestampAttributes.createdAt
, updatedAtAttr = this._timestampAttributes.updatedAt
, hadPrimary = this.primaryKeyField in values || this.primaryKeyAttribute in values
, instance = this.build(values);
return instance.hookValidate(options).bind(this).then(function () {
// Map field names
var updatedDataValues = _.pick(instance.dataValues, Object.keys(instance._changed))
, insertValues = Utils.mapValueFieldNames(instance.dataValues, options.fields, this)
, updateValues = Utils.mapValueFieldNames(updatedDataValues, options.fields, this)
, now = Utils.now(this.sequelize.options.dialect);
// Attach createdAt
if (createdAtAttr && !updateValues[createdAtAttr]) {
insertValues[createdAtAttr] = this.$getDefaultTimestamp(createdAtAttr) || now;
}
if (updatedAtAttr && !insertValues[updatedAtAttr]) {
insertValues[updatedAtAttr] = updateValues[updatedAtAttr] = this.$getDefaultTimestamp(updatedAtAttr) || now;
}
// Build adds a null value for the primary key, if none was given by the user.
// We need to remove that because of some Postgres technicalities.
if (!hadPrimary && this.primaryKeyAttribute && !this.rawAttributes[this.primaryKeyAttribute].defaultValue) {
delete insertValues[this.primaryKeyField];
delete updateValues[this.primaryKeyField];
}
return this.QueryInterface.upsert(this.getTableName(options), insertValues, updateValues, instance.where(), this, options);
});
}n/a
inspect = function () {
return this.name;
}n/a
max = function (field, options) {
return this.aggregate(field, 'max', options);
}n/a
min = function (field, options) {
return this.aggregate(field, 'min', options);
}n/a
refreshAttributes = function () {
var self = this
, attributeManipulation = {};
this.Instance.prototype._customGetters = {};
this.Instance.prototype._customSetters = {};
Utils._.each(['get', 'set'], function(type) {
var opt = type + 'terMethods'
, funcs = Utils._.clone(Utils._.isObject(self.options[opt]) ? self.options[opt] : {})
, _custom = type === 'get' ? self.Instance.prototype._customGetters : self.Instance.prototype._customSetters;
Utils._.each(funcs, function(method, attribute) {
_custom[attribute] = method;
if (type === 'get') {
funcs[attribute] = function() {
return this.get(attribute);
};
}
if (type === 'set') {
funcs[attribute] = function(value) {
return this.set(attribute, value);
};
}
});
Utils._.each(self.rawAttributes, function(options, attribute) {
if (options.hasOwnProperty(type)) {
_custom[attribute] = options[type];
}
if (type === 'get') {
funcs[attribute] = function() {
return this.get(attribute);
};
}
if (type === 'set') {
funcs[attribute] = function(value) {
return this.set(attribute, value);
};
}
});
Utils._.each(funcs, function(fct, name) {
if (!attributeManipulation[name]) {
attributeManipulation[name] = {
configurable: true
};
}
attributeManipulation[name][type] = fct;
});
});
this._booleanAttributes = [];
this._dateAttributes = [];
this._hstoreAttributes = [];
this._rangeAttributes = [];
this._jsonAttributes = [];
this._geometryAttributes = [];
this._virtualAttributes = [];
this._defaultValues = {};
this.Instance.prototype.validators = {};
this.fieldRawAttributesMap = {};
this.primaryKeys = {};
self.options.uniqueKeys = {};
_.each(this.rawAttributes, function(definition, name) {
definition.type = self.sequelize.normalizeDataType(definition.type);
definition.Model = self;
definition.fieldName = name;
definition._modelAttribute = true;
if (definition.field === undefined) {
definition.field = name;
}
if (definition.primaryKey === true) {
self.primaryKeys[name] = definition;
}
self.fieldRawAttributesMap[definition.field] = definition;
if (definition.type instanceof DataTypes.BOOLEAN) {
self._booleanAttributes.push(name);
} else if (definition.type instanceof DataTypes.DATE) {
self._dateAttributes.push(name);
} else if (definition.type instanceof DataTypes.HSTORE || DataTypes.ARRAY.is(definition.type, DataTypes.HSTORE)) {
self._hstoreAttributes.push(name);
} else if (definition.type instanceof DataTypes.RANGE || DataTypes.ARRAY.is(definition.type, DataTypes.RANGE)) {
self._rangeAttributes.push(name);
} else if (definition.type instanceof DataTypes.JSON) {
self._jsonAttributes.push(name);
} else if (definition.type instanceof DataTypes.VIRTUAL) {
self._virtualAttributes.push(name);
} else if (definition.type instanceof DataTypes.GEOMETRY) {
self._geometryAttributes.push(name);
}
if (definition.hasOwnProperty('defaultValue')) {
self._defaultValues[name] = Utils._.partial(Utils.toDefaultValue, definition.defaultValue);
}
if (definition.hasOwnProperty('unique') && definition.unique !== false) {
var idxName;
if (typeof definition.unique === 'object' && definition.unique.hasOwnProperty('name')) {
idxName = definition.unique.name;
} else if (typeof definition.unique === 'string') {
idxName = definition.unique;
} else {
idxName = self.tableName + '_' + name + '_unique';
}
var idx = self.options.uniqueKeys[idxName] || { fields: [] };
idx = idx || {fields: [], msg: null};
idx.fields.push(definition.field);
idx.msg = idx.msg || definition.unique.msg || null;
idx.name = idxName || false;
idx.column = name;
self.options.uniqueKeys[idxName] = idx;
}
if (definition.hasOwnProper ...n/a
removeAttribute = function (attribute) {
delete this.rawAttributes[attribute];
this.refreshAttributes();
}n/a
removeHook = function (hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
return this;
}n/a
replaceHookAliases = function (hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
}
});
return hooks;
}n/a
restore = function (options) {
if (!this._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = Utils._.extend({
hooks: true,
individualHooks: false
}, options || {});
options.type = QueryTypes.RAW;
// Expose model to global hooks
options.model = this;
var self = this
, instances;
Utils.mapOptionFieldNames(options, this);
return Promise.try(function() {
// Run before hook
if (options.hooks) {
return self.runHooks('beforeBulkRestore', options);
}
}).then(function() {
// Get daos and run beforeRestore hook on each record individually
if (options.individualHooks) {
return self.findAll({where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.
benchmark, paranoid: false}).map(function(instance) {
return self.runHooks('beforeRestore', instance, options).then(function() {
return instance;
});
}).then(function(_instances) {
instances = _instances;
});
}
}).then(function() {
// Run undelete query
var attrValueHash = {}
, deletedAtCol = self._timestampAttributes.deletedAt
, deletedAtAttribute = self.rawAttributes[deletedAtCol]
, deletedAtDefaultValue = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null;
attrValueHash[deletedAtAttribute.field || deletedAtCol] = deletedAtDefaultValue;
options.omitNull = false;
return self.QueryInterface.bulkUpdate(self.getTableName(options), attrValueHash, options.where, options, self._timestampAttributes
.deletedAt);
}).tap(function() {
// Run afterDestroy hook on each record individually
if (options.individualHooks) {
return Promise.map(instances, function(instance) {
return self.runHooks('afterRestore', instance, options);
});
}
}).tap(function() {
// Run after hook
if (options.hooks) {
return self.runHooks('afterBulkRestore', options);
}
}).then(function(affectedRows) {
return affectedRows;
});
}n/a
runHooks = function (hooks) {
var self = this
, fn
, fnArgs = Utils.sliceArgs(arguments, 1)
, hookType;
if (typeof fnArgs[fnArgs.length - 1] === 'function') {
fn = fnArgs.pop();
}
if (typeof hooks === 'string') {
hookType = hooks;
hooks = this.options.hooks[hookType] || [];
if (!Array.isArray(hooks)) hooks = hooks === undefined ? [] : [hooks];
if (this.sequelize) hooks = hooks.concat(this.sequelize.options.hooks[hookType] || []);
}
if (!Array.isArray(hooks)) {
hooks = hooks === undefined ? [] : [hooks];
}
// run hooks as sync functions if flagged as sync
if (hookTypes[hookType] && hookTypes[hookType].sync) {
hooks.forEach(function(hook) {
if (typeof hook === 'object') hook = hook.fn;
return hook.apply(self, fnArgs);
});
return;
}
// run hooks async
var promise = Promise.each(hooks, function (hook) {
if (typeof hook === 'object') {
hook = hook.fn;
}
if (hookType && hook.length > hookTypes[hookType].params) {
hook = Promise.promisify(hook, self);
}
return hook.apply(self, fnArgs);
}).return();
if (fn) {
return promise.nodeify(fn);
}
return promise;
}...
* - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance
, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
...schema = function (schema, options) { // testhint options:none
var self = this;
var clone = Object.create(self);
clone.$schema = schema;
if (!!options) {
if (typeof options === 'string') {
clone.$schemaDelimiter = options;
} else {
if (!!options.schemaDelimiter) {
clone.$schemaDelimiter = options.schemaDelimiter;
}
}
}
clone.Instance = function() {
self.Instance.apply(this, arguments);
};
clone.Instance.prototype = Object.create(self.Instance.prototype);
clone.Instance.prototype.$Model = clone;
return clone;
}n/a
scope = function (option) {
var self = Object.create(this)
, options
, scope
, scopeName;
self.$scope = {};
self.scoped = true;
if (!option) {
return self;
}
options = _.flatten(arguments);
options.forEach(function(option) {
scope = null;
scopeName = null;
if (_.isPlainObject(option)) {
if (!!option.method) {
if (Array.isArray(option.method) && !!self.options.scopes[option.method[0]]) {
scopeName = option.method[0];
scope = self.options.scopes[scopeName].apply(self, option.method.splice(1));
}
else if (!!self.options.scopes[option.method]) {
scopeName = option.method;
scope = self.options.scopes[scopeName].apply(self);
}
} else {
scope = option;
}
} else {
if (option === 'defaultScope' && _.isPlainObject(self.options.defaultScope)) {
scope = self.options.defaultScope;
} else {
scopeName = option;
scope = self.options.scopes[scopeName];
if (_.isFunction(scope)) {
scope = scope();
conformOptions(scope, self);
}
}
}
if (!!scope) {
_.assignWith(self.$scope, scope, function scopeCustomizer(objectValue, sourceValue, key) {
if (key === 'where') {
return Array.isArray(sourceValue) ? sourceValue : _.assign(objectValue || {}, sourceValue);
} else if ( (['attributes','include'].indexOf(key) >= 0) && Array.isArray(objectValue) && Array.isArray(sourceValue)) {
return objectValue.concat(sourceValue);
}
return objectValue ? objectValue : sourceValue;
});
} else {
throw new Error('Invalid scope ' + scopeName + ' called.');
}
});
return self;
}n/a
sum = function (field, options) {
return this.aggregate(field, 'sum', options);
}n/a
sync = function (options) {
options = _.extend({}, this.options, options);
options.hooks = options.hooks === undefined ? true : !!options.hooks;
var self = this
, attributes = this.tableAttributes;
return Promise.try(function () {
if (options.hooks) {
return self.runHooks('beforeSync', options);
}
}).then(function () {
if (options.force) {
return self.drop(options);
}
}).then(function () {
return self.QueryInterface.createTable(self.getTableName(options), attributes, options, self);
}).then(function () {
return self.QueryInterface.showIndex(self.getTableName(options), options);
}).then(function (indexes) {
// Assign an auto-generated name to indexes which are not named by the user
self.options.indexes = self.QueryInterface.nameIndexes(self.options.indexes, self.tableName);
indexes = _.filter(self.options.indexes, function (item1) {
return !_.some(indexes, function (item2) {
return item1.name === item2.name;
});
});
return Promise.map(indexes, function (index) {
return self.QueryInterface.addIndex(
self.getTableName(options),
_.assign({logging: options.logging,
benchmark: options.benchmark,
transaction: options.transaction}, index),
self.tableName);
});
}).then(function () {
if (options.hooks) {
return self.runHooks('afterSync', options);
}
}).return(this);
}...
const User = sequelize.define('user', {
name: Sequelize.STRING
});
return sequelize.sync({
force: true,
logging: console.log
})
.then(() => {
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount']]
...toString = function () {
return '[object SequelizeModel:'+this.name+']';
}n/a
truncate = function (options) {
options = Utils.cloneDeep(options) || {};
options.truncate = true;
return this.destroy(options);
}n/a
unscoped = function () {
return this.scope();
}n/a
update = function (values, options) {
var self = this;
if (!options || !options.where) {
throw new Error('Missing where attribute in the options parameter passed to update.');
}
if (!_.isPlainObject(options.where) && !_.isArray(options.where) && options.where._isSequelizeMethod !== true) {
throw new Error('Expected plain object, array or sequelize method in the options.where parameter of model.update.');
}
options = Utils.cloneDeep(options);
options = _.defaults(options, {
validate: true,
hooks: true,
individualHooks: false,
returning: false,
force: false,
sideEffects: true
});
options.type = QueryTypes.BULKUPDATE;
// Expose model to global hooks
options.model = this;
this.$injectScope(options);
// Clone values so it doesn't get modified for caller scope
values = _.clone(values);
// Remove values that are not in the options.fields
if (options.fields && options.fields instanceof Array) {
Object.keys(values).forEach(function(key) {
if (options.fields.indexOf(key) < 0) {
delete values[key];
}
});
} else {
var updatedAtAttr = this._timestampAttributes.updatedAt;
options.fields = _.intersection(Object.keys(values), Object.keys(this.tableAttributes));
if (updatedAtAttr && options.fields.indexOf(updatedAtAttr) === -1) {
options.fields.push(updatedAtAttr);
}
}
if (this._timestampAttributes.updatedAt && !options.silent) {
values[this._timestampAttributes.updatedAt] = this.$getDefaultTimestamp(this._timestampAttributes.updatedAt) || Utils.now(this
.sequelize.options.dialect);
}
var instances
, valuesUse;
return Promise.try(function() {
// Validate
if (options.validate) {
var build = self.build(values);
build.set(self._timestampAttributes.updatedAt, values[self._timestampAttributes.updatedAt], { raw: true });
if (options.sideEffects) {
values = Utils._.assign(values, Utils._.pick(build.get(), build.changed()));
options.fields = Utils._.union(options.fields, Object.keys(values));
}
// We want to skip validations for all other fields
options.skip = Utils._.difference(Object.keys(self.attributes), Object.keys(values));
return build.hookValidate(options).then(function(attributes) {
options.skip = undefined;
if (attributes && attributes.dataValues) {
values = Utils._.pick(attributes.dataValues, Object.keys(values));
}
});
}
return null;
}).then(function() {
// Run before hook
if (options.hooks) {
options.attributes = values;
return self.runHooks('beforeBulkUpdate', options).then(function() {
values = options.attributes;
delete options.attributes;
});
}
return null;
}).then(function() {
valuesUse = values;
// Get instances and run beforeUpdate hook on each record individually
if (options.individualHooks) {
return self.findAll({where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.
benchmark}).then(function(_instances) {
instances = _instances;
if (!instances.length) {
return [];
}
// Run beforeUpdate hooks on each record and check whether beforeUpdate hook changes values uniformly
// i.e. whether they change values for each record in the same way
var changedValues
, different = false;
return Promise.map(instances, function(instance) {
// Record updates in instances dataValues
Utils._.extend(instance.dataValues, values);
// Set the changed fields on the instance
Utils._.forIn(valuesUse, function(newValue, attr) {
if (newValue !== instance._previousDataValues[attr]) {
instance.setDataValue(attr, newValue);
}
});
// Run beforeUpdate hook
return self.runHooks('beforeUpdate', instance, options).then(function() {
if (!different) {
var thisChangedValues = {}; ...n/a
upsert = function (values, options) {
options = Utils.cloneDeep(options) || {};
if (!options.fields) {
options.fields = Object.keys(this.attributes);
}
var createdAtAttr = this._timestampAttributes.createdAt
, updatedAtAttr = this._timestampAttributes.updatedAt
, hadPrimary = this.primaryKeyField in values || this.primaryKeyAttribute in values
, instance = this.build(values);
return instance.hookValidate(options).bind(this).then(function () {
// Map field names
var updatedDataValues = _.pick(instance.dataValues, Object.keys(instance._changed))
, insertValues = Utils.mapValueFieldNames(instance.dataValues, options.fields, this)
, updateValues = Utils.mapValueFieldNames(updatedDataValues, options.fields, this)
, now = Utils.now(this.sequelize.options.dialect);
// Attach createdAt
if (createdAtAttr && !updateValues[createdAtAttr]) {
insertValues[createdAtAttr] = this.$getDefaultTimestamp(createdAtAttr) || now;
}
if (updatedAtAttr && !insertValues[updatedAtAttr]) {
insertValues[updatedAtAttr] = updateValues[updatedAtAttr] = this.$getDefaultTimestamp(updatedAtAttr) || now;
}
// Build adds a null value for the primary key, if none was given by the user.
// We need to remove that because of some Postgres technicalities.
if (!hadPrimary && this.primaryKeyAttribute && !this.rawAttributes[this.primaryKeyAttribute].defaultValue) {
delete insertValues[this.primaryKeyField];
delete updateValues[this.primaryKeyField];
}
return this.QueryInterface.upsert(this.getTableName(options), insertValues, updateValues, instance.where(), this, options);
});
}n/a
validationFailed = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
NOW = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
NUMBER = function (options) {
this.options = options;
this._length = options.length;
this._zerofill = options.zerofill;
this._decimals = options.decimals;
this._precision = options.precision;
this._scale = options.scale;
this._unsigned = options.unsigned;
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
var result = this.key;
if (this._length) {
result += '(' + this._length;
if (typeof this._decimals === 'number') {
result += ',' + this._decimals;
}
result += ')';
}
if (this._unsigned) {
result += ' UNSIGNED';
}
if (this._zerofill) {
result += ' ZEROFILL';
}
return result;
}n/a
validate = function (value) {
if (!Validator.isFloat(String(value))) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid number', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}n/a
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed()
? promise._settledValue() : undefined;
}
else {
this._bitField = 0;
this._settledValueField = undefined;
}
}n/a
function RangeError() { [native code] }n/a
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}n/a
Sequelize = function (database, username, password, options) {
var config;
if (arguments.length === 1 && typeof database === 'object') {
// new Sequelize({ ... options })
options = database;
config = _.pick(options, 'host', 'port', 'database', 'username', 'password');
} else if ((arguments.length === 1 && typeof database === 'string') || (arguments.length === 2 && typeof username === 'object')) {
// new Sequelize(URI, { ... options })
config = {};
options = username || {};
var urlParts = url.parse(arguments[0]);
// SQLite don't have DB in connection url
if (urlParts.pathname) {
config.database = urlParts.pathname.replace(/^\//, '');
}
options.dialect = urlParts.protocol.replace(/:$/, '');
options.host = urlParts.hostname;
if (urlParts.port) {
options.port = urlParts.port;
}
if (urlParts.auth) {
config.username = urlParts.auth.split(':')[0];
config.password = urlParts.auth.split(':')[1];
}
} else {
// new Sequelize(database, username, password, { ... options })
options = options || {};
config = {database: database, username: username, password: password};
}
Sequelize.runHooks('beforeInit', config, options);
this.options = Utils._.extend({
dialect: 'mysql',
dialectModulePath: null,
host: 'localhost',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone:'+00:00',
logging: console.log,
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: {max: 5, match: ['SQLITE_BUSY: database is locked']},
transactionType: Transaction.TYPES.DEFERRED,
isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
databaseVersion: 0,
typeValidation: false,
benchmark: false
}, options || {});
if (this.options.dialect === 'postgresql') {
this.options.dialect = 'postgres';
}
if (this.options.dialect === 'sqlite' && this.options.timezone !== '+00:00') {
throw new Error('Setting a custom timezone is not supported by SQLite, dates are always returned as UTC. Please remove the custom
timezone parameter.');
}
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
this.options.hooks = this.replaceHookAliases(this.options.hooks);
if ((['', null, false].indexOf(config.password) > -1) || (typeof config.password === 'undefined')) {
config.password = null;
}
this.config = {
database: config.database,
username: config.username,
password: config.password,
host: config.host || this.options.host,
port: config.port || this.options.port,
pool: this.options.pool,
protocol: this.options.protocol,
native: this.options.native,
ssl: this.options.ssl,
replication: this.options.replication,
dialectModulePath: this.options.dialectModulePath,
keepDefaultTimezone: this.options.keepDefaultTimezone,
dialectOptions: this.options.dialectOptions
};
var Dialect;
// Requiring the dialect in a switch-case to keep the
// require calls static. (Browserify fix)
switch (this.getDialect()){
case 'mariadb':
Dialect = require('./dialects/mariadb');
break;
case 'mssql':
Dialect = require('./dialects/mssql');
break;
case 'mysql':
Dialect = require('./dialects/mysql');
break;
case 'postgres':
Dialect = require('./dialects/postgres');
break;
case 'sqlite':
Dialect = require('./dialects/sqlite');
break;
default:
throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mariadb, mssql, mysql, postgres
, and sqlite.');
}
this.dialect = new Dialect(this);
this.dialect.QueryGenerator.typeValidation = options.typeValidation;
/**
* Models are stored here under the name given to `sequelize.define`
* @property models
*/
this.models = {};
this.mod ...n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function TypeError() { [native code] }n/a
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}n/a
_peekContext = function () {}n/a
all = function (promises) {
return new PromiseArray(promises).promise();
}...
InstanceValidator.prototype.validate = function() {
if (this.inProgress) {
throw new Error('Validations already in progress.');
}
this.inProgress = true;
var self = this;
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
...any = function (promises) {
return any(promises);
}n/a
attempt = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value;
if (arguments.length > 1) {
debug.deprecated("calling Promise.try with more than 1 argument");
var arg = arguments[1];
var ctx = arguments[2];
value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
: tryCatch(fn).call(ctx, arg);
} else {
value = tryCatch(fn)();
}
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.try", ret);
ret._resolveFromSyncValue(value);
return ret;
}n/a
bind = function (thisArg, value) {
return Promise.resolve(value).bind(thisArg);
}...
var validatorPromise = self._invokeBuiltinValidator(value, test, validatorType, field);
// errors are handled in settling, stub this
validatorPromise.catch(function() {});
validators.push(validatorPromise.reflect());
});
return Promise.all(validators).then(this._handleReflectedResult.bind(this, field));
};
/**
* Prepare and invoke a custom validator.
*
* @param {Function} validator The custom validator.
* @param {string} validatorType the custom validator type (name).
...cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._setFulfilled();
ret._rejectionHandler0 = obj;
}
return ret;
}n/a
config = function (opts) {
opts = Object(opts);
if ("longStackTraces" in opts) {
if (opts.longStackTraces) {
Promise.longStackTraces();
} else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
disableLongStackTraces();
}
}
if ("warnings" in opts) {
var warningsOption = opts.warnings;
config.warnings = !!warningsOption;
wForgottenReturn = config.warnings;
if (util.isObject(warningsOption)) {
if ("wForgottenReturn" in warningsOption) {
wForgottenReturn = !!warningsOption.wForgottenReturn;
}
}
}
if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
if (async.haveItemsQueued()) {
throw new Error(
"cannot enable cancellation after promises are in use");
}
Promise.prototype._clearCancellationData =
cancellationClearCancellationData;
Promise.prototype._propagateFrom = cancellationPropagateFrom;
Promise.prototype._onCancel = cancellationOnCancel;
Promise.prototype._setOnCancel = cancellationSetOnCancel;
Promise.prototype._attachCancellationCallback =
cancellationAttachCancellationCallback;
Promise.prototype._execute = cancellationExecute;
propagateFromFunction = cancellationPropagateFrom;
config.cancellation = true;
}
if ("monitoring" in opts) {
if (opts.monitoring && !config.monitoring) {
config.monitoring = true;
Promise.prototype._fireEvent = activeFireEvent;
} else if (!opts.monitoring && config.monitoring) {
config.monitoring = false;
Promise.prototype._fireEvent = defaultFireEvent;
}
}
return Promise;
}n/a
coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
var ret = spawn.promise();
spawn._generator = generator;
spawn._promiseFulfilled(undefined);
return ret;
};
}n/a
defer = function () {
debug.deprecated("Promise.defer", "new Promise");
var promise = new Promise(INTERNAL);
return {
promise: promise,
resolve: deferResolve,
reject: deferReject
};
}n/a
delay = function (ms, value) {
var ret;
var handle;
if (value !== undefined) {
ret = Promise.resolve(value)
._then(afterValue, null, null, ms, undefined);
if (debug.cancellation() && value instanceof Promise) {
ret._setOnCancel(value);
}
} else {
ret = new Promise(INTERNAL);
handle = setTimeout(function() { ret._fulfill(); }, +ms);
if (debug.cancellation()) {
ret._setOnCancel(new HandleWrapper(handle));
}
ret._captureStackTrace();
}
ret._setAsyncGuaranteed();
return ret;
}n/a
each = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
beforeConnection: 'beforeConnect'
};
var Hooks = {
replaceHookAliases: function(hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
...filter = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
...fromCallback = function (fn) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
: false;
var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
if (result === errorObj) {
ret._rejectCallback(result.e, true);
}
if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
return ret;
}n/a
fromNode = function (fn) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
: false;
var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
if (result === errorObj) {
ret._rejectCallback(result.e, true);
}
if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
return ret;
}n/a
fulfilled = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._setFulfilled();
ret._rejectionHandler0 = obj;
}
return ret;
}n/a
getNewLibraryCopy = function () {
var makeSelfResolutionError = function () {
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var reflectHandler = function() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
return Promise.reject(new TypeError(msg));
};
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = require("./util");
var getDomain;
if (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
return null;
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var es5 = require("./es5");
var Async = require("./async");
var async = new Async();
es5.defineProperty(Promise, "_async", {value: async});
var errors = require("./errors");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
var CancellationError = Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {};
var tryConvertToPromise = require("./thenables")(Promise, INTERNAL);
var PromiseArray =
require("./promise_array")(Promise, INTERNAL,
tryConvertToPromise, apiRejection, Proxyable);
var Context = require("./context")(Promise);
/*jshint unused:false*/
var createContext = Context.create;
var debug = require("./debuggability")(Promise, Context);
var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext =
require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
var catchFilter = require("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = require("./nodeback");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
if (self == null || self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor));
}
}
function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("Catch statement predicate: " +
"expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
};
Promise.prototype.reflect = function () {
return this._then(reflectHandler,
reflectHandler, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject) {
if (debug.warnings() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", ...n/a
hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
}n/a
is = function (val) {
return val instanceof Promise;
}n/a
join = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
* Gets all validation error items for the path / field specified.
*
...longStackTraces = function () {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
config.longStackTraces = true;
disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.
gl/MqrFmX\u000a");
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
}n/a
map = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
...mapSeries = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.method", ret);
ret._resolveFromSyncValue(value);
return ret;
};
}...
* @param {Function} validator The custom validator.
* @param {string} validatorType the custom validator type (name).
* @param {boolean=} optAttrDefined Set to true if custom validator was defined
* from the Attribute
* @return {Promise} A promise.
* @private
*/
InstanceValidator.prototype._invokeCustomValidator = Promise.method(function(validator
, validatorType, optAttrDefined, optValue, optField) {
var validatorFunction = null; // the validation function to call
var isAsync = false;
var validatorArity = validator.length;
// check if validator is async and requires a callback
var asyncArity = 1;
var errorKey = validatorType;
...function noConflict() {
try { if (Promise === bluebird) Promise = old; }
catch (e) {}
return bluebird;
}n/a
onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
}n/a
onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
}n/a
pending = function () {
debug.deprecated("Promise.defer", "new Promise");
var promise = new Promise(INTERNAL);
return {
promise: promise,
resolve: deferResolve,
reject: deferReject
};
}n/a
promisify = function (fn, options) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
if (isPromisified(fn)) {
return fn;
}
options = Object(options);
var receiver = options.context === undefined ? THIS : options.context;
var multiArgs = !!options.multiArgs;
var ret = promisify(fn, receiver, multiArgs);
util.copyDescriptors(fn, ret, propsFilter);
return ret;
}...
// run hooks async
var promise = Promise.each(hooks, function (hook) {
if (typeof hook === 'object') {
hook = hook.fn;
}
if (hookType && hook.length > hookTypes[hookType].params) {
hook = Promise.promisify(hook, self);
}
return hook.apply(self, fnArgs);
}).return();
if (fn) {
return promise.nodeify(fn);
...promisifyAll = function (target, options) {
if (typeof target !== "function" && typeof target !== "object") {
throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\
u000a");
}
options = Object(options);
var multiArgs = !!options.multiArgs;
var suffix = options.suffix;
if (typeof suffix !== "string") suffix = defaultSuffix;
var filter = options.filter;
if (typeof filter !== "function") filter = defaultFilter;
var promisifier = options.promisifier;
if (typeof promisifier !== "function") promisifier = makeNodePromisified;
if (!util.isIdentifier(suffix)) {
throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var keys = util.inheritedDataKeys(target);
for (var i = 0; i < keys.length; ++i) {
var value = target[keys[i]];
if (keys[i] !== "constructor" &&
util.isClass(value)) {
promisifyAll(value.prototype, suffix, filter, promisifier,
multiArgs);
promisifyAll(value, suffix, filter, promisifier, multiArgs);
}
}
return promisifyAll(target, suffix, filter, promisifier, multiArgs);
}n/a
props = function (promises) {
return props(promises);
}n/a
race = function (promises) {
return race(promises, undefined);
}n/a
reduce = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
/**
* Gets all validation error items for the path / field specified.
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
error.ValidationError.prototype.get = function(path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
};
...reject = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
}...
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 +
x27;" 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) {
...rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
}n/a
resolve = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._setFulfilled();
ret._rejectionHandler0 = obj;
}
return ret;
}...
* auto populates error on this.error local object.
* @private
*/
InstanceValidator.prototype._builtinAttrValidate = function(value, field) {
var self = this;
// check if value is null (if null not allowed the Schema pass will capture it)
if (value === null || typeof value === 'undefined') {
return Promise.resolve();
}
// Promisify each validator
var validators = [];
Utils._.forIn(this.modelInstance.validators[field], function(test,
validatorType) {
...setScheduler = function (fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
return async.setScheduler(fn);
}n/a
settle = function (promises) {
debug.deprecated(".settle()", ".reflect()");
return new SettledPromiseArray(promises).promise();
}n/a
some = function (promises, howMany) {
return some(promises, howMany);
}n/a
spawn = function (generatorFunction) {
debug.deprecated("Promise.spawn()", "Promise.coroutine()");
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
}n/a
try = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value;
if (arguments.length > 1) {
debug.deprecated("calling Promise.try with more than 1 argument");
var arg = arguments[1];
var ctx = arguments[2];
value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
: tryCatch(fn).call(ctx, arg);
} else {
value = tryCatch(fn)();
}
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.try", ret);
ret._resolveFromSyncValue(value);
return ret;
}...
if (optAttrDefined) {
validatorFunction = Promise.promisify(validator.bind(this.modelInstance, invokeArgs));
} else {
validatorFunction = Promise.promisify(validator.bind(this.modelInstance));
}
return validatorFunction().catch(this._pushError.bind(this, false, errorKey));
} else {
return Promise.try(validator.bind(this.modelInstance, invokeArgs)).catch(this._pushError
.bind(this, false, errorKey));
}
});
/**
* Prepare and invoke a build-in validator.
*
* @param {*} value Anything.
...using = function () {
var len = arguments.length;
if (len < 2) return apiRejection(
"you must pass at least 2 arguments to Promise.using");
var fn = arguments[len - 1];
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var input;
var spreadArgs = true;
if (len === 2 && Array.isArray(arguments[0])) {
input = arguments[0];
len = input.length;
spreadArgs = false;
} else {
input = arguments;
len--;
}
var resources = new ResourceList(len);
for (var i = 0; i < len; ++i) {
var resource = input[i];
if (Disposer.isDisposer(resource)) {
var disposer = resource;
resource = resource.promise();
resource._setDisposable(disposer);
} else {
var maybePromise = tryConvertToPromise(resource);
if (maybePromise instanceof Promise) {
resource =
maybePromise._then(maybeUnwrapDisposer, null, null, {
resources: resources,
index: i
}, undefined);
}
}
resources[i] = resource;
}
var reflectedResources = new Array(resources.length);
for (var i = 0; i < reflectedResources.length; ++i) {
reflectedResources[i] = Promise.resolve(resources[i]).reflect();
}
var resultPromise = Promise.all(reflectedResources)
.then(function(inspections) {
for (var i = 0; i < inspections.length; ++i) {
var inspection = inspections[i];
if (inspection.isRejected()) {
errorObj.e = inspection.error();
return errorObj;
} else if (!inspection.isFulfilled()) {
resultPromise.cancel();
return;
}
inspections[i] = inspection.value();
}
promise._pushContext();
fn = tryCatch(fn);
var ret = spreadArgs
? fn.apply(undefined, inspections) : fn(inspections);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret, promiseCreated, "Promise.using", promise);
return ret;
});
var promise = resultPromise.lastly(function() {
var inspection = new Promise.PromiseInspection(resultPromise);
return dispose(resources, inspection);
});
resources.promise = promise;
promise._setOnCancel(resources);
return promise;
}n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function every() { [native code] }n/a
function filter() { [native code] }...
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
...function forEach() { [native code] }...
if (!Array.isArray(hooks)) {
hooks = hooks === undefined ? [] : [hooks];
}
// run hooks as sync functions if flagged as sync
if (hookTypes[hookType] && hookTypes[hookType].sync) {
hooks.forEach(function(hook) {
if (typeof hook === 'object') hook = hook.fn;
return hook.apply(self, fnArgs);
});
return;
}
// run hooks async
...function indexOf() { [native code] }...
*/
InstanceValidator.prototype._builtinValidators = function() {
var self = this;
// promisify all attribute invocations
var validators = [];
Utils._.forIn(this.modelInstance.rawAttributes, function(rawAttribute, field) {
if (self.options.skip.indexOf(field) >= 0) {
return;
}
var value = self.modelInstance.dataValues[field];
if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
// perform validations based on schema
...function join() { [native code] }...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
* Gets all validation error items for the path / field specified.
*
...function lastIndexOf() { [native code] }n/a
function map() { [native code] }...
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
...function pop() { [native code] }...
runHooks: function(hooks) {
var self = this
, fn
, fnArgs = Utils.sliceArgs(arguments, 1)
, hookType;
if (typeof fnArgs[fnArgs.length - 1] === 'function') {
fn = fnArgs.pop();
}
if (typeof hooks === 'string') {
hookType = hooks;
hooks = this.options.hooks[hookType] || [];
if (!Array.isArray(hooks)) hooks = hooks === undefined ? [] : [hooks];
if (this.sequelize) hooks = hooks.concat(this.sequelize.options.hooks[hookType] || []);
...function push() { [native code] }...
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
error.ValidationError.prototype.get = function(path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
};
/**
* A base class for all database related errors.
...function reduce() { [native code] }...
/**
* Gets all validation error items for the path / field specified.
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
error.ValidationError.prototype.get = function(path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
};
...function reduceRight() { [native code] }n/a
function reverse() { [native code] }...
});
sorter.add(tableName, deps);
});
sorted = sorter.sort();
if (options.reverse) {
sorted = sorted.reverse();
}
sorted.forEach(function(name) {
iterator(models[name], name);
});
};
module.exports = ModelManager;
...function shift() { [native code] }...
values = [].concat(values);
return sql.replace(/\?/g, function(match) {
if (!values.length) {
return match;
}
return SqlString.escape(values.shift(), timeZone, dialect, true);
});
};
SqlString.formatNamedParameters = function(sql, values, timeZone, dialect) {
return sql.replace(/\:+(?!\d)(\w+)/g, function(value, key) {
if ('postgres' === dialect && '::' === value.slice(0, 2)) {
return value;
...function slice() { [native code] }...
validatorArgs = [validatorArgs, field];
} else if (isLocalizedValidator || validatorType === 'isIP') {
validatorArgs = [];
} else {
validatorArgs = [validatorArgs];
}
} else {
validatorArgs = validatorArgs.slice(0);
}
return validatorArgs;
};
/**
* Will validate a single field against its schema definition (isnull).
*
...function some() { [native code] }n/a
function sort() { [native code] }...
deps = deps.filter(function(dep) {
return tableName !== dep;
});
sorter.add(tableName, deps);
});
sorted = sorter.sort();
if (options.reverse) {
sorted = sorted.reverse();
}
sorted.forEach(function(name) {
iterator(models[name], name);
});
};
...toString = function () {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
}n/a
function unshift() { [native code] }n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}n/a
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}n/a
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed()
? promise._settledValue() : undefined;
}
else {
this._bitField = 0;
this._settledValueField = undefined;
}
}n/a
_settledValue = function () {
return this._settledValueField;
}n/a
error = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a
");
}
return this._settledValue();
}...
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects.
* @private
*/
InstanceValidator.prototype._handleReflectedResult = function(field, promiseInspections) {
var self = this;
promiseInspections.forEach(function(promiseInspection) {
if (promiseInspection.isRejected()) {
var rejection = promiseInspection.error();
self._pushError(true, field, rejection);
}
});
};
/**
* Signs all errors retaining the original.
...isCancelled = function () {
return (this._bitField & 8454144) !== 0;
}n/a
isFulfilled = function () {
return (this._bitField & 33554432) !== 0;
}n/a
isPending = function () {
return (this._bitField & 50397184) === 0;
}n/a
isRejected = function () {
return (this._bitField & 16777216) !== 0;
}...
* @param {string} field The attribute name.
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects.
* @private
*/
InstanceValidator.prototype._handleReflectedResult = function(field, promiseInspections) {
var self = this;
promiseInspections.forEach(function(promiseInspection) {
if (promiseInspection.isRejected()) {
var rejection = promiseInspection.error();
self._pushError(true, field, rejection);
}
});
};
/**
...isResolved = function () {
return (this._bitField & 50331648) !== 0;
}n/a
reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a
");
}
return this._settledValue();
}n/a
value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a
");
}
return this._settledValue();
}n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}n/a
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}n/a
_addFulfilled = function (value) {
this._values[this._totalResolved++] = value;
}n/a
_addRejected = function (reason) {
this._values.push(reason);
}n/a
_canPossiblyFulfill = function () {
return this.length() - this._rejected();
}n/a
_checkOutcome = function () {
if (this.howMany() > this._canPossiblyFulfill()) {
var e = new AggregateError();
for (var i = this.length(); i < this._values.length; ++i) {
if (this._values[i] !== CANCELLATION) {
e.push(this._values[i]);
}
}
if (e.length > 0) {
this._reject(e);
} else {
this._cancel();
}
return true;
}
return false;
}n/a
_fulfilled = function () {
return this._totalResolved;
}n/a
_getRangeError = function (count) {
var message = "Input array must contain at least " +
this._howMany + " items but contains only " + count + " items";
return new RangeError(message);
}n/a
_init = function () {
if (!this._initialized) {
return;
}
if (this._howMany === 0) {
this._resolve([]);
return;
}
this._init$(undefined, -5);
var isArrayResolved = isArray(this._values);
if (!this._isResolved() &&
isArrayResolved &&
this._howMany > this._canPossiblyFulfill()) {
this._reject(this._getRangeError(this.length()));
}
}n/a
_promiseCancelled = function () {
if (this._values instanceof Promise || this._values == null) {
return this._cancel();
}
this._addRejected(CANCELLATION);
return this._checkOutcome();
}n/a
_promiseFulfilled = function (value) {
this._addFulfilled(value);
if (this._fulfilled() === this.howMany()) {
this._values.length = this.howMany();
if (this.howMany() === 1 && this._unwrap) {
this._resolve(this._values[0]);
} else {
this._resolve(this._values);
}
return true;
}
return false;
}n/a
_promiseRejected = function (reason) {
this._addRejected(reason);
return this._checkOutcome();
}n/a
_rejected = function () {
return this._values.length - this.length();
}n/a
_resolveEmptyArray = function () {
this._reject(this._getRangeError(0));
}n/a
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}n/a
howMany = function () {
return this._howMany;
}n/a
init = function () {
this._initialized = true;
this._init();
}n/a
setHowMany = function (count) {
this._howMany = count;
}n/a
setUnwrap = function () {
this._unwrap = true;
}n/a
coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
var ret = spawn.promise();
spawn._generator = generator;
spawn._promiseFulfilled(undefined);
return ret;
};
}n/a
addYieldHandler = function (fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
yieldHandlers.push(fn);
}n/a
each = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
beforeConnection: 'beforeConnect'
};
var Hooks = {
replaceHookAliases: function(hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
...__original = function (promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, 0)
._then(promiseAllThis, undefined, undefined, promises, undefined);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
filter = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
...__original = function (promises, fn, options) {
return PromiseMap(promises, fn, options, INTERNAL);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
join = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
* Gets all validation error items for the path / field specified.
*
...__original = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!false) {
if (last <= 8 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var HolderClass = holderClasses[last - 1];
var holder = new HolderClass(fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
maybePromise._then(callbacks[i], reject,
undefined, ret, holder);
promiseSetters[i](maybePromise, holder);
holder.asyncNeeded = false;
} else if (((bitField & 33554432) !== 0)) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else if (((bitField & 16777216) !== 0)) {
ret._reject(maybePromise._reason());
} else {
ret._cancel();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
if (!ret._isFateSealed()) {
if (holder.asyncNeeded) {
var domain = getDomain();
if (domain !== null) {
holder.fn = util.domainBind(domain, holder.fn);
}
}
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
}
return ret;
}
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
map = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
...__original = function (promises, fn, options, _filter) {
return map(promises, fn, options, _filter);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
mapSeries = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
function PromiseMapSeries(promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
__isCancelled = function () {
return (this._bitField & 65536) === 65536;
}n/a
_addCallbacks = function ( fulfill, reject, promise, receiver, domain ) {
var index = this._length();
if (index >= 65535 - 4) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 =
domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : util.domainBind(domain, reject);
}
} else {
var base = index * 4 - 4;
this[base + 2] = promise;
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : util.domainBind(domain, reject);
}
}
this._setLength(index + 1);
return index;
}n/a
_attachCancellationCallback = function (onCancel) {
;
}n/a
_attachExtraTrace = function () {}n/a
_boundValue = function () {}n/a
_branchHasCancelled = function () {
this._branchesRemainingToCancel--;
}n/a
_cancel = function () {
if (!this._isCancellable()) return;
this._setCancelled();
async.invoke(this._cancelPromises, this, undefined);
}n/a
_cancelBranched = function () {
if (this._enoughBranchesHaveCancelled()) {
this._cancel();
}
}n/a
_cancelBy = function (canceller) {
if (canceller === this) {
this._branchesRemainingToCancel = 0;
this._invokeOnCancel();
return true;
} else {
this._branchHasCancelled();
if (this._enoughBranchesHaveCancelled()) {
this._invokeOnCancel();
return true;
}
}
return false;
}n/a
_cancelPromises = function () {
if (this._length() > 0) this._settlePromises();
}n/a
_captureStackTrace = function () {}n/a
_clearCallbackDataAtIndex = function (index) {
var base = index * 4 - 4;
this[base + 2] =
this[base + 3] =
this[base + 0] =
this[base + 1] = undefined;
}n/a
_clearCancellationData = function () {}n/a
_doInvokeOnCancel = function (onCancelCallback, internalOnly) {
if (util.isArray(onCancelCallback)) {
for (var i = 0; i < onCancelCallback.length; ++i) {
this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
}
} else if (onCancelCallback !== undefined) {
if (typeof onCancelCallback === "function") {
if (!internalOnly) {
var e = tryCatch(onCancelCallback).call(this._boundValue());
if (e === errorObj) {
this._attachExtraTrace(e.e);
async.throwLater(e.e);
}
}
} else {
onCancelCallback._resultCancelled(this);
}
}
}n/a
_enoughBranchesHaveCancelled = function () {
return this._branchesRemainingToCancel === undefined ||
this._branchesRemainingToCancel <= 0;
}n/a
_ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
}n/a
_execute = function (executor, resolve, reject) {
try {
executor(resolve, reject);
} catch (e) {
return e;
}
}n/a
function defaultFireEvent() { return false; }n/a
_followee = function () {
return this._rejectionHandler0;
}n/a
_fulfill = function (value) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._reject(err);
}
this._setFulfilled();
this._rejectionHandler0 = value;
if ((bitField & 65535) > 0) {
if (((bitField & 134217728) !== 0)) {
this._settlePromises();
} else {
async.settlePromises(this);
}
}
}n/a
_fulfillPromises = function (len, value) {
for (var i = 1; i < len; i++) {
var handler = this._fulfillmentHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, value);
}
}n/a
_fulfillmentHandlerAt = function (index) {
return this[
index * 4 - 4 + 0];
}n/a
_getDisposer = function () {
return this._disposer;
}n/a
_invokeInternalOnCancel = function () {
if (this._isCancellable()) {
this._doInvokeOnCancel(this._onCancel(), true);
this._unsetOnCancel();
}
}n/a
_invokeOnCancel = function () {
var onCancelCallback = this._onCancel();
this._unsetOnCancel();
async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
}n/a
_isBound = function () {
return (this._bitField & 2097152) === 2097152;
}n/a
_isCancellable = function () {
return this.isPending() && !this._isCancelled();
}n/a
_isCancelled = function () {
return this._target().__isCancelled();
}n/a
_isDisposable = function () {
return (this._bitField & 131072) > 0;
}n/a
_isFateSealed = function () {
return (this._bitField & 117506048) !== 0;
}n/a
_isFinal = function () {
return (this._bitField & 4194304) > 0;
}n/a
_isFollowing = function () {
return (this._bitField & 67108864) === 67108864;
}n/a
_isRejectionUnhandled = function () {
return (this._bitField & 1048576) > 0;
}n/a
_isUnhandledRejectionNotified = function () {
return (this._bitField & 262144) > 0;
}n/a
_length = function () {
return this._bitField & 65535;
}n/a
_migrateCallback0 = function (follower) {
var bitField = follower._bitField;
var fulfill = follower._fulfillmentHandler0;
var reject = follower._rejectionHandler0;
var promise = follower._promise0;
var receiver = follower._receiverAt(0);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
}n/a
_migrateCallbackAt = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
}n/a
_notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue();
this._setUnhandledRejectionIsNotified();
fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
}n/a
_notifyUnhandledRejectionIsHandled = function () {
fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
}n/a
_onCancel = function () {}n/a
_passThrough = function (handler, type, success, fail) {
if (typeof handler !== "function") return this.then();
return this._then(success,
fail,
undefined,
new PassThroughHandlerContext(this, type, handler),
undefined);
}n/a
_peekContext = function () {}n/a
_popContext = function () {return null;}n/a
_promiseAt = function (index) {
return this[
index * 4 - 4 + 2];
}n/a
_promiseCreated = function () {}n/a
_propagateFrom = function (parent, flags) {
;
;
}n/a
_proxy = function (proxyable, arg) {
this._addCallbacks(undefined, undefined, arg, proxyable, null);
}n/a
_pushContext = function () {}n/a
_reason = function () {
this._unsetRejectionIsUnhandled();
return this._settledValue();
}n/a
_receiverAt = function (index) {
var ret = index === 0 ? this._receiver0 : this[
index * 4 - 4 + 3];
if (ret === UNDEFINED_BINDING) {
return undefined;
} else if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
}n/a
_reject = function (reason) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
this._setRejected();
this._fulfillmentHandler0 = reason;
if (this._isFinal()) {
return async.fatalError(reason, util.isNode);
}
if ((bitField & 65535) > 0) {
async.settlePromises(this);
} else {
this._ensurePossibleRejectionHandled();
}
}n/a
_rejectCallback = function (reason, synchronous, ignoreNonErrorWarnings) {
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
var message = "a promise was rejected with a non-error: " +
util.classString(reason);
this._warn(message, true);
}
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason);
}n/a
_rejectPromises = function (len, reason) {
for (var i = 1; i < len; i++) {
var handler = this._rejectionHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, reason);
}
}n/a
_rejectionHandlerAt = function (index) {
return this[
index * 4 - 4 + 1];
}n/a
_resolveCallback = function (value, shouldBind) {
if (((this._bitField & 117506048) !== 0)) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
if (promise === this) {
this._reject(makeSelfResolutionError());
return;
}
var bitField = promise._bitField;
if (((bitField & 50397184) === 0)) {
var len = this._length();
if (len > 0) promise._migrateCallback0(this);
for (var i = 1; i < len; ++i) {
promise._migrateCallbackAt(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) {
this._reject(promise._reason());
} else {
var reason = new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
this._reject(reason);
}
}n/a
_resolveFromExecutor = function (executor) {
if (executor === INTERNAL) return;
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = this._execute(executor, function(value) {
promise._resolveCallback(value);
}, function (reason) {
promise._rejectCallback(reason, synchronous);
});
synchronous = false;
this._popContext();
if (r !== undefined) {
promise._rejectCallback(r, true);
}
}n/a
_resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false);
} else {
this._resolveCallback(value, true);
}
}n/a
_resultCancelled = function () {
this.cancel();
}n/a
_returnedNonUndefined = function () {
return (this._bitField & 268435456) !== 0;
}n/a
_setAsyncGuaranteed = function () {
if (async.hasCustomScheduler()) return;
this._bitField = this._bitField | 134217728;
}n/a
_setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 2097152;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~2097152);
}
}n/a
_setCancelled = function () {
this._bitField = this._bitField | 65536;
this._fireEvent("promiseCancelled", this);
}n/a
_setDisposable = function (disposer) {
this._bitField = this._bitField | 131072;
this._disposer = disposer;
}n/a
_setFollowee = function (promise) {
this._rejectionHandler0 = promise;
}n/a
_setFollowing = function () {
this._bitField = this._bitField | 67108864;
this._fireEvent("promiseResolved", this);
}n/a
_setFulfilled = function () {
this._bitField = this._bitField | 33554432;
this._fireEvent("promiseFulfilled", this);
}n/a
_setIsFinal = function () {
this._bitField = this._bitField | 4194304;
}n/a
_setLength = function (len) {
this._bitField = (this._bitField & -65536) |
(len & 65535);
}n/a
_setOnCancel = function (handler) { ; }n/a
_setRejected = function () {
this._bitField = this._bitField | 16777216;
this._fireEvent("promiseRejected", this);
}n/a
_setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 1048576;
}n/a
_setReturnedNonUndefined = function () {
this._bitField = this._bitField | 268435456;
}n/a
_setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 262144;
}n/a
_setWillBeCancelled = function () {
this._bitField = this._bitField | 8388608;
}n/a
_settlePromise = function (promise, handler, receiver, value) {
var isPromise = promise instanceof Promise;
var bitField = this._bitField;
var asyncGuaranteed = ((bitField & 134217728) !== 0);
if (((bitField & 65536) !== 0)) {
if (isPromise) promise._invokeInternalOnCancel();
if (receiver instanceof PassThroughHandlerContext &&
receiver.isFinallyHandler()) {
receiver.cancelPromise = promise;
if (tryCatch(handler).call(receiver, value) === errorObj) {
promise._reject(errorObj.e);
}
} else if (handler === reflectHandler) {
promise._fulfill(reflectHandler.call(receiver));
} else if (receiver instanceof Proxyable) {
receiver._promiseCancelled(promise);
} else if (isPromise || promise instanceof PromiseArray) {
promise._cancel();
} else {
receiver.cancel();
}
} else if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof Proxyable) {
if (!receiver._isResolved()) {
if (((bitField & 33554432) !== 0)) {
receiver._promiseFulfilled(value, promise);
} else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
if (((bitField & 33554432) !== 0)) {
promise._fulfill(value);
} else {
promise._reject(value);
}
}
}n/a
_settlePromise0 = function (handler, value, bitField) {
var promise = this._promise0;
var receiver = this._receiverAt(0);
this._promise0 = undefined;
this._receiver0 = undefined;
this._settlePromise(promise, handler, receiver, value);
}n/a
_settlePromiseCtx = function (ctx) {
this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
}n/a
_settlePromiseFromHandler = function ( handler, receiver, value, promise ) {
var bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
promise._pushContext();
var x;
if (receiver === APPLY) {
if (!value || typeof value.length !== "number") {
x = errorObj;
x.e = new TypeError("cannot .spread() a non-array: " +
util.classString(value));
} else {
x = tryCatch(handler).apply(this._boundValue(), value);
}
} else {
x = tryCatch(handler).call(receiver, value);
}
var promiseCreated = promise._popContext();
bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
if (x === NEXT_FILTER) {
promise._reject(value);
} else if (x === errorObj) {
promise._rejectCallback(x.e, false);
} else {
debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
promise._resolveCallback(x);
}
}n/a
_settlePromiseLateCancellationObserver = function (ctx) {
var handler = ctx.handler;
var promise = ctx.promise;
var receiver = ctx.receiver;
var value = ctx.value;
if (typeof handler === "function") {
if (!(promise instanceof Promise)) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (promise instanceof Promise) {
promise._reject(value);
}
}n/a
_settlePromises = function () {
var bitField = this._bitField;
var len = (bitField & 65535);
if (len > 0) {
if (((bitField & 16842752) !== 0)) {
var reason = this._fulfillmentHandler0;
this._settlePromise0(this._rejectionHandler0, reason, bitField);
this._rejectPromises(len, reason);
} else {
var value = this._rejectionHandler0;
this._settlePromise0(this._fulfillmentHandler0, value, bitField);
this._fulfillPromises(len, value);
}
this._setLength(0);
}
this._clearCancellationData();
}n/a
_settledValue = function () {
var bitField = this._bitField;
if (((bitField & 33554432) !== 0)) {
return this._rejectionHandler0;
} else if (((bitField & 16777216) !== 0)) {
return this._fulfillmentHandler0;
}
}n/a
_target = function () {
var ret = this;
while (ret._isFollowing()) ret = ret._followee();
return ret;
}n/a
_then = function ( didFulfill, didReject, _, receiver, internalData ) {
var haveInternalData = internalData !== undefined;
var promise = haveInternalData ? internalData : new Promise(INTERNAL);
var target = this._target();
var bitField = target._bitField;
if (!haveInternalData) {
promise._propagateFrom(this, 3);
promise._captureStackTrace();
if (receiver === undefined &&
((this._bitField & 2097152) !== 0)) {
if (!((bitField & 50397184) === 0)) {
receiver = this._boundValue();
} else {
receiver = target === this ? undefined : this._boundTo;
}
}
this._fireEvent("promiseChained", this, promise);
}
var domain = getDomain();
if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) {
value = target._rejectionHandler0;
handler = didFulfill;
} else if (((bitField & 16777216) !== 0)) {
value = target._fulfillmentHandler0;
handler = didReject;
target._unsetRejectionIsUnhandled();
} else {
settler = target._settlePromiseLateCancellationObserver;
value = new CancellationError("late cancellation observer");
target._attachExtraTrace(value);
handler = didReject;
}
async.invoke(settler, target, {
handler: domain === null ? handler
: (typeof handler === "function" &&
util.domainBind(domain, handler)),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
}
return promise;
}n/a
_unsetCancelled = function () {
this._bitField = this._bitField & (~65536);
}n/a
_unsetDisposable = function () {
this._bitField = this._bitField & (~131072);
this._disposer = undefined;
}n/a
_unsetOnCancel = function () {
this._onCancelField = undefined;
}n/a
_unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~1048576);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
}n/a
_unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~262144);
}n/a
_value = function () {
return this._settledValue();
}n/a
_warn = function (message, shouldUseOwnTrace, promise) {
return warn(message, shouldUseOwnTrace, promise || this);
}n/a
all = function () {
if (arguments.length > 0) {
this._warn(".all() was passed arguments but it does not take any");
}
return new PromiseArray(this).promise();
}...
InstanceValidator.prototype.validate = function() {
if (this.inProgress) {
throw new Error('Validations already in progress.');
}
this.inProgress = true;
var self = this;
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
...any = function () {
return any(this);
}n/a
asCallback = function (nodeback, options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(
adapter,
errorAdapter,
undefined,
this,
nodeback
);
}
return this;
}n/a
bind = function (thisArg) {
if (!calledBind) {
calledBind = true;
Promise.prototype._propagateFrom = debug.propagateFromFunction();
Promise.prototype._boundValue = debug.boundValueFunction();
}
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, undefined, ret, context);
maybePromise._then(
bindingResolved, bindingRejected, undefined, ret, context);
ret._setOnCancel(maybePromise);
} else {
ret._resolveCallback(target);
}
return ret;
}...
var validatorPromise = self._invokeBuiltinValidator(value, test, validatorType, field);
// errors are handled in settling, stub this
validatorPromise.catch(function() {});
validators.push(validatorPromise.reflect());
});
return Promise.all(validators).then(this._handleReflectedResult.bind(this, field));
};
/**
* Prepare and invoke a custom validator.
*
* @param {Function} validator The custom validator.
* @param {string} validatorType the custom validator type (name).
...break = function () {
if (!debug.cancellation()) return this._warn("cancellation is disabled");
var promise = this;
var child = promise;
while (promise._isCancellable()) {
if (!promise._cancelBy(child)) {
if (child._isFollowing()) {
child._followee().cancel();
} else {
child._cancelBranched();
}
break;
}
var parent = promise._cancellationParent;
if (parent == null || !parent._isCancellable()) {
if (promise._isFollowing()) {
promise._followee().cancel();
} else {
promise._cancelBranched();
}
break;
} else {
if (promise._isFollowing()) promise._followee().cancel();
promise._setWillBeCancelled();
child = promise;
promise = parent;
}
}
}n/a
call = function (methodName) {
var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i -
1] = arguments[$_i];};
if (!false) {
if (canEvaluate) {
var maybeCaller = getMethodCaller(methodName);
if (maybeCaller !== null) {
return this._then(
maybeCaller, undefined, undefined, args, undefined);
}
}
}
args.push(methodName);
return this._then(caller, undefined, undefined, args, undefined);
}...
/**
* Thrown when a database query times out because of a deadlock
* @extends DatabaseError
* @constructor
*/
error.TimeoutError = function (parent) {
error.DatabaseError.call(this, parent);
this.name = 'SequelizeTimeoutError';
};
util.inherits(error.TimeoutError, error.BaseError);
/**
* Thrown when a unique constraint is violated in the database
* @extends DatabaseError
...cancel = function () {
if (!debug.cancellation()) return this._warn("cancellation is disabled");
var promise = this;
var child = promise;
while (promise._isCancellable()) {
if (!promise._cancelBy(child)) {
if (child._isFollowing()) {
child._followee().cancel();
} else {
child._cancelBranched();
}
break;
}
var parent = promise._cancellationParent;
if (parent == null || !parent._isCancellable()) {
if (promise._isFollowing()) {
promise._followee().cancel();
} else {
promise._cancelBranched();
}
break;
} else {
if (promise._isFollowing()) promise._followee().cancel();
promise._setWillBeCancelled();
child = promise;
promise = parent;
}
}
}n/a
catch = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
Utils._.each(this.modelInstance.$modelOptions.validate, function(validator, validatorType) {
if (self.options.skip.indexOf(validatorType) >= 0) {
return;
}
var valprom = self._invokeCustomValidator(validator, validatorType)
// errors are handled in settling, stub this
.catch(function() {})
.reflect();
validators.push(valprom);
});
return Promise.all(validators);
};
...catchReturn = function (value) {
if (arguments.length <= 1) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
undefined, returner, undefined, {value: value}, undefined);
} else {
var _value = arguments[1];
if (_value instanceof Promise) _value.suppressUnhandledRejections();
var handler = function() {return _value;};
return this.caught(value, handler);
}
}n/a
catchThrow = function (reason) {
if (arguments.length <= 1) {
return this._then(
undefined, thrower, undefined, {reason: reason}, undefined);
} else {
var _reason = arguments[1];
var handler = function() {throw _reason;};
return this.caught(reason, handler);
}
}n/a
caught = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("Catch statement predicate: " +
"expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
}n/a
delay = function (ms) {
return delay(ms, this);
}n/a
disposer = function (fn) {
if (typeof fn === "function") {
return new FunctionDisposer(fn, this, createContext());
}
throw new TypeError();
}n/a
done = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
each = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
beforeConnection: 'beforeConnect'
};
var Hooks = {
replaceHookAliases: function(hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
...error = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects.
* @private
*/
InstanceValidator.prototype._handleReflectedResult = function(field, promiseInspections) {
var self = this;
promiseInspections.forEach(function(promiseInspection) {
if (promiseInspection.isRejected()) {
var rejection = promiseInspection.error();
self._pushError(true, field, rejection);
}
});
};
/**
* Signs all errors retaining the original.
...filter = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
...finally = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount']]
}
});
})
.then(console.log)
.finally(() => {
sequelize.close();
});
...get = function (propertyName) {
var isIndex = (typeof propertyName === "number");
var getter;
if (!isIndex) {
if (canEvaluate) {
var maybeGetter = getGetter(propertyName);
getter = maybeGetter !== null ? maybeGetter : namedGetter;
} else {
getter = namedGetter;
}
} else {
getter = indexedGetter;
}
return this._then(getter, undefined, undefined, propertyName, undefined);
}...
options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
};
QueryInterface.prototype.dropAllTables = function(options) {
var self = this
, skip;
...isCancellable = function () {
return this.isPending() && !this.isCancelled();
}n/a
isCancelled = function () {
return (this._target()._bitField & 8454144) !== 0;
}n/a
isFulfilled = function () {
return isFulfilled.call(this._target());
}n/a
isPending = function () {
return isPending.call(this._target());
}n/a
isRejected = function () {
return isRejected.call(this._target());
}...
* @param {string} field The attribute name.
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects.
* @private
*/
InstanceValidator.prototype._handleReflectedResult = function(field, promiseInspections) {
var self = this;
promiseInspections.forEach(function(promiseInspection) {
if (promiseInspection.isRejected()) {
var rejection = promiseInspection.error();
self._pushError(true, field, rejection);
}
});
};
/**
...isResolved = function () {
return isResolved.call(this._target());
}n/a
lastly = function (handler) {
return this._passThrough(handler,
0,
finallyHandler,
finallyHandler);
}n/a
map = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
...mapSeries = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
nodeify = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
hook = Promise.promisify(hook, self);
}
return hook.apply(self, fnArgs);
}).return();
if (fn) {
return promise.nodeify(fn);
}
return promise;
},
hook: function() {
return Hooks.addHook.apply(this, arguments);
...props = function () {
return props(this);
}n/a
race = function () {
return race(this, undefined);
}n/a
reason = function () {
var target = this._target();
target._unsetRejectionIsUnhandled();
return reason.call(target);
}n/a
reduce = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
/**
* Gets all validation error items for the path / field specified.
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
error.ValidationError.prototype.get = function(path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
};
...reflect = function () {
return this._then(reflectHandler,
reflectHandler, undefined, this, undefined);
}...
this.inProgress = true;
var self = this;
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
} else {
return null;
}
});
...return = function (value) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
returner, undefined, undefined, {value: value}, undefined);
}...
}
if (hookType && hook.length > hookTypes[hookType].params) {
hook = Promise.promisify(hook, self);
}
return hook.apply(self, fnArgs);
}).return();
if (fn) {
return promise.nodeify(fn);
}
return promise;
},
...settle = function () {
return Promise.settle(this);
}n/a
some = function (howMany) {
return some(this, howMany);
}n/a
spread = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
suppressUnhandledRejections = function () {
var target = this._target();
target._bitField = ((target._bitField & (~1048576)) |
524288);
}n/a
tap = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
tapCatch = function (handlerOrPredicate) {
var len = arguments.length;
if(len === 1) {
return this._passThrough(handlerOrPredicate,
1,
undefined,
finallyHandler);
} else {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return Promise.reject(new TypeError(
"tapCatch statement predicate: "
+ "expecting an object but got " + util.classString(item)
));
}
}
catchInstances.length = j;
var handler = arguments[i];
return this._passThrough(catchFilter(catchInstances, handler, this),
1,
undefined,
finallyHandler);
}
}n/a
then = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
return sequelize.sync({
force: true,
logging: console.log
})
.then(() => {
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount']]
}
});
})
.then(console.log)
...thenReturn = function (value) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
returner, undefined, undefined, {value: value}, undefined);
}n/a
thenThrow = function (reason) {
return this._then(
thrower, undefined, undefined, {reason: reason}, undefined);
}n/a
throw = function (reason) {
return this._then(
thrower, undefined, undefined, {reason: reason}, undefined);
}n/a
timeout = function (ms, message) {
ms = +ms;
var ret, parent;
var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
if (ret.isPending()) {
afterTimeout(ret, message, parent);
}
}, ms));
if (debug.cancellation()) {
parent = this.then();
ret = parent._then(successClear, failureClear,
undefined, handleWrapper, undefined);
ret._setOnCancel(handleWrapper);
} else {
ret = this._then(successClear, failureClear,
undefined, handleWrapper, undefined);
}
return ret;
}n/a
toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
}n/a
toString = function () {
return "[object Promise]";
}n/a
value = function () {
return value.call(this._target());
}n/a
catch = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
Utils._.each(this.modelInstance.$modelOptions.validate, function(validator, validatorType) {
if (self.options.skip.indexOf(validatorType) >= 0) {
return;
}
var valprom = self._invokeCustomValidator(validator, validatorType)
// errors are handled in settling, stub this
.catch(function() {})
.reflect();
validators.push(valprom);
});
return Promise.all(validators);
};
...__original = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("Catch statement predicate: " +
"expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
done = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
__original = function (didFulfill, didReject) {
var promise =
this._then(didFulfill, didReject, undefined, undefined, undefined);
promise._setIsFinal();
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
each = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
beforeConnection: 'beforeConnect'
};
var Hooks = {
replaceHookAliases: function(hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
...__original = function (fn) {
return PromiseReduce(this, fn, INTERNAL, 0)
._then(promiseAllThis, undefined, undefined, this, undefined);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
error = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects.
* @private
*/
InstanceValidator.prototype._handleReflectedResult = function(field, promiseInspections) {
var self = this;
promiseInspections.forEach(function(promiseInspection) {
if (promiseInspection.isRejected()) {
var rejection = promiseInspection.error();
self._pushError(true, field, rejection);
}
});
};
/**
* Signs all errors retaining the original.
...__original = function (fn) {
return this.caught(util.originatesFromRejection, fn);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
filter = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
...__original = function (fn, options) {
return PromiseMap(this, fn, options, INTERNAL);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
finally = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount']]
}
});
})
.then(console.log)
.finally(() => {
sequelize.close();
});
...__original = function (handler) {
return this._passThrough(handler,
0,
finallyHandler,
finallyHandler);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
map = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
...__original = function (fn, options) {
return map(this, fn, options, null);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
mapSeries = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
__original = function (fn) {
return PromiseReduce(this, fn, INTERNAL, INTERNAL);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
nodeify = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
hook = Promise.promisify(hook, self);
}
return hook.apply(self, fnArgs);
}).return();
if (fn) {
return promise.nodeify(fn);
}
return promise;
},
hook: function() {
return Hooks.addHook.apply(this, arguments);
...__original = function (nodeback, options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(
adapter,
errorAdapter,
undefined,
this,
nodeback
);
}
return this;
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
reduce = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
/**
* Gets all validation error items for the path / field specified.
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
error.ValidationError.prototype.get = function(path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
};
...__original = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
spread = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
__original = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
return this.all()._then(fn, undefined, undefined, APPLY, undefined);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
tap = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}n/a
__original = function (handler) {
return this._passThrough(handler, 1, finallyHandler);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
then = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
return sequelize.sync({
force: true,
logging: console.log
})
.then(() => {
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount']]
}
});
})
.then(console.log)
...__original = function (didFulfill, didReject) {
if (debug.warnings() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, undefined, undefined, undefined);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
reduce = function () {
if (Promise.Sequelize && Promise.Sequelize.cls) {
var ns = Promise.Sequelize.cls;
for(var x=0; x<fnArgs.length; x++) {
var argIndex = fnArgs[x] < 0 ? arguments.length + fnArgs[x] : fnArgs[x];
if ( argIndex < arguments.length && typeof arguments[argIndex] === 'function' ) {
arguments[argIndex] = ns.bind( arguments[argIndex] );
}
}
}
return fn.apply(this, arguments);
}...
/**
* Gets all validation error items for the path / field specified.
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
error.ValidationError.prototype.get = function(path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
};
...__original = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
}n/a
__unwrap = function () {
if (nodule[name] === wrapped) nodule[name] = original
}n/a
RANGE = function (subtype) {
var options = _.isPlainObject(subtype) ? subtype : { subtype: subtype };
if (!options.subtype) options.subtype = new INTEGER();
if (_.isFunction(options.subtype)) {
options.subtype = new options.subtype();
}
if (!(this instanceof RANGE)) return new RANGE(options);
ABSTRACT.apply(this, arguments);
this._subtype = options.subtype.key;
this.options = options;
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return pgRangeSubtypes[this._subtype.toLowerCase()];
}n/a
validate = function (value) {
if (_.isPlainObject(value) && value.inclusive) {
value = value.inclusive;
}
if (!_.isArray(value)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid range', value));
}
if (value.length !== 2) {
throw new sequelizeErrors.ValidationError('A range must be an array with two elements');
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...REAL = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof REAL)) return new REAL(options);
NUMBER.call(this, options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
STRING = function (length, binary) {
var options = typeof length === 'object' && length || {
length: length,
binary: binary
};
if (!(this instanceof STRING)) return new STRING(options);
this.options = options;
this._binary = options.binary;
this._length = options.length || 255;
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'VARCHAR(' + this._length + ')' + ((this._binary) ? ' BINARY' : '');
}n/a
validate = function (value) {
if (Object.prototype.toString.call(value) !== '[object String]') {
if ((this.options.binary && Buffer.isBuffer(value)) || _.isNumber(value)) {
return true;
}
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid string', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...Sequelize = function (database, username, password, options) {
var config;
if (arguments.length === 1 && typeof database === 'object') {
// new Sequelize({ ... options })
options = database;
config = _.pick(options, 'host', 'port', 'database', 'username', 'password');
} else if ((arguments.length === 1 && typeof database === 'string') || (arguments.length === 2 && typeof username === 'object')) {
// new Sequelize(URI, { ... options })
config = {};
options = username || {};
var urlParts = url.parse(arguments[0]);
// SQLite don't have DB in connection url
if (urlParts.pathname) {
config.database = urlParts.pathname.replace(/^\//, '');
}
options.dialect = urlParts.protocol.replace(/:$/, '');
options.host = urlParts.hostname;
if (urlParts.port) {
options.port = urlParts.port;
}
if (urlParts.auth) {
config.username = urlParts.auth.split(':')[0];
config.password = urlParts.auth.split(':')[1];
}
} else {
// new Sequelize(database, username, password, { ... options })
options = options || {};
config = {database: database, username: username, password: password};
}
Sequelize.runHooks('beforeInit', config, options);
this.options = Utils._.extend({
dialect: 'mysql',
dialectModulePath: null,
host: 'localhost',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone:'+00:00',
logging: console.log,
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: {max: 5, match: ['SQLITE_BUSY: database is locked']},
transactionType: Transaction.TYPES.DEFERRED,
isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
databaseVersion: 0,
typeValidation: false,
benchmark: false
}, options || {});
if (this.options.dialect === 'postgresql') {
this.options.dialect = 'postgres';
}
if (this.options.dialect === 'sqlite' && this.options.timezone !== '+00:00') {
throw new Error('Setting a custom timezone is not supported by SQLite, dates are always returned as UTC. Please remove the custom
timezone parameter.');
}
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
this.options.hooks = this.replaceHookAliases(this.options.hooks);
if ((['', null, false].indexOf(config.password) > -1) || (typeof config.password === 'undefined')) {
config.password = null;
}
this.config = {
database: config.database,
username: config.username,
password: config.password,
host: config.host || this.options.host,
port: config.port || this.options.port,
pool: this.options.pool,
protocol: this.options.protocol,
native: this.options.native,
ssl: this.options.ssl,
replication: this.options.replication,
dialectModulePath: this.options.dialectModulePath,
keepDefaultTimezone: this.options.keepDefaultTimezone,
dialectOptions: this.options.dialectOptions
};
var Dialect;
// Requiring the dialect in a switch-case to keep the
// require calls static. (Browserify fix)
switch (this.getDialect()){
case 'mariadb':
Dialect = require('./dialects/mariadb');
break;
case 'mssql':
Dialect = require('./dialects/mssql');
break;
case 'mysql':
Dialect = require('./dialects/mysql');
break;
case 'postgres':
Dialect = require('./dialects/postgres');
break;
case 'sqlite':
Dialect = require('./dialects/sqlite');
break;
default:
throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mariadb, mssql, mysql, postgres
, and sqlite.');
}
this.dialect = new Dialect(this);
this.dialect.QueryGenerator.typeValidation = options.typeValidation;
/**
* Models are stored here under the name given to `sequelize.define`
* @property models
*/
this.models = {};
this.mod ...n/a
ABSTRACT = function (options) {
}n/a
ARRAY = function (type) {
var options = _.isPlainObject(type) ? type : {
type: type
};
if (!(this instanceof ARRAY)) return new ARRAY(options);
this.type = typeof options.type === 'function' ? new options.type() : options.type;
}n/a
AccessDeniedError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeAccessDeniedError';
}n/a
Association = function () {}n/a
BIGINT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BIGINT)) return new BIGINT(options);
NUMBER.call(this, options);
}n/a
BLOB = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BLOB)) return new BLOB(options);
this.options = options;
this._length = options.length || '';
}n/a
BOOLEAN = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
CHAR = function (length, binary) {
var options = typeof length === 'object' && length || {
length: length,
binary: binary
};
if (!(this instanceof CHAR)) return new CHAR(options);
STRING.apply(this, arguments);
}n/a
ConnectionError = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
ConnectionRefusedError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeConnectionRefusedError';
}n/a
ConnectionTimedOutError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeConnectionTimedOutError';
}n/a
DATE = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof DATE)) return new DATE(options);
this.options = options;
this._length = options.length || '';
}n/a
DATEONLY = function () {
if (!(this instanceof DATEONLY)) return new DATEONLY();
ABSTRACT.apply(this, arguments);
}n/a
DECIMAL = function (precision, scale) {
var options = typeof precision === 'object' && precision || {
precision: precision,
scale: scale
};
if (!(this instanceof DECIMAL)) return new DECIMAL(options);
NUMBER.call(this, options);
}n/a
DOUBLE = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof DOUBLE)) return new DOUBLE(options);
NUMBER.call(this, options);
}n/a
DatabaseError = function (parent) {
error.BaseError.apply(this, [parent.message]);
this.name = 'SequelizeDatabaseError';
/**
* The database specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
/**
* The SQL that triggered the error
* @member sql
*/
this.sql = parent.sql;
/**
* The message from the DB.
* @member message
* @name message
*/
/**
* The fields of the unique constraint
* @member fields
* @name fields
*/
/**
* The value(s) which triggered the error
* @member value
* @name value
*/
/**
* The name of the index that triggered the error
* @member index
* @name index
*/
}n/a
ENUM = function (value) {
var options = typeof value === 'object' && !Array.isArray(value) && value || {
values: Array.prototype.slice.call(arguments).reduce(function(result, element) {
return result.concat(Array.isArray(element) ? element : [element]);
}, [])
};
if (!(this instanceof ENUM)) return new ENUM(options);
this.values = options.values;
this.options = options;
}n/a
EmptyResultError = function (message) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeEmptyResultError';
this.message = message;
}n/a
Error = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
ExclusionConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
error.DatabaseError.call(this, options.parent);
this.name = 'SequelizeExclusionConstraintError';
this.message = options.message || options.parent.message;
this.constraint = options.constraint;
this.fields = options.fields;
this.table = options.table;
}n/a
FLOAT = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof FLOAT)) return new FLOAT(options);
NUMBER.call(this, options);
}n/a
ForeignKeyConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
error.DatabaseError.call(this, options.parent);
this.name = 'SequelizeForeignKeyConstraintError';
this.message = options.message || options.parent.message || 'Database Error';
this.fields = options.fields;
this.table = options.table;
this.value = options.value;
this.index = options.index;
}n/a
GEOGRAPHY = function (type, srid) {
var options = _.isPlainObject(type) ? type : {
type: type,
srid: srid
};
if (!(this instanceof GEOGRAPHY)) return new GEOGRAPHY(options);
this.options = options;
this.type = options.type;
this.srid = options.srid;
}n/a
GEOMETRY = function (type, srid) {
var options = _.isPlainObject(type) ? type : {
type: type,
srid: srid
};
if (!(this instanceof GEOMETRY)) return new GEOMETRY(options);
this.options = options;
this.type = options.type;
this.srid = options.srid;
}n/a
HSTORE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
HostNotFoundError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeHostNotFoundError';
}n/a
HostNotReachableError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeHostNotReachableError';
}n/a
INTEGER = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof INTEGER)) return new INTEGER(options);
NUMBER.call(this, options);
}n/a
Instance = function (values, options) {
this.dataValues = {};
this._previousDataValues = {};
this._changed = {};
this.$modelOptions = this.Model.options;
this.$options = options || {};
this.hasPrimaryKeys = this.Model.options.hasPrimaryKeys;
this.__eagerlyLoadedAssociations = [];
/**
* Returns true if this instance has not yet been persisted to the database
* @property isNewRecord
* @return {Boolean}
*/
this.isNewRecord = options.isNewRecord;
/**
* Returns the Model the instance was created from.
* @see {Model}
* @property Model
* @return {Model}
*/
initValues.call(this, values, options);
}n/a
InstanceError = function (message) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeInstanceError';
this.message = message;
}n/a
InvalidConnectionError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeInvalidConnectionError';
}n/a
JSON = function () {
if (!(this instanceof JSONTYPE)) return new JSONTYPE();
ABSTRACT.apply(this, arguments);
}n/a
JSONB = function () {
if (!(this instanceof JSONB)) return new JSONB();
JSONTYPE.apply(this, arguments);
}n/a
Model = function (name, attributes, options) {
this.options = Utils._.extend({
timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: []
}, options || {});
this.associations = {};
this.modelManager = null;
this.name = name;
this.options.hooks = _.mapValues(this.replaceHookAliases(this.options.hooks), function (hooks) {
if (!Array.isArray(hooks)) hooks = [hooks];
return hooks;
});
this.sequelize = options.sequelize;
this.underscored = this.underscored || this.underscoredAll;
if (!this.options.tableName) {
this.tableName = this.options.freezeTableName ? name : Utils.underscoredIf(Utils.pluralize(name), this.options.underscoredAll
);
} else {
this.tableName = this.options.tableName;
}
this.$schema = this.options.schema;
this.$schemaDelimiter = this.options.schemaDelimiter;
// error check options
_.each(options.validate, function(validator, validatorType) {
if (_.includes(Utils._.keys(attributes), validatorType)) {
throw new Error('A model validator function must not have the same name as a field. Model: ' + name + ', field/validation
name: ' + validatorType);
}
if (!_.isFunction(validator)) {
throw new Error('Members of the validate option must be functions. Model: ' + name + ', error with validate member ' + validatorType
);
}
});
this.attributes = this.rawAttributes = _.mapValues(attributes, function(attribute, name) {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute };
}
attribute = this.sequelize.normalizeAttribute(attribute);
if (attribute.references) {
attribute = Utils.formatReferences(attribute);
if (attribute.references.model instanceof Model) {
attribute.references.model = attribute.references.model.tableName;
}
}
if (attribute.type === undefined) {
throw new Error('Unrecognized data type for field ' + name);
}
return attribute;
}.bind(this));
}n/a
NONE = function (ReturnType, fields) {
if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields);
if (typeof ReturnType === 'function') ReturnType = new ReturnType();
this.returnType = ReturnType;
this.fields = fields;
}n/a
NOW = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
NUMBER = function (options) {
this.options = options;
this._length = options.length;
this._zerofill = options.zerofill;
this._decimals = options.decimals;
this._precision = options.precision;
this._scale = options.scale;
this._unsigned = options.unsigned;
}n/a
NUMERIC = function (precision, scale) {
var options = typeof precision === 'object' && precision || {
precision: precision,
scale: scale
};
if (!(this instanceof DECIMAL)) return new DECIMAL(options);
NUMBER.call(this, options);
}n/a
function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}n/a
RANGE = function (subtype) {
var options = _.isPlainObject(subtype) ? subtype : { subtype: subtype };
if (!options.subtype) options.subtype = new INTEGER();
if (_.isFunction(options.subtype)) {
options.subtype = new options.subtype();
}
if (!(this instanceof RANGE)) return new RANGE(options);
ABSTRACT.apply(this, arguments);
this._subtype = options.subtype.key;
this.options = options;
}n/a
REAL = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof REAL)) return new REAL(options);
NUMBER.call(this, options);
}n/a
STRING = function (length, binary) {
var options = typeof length === 'object' && length || {
length: length,
binary: binary
};
if (!(this instanceof STRING)) return new STRING(options);
this.options = options;
this._binary = options.binary;
this._length = options.length || 255;
}n/a
TEXT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof TEXT)) return new TEXT(options);
this.options = options;
this._length = options.length || '';
}n/a
TIME = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
TimeoutError = function (parent) {
error.DatabaseError.call(this, parent);
this.name = 'SequelizeTimeoutError';
}n/a
function Transaction(sequelize, options) {
this.sequelize = sequelize;
this.savepoints = [];
var generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;
this.options = Utils._.extend({
autocommit: true,
type: sequelize.options.transactionType,
isolationLevel: sequelize.options.isolationLevel,
readOnly: false
}, options || {});
this.parent = this.options.transaction;
this.id = this.parent ? this.parent.id : generateTransactionId();
if (this.parent) {
this.id = this.parent.id;
this.parent.savepoints.push(this);
this.name = this.id + '-savepoint-' + this.parent.savepoints.length;
} else {
this.id = this.name = generateTransactionId();
}
delete this.options.transaction;
}n/a
UUID = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
UUIDV1 = function () {
if (!(this instanceof UUIDV1)) return new UUIDV1();
ABSTRACT.apply(this, arguments);
}n/a
UUIDV4 = function () {
if (!(this instanceof UUIDV4)) return new UUIDV4();
ABSTRACT.apply(this, arguments);
}n/a
UniqueConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
options.message = options.message || options.parent.message || 'Validation Error';
options.errors = options.errors || {};
error.ValidationError.call(this, options.message, options.errors);
this.name = 'SequelizeUniqueConstraintError';
this.message = options.message;
this.errors = options.errors;
this.fields = options.fields;
this.parent = options.parent;
this.original = options.parent;
this.sql = options.parent.sql;
}n/a
VIRTUAL = function (ReturnType, fields) {
if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields);
if (typeof ReturnType === 'function') ReturnType = new ReturnType();
this.returnType = ReturnType;
this.fields = fields;
}n/a
ValidationError = function (message, errors) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeValidationError';
this.message = 'Validation Error';
/**
* An array of ValidationErrorItems
* @member errors
*/
this.errors = errors || [];
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
}...
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
} else {
return null;
}
});
};
/**
...ValidationErrorItem = function (message, type, path, value) {
this.message = message || '';
this.type = type || null;
this.path = path || null;
this.value = value || null;
}...
* @param {*} value anything.
* @private
*/
InstanceValidator.prototype._validateSchema = function(rawAttribute, field, value) {
var error;
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be null',
x27;notNull Violation', field, value);
this.errors.push(error);
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes.TEXT
|| rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || (_.isObject(value) && !value._isSequelizeMethod) && !Buffer.isBuffer(value)) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be an array or an object', 'string violation
x27;, field, value);
this.errors.push(error);
...addHook = function (hookType, name, fn) {
if (typeof name === 'function') {
fn = name;
name = null;
}
hookType = hookAliases[hookType] || hookType;
this.options.hooks[hookType] = this.options.hooks[hookType] || [];
this.options.hooks[hookType].push(!!name ? {name: name, fn: fn} : fn);
return this;
}...
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
});
}
};
...and = function () {
return { $and: Utils.sliceArgs(arguments) };
}n/a
asIs = function (val) {
return new Utils.literal(val);
}n/a
cast = function (val, type) {
return new Utils.cast(val, type);
}n/a
col = function (col) {
return new Utils.col(col);
}n/a
condition = function (attr, comparator, logic) {
return new Utils.where(attr, comparator, logic);
}n/a
default = function (database, username, password, options) {
var config;
if (arguments.length === 1 && typeof database === 'object') {
// new Sequelize({ ... options })
options = database;
config = _.pick(options, 'host', 'port', 'database', 'username', 'password');
} else if ((arguments.length === 1 && typeof database === 'string') || (arguments.length === 2 && typeof username === 'object')) {
// new Sequelize(URI, { ... options })
config = {};
options = username || {};
var urlParts = url.parse(arguments[0]);
// SQLite don't have DB in connection url
if (urlParts.pathname) {
config.database = urlParts.pathname.replace(/^\//, '');
}
options.dialect = urlParts.protocol.replace(/:$/, '');
options.host = urlParts.hostname;
if (urlParts.port) {
options.port = urlParts.port;
}
if (urlParts.auth) {
config.username = urlParts.auth.split(':')[0];
config.password = urlParts.auth.split(':')[1];
}
} else {
// new Sequelize(database, username, password, { ... options })
options = options || {};
config = {database: database, username: username, password: password};
}
Sequelize.runHooks('beforeInit', config, options);
this.options = Utils._.extend({
dialect: 'mysql',
dialectModulePath: null,
host: 'localhost',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone:'+00:00',
logging: console.log,
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: {max: 5, match: ['SQLITE_BUSY: database is locked']},
transactionType: Transaction.TYPES.DEFERRED,
isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
databaseVersion: 0,
typeValidation: false,
benchmark: false
}, options || {});
if (this.options.dialect === 'postgresql') {
this.options.dialect = 'postgres';
}
if (this.options.dialect === 'sqlite' && this.options.timezone !== '+00:00') {
throw new Error('Setting a custom timezone is not supported by SQLite, dates are always returned as UTC. Please remove the custom
timezone parameter.');
}
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
this.options.hooks = this.replaceHookAliases(this.options.hooks);
if ((['', null, false].indexOf(config.password) > -1) || (typeof config.password === 'undefined')) {
config.password = null;
}
this.config = {
database: config.database,
username: config.username,
password: config.password,
host: config.host || this.options.host,
port: config.port || this.options.port,
pool: this.options.pool,
protocol: this.options.protocol,
native: this.options.native,
ssl: this.options.ssl,
replication: this.options.replication,
dialectModulePath: this.options.dialectModulePath,
keepDefaultTimezone: this.options.keepDefaultTimezone,
dialectOptions: this.options.dialectOptions
};
var Dialect;
// Requiring the dialect in a switch-case to keep the
// require calls static. (Browserify fix)
switch (this.getDialect()){
case 'mariadb':
Dialect = require('./dialects/mariadb');
break;
case 'mssql':
Dialect = require('./dialects/mssql');
break;
case 'mysql':
Dialect = require('./dialects/mysql');
break;
case 'postgres':
Dialect = require('./dialects/postgres');
break;
case 'sqlite':
Dialect = require('./dialects/sqlite');
break;
default:
throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mariadb, mssql, mysql, postgres
, and sqlite.');
}
this.dialect = new Dialect(this);
this.dialect.QueryGenerator.typeValidation = options.typeValidation;
/**
* Models are stored here under the name given to `sequelize.define`
* @property models
*/
this.models = {};
this.mod ...n/a
fn = function (fn) {
return new Utils.fn(fn, Utils.sliceArgs(arguments, 1));
}n/a
hasHook = function (hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
}...
*
* @param {String} hookType
* @param {String} name
*/
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
...hasHooks = function (hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
}n/a
hook = function () {
return Hooks.addHook.apply(this, arguments);
}...
* function () {},
* function() {} // Or an array of several
* ]
* }
* })
*
* // Method 2
* Model.hook('afterDestroy', function () {})
*
* // Method 3
* Model.afterBulkUpdate(function () {})
* ```
*
* @see {Sequelize#define}
* @mixin Hooks
...json = function (conditionsOrPath, value) {
return new Utils.json(conditionsOrPath, value);
}n/a
literal = function (val) {
return new Utils.literal(val);
}...
return sequelize.sync({
force: true,
logging: console.log
})
.then(() => {
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount'
;]]
}
});
})
.then(console.log)
.finally(() => {
sequelize.close();
});
...or = function () {
return { $or: Utils.sliceArgs(arguments) };
}n/a
removeHook = function (hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
return this;
}n/a
replaceHookAliases = function (hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
}
});
return hooks;
}n/a
runHooks = function (hooks) {
var self = this
, fn
, fnArgs = Utils.sliceArgs(arguments, 1)
, hookType;
if (typeof fnArgs[fnArgs.length - 1] === 'function') {
fn = fnArgs.pop();
}
if (typeof hooks === 'string') {
hookType = hooks;
hooks = this.options.hooks[hookType] || [];
if (!Array.isArray(hooks)) hooks = hooks === undefined ? [] : [hooks];
if (this.sequelize) hooks = hooks.concat(this.sequelize.options.hooks[hookType] || []);
}
if (!Array.isArray(hooks)) {
hooks = hooks === undefined ? [] : [hooks];
}
// run hooks as sync functions if flagged as sync
if (hookTypes[hookType] && hookTypes[hookType].sync) {
hooks.forEach(function(hook) {
if (typeof hook === 'object') hook = hook.fn;
return hook.apply(self, fnArgs);
});
return;
}
// run hooks async
var promise = Promise.each(hooks, function (hook) {
if (typeof hook === 'object') {
hook = hook.fn;
}
if (hookType && hook.length > hookTypes[hookType].params) {
hook = Promise.promisify(hook, self);
}
return hook.apply(self, fnArgs);
}).return();
if (fn) {
return promise.nodeify(fn);
}
return promise;
}...
* - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance
, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
...where = function (attr, comparator, logic) {
return new Utils.where(attr, comparator, logic);
}n/a
AccessDeniedError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeAccessDeniedError';
}n/a
Association = function () {}n/a
ConnectionError = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
ConnectionRefusedError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeConnectionRefusedError';
}n/a
ConnectionTimedOutError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeConnectionTimedOutError';
}n/a
DatabaseError = function (parent) {
error.BaseError.apply(this, [parent.message]);
this.name = 'SequelizeDatabaseError';
/**
* The database specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
/**
* The SQL that triggered the error
* @member sql
*/
this.sql = parent.sql;
/**
* The message from the DB.
* @member message
* @name message
*/
/**
* The fields of the unique constraint
* @member fields
* @name fields
*/
/**
* The value(s) which triggered the error
* @member value
* @name value
*/
/**
* The name of the index that triggered the error
* @member index
* @name index
*/
}n/a
EmptyResultError = function (message) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeEmptyResultError';
this.message = message;
}n/a
Error = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
ExclusionConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
error.DatabaseError.call(this, options.parent);
this.name = 'SequelizeExclusionConstraintError';
this.message = options.message || options.parent.message;
this.constraint = options.constraint;
this.fields = options.fields;
this.table = options.table;
}n/a
ForeignKeyConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
error.DatabaseError.call(this, options.parent);
this.name = 'SequelizeForeignKeyConstraintError';
this.message = options.message || options.parent.message || 'Database Error';
this.fields = options.fields;
this.table = options.table;
this.value = options.value;
this.index = options.index;
}n/a
HostNotFoundError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeHostNotFoundError';
}n/a
HostNotReachableError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeHostNotReachableError';
}n/a
Instance = function (values, options) {
this.dataValues = {};
this._previousDataValues = {};
this._changed = {};
this.$modelOptions = this.Model.options;
this.$options = options || {};
this.hasPrimaryKeys = this.Model.options.hasPrimaryKeys;
this.__eagerlyLoadedAssociations = [];
/**
* Returns true if this instance has not yet been persisted to the database
* @property isNewRecord
* @return {Boolean}
*/
this.isNewRecord = options.isNewRecord;
/**
* Returns the Model the instance was created from.
* @see {Model}
* @property Model
* @return {Model}
*/
initValues.call(this, values, options);
}n/a
InstanceError = function (message) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeInstanceError';
this.message = message;
}n/a
InvalidConnectionError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeInvalidConnectionError';
}n/a
Model = function (name, attributes, options) {
this.options = Utils._.extend({
timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: []
}, options || {});
this.associations = {};
this.modelManager = null;
this.name = name;
this.options.hooks = _.mapValues(this.replaceHookAliases(this.options.hooks), function (hooks) {
if (!Array.isArray(hooks)) hooks = [hooks];
return hooks;
});
this.sequelize = options.sequelize;
this.underscored = this.underscored || this.underscoredAll;
if (!this.options.tableName) {
this.tableName = this.options.freezeTableName ? name : Utils.underscoredIf(Utils.pluralize(name), this.options.underscoredAll
);
} else {
this.tableName = this.options.tableName;
}
this.$schema = this.options.schema;
this.$schemaDelimiter = this.options.schemaDelimiter;
// error check options
_.each(options.validate, function(validator, validatorType) {
if (_.includes(Utils._.keys(attributes), validatorType)) {
throw new Error('A model validator function must not have the same name as a field. Model: ' + name + ', field/validation
name: ' + validatorType);
}
if (!_.isFunction(validator)) {
throw new Error('Members of the validate option must be functions. Model: ' + name + ', error with validate member ' + validatorType
);
}
});
this.attributes = this.rawAttributes = _.mapValues(attributes, function(attribute, name) {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute };
}
attribute = this.sequelize.normalizeAttribute(attribute);
if (attribute.references) {
attribute = Utils.formatReferences(attribute);
if (attribute.references.model instanceof Model) {
attribute.references.model = attribute.references.model.tableName;
}
}
if (attribute.type === undefined) {
throw new Error('Unrecognized data type for field ' + name);
}
return attribute;
}.bind(this));
}n/a
function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}n/a
Sequelize = function (database, username, password, options) {
var config;
if (arguments.length === 1 && typeof database === 'object') {
// new Sequelize({ ... options })
options = database;
config = _.pick(options, 'host', 'port', 'database', 'username', 'password');
} else if ((arguments.length === 1 && typeof database === 'string') || (arguments.length === 2 && typeof username === 'object')) {
// new Sequelize(URI, { ... options })
config = {};
options = username || {};
var urlParts = url.parse(arguments[0]);
// SQLite don't have DB in connection url
if (urlParts.pathname) {
config.database = urlParts.pathname.replace(/^\//, '');
}
options.dialect = urlParts.protocol.replace(/:$/, '');
options.host = urlParts.hostname;
if (urlParts.port) {
options.port = urlParts.port;
}
if (urlParts.auth) {
config.username = urlParts.auth.split(':')[0];
config.password = urlParts.auth.split(':')[1];
}
} else {
// new Sequelize(database, username, password, { ... options })
options = options || {};
config = {database: database, username: username, password: password};
}
Sequelize.runHooks('beforeInit', config, options);
this.options = Utils._.extend({
dialect: 'mysql',
dialectModulePath: null,
host: 'localhost',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone:'+00:00',
logging: console.log,
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: {max: 5, match: ['SQLITE_BUSY: database is locked']},
transactionType: Transaction.TYPES.DEFERRED,
isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
databaseVersion: 0,
typeValidation: false,
benchmark: false
}, options || {});
if (this.options.dialect === 'postgresql') {
this.options.dialect = 'postgres';
}
if (this.options.dialect === 'sqlite' && this.options.timezone !== '+00:00') {
throw new Error('Setting a custom timezone is not supported by SQLite, dates are always returned as UTC. Please remove the custom
timezone parameter.');
}
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
this.options.hooks = this.replaceHookAliases(this.options.hooks);
if ((['', null, false].indexOf(config.password) > -1) || (typeof config.password === 'undefined')) {
config.password = null;
}
this.config = {
database: config.database,
username: config.username,
password: config.password,
host: config.host || this.options.host,
port: config.port || this.options.port,
pool: this.options.pool,
protocol: this.options.protocol,
native: this.options.native,
ssl: this.options.ssl,
replication: this.options.replication,
dialectModulePath: this.options.dialectModulePath,
keepDefaultTimezone: this.options.keepDefaultTimezone,
dialectOptions: this.options.dialectOptions
};
var Dialect;
// Requiring the dialect in a switch-case to keep the
// require calls static. (Browserify fix)
switch (this.getDialect()){
case 'mariadb':
Dialect = require('./dialects/mariadb');
break;
case 'mssql':
Dialect = require('./dialects/mssql');
break;
case 'mysql':
Dialect = require('./dialects/mysql');
break;
case 'postgres':
Dialect = require('./dialects/postgres');
break;
case 'sqlite':
Dialect = require('./dialects/sqlite');
break;
default:
throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mariadb, mssql, mysql, postgres
, and sqlite.');
}
this.dialect = new Dialect(this);
this.dialect.QueryGenerator.typeValidation = options.typeValidation;
/**
* Models are stored here under the name given to `sequelize.define`
* @property models
*/
this.models = {};
this.mod ...n/a
TimeoutError = function (parent) {
error.DatabaseError.call(this, parent);
this.name = 'SequelizeTimeoutError';
}n/a
function Transaction(sequelize, options) {
this.sequelize = sequelize;
this.savepoints = [];
var generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;
this.options = Utils._.extend({
autocommit: true,
type: sequelize.options.transactionType,
isolationLevel: sequelize.options.isolationLevel,
readOnly: false
}, options || {});
this.parent = this.options.transaction;
this.id = this.parent ? this.parent.id : generateTransactionId();
if (this.parent) {
this.id = this.parent.id;
this.parent.savepoints.push(this);
this.name = this.id + '-savepoint-' + this.parent.savepoints.length;
} else {
this.id = this.name = generateTransactionId();
}
delete this.options.transaction;
}n/a
UniqueConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
options.message = options.message || options.parent.message || 'Validation Error';
options.errors = options.errors || {};
error.ValidationError.call(this, options.message, options.errors);
this.name = 'SequelizeUniqueConstraintError';
this.message = options.message;
this.errors = options.errors;
this.fields = options.fields;
this.parent = options.parent;
this.original = options.parent;
this.sql = options.parent.sql;
}n/a
ValidationError = function (message, errors) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeValidationError';
this.message = 'Validation Error';
/**
* An array of ValidationErrorItems
* @member errors
*/
this.errors = errors || [];
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
}...
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
} else {
return null;
}
});
};
/**
...ValidationErrorItem = function (message, type, path, value) {
this.message = message || '';
this.type = type || null;
this.path = path || null;
this.value = value || null;
}...
* @param {*} value anything.
* @private
*/
InstanceValidator.prototype._validateSchema = function(rawAttribute, field, value) {
var error;
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be null',
x27;notNull Violation', field, value);
this.errors.push(error);
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes.TEXT
|| rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || (_.isObject(value) && !value._isSequelizeMethod) && !Buffer.isBuffer(value)) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be an array or an object', 'string violation
x27;, field, value);
this.errors.push(error);
...addHook = function (hookType, name, fn) {
if (typeof name === 'function') {
fn = name;
name = null;
}
hookType = hookAliases[hookType] || hookType;
this.options.hooks[hookType] = this.options.hooks[hookType] || [];
this.options.hooks[hookType].push(!!name ? {name: name, fn: fn} : fn);
return this;
}...
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
});
}
};
...afterBulkCreate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterBulkDelete = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterBulkDestroy = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterBulkRestore = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterBulkSync = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterBulkUpdate = function (name, callback) {
return this.addHook(hook, name, callback);
}...
* }
* })
*
* // Method 2
* Model.hook('afterDestroy', function () {})
*
* // Method 3
* Model.afterBulkUpdate(function () {})
* ```
*
* @see {Sequelize#define}
* @mixin Hooks
* @name Hooks
*/
...afterConnect = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterCreate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterDefine = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterDelete = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterDestroy = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterFind = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterInit = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterRestore = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterSync = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterUpdate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
afterValidate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
and = function () {
return { $and: Utils.sliceArgs(arguments) };
}n/a
asIs = function (val) {
return new Utils.literal(val);
}n/a
authenticate = function (options) {
return this.query('SELECT 1+1 AS result', Utils._.assign({ raw: true, plain: true }, options)).return();
}n/a
beforeBulkCreate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeBulkDelete = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeBulkDestroy = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeBulkRestore = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeBulkSync = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeBulkUpdate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeConnect = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeConnection = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeCount = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeCreate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeDefine = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeDelete = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeDestroy = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeFind = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeFindAfterExpandIncludeAll = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeFindAfterOptions = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeInit = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeRestore = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeSync = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeUpdate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
beforeValidate = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
cast = function (val, type) {
return new Utils.cast(val, type);
}n/a
close = function () {
this.connectionManager.close();
}...
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount']]
}
});
})
.then(console.log)
.finally(() => {
sequelize.close();
});
...col = function (col) {
return new Utils.col(col);
}n/a
condition = function (attr, comparator, logic) {
return new Utils.where(attr, comparator, logic);
}n/a
createSchema = function (schema, options) {
return this.getQueryInterface().createSchema(schema, options);
}...
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);
...databaseVersion = function (options) {
return this.getQueryInterface().databaseVersion(options);
}n/a
define = function (modelName, attributes, options) { // testhint options:none
options = options || {};
var globalOptions = this.options;
if (globalOptions.define) {
options = Utils.merge(_.cloneDeep(globalOptions.define), options);
}
options = Utils.merge({
name: {
plural: Utils.inflection.pluralize(modelName),
singular: Utils.inflection.singularize(modelName)
},
indexes: [],
omitNul: globalOptions.omitNull
}, options);
// if you call "define" multiple times for the same modelName, do not clutter the factory
if (this.isDefined(modelName)) {
this.modelManager.removeModel(this.modelManager.getModel(modelName));
}
options.sequelize = this;
options.modelName = modelName;
this.runHooks('beforeDefine', attributes, options);
modelName = options.modelName;
delete options.modelName;
var model = new Model(modelName, attributes, options);
model = model.init(this.modelManager);
this.modelManager.addModel(model);
this.runHooks('afterDefine', model);
return model;
}...
define: {
timestamps: false,
},
logging: console.log
});
const User = sequelize.define('user', {
name: Sequelize.STRING
});
return sequelize.sync({
force: true,
...drop = function (options) {
var models = [];
this.modelManager.forEachModel(function(model) {
if (model) {
models.push(model);
}
}, { reverse: false });
return Promise.each(models, function(model) {
return model.drop(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);
});
}
};
...dropAllSchemas = function (options) {
return this.getQueryInterface().dropAllSchemas(options);
}n/a
dropSchema = function (schema, options) {
return this.getQueryInterface().dropSchema(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;
...escape = function (value) {
return this.getQueryInterface().escape(value);
}...
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
};
/**
* Escape a value (e.g. a string, number or date)
*/
QueryInterface.prototype.escape = function(value) {
return this.QueryGenerator.escape(value);
};
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 (transaction.parent) {
...fn = function (fn) {
return new Utils.fn(fn, Utils.sliceArgs(arguments, 1));
}n/a
getDialect = function () {
return this.options.dialect;
}...
});
});
}
});
};
QueryInterface.prototype.dropAllEnums = function(options) {
if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve();
}
options = options || {};
var self = this;
...getQueryInterface = function () {
this.queryInterface = this.queryInterface || new QueryInterface(this);
return this.queryInterface;
}n/a
hasHook = function (hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
}...
*
* @param {String} hookType
* @param {String} name
*/
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
...hasHooks = function (hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
}n/a
hook = function () {
return Hooks.addHook.apply(this, arguments);
}...
* function () {},
* function() {} // Or an array of several
* ]
* }
* })
*
* // Method 2
* Model.hook('afterDestroy', function () {})
*
* // Method 3
* Model.afterBulkUpdate(function () {})
* ```
*
* @see {Sequelize#define}
* @mixin Hooks
...import = function (path) {
// is it a relative path?
if(Path.normalize(path) !== Path.resolve(path)){
// make path relative to the caller
var callerFilename = Utils.stack()[1].getFileName()
, callerPath = Path.dirname(callerFilename);
path = Path.resolve(callerPath, path);
}
if (!this.importCache[path]) {
var defineCall = (arguments.length > 1 ? arguments[1] : require(path));
if (typeof defineCall === 'object') {
// Babel/ES6 module compatability
defineCall = defineCall.default;
}
this.importCache[path] = defineCall(this, DataTypes);
}
return this.importCache[path];
}n/a
isDefined = function (modelName) {
var models = this.modelManager.models;
return (models.filter(function(model) { return model.name === modelName; }).length !== 0);
}n/a
json = function (conditionsOrPath, value) {
return new Utils.json(conditionsOrPath, value);
}n/a
literal = function (val) {
return new Utils.literal(val);
}...
return sequelize.sync({
force: true,
logging: console.log
})
.then(() => {
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount'
;]]
}
});
})
.then(console.log)
.finally(() => {
sequelize.close();
});
...log = function () {
var args = Utils.sliceArgs(arguments)
, last = Utils._.last(args)
, options;
if (last && Utils._.isPlainObject(last) && last.hasOwnProperty('logging')) {
options = last;
// remove options from set of logged arguments
args.splice(args.length-1, 1);
} else {
options = this.options;
}
if (options.logging) {
if (options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
options.logging = console.log;
}
// second argument is sql-timings, when benchmarking option enabled
if ((this.options.benchmark || options.benchmark) && options.logging === console.log) {
args = [args[0] + ' Elapsed time: ' + args[1] + 'ms'];
}
options.logging.apply(null, args);
}
}n/a
model = function (modelName) {
if (!this.isDefined(modelName)) {
throw new Error(modelName + ' has not been defined');
}
return this.modelManager.getModel(modelName);
}n/a
normalizeAttribute = function (attribute) {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute };
}
if (!attribute.type) return attribute;
attribute.type = this.normalizeDataType(attribute.type);
if (attribute.hasOwnProperty('defaultValue')) {
if (typeof attribute.defaultValue === 'function' && (
attribute.defaultValue === DataTypes.NOW ||
attribute.defaultValue === DataTypes.UUIDV1 ||
attribute.defaultValue === DataTypes.UUIDV4
)) {
attribute.defaultValue = new attribute.defaultValue();
}
}
if (attribute.type instanceof DataTypes.ENUM) {
// The ENUM is a special case where the type is an object containing the values
if (attribute.values) {
attribute.type.values = attribute.type.options.values = attribute.values;
} else {
attribute.values = attribute.type.values;
}
if (!attribute.values.length) {
throw new Error('Values for ENUM have not been defined.');
}
}
return attribute;
}...
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 = [];
...normalizeDataType = function (Type) {
var type = typeof Type === 'function' ? new Type() : Type
, dialectTypes = this.dialect.DataTypes || {};
if (dialectTypes[type.key]) {
type = dialectTypes[type.key].extend(type);
}
if (type instanceof DataTypes.ARRAY && dialectTypes[type.type.key]) {
type.type = dialectTypes[type.type.key].extend(type.type);
}
return type;
}...
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 change a column
return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options);
} else {
var query = this.QueryGenerator.attributesToSQL(attributes)
, sql = this.QueryGenerator.changeColumnQuery(tableName, query);
...or = function () {
return { $or: Utils.sliceArgs(arguments) };
}n/a
query = function (sql, options) {
if (arguments.length > 2) {
// TODO: Remove this note in the next major version (4.0)
throw new Error('Sequelize.query was refactored to only use the parameters `sql` and `options`. Please read the changelog about
BC.');
}
var self = this;
options = _.assign({}, this.options.query, options);
if (options.instance && !options.model) {
options.model = options.instance.Model;
}
// Map raw fields to model field names using the `fieldAttributeMap`
if (options.model && options.mapToModel && !Utils._.isEmpty(options.model.fieldAttributeMap)) {
options.fieldMap = options.model.fieldAttributeMap;
}
if (typeof sql === 'object') {
if (sql.values !== undefined) {
if (options.replacements !== undefined) {
throw new Error('Both `sql.values` and `options.replacements` cannot be set at the same time');
}
options.replacements = sql.values;
}
if (sql.bind !== undefined) {
if (options.bind !== undefined) {
throw new Error('Both `sql.bind` and `options.bind` cannot be set at the same time');
}
options.bind = sql.bind;
}
if (sql.query !== undefined) {
sql = sql.query;
}
}
sql = sql.trim();
if (!options.instance && !options.model) {
options.raw = true;
}
if (options.replacements && options.bind) {
throw new Error('Both `replacements` and `bind` cannot be set at the same time');
}
if (options.replacements) {
if (Array.isArray(options.replacements)) {
sql = Utils.format([sql].concat(options.replacements), this.options.dialect);
}
else {
sql = Utils.formatNamedParameters(sql, options.replacements, this.options.dialect);
}
}
var bindParameters;
if (options.bind) {
var bindSql = self.dialect.Query.formatBindParameters(sql, options.bind, this.options.dialect);
sql = bindSql[0];
bindParameters = bindSql[1];
}
options = _.defaults(options, {
logging: this.options.hasOwnProperty('logging') ? this.options.logging : console.log,
searchPath: this.options.hasOwnProperty('searchPath') ? this.options.searchPath : 'DEFAULT',
});
if (options.transaction === undefined && Sequelize.cls) {
options.transaction = Sequelize.cls.get('transaction');
}
if (!options.type) {
if (options.model || options.nest || options.plain) {
options.type = QueryTypes.SELECT;
} else {
options.type = QueryTypes.RAW;
}
}
if (options.transaction && options.transaction.finished) {
var error = new Error(options.transaction.finished+' has been called on this transaction('+options.transaction.id+'), you can
no longer use it. (The rejected query is attached as the\'sql\' property of this error)');
error.sql = sql;
return Promise.reject(error);
}
if (this.test.$trackRunningQueries) {
this.test.$runningQueries++;
}
//if dialect doesn't support search_path or dialect option
//to prepend searchPath is not true delete the searchPath option
if (!self.dialect.supports.searchPath || !this.options.dialectOptions || !this.options.dialectOptions.prependSearchPath ||
options.supportsSearchPath === false) {
delete options.searchPath;
} else if (!options.searchPath) {
//if user wants to always prepend searchPath (dialectOptions.preprendSearchPath = true)
//then set to DEFAULT if none is provided
options.searchPath = 'DEFAULT';
}
return Promise.resolve(
options.transaction ? options.transaction.connection : self.connectionManager.getConnection(options)
).then(function (connection) {
var query = new self.dialect.Query(connection, self, options);
return retry(function() {
return query.run(sql, bindParameters).finally(function() {
if (options.transaction) return;
return self.connectionManager.releaseConnection(connection);
});
}, Utils._.extend(self.options.retry, options.retry || {}));
}).finally(function () {
if (self.test.$trackRunningQueries) {
self.test.$runningQueries--;
}
});
}...
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);
};
...refreshTypes = function () {
this.connectionManager.refreshTypeParser(DataTypes);
}n/a
removeHook = function (hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
return this;
}n/a
replaceHookAliases = function (hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
}
});
return hooks;
}n/a
runHooks = function (hooks) {
var self = this
, fn
, fnArgs = Utils.sliceArgs(arguments, 1)
, hookType;
if (typeof fnArgs[fnArgs.length - 1] === 'function') {
fn = fnArgs.pop();
}
if (typeof hooks === 'string') {
hookType = hooks;
hooks = this.options.hooks[hookType] || [];
if (!Array.isArray(hooks)) hooks = hooks === undefined ? [] : [hooks];
if (this.sequelize) hooks = hooks.concat(this.sequelize.options.hooks[hookType] || []);
}
if (!Array.isArray(hooks)) {
hooks = hooks === undefined ? [] : [hooks];
}
// run hooks as sync functions if flagged as sync
if (hookTypes[hookType] && hookTypes[hookType].sync) {
hooks.forEach(function(hook) {
if (typeof hook === 'object') hook = hook.fn;
return hook.apply(self, fnArgs);
});
return;
}
// run hooks async
var promise = Promise.each(hooks, function (hook) {
if (typeof hook === 'object') {
hook = hook.fn;
}
if (hookType && hook.length > hookTypes[hookType].params) {
hook = Promise.promisify(hook, self);
}
return hook.apply(self, fnArgs);
}).return();
if (fn) {
return promise.nodeify(fn);
}
return promise;
}...
* - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance
, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
...set = function ( variables, options ) {
var query;
// Prepare options
options = Utils._.extend({}, this.options.set, typeof options === 'object' && options || {});
if (['mysql', 'mariadb'].indexOf(this.options.dialect) === -1) {
throw new Error('sequelize.set is only supported for mysql');
}
if (!options.transaction || !(options.transaction instanceof Transaction) ) {
throw new TypeError('options.transaction is required');
}
// Override some options, since this isn't a SELECT
options.raw = true;
options.plain = true;
options.type = 'SET';
// Generate SQL Query
query =
'SET '+
Utils._.map( variables, function ( v, k ) {
return '@'+k +' := '+ ( typeof v === 'string' ? '"'+v+'"' : v );
}).join(', ');
return this.query(query, options);
}n/a
showAllSchemas = function (options) {
return this.getQueryInterface().showAllSchemas(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);
});
}
};
QueryInterface.prototype.showAllSchemas = function(options) {
var self = this;
...sync = function (options) {
var self = this;
options = _.clone(options) || {};
options.hooks = options.hooks === undefined ? true : !!options.hooks;
options.logging = options.logging === undefined ? false : options.logging;
options = Utils._.defaults(options, this.options.sync, this.options);
if (options.match) {
if (!options.match.test(this.config.database)) {
return Promise.reject(new Error('Database does not match sync match parameter'));
}
}
return Promise.try(function () {
if (options.hooks) {
return self.runHooks('beforeBulkSync', options);
}
}).then(function () {
if (options.force) {
return self.drop(options);
}
}).then(function() {
var models = [];
// Topologically sort by foreign key constraints to give us an appropriate
// creation order
self.modelManager.forEachModel(function(model) {
if (model) {
models.push(model);
} else {
// DB should throw an SQL error if referencing inexistant table
}
});
return Promise.each(models, function(model) {
return model.sync(options);
});
}).then(function () {
if (options.hooks) {
return self.runHooks('afterBulkSync', options);
}
}).return(self);
}...
const User = sequelize.define('user', {
name: Sequelize.STRING
});
return sequelize.sync({
force: true,
logging: console.log
})
.then(() => {
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount']]
...transaction = function (options, autoCallback) {
if (typeof options === 'function') {
autoCallback = options;
options = undefined;
}
// testhint argsConform.end
var transaction = new Transaction(this, options)
, ns = Sequelize.cls;
if (autoCallback) {
var transactionResolver = function (resolve, reject) {
transaction.prepareEnvironment().then(function () {
if (ns) {
autoCallback = ns.bind(autoCallback);
}
var result = autoCallback(transaction);
if (!result || !result.then) throw new Error('You need to return a promise chain/thenable to the sequelize.transaction()
callback');
return result.then(function (result) {
return transaction.commit().then(function () {
resolve(result);
});
});
}).catch(function(err) {
// If the transaction has already finished (commit, rollback, etc), reject with the original error
if (transaction.finished) {
reject(err);
} else {
return transaction.rollback().finally(function () {
reject(err);
});
}
});
};
if (ns) {
transactionResolver = ns.bind(transactionResolver, ns.createContext());
}
return new Promise(transactionResolver);
} else {
return transaction.prepareEnvironment().return(transaction);
}
}n/a
truncate = function (options) {
var models = [];
this.modelManager.forEachModel(function(model) {
if (model) {
models.push(model);
}
}, { reverse: false });
var truncateModel = function(model) {
return model.truncate(options);
};
if (options && options.cascade) {
return Promise.each(models, truncateModel);
} else {
return Promise.map(models, truncateModel);
}
}n/a
validate = function (options) {
return this.query('SELECT 1+1 AS result', Utils._.assign({ raw: true, plain: true }, options)).return();
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...validationFailed = function (name, callback) {
return this.addHook(hook, name, callback);
}n/a
where = function (attr, comparator, logic) {
return new Utils.where(attr, comparator, logic);
}n/a
TEXT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof TEXT)) return new TEXT(options);
this.options = options;
this._length = options.length || '';
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
switch (this._length.toLowerCase()) {
case 'tiny':
return 'TINYTEXT';
case 'medium':
return 'MEDIUMTEXT';
case 'long':
return 'LONGTEXT';
default:
return this.key;
}
}n/a
validate = function (value) {
if (!_.isString(value)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid string', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...TIME = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'TIME';
}n/a
TimeoutError = function (parent) {
error.DatabaseError.call(this, parent);
this.name = 'SequelizeTimeoutError';
}n/a
super_ = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
function Transaction(sequelize, options) {
this.sequelize = sequelize;
this.savepoints = [];
var generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;
this.options = Utils._.extend({
autocommit: true,
type: sequelize.options.transactionType,
isolationLevel: sequelize.options.isolationLevel,
readOnly: false
}, options || {});
this.parent = this.options.transaction;
this.id = this.parent ? this.parent.id : generateTransactionId();
if (this.parent) {
this.id = this.parent.id;
this.parent.savepoints.push(this);
this.name = this.id + '-savepoint-' + this.parent.savepoints.length;
} else {
this.id = this.name = generateTransactionId();
}
delete this.options.transaction;
}n/a
function Transaction(sequelize, options) {
this.sequelize = sequelize;
this.savepoints = [];
var generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;
this.options = Utils._.extend({
autocommit: true,
type: sequelize.options.transactionType,
isolationLevel: sequelize.options.isolationLevel,
readOnly: false
}, options || {});
this.parent = this.options.transaction;
this.id = this.parent ? this.parent.id : generateTransactionId();
if (this.parent) {
this.id = this.parent.id;
this.parent.savepoints.push(this);
this.name = this.id + '-savepoint-' + this.parent.savepoints.length;
} else {
this.id = this.name = generateTransactionId();
}
delete this.options.transaction;
}n/a
begin = function () {
return this
.sequelize
.getQueryInterface()
.startTransaction(this, this.options);
}n/a
cleanup = function () {
var res = this.sequelize.connectionManager.releaseConnection(this.connection);
this.connection.uuid = undefined;
return res;
}n/a
commit = function () {
var self = this;
if (this.finished) {
throw new Error('Transaction cannot be committed because it has been finished with state: ' + self.finished);
}
this.$clearCls();
return this
.sequelize
.getQueryInterface()
.commitTransaction(this, this.options)
.finally(function() {
self.finished = 'commit';
if (!self.parent) {
return self.cleanup();
}
return null;
});
}n/a
prepareEnvironment = function () {
var self = this;
var connectionPromise;
if (this.parent) {
connectionPromise = Utils.Promise.resolve(this.parent.connection);
} else {
var acquireOptions = {uuid: this.id};
if (this.options.readOnly) {
acquireOptions.type = 'SELECT';
}
connectionPromise = this.sequelize.connectionManager.getConnection(acquireOptions);
}
return connectionPromise
.then(function (connection) {
self.connection = connection;
self.connection.uuid = self.id;
}).then(function () {
return self.begin();
}).then(function () {
return self.setDeferrable();
}).then(function () {
return self.setIsolationLevel();
}).then(function () {
return self.setAutocommit();
}).catch(function (setupErr) {
return self.rollback().finally(function () {
throw setupErr;
});
}).tap(function () {
if (self.sequelize.constructor.cls) {
self.sequelize.constructor.cls.set('transaction', self);
}
return null;
});
}n/a
rollback = function () {
var self = this;
if (this.finished) {
throw new Error('Transaction cannot be rolled back because it has been finished with state: ' + self.finished);
}
this.$clearCls();
return this
.sequelize
.getQueryInterface()
.rollbackTransaction(this, this.options)
.finally(function() {
if (!self.parent) {
return self.cleanup();
}
return self;
});
}n/a
setAutocommit = function () {
return this
.sequelize
.getQueryInterface()
.setAutocommit(this, this.options.autocommit, this.options);
}n/a
setDeferrable = function () {
if (this.options.deferrable) {
return this
.sequelize
.getQueryInterface()
.deferConstraints(this, this.options);
}
}n/a
setIsolationLevel = function () {
return this
.sequelize
.getQueryInterface()
.setIsolationLevel(this, this.options.isolationLevel, this.options);
}n/a
UUID = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
validate = function (value, options) {
if (!_.isString(value) || !Validator.isUUID(value) && (!options || !options.acceptStrings)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid uuid', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...UUIDV1 = function () {
if (!(this instanceof UUIDV1)) return new UUIDV1();
ABSTRACT.apply(this, arguments);
}n/a
super_ = function (options) {
}n/a
validate = function (value, options) {
if (!_.isString(value) || !Validator.isUUID(value) && (!options || !options.acceptStrings)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid uuid', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...UUIDV4 = function () {
if (!(this instanceof UUIDV4)) return new UUIDV4();
ABSTRACT.apply(this, arguments);
}n/a
super_ = function (options) {
}n/a
validate = function (value, options) {
if (!_.isString(value) || !Validator.isUUID(value, 4) && (!options || !options.acceptStrings)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid uuidv4', value));
}
return true;
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...UniqueConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
options.message = options.message || options.parent.message || 'Validation Error';
options.errors = options.errors || {};
error.ValidationError.call(this, options.message, options.errors);
this.name = 'SequelizeUniqueConstraintError';
this.message = options.message;
this.errors = options.errors;
this.fields = options.fields;
this.parent = options.parent;
this.original = options.parent;
this.sql = options.parent.sql;
}n/a
super_ = function (message, errors) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeValidationError';
this.message = 'Validation Error';
/**
* An array of ValidationErrorItems
* @member errors
*/
this.errors = errors || [];
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
}n/a
function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}n/a
n/a
n/a
addTicks = function (s, tickChar) {
tickChar = tickChar || Utils.TICK_CHAR;
return tickChar + Utils.removeTicks(s, tickChar) + tickChar;
}n/a
argsArePrimaryKeys = function (args, primaryKeys) {
var result = (args.length === Object.keys(primaryKeys).length);
if (result) {
Utils._.each(args, function(arg) {
if (result) {
if (['number', 'string'].indexOf(typeof arg) !== -1) {
result = true;
} else {
result = (arg instanceof Date) || Buffer.isBuffer(arg);
}
}
});
}
return result;
}n/a
camelize = function (str){
return str.trim().replace(/[-_\s]+(.)?/g, function(match, c){ return c.toUpperCase(); });
}n/a
camelizeIf = function (string, condition) {
var result = string;
if (condition) {
result = Utils.camelize(string);
}
return result;
}n/a
canTreatArrayAsAnd = function (arr) {
return arr.reduce(function(treatAsAnd, arg) {
if (treatAsAnd) {
return treatAsAnd;
} else {
return Utils._.isPlainObject(arg);
}
}, false);
}n/a
cast = function (val, type) {
this.val = val;
this.type = (type || '').trim();
}n/a
cloneDeep = function (obj) {
obj = obj || {};
return _.cloneDeepWith(obj, function (elem) {
// Do not try to customize cloning of arrays or POJOs
if (Array.isArray(elem) || _.isPlainObject(elem)) {
return undefined;
}
// Don't clone stuff that's an object, but not a plain one - fx example sequelize models and instances
if (typeof elem === 'object') {
return elem;
}
// Preserve special data-types like `fn` across clones. _.get() is used for checking up the prototype chain
if (elem && typeof elem.clone === 'function') {
return elem.clone();
}
});
}...
// testhint argsConform.end
if (!rawTablename) {
// Map for backwards compat
rawTablename = tableName;
}
options = Utils.cloneDeep(options);
options.fields = attributes;
var sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false }));
};
QueryInterface.prototype.showIndex = function(tableName, options) {
var sql = this.QueryGenerator.showIndexesQuery(tableName, options);
...col = function (col) {
if (arguments.length > 1) {
col = this.sliceArgs(arguments);
}
this.col = col;
}n/a
combineTableNames = function (tableName1, tableName2) {
return (tableName1.toLowerCase() < tableName2.toLowerCase()) ? (tableName1 + tableName2) : (tableName2 + tableName1);
}n/a
defaultValueSchemable = function (value) {
if (typeof value === 'undefined') { return false; }
// TODO this will be schemable when all supported db
// have been normalized for this case
if (value instanceof DataTypes.NOW) { return false; }
if (value instanceof DataTypes.UUIDV1 || value instanceof DataTypes.UUIDV4) { return false; }
if (_.isFunction(value)) {
return false;
}
return true;
}n/a
fn = function (fn, args) {
this.fn = fn;
this.args = args;
}n/a
format = function (arr, dialect) {
var timeZone = null;
// Make a clone of the array beacuse format modifies the passed args
return SqlString.format(arr[0], arr.slice(1), timeZone, dialect);
}n/a
formatNamedParameters = function (sql, parameters, dialect) {
var timeZone = null;
return SqlString.formatNamedParameters(sql, parameters, timeZone, dialect);
}n/a
formatReferences = function (obj) {
if (!_.isPlainObject(obj.references)) {
deprecate('Non-object references property found. Support for that will be removed in version 4. Expected { references: { model
: "value", key: "key" } } instead of { references: "value", referencesKey: "key" }.');
obj.references = { model: obj.references, key: obj.referencesKey, deferrable: obj.referencesDeferrable };
obj.referencesKey = undefined;
obj.referencesDeferrable = undefined;
}
return obj;
}...
models[tableName] = model;
for (var attrName in model.rawAttributes) {
if (model.rawAttributes.hasOwnProperty(attrName)) {
var attribute = model.rawAttributes[attrName];
if (attribute.references) {
attribute = Utils.formatReferences(attribute);
dep = attribute.references.model;
if (_.isObject(dep)) {
dep = dep.schema + '.' + dep.tableName;
}
deps.push(dep);
...inherit = function (SubClass, SuperClass) {
if (SuperClass.constructor === Function) {
// Normal Inheritance
SubClass.prototype = new SuperClass();
SubClass.prototype.constructor = SubClass;
SubClass.prototype.parent = SuperClass.prototype;
} else {
// Pure Virtual Inheritance
SubClass.prototype = SuperClass;
SubClass.prototype.constructor = SubClass;
SubClass.prototype.parent = SuperClass;
}
return SubClass;
}n/a
isColString = function (value) {
return typeof value === 'string' && value.substr(0, 1) === '$' && value.substr(value.length - 1, 1) === '$';
}n/a
isPrimitive = function (val) {
return primitives.indexOf(typeof val) !== -1;
}n/a
json = function (conditionsOrPath, value) {
if (Utils._.isObject(conditionsOrPath)) {
this.conditions = conditionsOrPath;
} else {
this.path = conditionsOrPath;
if (value) {
this.value = value;
}
}
}n/a
literal = function (val) {
this.val = val;
}...
return sequelize.sync({
force: true,
logging: console.log
})
.then(() => {
return User.findAll({
attributes: {
include: [[sequelize.literal('COUNT(*) OVER()'), 'totalCount'
;]]
}
});
})
.then(console.log)
.finally(() => {
sequelize.close();
});
...lowercaseFirst = function (s) {
return s[0].toLowerCase() + s.slice(1);
}n/a
mapFinderOptions = function (options, Model) {
if (Model._hasVirtualAttributes && Array.isArray(options.attributes)) {
options.attributes.forEach(function (attribute) {
if (Model._isVirtualAttribute(attribute) && Model.rawAttributes[attribute].type.fields) {
options.attributes = options.attributes.concat(Model.rawAttributes[attribute].type.fields);
}
}.bind(Model));
options.attributes = _.without.apply(_, [options.attributes].concat(Model._virtualAttributes));
options.attributes = _.uniq(options.attributes);
}
Utils.mapOptionFieldNames(options, Model);
return options;
}n/a
mapOptionFieldNames = function (options, Model) {
if (Array.isArray(options.attributes)) {
options.attributes = options.attributes.map(function(attr) {
// Object lookups will force any variable to strings, we don't want that for special objects etc
if (typeof attr !== 'string') return attr;
// Map attributes to aliased syntax attributes
if (Model.rawAttributes[attr] && attr !== Model.rawAttributes[attr].field) {
return [Model.rawAttributes[attr].field, attr];
}
return attr;
});
}
if (options.where && _.isPlainObject(options.where)) {
options.where = Utils.mapWhereFieldNames(options.where, Model);
}
if (Array.isArray(options.order)) {
options.order.forEach(function(oGroup) {
var OrderModel, attr, attrOffset;
if (Array.isArray(oGroup)) {
OrderModel = Model;
// Check if we have ['attr', 'DESC'] or [Model, 'attr', 'DESC']
if (typeof oGroup[oGroup.length - 2] === 'string') {
attrOffset = 2;
// Assume ['attr'], [Model, 'attr'] or [seq.fn('somefn', 1), 'DESC']
} else {
attrOffset = 1;
}
attr = oGroup[oGroup.length - attrOffset];
if (oGroup.length > attrOffset) {
OrderModel = oGroup[oGroup.length - (attrOffset + 1)];
if (OrderModel.model) {
OrderModel = OrderModel.model;
}
}
if (OrderModel.rawAttributes && OrderModel.rawAttributes[attr] && attr !== OrderModel.rawAttributes[attr].field) {
oGroup[oGroup.length - attrOffset] = OrderModel.rawAttributes[attr].field;
}
}
});
}
return options;
}n/a
mapValueFieldNames = function (dataValues, fields, Model) {
var values = {};
fields.forEach(function(attr) {
if (dataValues[attr] !== undefined && !Model._isVirtualAttribute(attr)) {
// Field name mapping
if (Model.rawAttributes[attr] && Model.rawAttributes[attr].field && Model.rawAttributes[attr].field !== attr) {
values[Model.rawAttributes[attr].field] = dataValues[attr];
} else {
values[attr] = dataValues[attr];
}
}
});
return values;
}n/a
mapWhereFieldNames = function (attributes, Model) {
var attribute
, rawAttribute;
if (attributes) {
for (attribute in attributes) {
rawAttribute = Model.rawAttributes[attribute];
if (rawAttribute && rawAttribute.field !== rawAttribute.fieldName) {
attributes[rawAttribute.field] = attributes[attribute];
delete attributes[attribute];
}
if (_.isPlainObject(attributes[attribute])) {
attributes[attribute] = Utils.mapOptionFieldNames({
where: attributes[attribute]
}, Model).where;
}
if (Array.isArray(attributes[attribute])) {
attributes[attribute] = attributes[attribute].map(function (where) {
if (_.isPlainObject(where)) {
return Utils.mapWhereFieldNames(where, Model);
}
return where;
});
}
}
}
return attributes;
}n/a
merge = function () {
var result = {};
Array.prototype.slice.apply(arguments).forEach(function (obj) {
_.forOwn(obj, function (value, key) {
if (typeof value !== 'undefined') {
if (!result[key]) {
result[key] = value;
} else if (_.isPlainObject(value) && _.isPlainObject(result[key])) {
result[key] = Utils.merge(result[key], value);
} else if (Array.isArray(value) && Array.isArray(result[key])) {
result[key] = value.concat(result[key]);
} else {
result[key] = value;
}
}
});
});
return result;
}n/a
mergeDefaults = function (a, b) {
return _.mergeWith(a, b, function (objectValue, sourceValue) {
// If it's an object, let _ handle it this time, we will be called again for each property
if (!this._.isPlainObject(objectValue) && objectValue !== undefined) {
return objectValue;
}
}.bind(this));
}n/a
now = function (dialect) {
var now = new Date();
if (['postgres', 'sqlite'].indexOf(dialect) === -1) {
now.setMilliseconds(0);
}
return now;
}n/a
pluralize = function (s) {
return inflection.pluralize(s);
}n/a
removeCommentsFromFunctionString = function (s) {
s = s.replace(/\s*(\/\/.*)/g, '');
s = s.replace(/(\/\*[\n\r\s\S]*?\*\/)/mg, '');
return s;
}n/a
removeNullValuesFromHash = function (hash, omitNull, options) {
var result = hash;
options = options || {};
options.allowNull = options.allowNull || [];
if (omitNull) {
var _hash = {};
Utils._.forIn(hash, function(val, key) {
if (options.allowNull.indexOf(key) > -1 || key.match(/Id$/) || ((val !== null) && (val !== undefined))) {
_hash[key] = val;
}
});
result = _hash;
}
return result;
}n/a
removeTicks = function (s, tickChar) {
tickChar = tickChar || Utils.TICK_CHAR;
return s.replace(new RegExp(tickChar, 'g'), '');
}n/a
singularize = function (s) {
return inflection.singularize(s);
}n/a
sliceArgs = function (args, begin) {
begin = begin || 0;
var tmp = new Array(args.length - begin);
for (var i = begin; i < args.length; ++i) {
tmp[i - begin] = args[i];
}
return tmp;
}...
return hooks;
},
runHooks: function(hooks) {
var self = this
, fn
, fnArgs = Utils.sliceArgs(arguments, 1)
, hookType;
if (typeof fnArgs[fnArgs.length - 1] === 'function') {
fn = fnArgs.pop();
}
if (typeof hooks === 'string') {
...spliceStr = function (str, index, count, add) {
return str.slice(0, index) + add + str.slice(index + count);
}n/a
function _stackGrabber() {
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack) { return stack; };
var err = new Error();
Error.captureStackTrace(err, _stackGrabber);
var errStack = err.stack;
Error.prepareStackTrace = orig;
return errStack;
}n/a
tick = function (func) {
var tick = (global.hasOwnProperty('setImmediate') ? global.setImmediate : process.nextTick);
tick(func);
}n/a
toDefaultValue = function (value) {
if (typeof value === 'function') {
var tmp = value();
if (tmp instanceof DataTypes.ABSTRACT) {
return tmp.toSql();
} else {
return tmp;
}
} else if (value instanceof DataTypes.UUIDV1) {
return uuid.v1();
} else if (value instanceof DataTypes.UUIDV4) {
return uuid.v4();
} else if (value instanceof DataTypes.NOW) {
return Utils.now();
} else if(_.isPlainObject(value) || _.isArray(value)) {
return _.clone(value);
} else {
return value;
}
}n/a
underscoredIf = function (string, condition) {
var result = string;
if (condition) {
result = inflection.underscore(string);
}
return result;
}n/a
uppercaseFirst = function (s) {
return s[0].toUpperCase() + s.slice(1);
}n/a
function check(value, expectation, options) {
options = _.extend({
deprecated: false,
index: null,
method: null,
optional: false
}, options || {});
if (!value && options.optional) {
return true;
}
if (value === undefined) {
throw new Error('No value has been passed.');
}
if (expectation === undefined) {
throw new Error('No expectation has been passed.');
}
return false
|| validateDeprecation(value, expectation, options)
|| validate(value, expectation, options);
}n/a
where = function (attribute, comparator, logic) {
if (logic === undefined) {
logic = comparator;
comparator = '=';
}
this.attribute = attribute;
this.comparator = comparator;
this.logic = logic;
}n/a
n/a
n/a
add = function (value, other) {
var result;
if (value === undefined && other === undefined) {
return 0;
}
if (value !== undefined) {
result = value;
}
if (other !== undefined) {
if (result === undefined) {
return other;
}
if (typeof value == 'string' || typeof other == 'string') {
value = baseToString(value);
other = baseToString(other);
} else {
value = baseToNumber(value);
other = baseToNumber(other);
}
result = operator(value, other);
}
return result;
}...
}
}
deps = deps.filter(function(dep) {
return tableName !== dep;
});
sorter.add(tableName, deps);
});
sorted = sorter.sort();
if (options.reverse) {
sorted = sorted.reverse();
}
sorted.forEach(function(name) {
...function after(n, func) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}n/a
function ary(func, n, guard) {
n = guard ? undefined : n;
n = (func && n == null) ? func.length : n;
return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
}n/a
assign = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}...
});
}
};
QueryInterface.prototype.showAllSchemas = function(options) {
var self = this;
options = _.assign({}, options, {
raw: true,
type: this.sequelize.QueryTypes.SELECT
});
var showSchemasSql = self.QueryGenerator.showSchemasQuery();
return this.sequelize.query(showSchemasSql, options).then(function(schemaNames) {
...assignIn = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
assignInWith = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
assignWith = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
at = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
attempt = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function before(n, func) {
var result;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
}
if (n <= 1) {
func = undefined;
}
return result;
};
}n/a
bind = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}...
var validatorPromise = self._invokeBuiltinValidator(value, test, validatorType, field);
// errors are handled in settling, stub this
validatorPromise.catch(function() {});
validators.push(validatorPromise.reflect());
});
return Promise.all(validators).then(this._handleReflectedResult.bind(this, field));
};
/**
* Prepare and invoke a custom validator.
*
* @param {Function} validator The custom validator.
* @param {string} validatorType the custom validator type (name).
...bindAll = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
bindKey = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
camelCase = function (string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
}n/a
function capitalize(string) {
return upperFirst(toString(string).toLowerCase());
}n/a
function castArray() {
if (!arguments.length) {
return [];
}
var value = arguments[0];
return isArray(value) ? value : [value];
}n/a
ceil = function (number, precision) {
number = toNumber(number);
precision = toInteger(precision);
if (precision) {
// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
}
return func(number);
}n/a
function chain(value) {
var result = lodash(value);
result.__chain__ = true;
return result;
}n/a
function chunk(array, size, guard) {
if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
size = 1;
} else {
size = nativeMax(toInteger(size), 0);
}
var length = array ? array.length : 0;
if (!length || size < 1) {
return [];
}
var index = 0,
resIndex = 0,
result = Array(nativeCeil(length / size));
while (index < length) {
result[resIndex++] = baseSlice(array, index, (index += size));
}
return result;
}n/a
function clamp(number, lower, upper) {
if (upper === undefined) {
upper = lower;
lower = undefined;
}
if (upper !== undefined) {
upper = toNumber(upper);
upper = upper === upper ? upper : 0;
}
if (lower !== undefined) {
lower = toNumber(lower);
lower = lower === lower ? lower : 0;
}
return baseClamp(toNumber(number), lower, upper);
}n/a
function clone(value) {
return baseClone(value, false, true);
}...
* The Main Instance Validator.
*
* @param {Instance} modelInstance The model instance.
* @param {Object} options A dict with options.
* @constructor
*/
function InstanceValidator(modelInstance, options) {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
...function cloneDeep(value) {
return baseClone(value, true, true);
}...
// testhint argsConform.end
if (!rawTablename) {
// Map for backwards compat
rawTablename = tableName;
}
options = Utils.cloneDeep(options);
options.fields = attributes;
var sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false }));
};
QueryInterface.prototype.showIndex = function(tableName, options) {
var sql = this.QueryGenerator.showIndexesQuery(tableName, options);
...function cloneDeepWith(value, customizer) {
return baseClone(value, true, true, customizer);
}n/a
function cloneWith(value, customizer) {
return baseClone(value, false, true, customizer);
}n/a
function compact(array) {
var index = -1,
length = array ? array.length : 0,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}...
var result = {};
tableNames.forEach(function(tableName, i) {
if (Utils._.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
result[tableName] = Utils._.compact(results[i]).map(function(r) {
return r.constraint_name;
});
});
return result;
});
};
...function concat() {
var length = arguments.length,
args = Array(length ? length - 1 : 0),
array = arguments[0],
index = length;
while (index--) {
args[index - 1] = arguments[index];
}
return length
? arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1))
: [];
}...
replaceHookAliases: function(hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
}
});
return hooks;
...function cond(pairs) {
var length = pairs ? pairs.length : 0,
toIteratee = getIteratee();
pairs = !length ? [] : arrayMap(pairs, function(pair) {
if (typeof pair[1] != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return [toIteratee(pair[0]), pair[1]];
});
return rest(function(args) {
var index = -1;
while (++index < length) {
var pair = pairs[index];
if (apply(pair[0], this, args)) {
return apply(pair[1], this, args);
}
}
});
}n/a
function conforms(source) {
return baseConforms(baseClone(source, true));
}n/a
function constant(value) {
return function() {
return value;
};
}n/a
countBy = function (collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, getIteratee(iteratee), accumulator);
}n/a
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties ? baseAssign(result, properties) : result;
}n/a
function curry(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrapper(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curry.placeholder;
return result;
}n/a
function curryRight(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrapper(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curryRight.placeholder;
return result;
}n/a
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime = 0,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
result = wait - timeSinceLastCall;
return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (!lastCallTime || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
clearTimeout(timerId);
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastCallTime = lastInvokeTime = 0;
lastArgs = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}n/a
function deburr(string) {
string = toString(string);
return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
}n/a
defaults = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}...
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
skip: []
});
this.modelInstance = modelInstance;
/**
* Exposes a reference to validator.js. This allows you to add custom validations using `validator.extend`
...defaultsDeep = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
defer = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
delay = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
difference = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}...
* @param {Object} options A dict with options.
* @constructor
*/
function InstanceValidator(modelInstance, options) {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options
.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
skip: []
});
...differenceBy = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
differenceWith = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
divide = function (value, other) {
var result;
if (value === undefined && other === undefined) {
return 0;
}
if (value !== undefined) {
result = value;
}
if (other !== undefined) {
if (result === undefined) {
return other;
}
if (typeof value == 'string' || typeof other == 'string') {
value = baseToString(value);
other = baseToString(other);
} else {
value = baseToNumber(value);
other = baseToNumber(other);
}
result = operator(value, other);
}
return result;
}n/a
function drop(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, n < 0 ? 0 : n, length);
}...
};
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);
});
}
};
...function dropRight(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, 0, n < 0 ? 0 : n);
}n/a
function dropRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true, true)
: [];
}n/a
function dropWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true)
: [];
}n/a
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, getIteratee(iteratee, 3));
}...
beforeConnection: 'beforeConnect'
};
var Hooks = {
replaceHookAliases: function(hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
...function forEachRight(collection, iteratee) {
var func = isArray(collection) ? arrayEachRight : baseEachRight;
return func(collection, getIteratee(iteratee, 3));
}n/a
function endsWith(string, target, position) {
string = toString(string);
target = baseToString(target);
var length = string.length;
position = position === undefined
? length
: baseClamp(toInteger(position), 0, length);
position -= target.length;
return position >= 0 && string.indexOf(target, position) == position;
}n/a
entries = function (object) {
var tag = getTag(object);
if (tag == mapTag) {
return mapToArray(object);
}
if (tag == setTag) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
}n/a
entriesIn = function (object) {
var tag = getTag(object);
if (tag == mapTag) {
return mapToArray(object);
}
if (tag == setTag) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
}n/a
function eq(value, other) {
return value === other || (value !== value && other !== other);
}n/a
function escape(string) {
string = toString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
}...
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
};
/**
* Escape a value (e.g. a string, number or date)
*/
QueryInterface.prototype.escape = function(value) {
return this.QueryGenerator.escape(value);
};
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 (transaction.parent) {
...function escapeRegExp(string) {
string = toString(string);
return (string && reHasRegExpChar.test(string))
? string.replace(reRegExpChar, '\\$&')
: string;
}n/a
function every(collection, predicate, guard) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}n/a
extend = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
extendWith = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function fill(array, value, start, end) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
start = 0;
end = length;
}
return baseFill(array, value, start, end);
}n/a
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, getIteratee(predicate, 3));
}...
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
...function find(collection, predicate) {
predicate = getIteratee(predicate, 3);
if (isArray(collection)) {
var index = baseFindIndex(collection, predicate);
return index > -1 ? collection[index] : undefined;
}
return baseFind(collection, predicate, baseEach);
}...
QueryInterface.prototype.bulkUpdate = function(tableName, values, identifier, options, attributes) {
options = Utils.cloneDeep(options);
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
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
});
options.model = model;
return this.sequelize.query(sql, options);
};
QueryInterface.prototype.delete = function(instance, tableName, identifier, options) {
var self = this
...function findIndex(array, predicate) {
return (array && array.length)
? baseFindIndex(array, getIteratee(predicate, 3))
: -1;
}n/a
function findKey(object, predicate) {
return baseFind(object, getIteratee(predicate, 3), baseForOwn, true);
}n/a
function findLast(collection, predicate) {
predicate = getIteratee(predicate, 3);
if (isArray(collection)) {
var index = baseFindIndex(collection, predicate, true);
return index > -1 ? collection[index] : undefined;
}
return baseFind(collection, predicate, baseEachRight);
}n/a
function findLastIndex(array, predicate) {
return (array && array.length)
? baseFindIndex(array, getIteratee(predicate, 3), true)
: -1;
}n/a
function findLastKey(object, predicate) {
return baseFind(object, getIteratee(predicate, 3), baseForOwnRight, true);
}n/a
function head(array) {
return (array && array.length) ? array[0] : undefined;
}n/a
function flatMap(collection, iteratee) {
return baseFlatten(map(collection, iteratee), 1);
}n/a
function flatMapDeep(collection, iteratee) {
return baseFlatten(map(collection, iteratee), INFINITY);
}n/a
function flatMapDepth(collection, iteratee, depth) {
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(map(collection, iteratee), depth);
}n/a
function flatten(array) {
var length = array ? array.length : 0;
return length ? baseFlatten(array, 1) : [];
}...
raw: true,
type: this.sequelize.QueryTypes.SELECT
});
var showSchemasSql = self.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);
})
);
});
};
...function flattenDeep(array) {
var length = array ? array.length : 0;
return length ? baseFlatten(array, INFINITY) : [];
}n/a
function flattenDepth(array, depth) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(array, depth);
}n/a
function flip(func) {
return createWrapper(func, FLIP_FLAG);
}n/a
floor = function (number, precision) {
number = toNumber(number);
precision = toInteger(precision);
if (precision) {
// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
}
return func(number);
}n/a
flow = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
flowRight = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, getIteratee(iteratee, 3));
}...
if (!Array.isArray(hooks)) {
hooks = hooks === undefined ? [] : [hooks];
}
// run hooks as sync functions if flagged as sync
if (hookTypes[hookType] && hookTypes[hookType].sync) {
hooks.forEach(function(hook) {
if (typeof hook === 'object') hook = hook.fn;
return hook.apply(self, fnArgs);
});
return;
}
// run hooks async
...function forEachRight(collection, iteratee) {
var func = isArray(collection) ? arrayEachRight : baseEachRight;
return func(collection, getIteratee(iteratee, 3));
}n/a
function forIn(object, iteratee) {
return object == null
? object
: baseFor(object, getIteratee(iteratee, 3), keysIn);
}...
* @private
*/
InstanceValidator.prototype._builtinValidators = function() {
var self = this;
// promisify all attribute invocations
var validators = [];
Utils._.forIn(this.modelInstance.rawAttributes, function(rawAttribute, field) {
if (self.options.skip.indexOf(field) >= 0) {
return;
}
var value = self.modelInstance.dataValues[field];
if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
...function forInRight(object, iteratee) {
return object == null
? object
: baseForRight(object, getIteratee(iteratee, 3), keysIn);
}n/a
function forOwn(object, iteratee) {
return object && baseForOwn(object, getIteratee(iteratee, 3));
}n/a
function forOwnRight(object, iteratee) {
return object && baseForOwnRight(object, getIteratee(iteratee, 3));
}n/a
function fromPairs(pairs) {
var index = -1,
length = pairs ? pairs.length : 0,
result = {};
while (++index < length) {
var pair = pairs[index];
result[pair[0]] = pair[1];
}
return result;
}n/a
function functions(object) {
return object == null ? [] : baseFunctions(object, keys(object));
}n/a
function functionsIn(object) {
return object == null ? [] : baseFunctions(object, keysIn(object));
}n/a
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}...
options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
};
QueryInterface.prototype.dropAllTables = function(options) {
var self = this
, skip;
...groupBy = function (collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, getIteratee(iteratee), accumulator);
}n/a
gt = function (value, other) {
if (!(typeof value == 'string' && typeof other == 'string')) {
value = toNumber(value);
other = toNumber(other);
}
return operator(value, other);
}n/a
gte = function (value, other) {
if (!(typeof value == 'string' && typeof other == 'string')) {
value = toNumber(value);
other = toNumber(other);
}
return operator(value, other);
}n/a
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}n/a
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}n/a
function head(array) {
return (array && array.length) ? array[0] : undefined;
}n/a
function identity(value) {
return value;
}n/a
function inRange(number, start, end) {
start = toNumber(start) || 0;
if (end === undefined) {
end = start;
start = 0;
} else {
end = toNumber(end) || 0;
}
number = toNumber(number);
return baseInRange(number, start, end);
}n/a
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}n/a
function indexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
fromIndex = toInteger(fromIndex);
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return baseIndexOf(array, value, fromIndex);
}...
*/
InstanceValidator.prototype._builtinValidators = function() {
var self = this;
// promisify all attribute invocations
var validators = [];
Utils._.forIn(this.modelInstance.rawAttributes, function(rawAttribute, field) {
if (self.options.skip.indexOf(field) >= 0) {
return;
}
var value = self.modelInstance.dataValues[field];
if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
// perform validations based on schema
...function initial(array) {
return dropRight(array, 1);
}n/a
intersection = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}...
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];
});
wheres.push(where);
}
});
...intersectionBy = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
intersectionWith = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
invert = function (object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
}n/a
invertBy = function (object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
}n/a
invoke = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
invokeMap = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function isArguments(value) {
// Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}n/a
function isArray() { [native code] }...
if (typeof fnArgs[fnArgs.length - 1] === 'function') {
fn = fnArgs.pop();
}
if (typeof hooks === 'string') {
hookType = hooks;
hooks = this.options.hooks[hookType] || [];
if (!Array.isArray(hooks)) hooks = hooks === undefined ? [] : [hooks];
if (this.sequelize) hooks = hooks.concat(this.sequelize.options.hooks[hookType] || []);
}
if (!Array.isArray(hooks)) {
hooks = hooks === undefined ? [] : [hooks];
}
...function isArrayBuffer(value) {
return isObjectLike(value) && objectToString.call(value) == arrayBufferTag;
}n/a
function isArrayLike(value) {
return value != null && isLength(getLength(value)) && !isFunction(value);
}n/a
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}n/a
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && objectToString.call(value) == boolTag);
}n/a
isBuffer = function (value) {
return value instanceof Buffer;
}...
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be null', 'notNull Violation', field, value
);
this.errors.push(error);
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes
.TEXT || rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || (_.isObject(value) && !value._isSequelizeMethod) && !Buffer.isBuffer(value)) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be an array or an object', 'string violation
', field, value);
this.errors.push(error);
}
}
};
...function isDate(value) {
return isObjectLike(value) && objectToString.call(value) == dateTag;
}...
var 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.
}
}
...function isElement(value) {
return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
}n/a
function isEmpty(value) {
if (isArrayLike(value) &&
(isArray(value) || isString(value) || isFunction(value.splice) ||
isArguments(value) || isBuffer(value))) {
return !value.length;
}
if (isObjectLike(value)) {
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return !(nonEnumShadows && keys(value).length);
}...
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);
}
});
};
...function isEqual(value, other) {
return baseIsEqual(value, other);
}n/a
function isEqualWith(value, other, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
var result = customizer ? customizer(value, other) : undefined;
return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
}n/a
function isError(value) {
if (!isObjectLike(value)) {
return false;
}
return (objectToString.call(value) == errorTag) ||
(typeof value.message == 'string' && typeof value.name == 'string');
}n/a
function isFinite(value) {
return typeof value == 'number' && nativeIsFinite(value);
}n/a
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8 which returns 'object' for typed array and weak map constructors,
// and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}n/a
function isInteger(value) {
return typeof value == 'number' && value == toInteger(value);
}n/a
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}n/a
function isMap(value) {
return isObjectLike(value) && getTag(value) == mapTag;
}n/a
function isMatch(object, source) {
return object === source || baseIsMatch(object, source, getMatchData(source));
}n/a
function isMatchWith(object, source, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseIsMatch(object, source, getMatchData(source), customizer);
}n/a
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}n/a
function isNative(value) {
if (!isObject(value)) {
return false;
}
var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}n/a
function isNil(value) {
return value == null;
}n/a
function isNull(value) {
return value === null;
}...
var 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.
}
}
...function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && objectToString.call(value) == numberTag);
}n/a
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}...
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be null', 'notNull Violation', field, value
);
this.errors.push(error);
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes
.TEXT || rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || (_.isObject(value) && !value._isSequelizeMethod
) && !Buffer.isBuffer(value)) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be an array or an object', 'string violation
', field, value);
this.errors.push(error);
}
}
};
...function isObjectLike(value) {
return !!value && typeof value == 'object';
}n/a
function isPlainObject(value) {
if (!isObjectLike(value) ||
objectToString.call(value) != objectTag || isHostObject(value)) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return (typeof Ctor == 'function' &&
Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
}...
, 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;
});
...function isRegExp(value) {
return isObject(value) && objectToString.call(value) == regexpTag;
}n/a
function isSafeInteger(value) {
return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
}n/a
function isSet(value) {
return isObjectLike(value) && getTag(value) == setTag;
}n/a
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
}n/a
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}n/a
function isTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
}n/a
function isUndefined(value) {
return value === undefined;
}n/a
function isWeakMap(value) {
return isObjectLike(value) && getTag(value) == weakMapTag;
}n/a
function isWeakSet(value) {
return isObjectLike(value) && objectToString.call(value) == weakSetTag;
}n/a
function iteratee(func) {
return baseIteratee(typeof func == 'function' ? func : baseClone(func, true));
}n/a
function join(array, separator) {
return array ? nativeJoin.call(array, separator) : '';
}...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
* Gets all validation error items for the path / field specified.
*
...kebabCase = function (string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
}n/a
keyBy = function (collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, getIteratee(iteratee), accumulator);
}n/a
function keys(object) {
var isProto = isPrototype(object);
if (!(isProto || isArrayLike(object))) {
return baseKeys(object);
}
var indexes = indexKeys(object),
skipIndexes = !!indexes,
result = indexes || [],
length = result.length;
for (var key in object) {
if (baseHas(object, key) &&
!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
!(isProto && key == 'constructor')) {
result.push(key);
}
}
return result;
}...
hooks: hookTypes,
hookAliases: hookAliases,
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
});
}
};
...function keysIn(object) {
var index = -1,
isProto = isPrototype(object),
props = baseKeysIn(object),
propsLength = props.length,
indexes = indexKeys(object),
skipIndexes = !!indexes,
result = indexes || [],
length = result.length;
while (++index < propsLength) {
var key = props[index];
if (!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}n/a
function last(array) {
var length = array ? array.length : 0;
return length ? array[length - 1] : undefined;
}n/a
function lastIndexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
var index = length;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = (
index < 0
? nativeMax(length + index, 0)
: nativeMin(index, length - 1)
) + 1;
}
if (value !== value) {
return indexOfNaN(array, index, true);
}
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
}n/a
lowerCase = function (string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
}n/a
lowerFirst = function (string) {
string = toString(string);
var strSymbols = reHasComplexSymbol.test(string)
? stringToArray(string)
: undefined;
var chr = strSymbols
? strSymbols[0]
: string.charAt(0);
var trailing = strSymbols
? castSlice(strSymbols, 1).join('')
: string.slice(1);
return chr[methodName]() + trailing;
}n/a
lt = function (value, other) {
if (!(typeof value == 'string' && typeof other == 'string')) {
value = toNumber(value);
other = toNumber(other);
}
return operator(value, other);
}n/a
lte = function (value, other) {
if (!(typeof value == 'string' && typeof other == 'string')) {
value = toNumber(value);
other = toNumber(other);
}
return operator(value, other);
}n/a
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, getIteratee(iteratee, 3));
}...
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
...function mapKeys(object, iteratee) {
var result = {};
iteratee = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
result[iteratee(value, key, object)] = value;
});
return result;
}n/a
function mapValues(object, iteratee) {
var result = {};
iteratee = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
result[key] = iteratee(value, key, object);
});
return result;
}...
, 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;
...function matches(source) {
return baseMatches(baseClone(source, true));
}n/a
function matchesProperty(path, srcValue) {
return baseMatchesProperty(path, baseClone(srcValue, true));
}n/a
function max(array) {
return (array && array.length)
? baseExtremum(array, identity, baseGt)
: undefined;
}n/a
function maxBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee), baseGt)
: undefined;
}n/a
function mean(array) {
return baseMean(array, identity);
}n/a
function meanBy(array, iteratee) {
return baseMean(array, getIteratee(iteratee));
}n/a
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result);
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}n/a
merge = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
mergeWith = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
method = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}...
* @param {Function} validator The custom validator.
* @param {string} validatorType the custom validator type (name).
* @param {boolean=} optAttrDefined Set to true if custom validator was defined
* from the Attribute
* @return {Promise} A promise.
* @private
*/
InstanceValidator.prototype._invokeCustomValidator = Promise.method(function(validator
, validatorType, optAttrDefined, optValue, optField) {
var validatorFunction = null; // the validation function to call
var isAsync = false;
var validatorArity = validator.length;
// check if validator is async and requires a callback
var asyncArity = 1;
var errorKey = validatorType;
...methodOf = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function min(array) {
return (array && array.length)
? baseExtremum(array, identity, baseLt)
: undefined;
}n/a
function minBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee), baseLt)
: undefined;
}n/a
function mixin(object, source, options) {
var props = keys(source),
methodNames = baseFunctions(source, props);
if (options == null &&
!(isObject(source) && (methodNames.length || !props.length))) {
options = source;
source = object;
object = this;
methodNames = baseFunctions(source, keys(source));
}
var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
isFunc = isFunction(object);
arrayEach(methodNames, function(methodName) {
var func = source[methodName];
object[methodName] = func;
if (isFunc) {
object.prototype[methodName] = function() {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
};
}
});
return object;
}...
*/
module.exports = {
hooks: hookTypes,
hookAliases: hookAliases,
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
...multiply = function (value, other) {
var result;
if (value === undefined && other === undefined) {
return 0;
}
if (value !== undefined) {
result = value;
}
if (other !== undefined) {
if (result === undefined) {
return other;
}
if (typeof value == 'string' || typeof other == 'string') {
value = baseToString(value);
other = baseToString(other);
} else {
value = baseToNumber(value);
other = baseToNumber(other);
}
result = operator(value, other);
}
return result;
}n/a
function negate(predicate) {
if (typeof predicate != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
return !predicate.apply(this, arguments);
};
}n/a
function noConflict() {
if (root._ === this) {
root._ = oldDash;
}
return this;
}n/a
function noop() {
// No operation performed.
}n/a
function now() { [native code] }n/a
function nth(array, n) {
return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
}n/a
function nthArg(n) {
n = toInteger(n);
return rest(function(args) {
return baseNth(args, n);
});
}n/a
omit = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function omitBy(object, predicate) {
predicate = getIteratee(predicate);
return basePickBy(object, function(value, key) {
return !predicate(value, key);
});
}n/a
function once(func) {
return before(2, func);
}n/a
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}n/a
over = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
overArgs = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
overEvery = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
overSome = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function pad(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
if (!length || strLength >= length) {
return string;
}
var mid = (length - strLength) / 2;
return (
createPadding(nativeFloor(mid), chars) +
string +
createPadding(nativeCeil(mid), chars)
);
}n/a
function padEnd(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (string + createPadding(length - strLength, chars))
: string;
}n/a
function padStart(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (createPadding(length - strLength, chars) + string)
: string;
}n/a
function parseInt(string, radix, guard) {
// Chrome fails to trim leading <BOM> whitespace characters.
// See https://bugs.chromium.org/p/v8/issues/detail?id=3109 for more details.
if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
string = toString(string).replace(reTrim, '');
return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
}n/a
partial = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}...
return dataTypes[dialect].BLOB.prototype.stringify(val);
}
return dataTypes.BLOB.prototype.stringify(val);
}
if (Array.isArray(val)) {
var escape = _.partial(SqlString.escape, _, timeZone, dialect, format);
if (dialect === 'postgres' && !format) {
return dataTypes.ARRAY.prototype.stringify(val, {escape: escape});
}
return val.map(escape);
}
if (dialect === 'postgres' || dialect === 'sqlite' || dialect === 'mssql') {
...partialRight = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
partition = function (collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, getIteratee(iteratee), accumulator);
}n/a
pick = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function pickBy(object, predicate) {
return object == null ? {} : basePickBy(object, getIteratee(predicate));
}n/a
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}n/a
function propertyOf(object) {
return function(path) {
return object == null ? undefined : baseGet(object, path);
};
}n/a
pull = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function pullAll(array, values) {
return (array && array.length && values && values.length)
? basePullAll(array, values)
: array;
}n/a
function pullAllBy(array, values, iteratee) {
return (array && array.length && values && values.length)
? basePullAll(array, values, getIteratee(iteratee))
: array;
}n/a
function pullAllWith(array, values, comparator) {
return (array && array.length && values && values.length)
? basePullAll(array, values, undefined, comparator)
: array;
}n/a
pullAt = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function random(lower, upper, floating) {
if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
upper = floating = undefined;
}
if (floating === undefined) {
if (typeof upper == 'boolean') {
floating = upper;
upper = undefined;
}
else if (typeof lower == 'boolean') {
floating = lower;
lower = undefined;
}
}
if (lower === undefined && upper === undefined) {
lower = 0;
upper = 1;
}
else {
lower = toNumber(lower) || 0;
if (upper === undefined) {
upper = lower;
lower = 0;
} else {
upper = toNumber(upper) || 0;
}
}
if (lower > upper) {
var temp = lower;
lower = upper;
upper = temp;
}
if (floating || lower % 1 || upper % 1) {
var rand = nativeRandom();
return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
}
return baseRandom(lower, upper);
}n/a
range = function (start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toNumber(start);
start = start === start ? start : 0;
if (end === undefined) {
end = start;
start = 0;
} else {
end = toNumber(end) || 0;
}
step = step === undefined ? (start < end ? 1 : -1) : (toNumber(step) || 0);
return baseRange(start, end, step, fromRight);
}n/a
rangeRight = function (start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toNumber(start);
start = start === start ? start : 0;
if (end === undefined) {
end = start;
start = 0;
} else {
end = toNumber(end) || 0;
}
step = step === undefined ? (start < end ? 1 : -1) : (toNumber(step) || 0);
return baseRange(start, end, step, fromRight);
}n/a
rearg = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}...
/**
* Gets all validation error items for the path / field specified.
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
error.ValidationError.prototype.get = function(path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
};
...function reduceRight(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduceRight : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
}n/a
function reject(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
predicate = getIteratee(predicate, 3);
return func(collection, function(value, index, collection) {
return !predicate(value, index, collection);
});
}...
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 +
x27;" 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) {
...function remove(array, predicate) {
var result = [];
if (!(array && array.length)) {
return result;
}
var index = -1,
indexes = [],
length = array.length;
predicate = getIteratee(predicate, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
indexes.push(index);
}
}
basePullAt(array, indexes);
return result;
}n/a
function repeat(string, n, guard) {
if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
return baseRepeat(toString(string), n);
}n/a
function replace() {
var args = arguments,
string = toString(args[0]);
return args.length < 3 ? string : nativeReplace.call(string, args[1], args[2]);
}...
/* jshint -W110 */
var dataTypes = require('./data-types')
, _ = require('lodash')
, SqlString = exports;
SqlString.escapeId = function(val, forbidQualified) {
if (forbidQualified) {
return '`' + val.replace(/`/g, '``') + '`';
}
return '`' + val.replace(/`/g, '``').replace(/\./g, '`.`') + '`';
};
SqlString.escape = function(val, timeZone, dialect, format) {
var prependN = false;
if (val === undefined || val === null) {
...function rest(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
};
}n/a
function result(object, path, defaultValue) {
path = isKey(path, object) ? [path] : castPath(path);
var index = -1,
length = path.length;
// Ensure the loop is entered when path is empty.
if (!length) {
object = undefined;
length = 1;
}
while (++index < length) {
var value = object == null ? undefined : object[toKey(path[index])];
if (value === undefined) {
index = length;
value = defaultValue;
}
object = isFunction(value) ? value.call(object) : value;
}
return object;
}n/a
function reverse(array) {
return array ? nativeReverse.call(array) : array;
}...
});
sorter.add(tableName, deps);
});
sorted = sorter.sort();
if (options.reverse) {
sorted = sorted.reverse();
}
sorted.forEach(function(name) {
iterator(models[name], name);
});
};
module.exports = ModelManager;
...round = function (number, precision) {
number = toNumber(number);
precision = toInteger(precision);
if (precision) {
// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
}
return func(number);
}n/a
function runInContext(context) {
context = context ? _.defaults({}, context, _.pick(root, contextProps)) : root;
/** Built-in constructor references. */
var Date = context.Date,
Error = context.Error,
Math = context.Math,
RegExp = context.RegExp,
TypeError = context.TypeError;
/** Used for built-in method references. */
var arrayProto = context.Array.prototype,
objectProto = context.Object.prototype,
stringProto = context.String.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = context.Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to generate unique IDs. */
var idCounter = 0;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Used to restore the original `_` reference in `_.noConflict`. */
var oldDash = root._;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? context.Buffer : undefined,
Reflect = context.Reflect,
Symbol = context.Symbol,
Uint8Array = context.Uint8Array,
clearTimeout = context.clearTimeout,
enumerate = Reflect ? Reflect.enumerate : undefined,
getOwnPropertySymbols = Object.getOwnPropertySymbols,
iteratorSymbol = typeof (iteratorSymbol = Symbol && Symbol.iterator) == 'symbol' ? iteratorSymbol : undefined,
objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
setTimeout = context.setTimeout,
splice = arrayProto.splice;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeFloor = Math.floor,
nativeGetPrototype = Object.getPrototypeOf,
nativeIsFinite = context.isFinite,
nativeJoin = arrayProto.join,
nativeKeys = Object.keys,
nativeMax = Math.max,
nativeMin = Math.min,
nativeParseInt = context.parseInt,
nativeRandom = Math.random,
nativeReplace = stringProto.replace,
nativeReverse = arrayProto.reverse,
nativeSplit = stringProto.split;
/* Built-in method references that are verified to be native. */
var DataView = getNative(context, 'DataView'),
Map = getNative(context, 'Map'),
Promise = getNative(context, 'Promise'),
Set = getNative(context, 'Set'),
WeakMap = getNative(context, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
/** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */
var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf');
/** Used to lookup unminified function names. */
var realNames = {};
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together ...n/a
function sample(collection) {
var array = isArrayLike(collection) ? collection : values(collection),
length = array.length;
return length > 0 ? array[baseRandom(0, length - 1)] : undefined;
}n/a
function sampleSize(collection, n, guard) {
var index = -1,
result = toArray(collection),
length = result.length,
lastIndex = length - 1;
if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
n = 1;
} else {
n = baseClamp(toInteger(n), 0, length);
}
while (++index < n) {
var rand = baseRandom(index, lastIndex),
value = result[rand];
result[rand] = result[index];
result[index] = value;
}
result.length = n;
return result;
}n/a
function set(object, path, value) {
return object == null ? object : baseSet(object, path, value);
}n/a
function setWith(object, path, value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseSet(object, path, value, customizer);
}n/a
function shuffle(collection) {
return sampleSize(collection, MAX_ARRAY_LENGTH);
}n/a
function size(collection) {
if (collection == null) {
return 0;
}
if (isArrayLike(collection)) {
var result = collection.length;
return (result && isString(collection)) ? stringSize(collection) : result;
}
if (isObjectLike(collection)) {
var tag = getTag(collection);
if (tag == mapTag || tag == setTag) {
return collection.size;
}
}
return keys(collection).length;
}n/a
function slice(array, start, end) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
start = 0;
end = length;
}
else {
start = start == null ? 0 : toInteger(start);
end = end === undefined ? length : toInteger(end);
}
return baseSlice(array, start, end);
}...
validatorArgs = [validatorArgs, field];
} else if (isLocalizedValidator || validatorType === 'isIP') {
validatorArgs = [];
} else {
validatorArgs = [validatorArgs];
}
} else {
validatorArgs = validatorArgs.slice(0);
}
return validatorArgs;
};
/**
* Will validate a single field against its schema definition (isnull).
*
...snakeCase = function (string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
}n/a
function some(collection, predicate, guard) {
var func = isArray(collection) ? arraySome : baseSome;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}n/a
sortBy = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function sortedIndex(array, value) {
return baseSortedIndex(array, value);
}n/a
function sortedIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee));
}n/a
function sortedIndexOf(array, value) {
var length = array ? array.length : 0;
if (length) {
var index = baseSortedIndex(array, value);
if (index < length && eq(array[index], value)) {
return index;
}
}
return -1;
}n/a
function sortedLastIndex(array, value) {
return baseSortedIndex(array, value, true);
}n/a
function sortedLastIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee), true);
}n/a
function sortedLastIndexOf(array, value) {
var length = array ? array.length : 0;
if (length) {
var index = baseSortedIndex(array, value, true) - 1;
if (eq(array[index], value)) {
return index;
}
}
return -1;
}n/a
function sortedUniq(array) {
return (array && array.length)
? baseSortedUniq(array)
: [];
}n/a
function sortedUniqBy(array, iteratee) {
return (array && array.length)
? baseSortedUniq(array, getIteratee(iteratee))
: [];
}n/a
function split(string, separator, limit) {
if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
separator = limit = undefined;
}
limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
if (!limit) {
return [];
}
string = toString(string);
if (string && (
typeof separator == 'string' ||
(separator != null && !isRegExp(separator))
)) {
separator = baseToString(separator);
if (separator == '' && reHasComplexSymbol.test(string)) {
return castSlice(stringToArray(string), 0, limit);
}
}
return nativeSplit.call(string, separator, limit);
}n/a
function spread(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = start === undefined ? 0 : nativeMax(toInteger(start), 0);
return rest(function(args) {
var array = args[start],
otherArgs = castSlice(args, 0, start);
if (array) {
arrayPush(otherArgs, array);
}
return apply(func, this, otherArgs);
});
}n/a
startCase = function (string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
}n/a
function startsWith(string, target, position) {
string = toString(string);
position = baseClamp(toInteger(position), 0, string.length);
return string.lastIndexOf(baseToString(target), position) == position;
}n/a
subtract = function (value, other) {
var result;
if (value === undefined && other === undefined) {
return 0;
}
if (value !== undefined) {
result = value;
}
if (other !== undefined) {
if (result === undefined) {
return other;
}
if (typeof value == 'string' || typeof other == 'string') {
value = baseToString(value);
other = baseToString(other);
} else {
value = baseToNumber(value);
other = baseToNumber(other);
}
result = operator(value, other);
}
return result;
}n/a
function sum(array) {
return (array && array.length)
? baseSum(array, identity)
: 0;
}n/a
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, getIteratee(iteratee))
: 0;
}n/a
function tail(array) {
return drop(array, 1);
}n/a
function take(array, n, guard) {
if (!(array && array.length)) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, 0, n < 0 ? 0 : n);
}n/a
function takeRight(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, n < 0 ? 0 : n, length);
}n/a
function takeRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), false, true)
: [];
}n/a
function takeWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3))
: [];
}n/a
function tap(value, interceptor) {
interceptor(value);
return value;
}n/a
function template(string, options, guard) {
// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = lodash.templateSettings;
if (guard && isIterateeCall(string, options, guard)) {
options = undefined;
}
string = toString(string);
options = assignInWith({}, options, settings, assignInDefaults);
var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults),
importsKeys = keys(imports),
importsValues = baseValues(imports, importsKeys);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// Compile the regexp to match each delimiter.
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
// Use a sourceURL for easier debugging.
var sourceURL = '//# sourceURL=' +
('sourceURL' in options
? options.sourceURL
: ('lodash.templateSources[' + (++templateCounter) + ']')
) + '\n';
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// Replace delimiters with snippets.
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
return match;
});
source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable = options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
var result = attempt(function() {
return Function(importsKeys, sourceURL + 'return ' + source)
.apply(undefined, importsValues);
});
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
if (isError(result)) {
throw result;
}
return result;
}n/a
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
});
}n/a
function thru(value, interceptor) {
return interceptor(value);
}n/a
function times(n, iteratee) {
n = toInteger(n);
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = MAX_ARRAY_LENGTH,
length = nativeMin(n, MAX_ARRAY_LENGTH);
iteratee = getIteratee(iteratee);
n -= MAX_ARRAY_LENGTH;
var result = baseTimes(length, iteratee);
while (++index < n) {
iteratee(index);
}
return result;
}n/a
function toArray(value) {
if (!value) {
return [];
}
if (isArrayLike(value)) {
return isString(value) ? stringToArray(value) : copyArray(value);
}
if (iteratorSymbol && value[iteratorSymbol]) {
return iteratorToArray(value[iteratorSymbol]());
}
var tag = getTag(value),
func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
return func(value);
}n/a
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}n/a
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}n/a
function toLength(value) {
return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
}n/a
function toLower(value) {
return toString(value).toLowerCase();
}n/a
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = isFunction(value.valueOf) ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}n/a
toPairs = function (object) {
var tag = getTag(object);
if (tag == mapTag) {
return mapToArray(object);
}
if (tag == setTag) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
}n/a
toPairsIn = function (object) {
var tag = getTag(object);
if (tag == mapTag) {
return mapToArray(object);
}
if (tag == setTag) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
}n/a
function toPath(value) {
if (isArray(value)) {
return arrayMap(value, toKey);
}
return isSymbol(value) ? [value] : copyArray(stringToPath(value));
}n/a
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}n/a
function toSafeInteger(value) {
return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
}n/a
function toString(value) {
return value == null ? '' : baseToString(value);
}n/a
function toUpper(value) {
return toString(value).toUpperCase();
}n/a
function transform(object, iteratee, accumulator) {
var isArr = isArray(object) || isTypedArray(object);
iteratee = getIteratee(iteratee, 4);
if (accumulator == null) {
if (isArr || isObject(object)) {
var Ctor = object.constructor;
if (isArr) {
accumulator = isArray(object) ? new Ctor : [];
} else {
accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
}
} else {
accumulator = {};
}
}
(isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
return iteratee(accumulator, value, index, object);
});
return accumulator;
}n/a
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrim, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}n/a
function trimEnd(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimEnd, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}n/a
function trimStart(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimStart, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
start = charsStartIndex(strSymbols, stringToArray(chars));
return castSlice(strSymbols, start).join('');
}n/a
function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? toInteger(options.length) : length;
omission = 'omission' in options ? baseToString(options.omission) : omission;
}
string = toString(string);
var strLength = string.length;
if (reHasComplexSymbol.test(string)) {
var strSymbols = stringToArray(string);
strLength = strSymbols.length;
}
if (length >= strLength) {
return string;
}
var end = length - stringSize(omission);
if (end < 1) {
return omission;
}
var result = strSymbols
? castSlice(strSymbols, 0, end).join('')
: string.slice(0, end);
if (separator === undefined) {
return result + omission;
}
if (strSymbols) {
end += (result.length - end);
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
substring = result;
if (!separator.global) {
separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
var newEnd = match.index;
}
result = result.slice(0, newEnd === undefined ? end : newEnd);
}
} else if (string.indexOf(baseToString(separator), end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
}n/a
function unary(func) {
return ary(func, 1);
}n/a
function unescape(string) {
string = toString(string);
return (string && reHasEscapedHtml.test(string))
? string.replace(reEscapedHtml, unescapeHtmlChar)
: string;
}n/a
union = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
unionBy = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
unionWith = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function uniq(array) {
return (array && array.length)
? baseUniq(array)
: [];
}n/a
function uniqBy(array, iteratee) {
return (array && array.length)
? baseUniq(array, getIteratee(iteratee))
: [];
}n/a
function uniqWith(array, comparator) {
return (array && array.length)
? baseUniq(array, undefined, comparator)
: [];
}n/a
function uniqueId(prefix) {
var id = ++idCounter;
return toString(prefix) + id;
}n/a
function unset(object, path) {
return object == null ? true : baseUnset(object, path);
}n/a
function unzip(array) {
if (!(array && array.length)) {
return [];
}
var length = 0;
array = arrayFilter(array, function(group) {
if (isArrayLikeObject(group)) {
length = nativeMax(group.length, length);
return true;
}
});
return baseTimes(length, function(index) {
return arrayMap(array, baseProperty(index));
});
}n/a
function unzipWith(array, iteratee) {
if (!(array && array.length)) {
return [];
}
var result = unzip(array);
if (iteratee == null) {
return result;
}
return arrayMap(result, function(group) {
return apply(iteratee, undefined, group);
});
}n/a
function update(object, path, updater) {
return object == null ? object : baseUpdate(object, path, castFunction(updater));
}n/a
function updateWith(object, path, updater, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
}n/a
upperCase = function (string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
}n/a
upperFirst = function (string) {
string = toString(string);
var strSymbols = reHasComplexSymbol.test(string)
? stringToArray(string)
: undefined;
var chr = strSymbols
? strSymbols[0]
: string.charAt(0);
var trailing = strSymbols
? castSlice(strSymbols, 1).join('')
: string.slice(1);
return chr[methodName]() + trailing;
}n/a
function values(object) {
return object ? baseValues(object, keys(object)) : [];
}...
}
};
QueryInterface.prototype.changeColumn = function(tableName, attributeName, dataTypeOrOptions, options) {
var attributes = {};
options = options || {};
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);
...function valuesIn(object) {
return object == null ? [] : baseValues(object, keysIn(object));
}n/a
without = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function words(string, pattern, guard) {
string = toString(string);
pattern = guard ? undefined : pattern;
if (pattern === undefined) {
pattern = reHasComplexWord.test(string) ? reComplexWord : reBasicWord;
}
return string.match(pattern) || [];
}n/a
function wrap(value, wrapper) {
wrapper = wrapper == null ? identity : wrapper;
return partial(wrapper, value);
}n/a
xor = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
xorBy = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
xorWith = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
zip = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
function zipObject(props, values) {
return baseZipObject(props || [], values || [], assignValue);
}n/a
function zipObjectDeep(props, values) {
return baseZipObject(props || [], values || [], baseSet);
}n/a
zipWith = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
add = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
}
}
deps = deps.filter(function(dep) {
return tableName !== dep;
});
sorter.add(tableName, deps);
});
sorted = sorter.sort();
if (options.reverse) {
sorted = sorted.reverse();
}
sorted.forEach(function(name) {
...after = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
ary = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
assign = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
});
}
};
QueryInterface.prototype.showAllSchemas = function(options) {
var self = this;
options = _.assign({}, options, {
raw: true,
type: this.sequelize.QueryTypes.SELECT
});
var showSchemasSql = self.QueryGenerator.showSchemasQuery();
return this.sequelize.query(showSchemasSql, options).then(function(schemaNames) {
...assignIn = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
assignInWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
assignWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
at = function () {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
}n/a
attempt = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
before = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
bind = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
var validatorPromise = self._invokeBuiltinValidator(value, test, validatorType, field);
// errors are handled in settling, stub this
validatorPromise.catch(function() {});
validators.push(validatorPromise.reflect());
});
return Promise.all(validators).then(this._handleReflectedResult.bind(this, field));
};
/**
* Prepare and invoke a custom validator.
*
* @param {Function} validator The custom validator.
* @param {string} validatorType the custom validator type (name).
...bindAll = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
bindKey = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
camelCase = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
capitalize = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
castArray = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
ceil = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
function wrapperChain() {
return chain(this);
}n/a
chunk = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
clamp = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
clone = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
* The Main Instance Validator.
*
* @param {Instance} modelInstance The model instance.
* @param {Object} options A dict with options.
* @constructor
*/
function InstanceValidator(modelInstance, options) {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
...cloneDeep = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
// testhint argsConform.end
if (!rawTablename) {
// Map for backwards compat
rawTablename = tableName;
}
options = Utils.cloneDeep(options);
options.fields = attributes;
var sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false }));
};
QueryInterface.prototype.showIndex = function(tableName, options) {
var sql = this.QueryGenerator.showIndexesQuery(tableName, options);
...cloneDeepWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
cloneWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
function wrapperCommit() {
return new LodashWrapper(this.value(), this.__chain__);
}n/a
compact = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}...
var result = {};
tableNames.forEach(function(tableName, i) {
if (Utils._.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
result[tableName] = Utils._.compact(results[i]).map(function(r) {
return r.constraint_name;
});
});
return result;
});
};
...concat = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
replaceHookAliases: function(hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
}
});
return hooks;
...cond = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
conforms = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
constant = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
countBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
create = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
curry = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
curryRight = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
debounce = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
deburr = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
defaults = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
skip: []
});
this.modelInstance = modelInstance;
/**
* Exposes a reference to validator.js. This allows you to add custom validations using `validator.extend`
...defaultsDeep = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
defer = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
delay = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
difference = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
* @param {Object} options A dict with options.
* @constructor
*/
function InstanceValidator(modelInstance, options) {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options
.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
skip: []
});
...differenceBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
differenceWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
divide = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
drop = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}...
};
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);
});
}
};
...dropRight = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
dropRightWhile = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
dropWhile = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
each = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
beforeConnection: 'beforeConnect'
};
var Hooks = {
replaceHookAliases: function(hooks) {
var realHookName;
Utils._.each(hooks, function(hooksArray, name) {
// Does an alias for this hook name exist?
if (realHookName = hookAliases[name]) {
// Add the hooks to the actual hook
hooks[realHookName] = (hooks[realHookName] || []).concat(hooksArray);
// Delete the alias
delete hooks[name];
...eachRight = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
endsWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
entries = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
entriesIn = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
eq = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
escape = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
};
/**
* Escape a value (e.g. a string, number or date)
*/
QueryInterface.prototype.escape = function(value) {
return this.QueryGenerator.escape(value);
};
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 (transaction.parent) {
...escapeRegExp = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
every = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
extend = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
extendWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
fill = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
filter = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}...
removeHook: function(hookType, name) {
hookType = hookAliases[hookType] || hookType;
if (!this.hasHook(hookType)) {
return this;
}
this.options.hooks[hookType] = this.options.hooks[hookType].filter(function (hook) {
// don't remove unnamed hooks
if (typeof hook === 'function') {
return true;
}
return typeof hook === 'object' && hook.name !== name;
});
...find = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}...
QueryInterface.prototype.bulkUpdate = function(tableName, values, identifier, options, attributes) {
options = Utils.cloneDeep(options);
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
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
});
options.model = model;
return this.sequelize.query(sql, options);
};
QueryInterface.prototype.delete = function(instance, tableName, identifier, options) {
var self = this
...findIndex = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
findKey = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
findLast = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
findLastIndex = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
findLastKey = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
first = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
flatMap = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
flatMapDeep = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
flatMapDepth = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
flatten = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
raw: true,
type: this.sequelize.QueryTypes.SELECT
});
var showSchemasSql = self.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);
})
);
});
};
...flattenDeep = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
flattenDepth = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
flip = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
floor = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
flow = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
flowRight = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
forEach = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
if (!Array.isArray(hooks)) {
hooks = hooks === undefined ? [] : [hooks];
}
// run hooks as sync functions if flagged as sync
if (hookTypes[hookType] && hookTypes[hookType].sync) {
hooks.forEach(function(hook) {
if (typeof hook === 'object') hook = hook.fn;
return hook.apply(self, fnArgs);
});
return;
}
// run hooks async
...forEachRight = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
forIn = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
* @private
*/
InstanceValidator.prototype._builtinValidators = function() {
var self = this;
// promisify all attribute invocations
var validators = [];
Utils._.forIn(this.modelInstance.rawAttributes, function(rawAttribute, field) {
if (self.options.skip.indexOf(field) >= 0) {
return;
}
var value = self.modelInstance.dataValues[field];
if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
...forInRight = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
forOwn = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
forOwnRight = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
fromPairs = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
functions = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
functionsIn = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
get = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
};
QueryInterface.prototype.dropAllTables = function(options) {
var self = this
, skip;
...groupBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
gt = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
gte = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
has = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
hasIn = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
head = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
identity = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
inRange = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
includes = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
indexOf = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
*/
InstanceValidator.prototype._builtinValidators = function() {
var self = this;
// promisify all attribute invocations
var validators = [];
Utils._.forIn(this.modelInstance.rawAttributes, function(rawAttribute, field) {
if (self.options.skip.indexOf(field) >= 0) {
return;
}
var value = self.modelInstance.dataValues[field];
if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
// perform validations based on schema
...initial = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
intersection = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
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];
});
wheres.push(where);
}
});
...intersectionBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
intersectionWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
invert = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
invertBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
invoke = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
invokeMap = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
isArguments = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isArray = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
if (typeof fnArgs[fnArgs.length - 1] === 'function') {
fn = fnArgs.pop();
}
if (typeof hooks === 'string') {
hookType = hooks;
hooks = this.options.hooks[hookType] || [];
if (!Array.isArray(hooks)) hooks = hooks === undefined ? [] : [hooks];
if (this.sequelize) hooks = hooks.concat(this.sequelize.options.hooks[hookType] || []);
}
if (!Array.isArray(hooks)) {
hooks = hooks === undefined ? [] : [hooks];
}
...isArrayBuffer = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isArrayLike = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isArrayLikeObject = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isBoolean = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isBuffer = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be null', 'notNull Violation', field, value
);
this.errors.push(error);
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes
.TEXT || rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || (_.isObject(value) && !value._isSequelizeMethod) && !Buffer.isBuffer(value)) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be an array or an object', 'string violation
', field, value);
this.errors.push(error);
}
}
};
...isDate = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
var 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.
}
}
...isElement = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isEmpty = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
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);
}
});
};
...isEqual = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isEqualWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isError = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isFinite = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isFunction = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isInteger = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isLength = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isMap = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isMatch = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isMatchWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isNaN = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isNative = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isNil = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isNull = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
var 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.
}
}
...isNumber = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isObject = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be null', 'notNull Violation', field, value
);
this.errors.push(error);
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes
.TEXT || rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || (_.isObject(value) && !value._isSequelizeMethod
) && !Buffer.isBuffer(value)) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be an array or an object', 'string violation
', field, value);
this.errors.push(error);
}
}
};
...isObjectLike = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isPlainObject = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
, 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;
});
...isRegExp = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isSafeInteger = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isSet = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isString = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isSymbol = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isTypedArray = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isUndefined = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isWeakMap = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
isWeakSet = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
iteratee = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
join = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
* Gets all validation error items for the path / field specified.
*
...kebabCase = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
keyBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
keys = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
hooks: hookTypes,
hookAliases: hookAliases,
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
});
}
};
...keysIn = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
last = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
lastIndexOf = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
lowerCase = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
lowerFirst = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
lt = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
lte = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
map = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}...
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
};
util.inherits(error.ValidationError, error.BaseError);
/**
...mapKeys = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
mapValues = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
, 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;
...matches = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
matchesProperty = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
max = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
maxBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
mean = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
meanBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
memoize = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
merge = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
mergeWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
method = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
* @param {Function} validator The custom validator.
* @param {string} validatorType the custom validator type (name).
* @param {boolean=} optAttrDefined Set to true if custom validator was defined
* from the Attribute
* @return {Promise} A promise.
* @private
*/
InstanceValidator.prototype._invokeCustomValidator = Promise.method(function(validator
, validatorType, optAttrDefined, optValue, optField) {
var validatorFunction = null; // the validation function to call
var isAsync = false;
var validatorArity = validator.length;
// check if validator is async and requires a callback
var asyncArity = 1;
var errorKey = validatorType;
...methodOf = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
min = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
minBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
mixin = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
*/
module.exports = {
hooks: hookTypes,
hookAliases: hookAliases,
applyTo: function(Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
...multiply = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
negate = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
function wrapperNext() {
if (this.__values__ === undefined) {
this.__values__ = toArray(this.value());
}
var done = this.__index__ >= this.__values__.length,
value = done ? undefined : this.__values__[this.__index__++];
return { 'done': done, 'value': value };
}n/a
noConflict = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
noop = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
now = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
nth = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
nthArg = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
omit = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
omitBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
once = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
orderBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
over = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
overArgs = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
overEvery = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
overSome = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
pad = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
padEnd = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
padStart = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
parseInt = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
partial = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
return dataTypes[dialect].BLOB.prototype.stringify(val);
}
return dataTypes.BLOB.prototype.stringify(val);
}
if (Array.isArray(val)) {
var escape = _.partial(SqlString.escape, _, timeZone, dialect, format);
if (dialect === 'postgres' && !format) {
return dataTypes.ARRAY.prototype.stringify(val, {escape: escape});
}
return val.map(escape);
}
if (dialect === 'postgres' || dialect === 'sqlite' || dialect === 'mssql') {
...partialRight = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
partition = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
pick = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
pickBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
function wrapperPlant(value) {
var result,
parent = this;
while (parent instanceof baseLodash) {
var clone = wrapperClone(parent);
clone.__index__ = 0;
clone.__values__ = undefined;
if (result) {
previous.__wrapped__ = clone;
} else {
result = clone;
}
var previous = clone;
parent = parent.__wrapped__;
}
previous.__wrapped__ = value;
return result;
}n/a
pop = function () {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
}...
runHooks: function(hooks) {
var self = this
, fn
, fnArgs = Utils.sliceArgs(arguments, 1)
, hookType;
if (typeof fnArgs[fnArgs.length - 1] === 'function') {
fn = fnArgs.pop();
}
if (typeof hooks === 'string') {
hookType = hooks;
hooks = this.options.hooks[hookType] || [];
if (!Array.isArray(hooks)) hooks = hooks === undefined ? [] : [hooks];
if (this.sequelize) hooks = hooks.concat(this.sequelize.options.hooks[hookType] || []);
...property = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
propertyOf = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
pull = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
pullAll = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
pullAllBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
pullAllWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
pullAt = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
push = function () {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
}...
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
error.ValidationError.prototype.get = function(path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
};
/**
* A base class for all database related errors.
...random = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
range = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
rangeRight = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
rearg = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
reduce = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
/**
* Gets all validation error items for the path / field specified.
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
error.ValidationError.prototype.get = function(path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
};
...reduceRight = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
reject = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}...
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 +
x27;" 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) {
...remove = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
repeat = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
replace = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
/* jshint -W110 */
var dataTypes = require('./data-types')
, _ = require('lodash')
, SqlString = exports;
SqlString.escapeId = function(val, forbidQualified) {
if (forbidQualified) {
return '`' + val.replace(/`/g, '``') + '`';
}
return '`' + val.replace(/`/g, '``').replace(/\./g, '`.`') + '`';
};
SqlString.escape = function(val, timeZone, dialect, format) {
var prependN = false;
if (val === undefined || val === null) {
...rest = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
result = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
var wrapped = value;
if (this.__actions__.length) {
wrapped = new LazyWrapper(this);
}
wrapped = wrapped.reverse();
wrapped.__actions__.push({
'func': thru,
'args': [reverse],
'thisArg': undefined
});
return new LodashWrapper(wrapped, this.__chain__);
}
return this.thru(reverse);
}...
});
sorter.add(tableName, deps);
});
sorted = sorter.sort();
if (options.reverse) {
sorted = sorted.reverse();
}
sorted.forEach(function(name) {
iterator(models[name], name);
});
};
module.exports = ModelManager;
...round = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
runInContext = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sample = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sampleSize = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
set = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
setWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
shift = function () {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
}...
values = [].concat(values);
return sql.replace(/\?/g, function(match) {
if (!values.length) {
return match;
}
return SqlString.escape(values.shift(), timeZone, dialect, true);
});
};
SqlString.formatNamedParameters = function(sql, values, timeZone, dialect) {
return sql.replace(/\:+(?!\d)(\w+)/g, function(value, key) {
if ('postgres' === dialect && '::' === value.slice(0, 2)) {
return value;
...shuffle = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
size = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
slice = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}...
validatorArgs = [validatorArgs, field];
} else if (isLocalizedValidator || validatorType === 'isIP') {
validatorArgs = [];
} else {
validatorArgs = [validatorArgs];
}
} else {
validatorArgs = validatorArgs.slice(0);
}
return validatorArgs;
};
/**
* Will validate a single field against its schema definition (isnull).
*
...snakeCase = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
some = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sort = function () {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
}...
deps = deps.filter(function(dep) {
return tableName !== dep;
});
sorter.add(tableName, deps);
});
sorted = sorter.sort();
if (options.reverse) {
sorted = sorted.reverse();
}
sorted.forEach(function(name) {
iterator(models[name], name);
});
};
...sortBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sortedIndex = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sortedIndexBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sortedIndexOf = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sortedLastIndex = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sortedLastIndexBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sortedLastIndexOf = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sortedUniq = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sortedUniqBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
splice = function () {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
}n/a
split = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
spread = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
startCase = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
startsWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
subtract = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sum = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
sumBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
tail = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
take = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
takeRight = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
takeRightWhile = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
takeWhile = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
tap = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
template = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
throttle = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
thru = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
times = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toArray = function () {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
}n/a
toFinite = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toInteger = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
function wrapperValue() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}n/a
toLength = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toLower = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toNumber = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toPairs = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toPairsIn = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toPath = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toPlainObject = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toSafeInteger = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toString = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
toUpper = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
transform = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
trim = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
trimEnd = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
trimStart = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
truncate = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
unary = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
unescape = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
union = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
unionBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
unionWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
uniq = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
uniqBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
uniqWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
uniqueId = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
unset = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
unshift = function () {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
}n/a
unzip = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
unzipWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
update = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
updateWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
upperCase = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
upperFirst = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
function wrapperValue() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}n/a
function wrapperValue() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}n/a
values = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}...
}
};
QueryInterface.prototype.changeColumn = function(tableName, attributeName, dataTypeOrOptions, options) {
var attributes = {};
options = options || {};
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);
...valuesIn = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
without = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
words = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
wrap = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
xor = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
xorBy = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
xorWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
zip = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
zipObject = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
zipObjectDeep = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
zipWith = function () {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
}n/a
fn = function (fn, args) {
this.fn = fn;
this.args = args;
}n/a
clone = function () {
return new Utils.fn(this.fn, this.args);
}...
* The Main Instance Validator.
*
* @param {Instance} modelInstance The model instance.
* @param {Object} options A dict with options.
* @constructor
*/
function InstanceValidator(modelInstance, options) {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
..._apply_rules = function ( str, rules, skip, override ){
if( override ){
str = override;
}else{
var ignore = ( inflector.indexOf( skip, str.toLowerCase()) > -1 );
if( !ignore ){
var i = 0;
var j = rules.length;
for( ; i < j; i++ ){
if( str.match( rules[ i ][ 0 ])){
if( rules[ i ][ 1 ] !== undefined ){
str = str.replace( rules[ i ][ 0 ], rules[ i ][ 1 ]);
}
break;
}
}
}
}
return str;
}n/a
camelize = function ( str, low_first_letter ){
var str_path = str.split( '/' );
var i = 0;
var j = str_path.length;
var str_arr, init_x, k, l, first;
for( ; i < j; i++ ){
str_arr = str_path[ i ].split( '_' );
k = 0;
l = str_arr.length;
for( ; k < l; k++ ){
if( k !== 0 ){
str_arr[ k ] = str_arr[ k ].toLowerCase();
}
first = str_arr[ k ].charAt( 0 );
first = low_first_letter && i === 0 && k === 0
? first.toLowerCase() : first.toUpperCase();
str_arr[ k ] = first + str_arr[ k ].substring( 1 );
}
str_path[ i ] = str_arr.join( '' );
}
return str_path.join( '::' );
}n/a
capitalize = function ( str ){
str = str.toLowerCase();
return str.substring( 0, 1 ).toUpperCase() + str.substring( 1 );
}n/a
classify = function ( str ){
str = inflector.camelize( str );
str = inflector.singularize( str );
return str;
}n/a
dasherize = function ( str ){
return str.replace( space_or_underbar, '-' );
}n/a
demodulize = function ( str ){
var str_arr = str.split( '::' );
return str_arr[ str_arr.length - 1 ];
}n/a
foreign_key = function ( str, drop_id_ubar ){
str = inflector.demodulize( str );
str = inflector.underscore( str ) + (( drop_id_ubar ) ? ( '' ) : ( '_' )) + 'id';
return str;
}n/a
humanize = function ( str, low_first_letter ){
str = str.toLowerCase();
str = str.replace( id_suffix, '' );
str = str.replace( underbar, ' ' );
if( !low_first_letter ){
str = inflector.capitalize( str );
}
return str;
}n/a
indexOf = function ( arr, item, from_index, compare_func ){
if( !from_index ){
from_index = -1;
}
var index = -1;
var i = from_index;
var j = arr.length;
for( ; i < j; i++ ){
if( arr[ i ] === item || compare_func && compare_func( arr[ i ], item )){
index = i;
break;
}
}
return index;
}...
*/
InstanceValidator.prototype._builtinValidators = function() {
var self = this;
// promisify all attribute invocations
var validators = [];
Utils._.forIn(this.modelInstance.rawAttributes, function(rawAttribute, field) {
if (self.options.skip.indexOf(field) >= 0) {
return;
}
var value = self.modelInstance.dataValues[field];
if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
// perform validations based on schema
...inflect = function ( str, count, singular, plural ){
count = parseInt( count, 10 );
if( isNaN( count )) return str;
if( count === 0 || count > 1 ){
return inflector._apply_rules( str, plural_rules, uncountable_words, plural );
}else{
return inflector._apply_rules( str, singular_rules, uncountable_words, singular );
}
}n/a
ordinalize = function ( str ){
var str_arr = str.split( ' ' );
var i = 0;
var j = str_arr.length;
for( ; i < j; i++ ){
var k = parseInt( str_arr[ i ], 10 );
if( !isNaN( k )){
var ltd = str_arr[ i ].substring( str_arr[ i ].length - 2 );
var ld = str_arr[ i ].substring( str_arr[ i ].length - 1 );
var suf = 'th';
if( ltd != '11' && ltd != '12' && ltd != '13' ){
if( ld === '1' ){
suf = 'st';
}else if( ld === '2' ){
suf = 'nd';
}else if( ld === '3' ){
suf = 'rd';
}
}
str_arr[ i ] += suf;
}
}
return str_arr.join( ' ' );
}n/a
pluralize = function ( str, plural ){
return inflector._apply_rules( str, plural_rules, uncountable_words, plural );
}n/a
singularize = function ( str, singular ){
return inflector._apply_rules( str, singular_rules, uncountable_words, singular );
}n/a
tableize = function ( str ){
str = inflector.underscore( str );
str = inflector.pluralize( str );
return str;
}n/a
titleize = function ( str ){
str = str.toLowerCase().replace( underbar, ' ' );
var str_arr = str.split( ' ' );
var i = 0;
var j = str_arr.length;
var d, k, l;
for( ; i < j; i++ ){
d = str_arr[ i ].split( '-' );
k = 0;
l = d.length;
for( ; k < l; k++){
if( inflector.indexOf( non_titlecased_words, d[ k ].toLowerCase()) < 0 ){
d[ k ] = inflector.capitalize( d[ k ]);
}
}
str_arr[ i ] = d.join( '-' );
}
str = str_arr.join( ' ' );
str = str.substring( 0, 1 ).toUpperCase() + str.substring( 1 );
return str;
}n/a
transform = function ( str, arr ){
var i = 0;
var j = arr.length;
for( ;i < j; i++ ){
var method = arr[ i ];
if( inflector.hasOwnProperty( method )){
str = inflector[ method ]( str );
}
}
return str;
}n/a
underscore = function ( str, all_upper_case ){
if( all_upper_case && str === str.toUpperCase()) return str;
var str_path = str.split( '::' );
var i = 0;
var j = str_path.length;
for( ; i < j; i++ ){
str_path[ i ] = str_path[ i ].replace( uppercase, '_$1' );
str_path[ i ] = str_path[ i ].replace( underbar_prefix, '' );
}
return str_path.join( '/' ).toLowerCase();
}n/a
VIRTUAL = function (ReturnType, fields) {
if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields);
if (typeof ReturnType === 'function') ReturnType = new ReturnType();
this.returnType = ReturnType;
this.fields = fields;
}n/a
super_ = function (options) {
}n/a
ValidationError = function (message, errors) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeValidationError';
this.message = 'Validation Error';
/**
* An array of ValidationErrorItems
* @member errors
*/
this.errors = errors || [];
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
}...
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
} else {
return null;
}
});
};
/**
...super_ = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
get = function (path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
}...
options.supportsSearchPath = false;
promises.push(self.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
};
QueryInterface.prototype.dropAllTables = function(options) {
var self = this
, skip;
...function blacklist(str, chars) {
(0, _assertString2.default)(str);
return str.replace(new RegExp('[' + chars + ']+', 'g'), '');
}n/a
contains = function (str, elem) {
return str.indexOf(elem) >= 0 && !!elem;
}n/a
function equals(str, comparison) {
(0, _assertString2.default)(str);
return str === comparison;
}n/a
function escape(str) {
(0, _assertString2.default)(str);
return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>
;').replace(/\//g, '/').replace(/`/g, '`');
}...
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
};
/**
* Escape a value (e.g. a string, number or date)
*/
QueryInterface.prototype.escape = function(value) {
return this.QueryGenerator.escape(value);
};
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 (transaction.parent) {
...extend = function (name, fn) {
this[name] = fn;
return this;
}n/a
is = function (str, pattern, modifiers) {
return this.regex(str, pattern, modifiers);
}n/a
function isAfter(str) {
var date = arguments.length <= 1 || arguments[1] === undefined ? String(new Date()) : arguments[1];
(0, _assertString2.default)(str);
var comparison = (0, _toDate2.default)(date);
var original = (0, _toDate2.default)(str);
return !!(original && comparison && original > comparison);
}n/a
function isAlpha(str) {
var locale = arguments.length <= 1 || arguments[1] === undefined ? 'en-US' : arguments[1];
(0, _assertString2.default)(str);
if (locale in _alpha.alpha) {
return _alpha.alpha[locale].test(str);
}
throw new Error('Invalid locale \'' + locale + '\'');
}n/a
function isAlphanumeric(str) {
var locale = arguments.length <= 1 || arguments[1] === undefined ? 'en-US' : arguments[1];
(0, _assertString2.default)(str);
if (locale in _alpha.alphanumeric) {
return _alpha.alphanumeric[locale].test(str);
}
throw new Error('Invalid locale \'' + locale + '\'');
}n/a
function isAscii(str) {
(0, _assertString2.default)(str);
return ascii.test(str);
}n/a
function isBase64(str) {
(0, _assertString2.default)(str);
var len = str.length;
if (!len || len % 4 !== 0 || notBase64.test(str)) {
return false;
}
var firstPaddingChar = str.indexOf('=');
return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '=';
}n/a
function isBefore(str) {
var date = arguments.length <= 1 || arguments[1] === undefined ? String(new Date()) : arguments[1];
(0, _assertString2.default)(str);
var comparison = (0, _toDate2.default)(date);
var original = (0, _toDate2.default)(str);
return !!(original && comparison && original < comparison);
}n/a
function isBoolean(str) {
(0, _assertString2.default)(str);
return ['true', 'false', '1', '0'].indexOf(str) >= 0;
}n/a
function isByteLength(str, options) {
(0, _assertString2.default)(str);
var min = void 0;
var max = void 0;
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
min = options.min || 0;
max = options.max;
} else {
// backwards compatibility: isByteLength(str, min [, max])
min = arguments[1];
max = arguments[2];
}
var len = encodeURI(str).split(/%..|./).length - 1;
return len >= min && (typeof max === 'undefined' || len <= max);
}n/a
function isCreditCard(str) {
(0, _assertString2.default)(str);
var sanitized = str.replace(/[^0-9]+/g, '');
if (!creditCard.test(sanitized)) {
return false;
}
var sum = 0;
var digit = void 0;
var tmpNum = void 0;
var shouldDouble = void 0;
for (var i = sanitized.length - 1; i >= 0; i--) {
digit = sanitized.substring(i, i + 1);
tmpNum = parseInt(digit, 10);
if (shouldDouble) {
tmpNum *= 2;
if (tmpNum >= 10) {
sum += tmpNum % 10 + 1;
} else {
sum += tmpNum;
}
} else {
sum += tmpNum;
}
shouldDouble = !shouldDouble;
}
return !!(sum % 10 === 0 ? sanitized : false);
}n/a
function isCurrency(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_currency_options);
return currencyRegex(options).test(str);
}n/a
function isDataURI(str) {
(0, _assertString2.default)(str);
return dataURI.test(str);
}n/a
function isDate(str) {
(0, _assertString2.default)(str);
var normalizedDate = new Date(Date.parse(str));
if (isNaN(normalizedDate)) {
return false;
}
// normalizedDate is in the user's timezone. Apply the input
// timezone offset to the date so that the year and day match
// the input
var timezoneOffset = getTimezoneOffset(str);
if (timezoneOffset !== null) {
var timezoneDifference = normalizedDate.getTimezoneOffset() - timezoneOffset;
normalizedDate = new Date(normalizedDate.getTime() + 60000 * timezoneDifference);
}
var day = String(normalizedDate.getDate());
var dayOrYear = void 0,
dayOrYearMatches = void 0,
year = void 0;
// check for valid double digits that could be late days
// check for all matches since a string like '12/23' is a valid date
// ignore everything with nearby colons
dayOrYearMatches = str.match(/(^|[^:\d])[23]\d([^T:\d]|$)/g);
if (!dayOrYearMatches) {
return true;
}
dayOrYear = dayOrYearMatches.map(function (digitString) {
return digitString.match(/\d+/g)[0];
}).join('/');
year = String(normalizedDate.getFullYear()).slice(-2);
if (dayOrYear === day || dayOrYear === year) {
return true;
} else if (dayOrYear === '' + day / year || dayOrYear === '' + year / day) {
return true;
}
return false;
}...
var 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.
}
}
...isDecimal = function (str) {
return str !== '' && str.match(/^(?:-?(?:[0-9]+))?(?:\.[0-9]*)?(?:[eE][\+\-]?(?:[0-9]+))?$/);
}n/a
function isDivisibleBy(str, num) {
(0, _assertString2.default)(str);
return (0, _toFloat2.default)(str) % parseInt(num, 10) === 0;
}n/a
function isEmail(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_email_options);
if (options.allow_display_name) {
var display_email = str.match(displayName);
if (display_email) {
str = display_email[1];
}
}
var parts = str.split('@');
var domain = parts.pop();
var user = parts.join('@');
var lower_domain = domain.toLowerCase();
if (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com') {
user = user.replace(/\./g, '').toLowerCase();
}
if (!(0, _isByteLength2.default)(user, { max: 64 }) || !(0, _isByteLength2.default)(domain, { max: 256 })) {
return false;
}
if (!(0, _isFQDN2.default)(domain, { require_tld: options.require_tld })) {
return false;
}
if (user[0] === '"') {
user = user.slice(1, user.length - 1);
return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user);
}
var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart;
var user_parts = user.split('.');
for (var i = 0; i < user_parts.length; i++) {
if (!pattern.test(user_parts[i])) {
return false;
}
}
return true;
}n/a
function isFDQN(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_fqdn_options);
/* Remove the optional trailing dot before checking validity */
if (options.allow_trailing_dot && str[str.length - 1] === '.') {
str = str.substring(0, str.length - 1);
}
var parts = str.split('.');
if (options.require_tld) {
var tld = parts.pop();
if (!parts.length || !/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {
return false;
}
}
for (var part, i = 0; i < parts.length; i++) {
part = parts[i];
if (options.allow_underscores) {
part = part.replace(/_/g, '');
}
if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) {
return false;
}
if (/[\uff01-\uff5e]/.test(part)) {
// disallow full-width chars
return false;
}
if (part[0] === '-' || part[part.length - 1] === '-') {
return false;
}
}
return true;
}n/a
function isFloat(str, options) {
(0, _assertString2.default)(str);
options = options || {};
if (str === '' || str === '.') {
return false;
}
return float.test(str) && (!options.hasOwnProperty('min') || str >= options.min) && (!options.hasOwnProperty('max') || str <=
options.max);
}n/a
function isFullWidth(str) {
(0, _assertString2.default)(str);
return fullWidth.test(str);
}n/a
function isHalfWidth(str) {
(0, _assertString2.default)(str);
return halfWidth.test(str);
}n/a
function isHexColor(str) {
(0, _assertString2.default)(str);
return hexcolor.test(str);
}n/a
function isHexadecimal(str) {
(0, _assertString2.default)(str);
return hexadecimal.test(str);
}n/a
function isIP(str) {
var version = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
(0, _assertString2.default)(str);
version = String(version);
if (!version) {
return isIP(str, 4) || isIP(str, 6);
} else if (version === '4') {
if (!ipv4Maybe.test(str)) {
return false;
}
var parts = str.split('.').sort(function (a, b) {
return a - b;
});
return parts[3] <= 255;
} else if (version === '6') {
var blocks = str.split(':');
var foundOmissionBlock = false; // marker to indicate ::
// At least some OS accept the last 32 bits of an IPv6 address
// (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says
// that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses,
// and '::a.b.c.d' is deprecated, but also valid.
var foundIPv4TransitionBlock = isIP(blocks[blocks.length - 1], 4);
var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8;
if (blocks.length > expectedNumberOfBlocks) {
return false;
}
// initial or final ::
if (str === '::') {
return true;
} else if (str.substr(0, 2) === '::') {
blocks.shift();
blocks.shift();
foundOmissionBlock = true;
} else if (str.substr(str.length - 2) === '::') {
blocks.pop();
blocks.pop();
foundOmissionBlock = true;
}
for (var i = 0; i < blocks.length; ++i) {
// test for a :: which can not be at the string start/end
// since those cases have been handled above
if (blocks[i] === '' && i > 0 && i < blocks.length - 1) {
if (foundOmissionBlock) {
return false; // multiple :: in address
}
foundOmissionBlock = true;
} else if (foundIPv4TransitionBlock && i === blocks.length - 1) {
// it has been checked before that the last
// block is a valid IPv4 address
} else if (!ipv6Block.test(blocks[i])) {
return false;
}
}
if (foundOmissionBlock) {
return blocks.length >= 1;
}
return blocks.length === expectedNumberOfBlocks;
}
return false;
}n/a
isIPv4 = function (str) {
return this.isIP(str, 4);
}n/a
isIPv6 = function (str) {
return this.isIP(str, 6);
}n/a
function isISBN(str) {
var version = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
(0, _assertString2.default)(str);
version = String(version);
if (!version) {
return isISBN(str, 10) || isISBN(str, 13);
}
var sanitized = str.replace(/[\s-]+/g, '');
var checksum = 0;
var i = void 0;
if (version === '10') {
if (!isbn10Maybe.test(sanitized)) {
return false;
}
for (i = 0; i < 9; i++) {
checksum += (i + 1) * sanitized.charAt(i);
}
if (sanitized.charAt(9) === 'X') {
checksum += 10 * 10;
} else {
checksum += 10 * sanitized.charAt(9);
}
if (checksum % 11 === 0) {
return !!sanitized;
}
} else if (version === '13') {
if (!isbn13Maybe.test(sanitized)) {
return false;
}
for (i = 0; i < 12; i++) {
checksum += factor[i % 2] * sanitized.charAt(i);
}
if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) {
return !!sanitized;
}
}
return false;
}n/a
function isISIN(str) {
(0, _assertString2.default)(str);
if (!isin.test(str)) {
return false;
}
var checksumStr = str.replace(/[A-Z]/g, function (character) {
return parseInt(character, 36);
});
var sum = 0;
var digit = void 0;
var tmpNum = void 0;
var shouldDouble = true;
for (var i = checksumStr.length - 2; i >= 0; i--) {
digit = checksumStr.substring(i, i + 1);
tmpNum = parseInt(digit, 10);
if (shouldDouble) {
tmpNum *= 2;
if (tmpNum >= 10) {
sum += tmpNum + 1;
} else {
sum += tmpNum;
}
} else {
sum += tmpNum;
}
shouldDouble = !shouldDouble;
}
return parseInt(str.substr(str.length - 1), 10) === (10000 - sum) % 10;
}n/a
isISO8601 = function (str) {
(0, _assertString2.default)(str);
return iso8601.test(str);
}n/a
function isIn(str, options) {
(0, _assertString2.default)(str);
var i = void 0;
if (Object.prototype.toString.call(options) === '[object Array]') {
var array = [];
for (i in options) {
if ({}.hasOwnProperty.call(options, i)) {
array[i] = (0, _toString2.default)(options[i]);
}
}
return array.indexOf(str) >= 0;
} else if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
return options.hasOwnProperty(str);
} else if (options && typeof options.indexOf === 'function') {
return options.indexOf(str) >= 0;
}
return false;
}n/a
function isInt(str, options) {
(0, _assertString2.default)(str);
options = options || {};
// Get the regex to use for testing, based on whether
// leading zeroes are allowed or not.
var regex = options.hasOwnProperty('allow_leading_zeroes') && options.allow_leading_zeroes ? intLeadingZeroes : int;
// Check min/max
var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min;
var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max;
return regex.test(str) && minCheckPassed && maxCheckPassed;
}n/a
function isJSON(str) {
(0, _assertString2.default)(str);
try {
var obj = JSON.parse(str);
return !!obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object';
} catch (e) {/* ignore */}
return false;
}n/a
function isLength(str, options) {
(0, _assertString2.default)(str);
var min = void 0;
var max = void 0;
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
min = options.min || 0;
max = options.max;
} else {
// backwards compatibility: isLength(str, min [, max])
min = arguments[1];
max = arguments[2];
}
var surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || [];
var len = str.length - surrogatePairs.length;
return len >= min && (typeof max === 'undefined' || len <= max);
}n/a
function isLowercase(str) {
(0, _assertString2.default)(str);
return str === str.toLowerCase();
}n/a
function isMACAddress(str) {
(0, _assertString2.default)(str);
return macAddress.test(str);
}n/a
function isMD5(str) {
(0, _assertString2.default)(str);
return md5.test(str);
}n/a
function isMobilePhone(str, locale) {
(0, _assertString2.default)(str);
if (locale in phones) {
return phones[locale].test(str);
}
return false;
}n/a
function isMongoId(str) {
(0, _assertString2.default)(str);
return (0, _isHexadecimal2.default)(str) && str.length === 24;
}n/a
function isMultibyte(str) {
(0, _assertString2.default)(str);
return multibyte.test(str);
}n/a
function isNull(str) {
(0, _assertString2.default)(str);
return str.length === 0;
}...
var 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.
}
}
...function isNumeric(str) {
(0, _assertString2.default)(str);
return numeric.test(str);
}n/a
function isSurrogatePair(str) {
(0, _assertString2.default)(str);
return surrogatePair.test(str);
}n/a
function isURL(url, options) {
(0, _assertString2.default)(url);
if (!url || url.length >= 2083 || /\s/.test(url)) {
return false;
}
if (url.indexOf('mailto:') === 0) {
return false;
}
options = (0, _merge2.default)(options, default_url_options);
var protocol = void 0,
auth = void 0,
host = void 0,
hostname = void 0,
port = void 0,
port_str = void 0,
split = void 0,
ipv6 = void 0;
split = url.split('#');
url = split.shift();
split = url.split('?');
url = split.shift();
split = url.split('://');
if (split.length > 1) {
protocol = split.shift();
if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) {
return false;
}
} else if (options.require_protocol) {
return false;
} else if (options.allow_protocol_relative_urls && url.substr(0, 2) === '//') {
split[0] = url.substr(2);
}
url = split.join('://');
split = url.split('/');
url = split.shift();
if (url === '' && !options.require_host) {
return true;
}
split = url.split('@');
if (split.length > 1) {
auth = split.shift();
if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) {
return false;
}
}
hostname = split.join('@');
port_str = ipv6 = null;
var ipv6_match = hostname.match(wrapped_ipv6);
if (ipv6_match) {
host = '';
ipv6 = ipv6_match[1];
port_str = ipv6_match[2] || null;
} else {
split = hostname.split(':');
host = split.shift();
if (split.length) {
port_str = split.join(':');
}
}
if (port_str !== null) {
port = parseInt(port_str, 10);
if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) {
return false;
}
}
if (!(0, _isIP2.default)(host) && !(0, _isFQDN2.default)(host, options) && (!ipv6 || !(0, _isIP2.default)(ipv6, 6)) && host !== '
localhost') {
return false;
}
host = host || ipv6;
if (options.host_whitelist && !checkHost(host, options.host_whitelist)) {
return false;
}
if (options.host_blacklist && checkHost(host, options.host_blacklist)) {
return false;
}
return true;
}n/a
function isUUID(str) {
var version = arguments.length <= 1 || arguments[1] === undefined ? 'all' : arguments[1];
(0, _assertString2.default)(str);
var pattern = uuid[version];
return pattern && pattern.test(str);
}n/a
function isUppercase(str) {
(0, _assertString2.default)(str);
return str === str.toUpperCase();
}n/a
isUrl = function (str) {
return this.isURL(str);
}n/a
function isVariableWidth(str) {
(0, _assertString2.default)(str);
return _isFullWidth.fullWidth.test(str) && _isHalfWidth.halfWidth.test(str);
}n/a
function isWhitelisted(str, chars) {
(0, _assertString2.default)(str);
for (var i = str.length - 1; i >= 0; i--) {
if (chars.indexOf(str[i]) === -1) {
return false;
}
}
return true;
}n/a
len = function (str, min, max) {
return this.isLength(str, min, max);
}n/a
function ltrim(str, chars) {
(0, _assertString2.default)(str);
var pattern = chars ? new RegExp('^[' + chars + ']+', 'g') : /^\s+/g;
return str.replace(pattern, '');
}n/a
function matches(str, pattern, modifiers) {
(0, _assertString2.default)(str);
if (Object.prototype.toString.call(pattern) !== '[object RegExp]') {
pattern = new RegExp(pattern, modifiers);
}
return pattern.test(str);
}n/a
max = function (str, val) {
var number = parseFloat(str);
return isNaN(number) || number <= val;
}n/a
min = function (str, val) {
var number = parseFloat(str);
return isNaN(number) || number >= val;
}n/a
function normalizeEmail(email, options) {
options = (0, _merge2.default)(options, default_normalize_email_options);
if (!(0, _isEmail2.default)(email)) {
return false;
}
var parts = email.split('@', 2);
parts[1] = parts[1].toLowerCase();
if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') {
if (options.remove_extension) {
parts[0] = parts[0].split('+')[0];
}
if (options.remove_dots) {
parts[0] = parts[0].replace(/\./g, '');
}
if (!parts[0].length) {
return false;
}
parts[0] = parts[0].toLowerCase();
parts[1] = 'gmail.com';
} else if (options.lowercase) {
parts[0] = parts[0].toLowerCase();
}
return parts.join('@');
}n/a
not = function (str, pattern, modifiers) {
return this.notRegex(str, pattern, modifiers);
}n/a
notContains = function (str, elem) {
return !this.contains(str, elem);
}n/a
notEmpty = function (str) {
return !str.match(/^[\s\t\r\n]*$/);
}n/a
notIn = function (str, values) {
return !this.isIn(str, values);
}n/a
notNull = function () {
throw new Error('Warning "notNull" validation has been deprecated in favor of Schema based "allowNull"');
}n/a
notRegex = function (str, pattern, modifiers) {
return !this.regex(str, pattern, modifiers);
}n/a
regex = function (str, pattern, modifiers) {
str += '';
if (Object.prototype.toString.call(pattern).slice(8, -1) !== 'RegExp') {
pattern = new RegExp(pattern, modifiers);
}
return str.match(pattern);
}n/a
function rtrim(str, chars) {
(0, _assertString2.default)(str);
var pattern = chars ? new RegExp('[' + chars + ']') : /\s/;
var idx = str.length - 1;
while (idx >= 0 && pattern.test(str[idx])) {
idx--;
}
return idx < str.length ? str.substr(0, idx + 1) : str;
}n/a
function stripLow(str, keep_new_lines) {
(0, _assertString2.default)(str);
var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F';
return (0, _blacklist2.default)(str, chars);
}n/a
function toBoolean(str, strict) {
(0, _assertString2.default)(str);
if (strict) {
return str === '1' || str === 'true';
}
return str !== '0' && str !== 'false' && str !== '';
}n/a
function toDate(date) {
(0, _assertString2.default)(date);
date = Date.parse(date);
return !isNaN(date) ? new Date(date) : null;
}n/a
function toFloat(str) {
(0, _assertString2.default)(str);
return parseFloat(str);
}n/a
function toInt(str, radix) {
(0, _assertString2.default)(str);
return parseInt(str, radix || 10);
}n/a
function toString(input) {
if ((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object' && input !== null) {
if (typeof input.toString === 'function') {
input = input.toString();
} else {
input = '[object Object]';
}
} else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) {
input = '';
}
return String(input);
}n/a
function trim(str, chars) {
return (0, _rtrim2.default)((0, _ltrim2.default)(str, chars), chars);
}n/a
function unescape(str) {
(0, _assertString2.default)(str);
return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').
replace(///g, '/').replace(/`/g, '`');
}n/a
function whitelist(str, chars) {
(0, _assertString2.default)(str);
return str.replace(new RegExp('[^' + chars + ']+', 'g'), '');
}n/a
AccessDeniedError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeAccessDeniedError';
}n/a
BaseError = function () {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
}n/a
ConnectionError = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
}n/a
ConnectionRefusedError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeConnectionRefusedError';
}n/a
ConnectionTimedOutError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeConnectionTimedOutError';
}n/a
DatabaseError = function (parent) {
error.BaseError.apply(this, [parent.message]);
this.name = 'SequelizeDatabaseError';
/**
* The database specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
/**
* The SQL that triggered the error
* @member sql
*/
this.sql = parent.sql;
/**
* The message from the DB.
* @member message
* @name message
*/
/**
* The fields of the unique constraint
* @member fields
* @name fields
*/
/**
* The value(s) which triggered the error
* @member value
* @name value
*/
/**
* The name of the index that triggered the error
* @member index
* @name index
*/
}n/a
EmptyResultError = function (message) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeEmptyResultError';
this.message = message;
}n/a
ExclusionConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
error.DatabaseError.call(this, options.parent);
this.name = 'SequelizeExclusionConstraintError';
this.message = options.message || options.parent.message;
this.constraint = options.constraint;
this.fields = options.fields;
this.table = options.table;
}n/a
ForeignKeyConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
error.DatabaseError.call(this, options.parent);
this.name = 'SequelizeForeignKeyConstraintError';
this.message = options.message || options.parent.message || 'Database Error';
this.fields = options.fields;
this.table = options.table;
this.value = options.value;
this.index = options.index;
}n/a
HostNotFoundError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeHostNotFoundError';
}n/a
HostNotReachableError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeHostNotReachableError';
}n/a
InstanceError = function (message) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeInstanceError';
this.message = message;
}n/a
InvalidConnectionError = function (parent) {
error.ConnectionError.call(this, parent);
this.name = 'SequelizeInvalidConnectionError';
}n/a
TimeoutError = function (parent) {
error.DatabaseError.call(this, parent);
this.name = 'SequelizeTimeoutError';
}n/a
UniqueConstraintError = function (options) {
options = options || {};
options.parent = options.parent || { sql: '' };
options.message = options.message || options.parent.message || 'Validation Error';
options.errors = options.errors || {};
error.ValidationError.call(this, options.message, options.errors);
this.name = 'SequelizeUniqueConstraintError';
this.message = options.message;
this.errors = options.errors;
this.fields = options.fields;
this.parent = options.parent;
this.original = options.parent;
this.sql = options.parent.sql;
}n/a
ValidationError = function (message, errors) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeValidationError';
this.message = 'Validation Error';
/**
* An array of ValidationErrorItems
* @member errors
*/
this.errors = errors || [];
// Use provided error message if available...
if (message) {
this.message = message;
// ... otherwise create a concatenated message out of existing errors.
} else if (this.errors.length > 0 && this.errors[0].message) {
this.message = this.errors.map(function(err) {
return err.type + ': ' + err.message;
}).join(',\n');
}
}...
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
} else {
return null;
}
});
};
/**
...ValidationErrorItem = function (message, type, path, value) {
this.message = message || '';
this.type = type || null;
this.path = path || null;
this.value = value || null;
}...
* @param {*} value anything.
* @private
*/
InstanceValidator.prototype._validateSchema = function(rawAttribute, field, value) {
var error;
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be null',
x27;notNull Violation', field, value);
this.errors.push(error);
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes.TEXT
|| rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || (_.isObject(value) && !value._isSequelizeMethod) && !Buffer.isBuffer(value)) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be an array or an object', 'string violation
x27;, field, value);
this.errors.push(error);
...applyTo = function (Model) {
Utils._.mixin(Model, Hooks);
Utils._.mixin(Model.prototype, Hooks);
var allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
allHooks.forEach(function(hook) {
Model.prototype[hook] = function(name, callback) {
return this.addHook(hook, name, callback);
};
});
}n/a
function InstanceValidator(modelInstance, options) {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
skip: []
});
this.modelInstance = modelInstance;
/**
* Exposes a reference to validator.js. This allows you to add custom validations using `validator.extend`
* @name validator
*/
this.validator = validator;
/**
* All errors will be stored here from the validations.
*
* @type {Array} Will contain keys that correspond to attributes which will
* be Arrays of Errors.
*/
this.errors = [];
/** @type {boolean} Indicates if validations are in progress */
this.inProgress = false;
extendModelValidations(modelInstance);
}n/a
function InstanceValidator(modelInstance, options) {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
skip: []
});
this.modelInstance = modelInstance;
/**
* Exposes a reference to validator.js. This allows you to add custom validations using `validator.extend`
* @name validator
*/
this.validator = validator;
/**
* All errors will be stored here from the validations.
*
* @type {Array} Will contain keys that correspond to attributes which will
* be Arrays of Errors.
*/
this.errors = [];
/** @type {boolean} Indicates if validations are in progress */
this.inProgress = false;
extendModelValidations(modelInstance);
}n/a
function InstanceValidator(modelInstance, options) {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.Model.attributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
skip: []
});
this.modelInstance = modelInstance;
/**
* Exposes a reference to validator.js. This allows you to add custom validations using `validator.extend`
* @name validator
*/
this.validator = validator;
/**
* All errors will be stored here from the validations.
*
* @type {Array} Will contain keys that correspond to attributes which will
* be Arrays of Errors.
*/
this.errors = [];
/** @type {boolean} Indicates if validations are in progress */
this.inProgress = false;
extendModelValidations(modelInstance);
}n/a
_builtinAttrValidate = function (value, field) {
var self = this;
// check if value is null (if null not allowed the Schema pass will capture it)
if (value === null || typeof value === 'undefined') {
return Promise.resolve();
}
// Promisify each validator
var validators = [];
Utils._.forIn(this.modelInstance.validators[field], function(test,
validatorType) {
if (['isUrl', 'isURL', 'isEmail'].indexOf(validatorType) !== -1) {
// Preserve backwards compat. Validator.js now expects the second param to isURL and isEmail to be an object
if (typeof test === 'object' && test !== null && test.msg) {
test = {
msg: test.msg
};
} else if (test === true) {
test = {};
}
}
// Check for custom validator.
if (typeof test === 'function') {
return validators.push(self._invokeCustomValidator(test, validatorType, true, value, field).reflect());
}
var validatorPromise = self._invokeBuiltinValidator(value, test, validatorType, field);
// errors are handled in settling, stub this
validatorPromise.catch(function() {});
validators.push(validatorPromise.reflect());
});
return Promise.all(validators).then(this._handleReflectedResult.bind(this, field));
}n/a
_builtinValidators = function () {
var self = this;
// promisify all attribute invocations
var validators = [];
Utils._.forIn(this.modelInstance.rawAttributes, function(rawAttribute, field) {
if (self.options.skip.indexOf(field) >= 0) {
return;
}
var value = self.modelInstance.dataValues[field];
if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
// perform validations based on schema
self._validateSchema(rawAttribute, field, value);
}
if (self.modelInstance.validators.hasOwnProperty(field)) {
validators.push(self._builtinAttrValidate.call(self, value, field).reflect());
}
});
return Promise.all(validators);
}...
if (this.inProgress) {
throw new Error('Validations already in progress.');
}
this.inProgress = true;
var self = this;
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
} else {
..._customValidators = function () {
var validators = [];
var self = this;
Utils._.each(this.modelInstance.$modelOptions.validate, function(validator, validatorType) {
if (self.options.skip.indexOf(validatorType) >= 0) {
return;
}
var valprom = self._invokeCustomValidator(validator, validatorType)
// errors are handled in settling, stub this
.catch(function() {})
.reflect();
validators.push(valprom);
});
return Promise.all(validators);
}...
throw new Error('Validations already in progress.');
}
this.inProgress = true;
var self = this;
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
} else {
return null;
..._extractValidatorArgs = function (test, validatorType, field) {
var validatorArgs = test.args || test;
var isLocalizedValidator = typeof(validatorArgs) !== 'string' && (validatorType === 'isAlpha' || validatorType === 'isAlphanumeric
' || validatorType === 'isMobilePhone');
if (!Array.isArray(validatorArgs)) {
if (validatorType === 'isImmutable') {
validatorArgs = [validatorArgs, field];
} else if (isLocalizedValidator || validatorType === 'isIP') {
validatorArgs = [];
} else {
validatorArgs = [validatorArgs];
}
} else {
validatorArgs = validatorArgs.slice(0);
}
return validatorArgs;
}...
var self = this;
// Cast value as string to pass new Validator.js string requirement
var valueString = String(value);
// check if Validator knows that kind of validation test
if (typeof validator[validatorType] !== 'function') {
throw new Error('Invalid validator function: ' + validatorType);
}
var validatorArgs = self._extractValidatorArgs(test, validatorType, field);
if (!validator[validatorType].apply(validator, [valueString].concat(validatorArgs))) {
// extract the error msg
throw new Error(test.msg || 'Validation ' + validatorType + ' failed');
}
});
/**
..._handleReflectedResult = function (field, promiseInspections) {
var self = this;
promiseInspections.forEach(function(promiseInspection) {
if (promiseInspection.isRejected()) {
var rejection = promiseInspection.error();
self._pushError(true, field, rejection);
}
});
}n/a
_invokeBuiltinValidator = function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.method", ret);
ret._resolveFromSyncValue(value);
return ret;
}...
}
// Check for custom validator.
if (typeof test === 'function') {
return validators.push(self._invokeCustomValidator(test, validatorType, true, value, field).reflect());
}
var validatorPromise = self._invokeBuiltinValidator(value, test, validatorType, field
);
// errors are handled in settling, stub this
validatorPromise.catch(function() {});
validators.push(validatorPromise.reflect());
});
return Promise.all(validators).then(this._handleReflectedResult.bind(this, field));
};
..._invokeCustomValidator = function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.method", ret);
ret._resolveFromSyncValue(value);
return ret;
}...
var validators = [];
var self = this;
Utils._.each(this.modelInstance.$modelOptions.validate, function(validator, validatorType) {
if (self.options.skip.indexOf(validatorType) >= 0) {
return;
}
var valprom = self._invokeCustomValidator(validator, validatorType)
// errors are handled in settling, stub this
.catch(function() {})
.reflect();
validators.push(valprom);
});
..._pushError = function (isBuiltin, errorKey, rawError) {
var message = rawError.message || rawError || 'Validation error';
var error = new sequelizeError.ValidationErrorItem(message, 'Validation error', errorKey, rawError);
error[InstanceValidator.RAW_KEY_NAME] = rawError;
this.errors.push(error);
}...
* @private
*/
InstanceValidator.prototype._handleReflectedResult = function(field, promiseInspections) {
var self = this;
promiseInspections.forEach(function(promiseInspection) {
if (promiseInspection.isRejected()) {
var rejection = promiseInspection.error();
self._pushError(true, field, rejection);
}
});
};
/**
* Signs all errors retaining the original.
*
..._validateSchema = function (rawAttribute, field, value) {
var error;
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be null', 'notNull Violation', field, value);
this.errors.push(error);
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes
.TEXT || rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || (_.isObject(value) && !value._isSequelizeMethod) && !Buffer.isBuffer(value)) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be an array or an object', 'string violation', field, value
);
this.errors.push(error);
}
}
}...
return;
}
var value = self.modelInstance.dataValues[field];
if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
// perform validations based on schema
self._validateSchema(rawAttribute, field, value);
}
if (self.modelInstance.validators.hasOwnProperty(field)) {
validators.push(self._builtinAttrValidate.call(self, value, field).reflect());
}
});
...hookValidate = function () {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function(newError
) {
throw newError || error;
});
}
});
}).then(function() {
return self.modelInstance.Model.runHooks('afterValidate', self.modelInstance, self.options);
}).return(self.modelInstance);
}n/a
validate = function () {
if (this.inProgress) {
throw new Error('Validations already in progress.');
}
this.inProgress = true;
var self = this;
return Promise.all([
self._builtinValidators(),
self._customValidators()
].map(function(promise) {
return promise.reflect();
})).then(function() {
if (self.errors.length) {
return new sequelizeError.ValidationError(null, self.errors);
} else {
return null;
}
});
}...
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
*/
InstanceValidator.prototype.hookValidate = function() {
var self = this;
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance, self.options).then(function() {
return self.validate().then(function(error) {
if (error) {
return self.modelInstance.Model.runHooks('validationFailed', self.modelInstance, self.options, error).then(function
(newError) {
throw newError || error;
});
}
});
}).then(function() {
...model_manager = function (sequelize) {
this.models = [];
this.sequelize = sequelize;
}n/a
ModelManager = function (sequelize) {
this.models = [];
this.sequelize = sequelize;
}n/a
default = function (sequelize) {
this.models = [];
this.sequelize = sequelize;
}n/a
addModel = function (model) {
this.models.push(model);
this.sequelize.models[model.name] = model;
return model;
}n/a
forEachModel = function (iterator, options) {
var models = {}
, sorter = new Toposort()
, sorted
, dep;
options = _.defaults(options || {}, {
reverse: true
});
this.models.forEach(function(model) {
var deps = []
, tableName = model.getTableName();
if (_.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
models[tableName] = model;
for (var attrName in model.rawAttributes) {
if (model.rawAttributes.hasOwnProperty(attrName)) {
var attribute = model.rawAttributes[attrName];
if (attribute.references) {
attribute = Utils.formatReferences(attribute);
dep = attribute.references.model;
if (_.isObject(dep)) {
dep = dep.schema + '.' + dep.tableName;
}
deps.push(dep);
}
}
}
deps = deps.filter(function(dep) {
return tableName !== dep;
});
sorter.add(tableName, deps);
});
sorted = sorter.sort();
if (options.reverse) {
sorted = sorted.reverse();
}
sorted.forEach(function(name) {
iterator(models[name], name);
});
}n/a
getModel = function (against, options) {
options = _.defaults(options || {}, {
attribute: 'name'
});
var model = this.models.filter(function(model) {
return model[options.attribute] === against;
});
return !!model ? model[0] : null;
}...
return this.sequelize.query(sql, options).then(function() {
var 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' });
if (!!instanceTable) {
var getTableName = (!options || !options.schema || options.schema === 'public' ? '' : options.schema + '
;_') + tableName;
var keys = Object.keys(instanceTable.rawAttributes)
, keyLen = keys.length
, i = 0;
...removeModel = function (model) {
this.models = this.models.filter(function($model) {
return $model.name !== model.name;
});
delete this.sequelize.models[model.name];
}n/a
BIGINT = function () {
if (!(this instanceof BIGINT)) return new BIGINT();
BaseTypes.BIGINT.apply(this, arguments);
// MSSQL does not support any options for bigint
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('MSSQL does not support BIGINT with options. Plain `BIGINT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
BLOB = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
BOOLEAN = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
ENUM = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
FLOAT = function () {
if (!(this instanceof FLOAT)) return new FLOAT();
BaseTypes.FLOAT.apply(this, arguments);
// MSSQL does only support lengths as option.
// Values between 1-24 result in 7 digits precision (4 bytes storage size)
// Values between 25-53 result in 15 digits precision (8 bytes storage size)
// If decimals are provided remove these and print a warning
if (this._decimals) {
warn('MSSQL does not support Float with decimals. Plain `FLOAT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
}
if (this._unsigned) {
warn('MSSQL does not support Float unsigned. `UNSIGNED` was removed.');
this._unsigned = undefined;
}
if (this._zerofill) {
warn('MSSQL does not support Float zerofill. `ZEROFILL` was removed.');
this._zerofill = undefined;
}
}n/a
INTEGER = function () {
if (!(this instanceof INTEGER)) return new INTEGER();
BaseTypes.INTEGER.apply(this, arguments);
// MSSQL does not support any options for integer
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('MSSQL does not support INTEGER with options. Plain `INTEGER` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
NOW = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
REAL = function () {
if (!(this instanceof REAL)) return new REAL();
BaseTypes.REAL.apply(this, arguments);
// MSSQL does not support any options for real
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('MSSQL does not support REAL with options. Plain `REAL` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
STRING = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
TEXT = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
UUID = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
BIGINT = function () {
if (!(this instanceof BIGINT)) return new BIGINT();
BaseTypes.BIGINT.apply(this, arguments);
// MSSQL does not support any options for bigint
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('MSSQL does not support BIGINT with options. Plain `BIGINT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
BLOB = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
if (this._length) {
if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8
warn('MSSQL does not support BLOB with the `length` = `tiny` option. `VARBINARY(256)` will be used instead.');
return 'VARBINARY(256)';
}
warn('MSSQL does not support BLOB with the `length` option. `VARBINARY(MAX)` will be used instead.');
}
return 'VARBINARY(MAX)';
}n/a
BOOLEAN = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'BIT';
}n/a
DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'DATETIME2';
}n/a
ENUM = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'VARCHAR(255)';
}n/a
FLOAT = function () {
if (!(this instanceof FLOAT)) return new FLOAT();
BaseTypes.FLOAT.apply(this, arguments);
// MSSQL does only support lengths as option.
// Values between 1-24 result in 7 digits precision (4 bytes storage size)
// Values between 25-53 result in 15 digits precision (8 bytes storage size)
// If decimals are provided remove these and print a warning
if (this._decimals) {
warn('MSSQL does not support Float with decimals. Plain `FLOAT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
}
if (this._unsigned) {
warn('MSSQL does not support Float unsigned. `UNSIGNED` was removed.');
this._unsigned = undefined;
}
if (this._zerofill) {
warn('MSSQL does not support Float zerofill. `ZEROFILL` was removed.');
this._zerofill = undefined;
}
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
INTEGER = function () {
if (!(this instanceof INTEGER)) return new INTEGER();
BaseTypes.INTEGER.apply(this, arguments);
// MSSQL does not support any options for integer
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('MSSQL does not support INTEGER with options. Plain `INTEGER` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
NOW = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'GETDATE()';
}n/a
REAL = function () {
if (!(this instanceof REAL)) return new REAL();
BaseTypes.REAL.apply(this, arguments);
// MSSQL does not support any options for real
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('MSSQL does not support REAL with options. Plain `REAL` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
STRING = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
if (!this._binary) {
return 'NVARCHAR(' + this._length + ')';
} else{
return 'BINARY(' + this._length + ')';
}
}n/a
TEXT = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
// TEXT is deprecated in mssql and it would normally be saved as a non-unicode string.
// Using unicode is just future proof
if (this._length) {
if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8
warn('MSSQL does not support TEXT with the `length` = `tiny` option. `NVARCHAR(256)` will be used instead.');
return 'NVARCHAR(256)';
}
warn('MSSQL does not support TEXT with the `length` option. `NVARCHAR(MAX)` will be used instead.');
}
return 'NVARCHAR(MAX)';
}n/a
UUID = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'CHAR(36)';
}n/a
DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
ENUM = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
GEOMETRY = function () {
if (!(this instanceof GEOMETRY)) return new GEOMETRY();
BaseTypes.GEOMETRY.apply(this, arguments);
if (_.isEmpty(this.type)) {
this.sqlType = this.key;
} else if (_.includes(SUPPORTED_GEOMETRY_TYPES, this.type)) {
this.sqlType = this.type;
} else {
throw new Error('Supported geometry types are: ' + SUPPORTED_GEOMETRY_TYPES.join(', '));
}
}n/a
UUID = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (value, options) {
value = value.string();
if (value === null) {
return value;
}
if (moment.tz.zone(options.timezone)) {
value = moment.tz(value, options.timezone).toDate();
} else {
value = new Date(value + ' ' + options.timezone);
}
return value;
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'DATETIME' + (this._length ? '(' + this._length + ')' : '');
}n/a
ENUM = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function (options) {
return 'ENUM(' + _.map(this.values, function(value) {
return options.escape(value);
}).join(', ') + ')';
}n/a
GEOMETRY = function () {
if (!(this instanceof GEOMETRY)) return new GEOMETRY();
BaseTypes.GEOMETRY.apply(this, arguments);
if (_.isEmpty(this.type)) {
this.sqlType = this.key;
} else if (_.includes(SUPPORTED_GEOMETRY_TYPES, this.type)) {
this.sqlType = this.type;
} else {
throw new Error('Supported geometry types are: ' + SUPPORTED_GEOMETRY_TYPES.join(', '));
}
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (value) {
value = value.buffer();
//MySQL doesn't support POINT EMPTY, https://dev.mysql.com/worklog/task/?id=2381
if (value === null) {
return null;
}
// For some reason, discard the first 4 bytes
value = value.slice(4);
return wkx.Geometry.parse(value).toGeoJSON();
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
parse = function (value) {
value = value.buffer();
//MySQL doesn't support POINT EMPTY, https://dev.mysql.com/worklog/task/?id=2381
if (value === null) {
return null;
}
// For some reason, discard the first 4 bytes
value = value.slice(4);
return wkx.Geometry.parse(value).toGeoJSON();
}n/a
toSql = function () {
return this.sqlType;
}n/a
UUID = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'CHAR(36) BINARY';
}n/a
BIGINT = function () {
if (!(this instanceof BIGINT)) return new BIGINT();
BaseTypes.BIGINT.apply(this, arguments);
// POSTGRES does not support any parameters for bigint
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('PostgreSQL does not support BIGINT with options. Plain `BIGINT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
BLOB = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
BOOLEAN = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
CHAR = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
DECIMAL = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
FLOAT = function () {
if (!(this instanceof FLOAT)) return new FLOAT();
BaseTypes.FLOAT.apply(this, arguments);
// POSTGRES does only support lengths as parameter.
// Values between 1-24 result in REAL
// Values between 25-53 result in DOUBLE PRECISION
// If decimals are provided remove these and print a warning
if (this._decimals) {
warn('PostgreSQL does not support FLOAT with decimals. Plain `FLOAT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._decimals = undefined;
}
if (this._unsigned) {
warn('PostgreSQL does not support FLOAT unsigned. `UNSIGNED` was removed.');
this._unsigned = undefined;
}
if (this._zerofill) {
warn('PostgreSQL does not support FLOAT zerofill. `ZEROFILL` was removed.');
this._zerofill = undefined;
}
}n/a
GEOGRAPHY = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
GEOMETRY = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
HSTORE = function () {
if (!(this instanceof HSTORE)) return new HSTORE();
BaseTypes.HSTORE.apply(this, arguments);
if (!hstore) {
// All datatype files are loaded at import - make sure we don't load the hstore parser before a hstore is instantiated
hstore = require('./hstore');
}
}n/a
INTEGER = function () {
if (!(this instanceof INTEGER)) return new INTEGER();
BaseTypes.INTEGER.apply(this, arguments);
// POSTGRES does not support any parameters for integer
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('PostgreSQL does not support INTEGER with options. Plain `INTEGER` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
RANGE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
REAL = function () {
if (!(this instanceof REAL)) return new REAL();
BaseTypes.REAL.apply(this, arguments);
// POSTGRES does not support any parameters for real
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('PostgreSQL does not support REAL with options. Plain `REAL` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
STRING = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
TEXT = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
BIGINT = function () {
if (!(this instanceof BIGINT)) return new BIGINT();
BaseTypes.BIGINT.apply(this, arguments);
// POSTGRES does not support any parameters for bigint
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('PostgreSQL does not support BIGINT with options. Plain `BIGINT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
BLOB = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
if (this._length) {
warn('PostgreSQL does not support BLOB (BYTEA) with options. Plain `BYTEA` will be used instead.');
this._length = undefined;
}
return 'BYTEA';
}n/a
BOOLEAN = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'BOOLEAN';
}n/a
CHAR = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
if (this._binary) {
return 'BYTEA';
}
return BaseTypes.CHAR.prototype.toSql.call(this);
}n/a
DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'TIMESTAMP WITH TIME ZONE';
}n/a
DECIMAL = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (value) {
return value;
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
FLOAT = function () {
if (!(this instanceof FLOAT)) return new FLOAT();
BaseTypes.FLOAT.apply(this, arguments);
// POSTGRES does only support lengths as parameter.
// Values between 1-24 result in REAL
// Values between 25-53 result in DOUBLE PRECISION
// If decimals are provided remove these and print a warning
if (this._decimals) {
warn('PostgreSQL does not support FLOAT with decimals. Plain `FLOAT` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._decimals = undefined;
}
if (this._unsigned) {
warn('PostgreSQL does not support FLOAT unsigned. `UNSIGNED` was removed.');
this._unsigned = undefined;
}
if (this._zerofill) {
warn('PostgreSQL does not support FLOAT zerofill. `ZEROFILL` was removed.');
this._zerofill = undefined;
}
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
GEOGRAPHY = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (value) {
var b = new Buffer(value, 'hex');
return wkx.Geometry.parse(b).toGeoJSON();
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
parse = function (value) {
var b = new Buffer(value, 'hex');
return wkx.Geometry.parse(b).toGeoJSON();
}n/a
toSql = function () {
var result = 'GEOGRAPHY';
if (this.type){
result += '(' + this.type;
if (this.srid){
result += ',' + this.srid;
}
result += ')';
}
return result;
}n/a
GEOMETRY = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (value) {
var b = new Buffer(value, 'hex');
return wkx.Geometry.parse(b).toGeoJSON();
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
parse = function (value) {
var b = new Buffer(value, 'hex');
return wkx.Geometry.parse(b).toGeoJSON();
}n/a
toSql = function () {
var result = this.key;
if (this.type){
result += '(' + this.type;
if (this.srid){
result += ',' + this.srid;
}
result += ')';
}
return result;
}n/a
HSTORE = function () {
if (!(this instanceof HSTORE)) return new HSTORE();
BaseTypes.HSTORE.apply(this, arguments);
if (!hstore) {
// All datatype files are loaded at import - make sure we don't load the hstore parser before a hstore is instantiated
hstore = require('./hstore');
}
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (value) {
if (!hstore) {
// All datatype files are loaded at import - make sure we don't load the hstore parser before a hstore is instantiated
hstore = require('./hstore');
}
return hstore.parse(value);
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
INTEGER = function () {
if (!(this instanceof INTEGER)) return new INTEGER();
BaseTypes.INTEGER.apply(this, arguments);
// POSTGRES does not support any parameters for integer
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('PostgreSQL does not support INTEGER with options. Plain `INTEGER` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (value) {
return parseInt(value, 10);
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
RANGE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (value, oid, getTypeParser) {
var parser = getTypeParser(RANGE.oid_map[oid]);
return range.parse(value, parser);
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
REAL = function () {
if (!(this instanceof REAL)) return new REAL();
BaseTypes.REAL.apply(this, arguments);
// POSTGRES does not support any parameters for real
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn('PostgreSQL does not support REAL with options. Plain `REAL` will be used instead.');
this._length = undefined;
this.options.length = undefined;
this._unsigned = undefined;
this._zerofill = undefined;
}
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
STRING = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
if (this._binary) {
return 'BYTEA';
}
return BaseTypes.STRING.prototype.toSql.call(this);
}n/a
TEXT = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
if (this._length) {
warn('PostgreSQL does not support TEXT with options. Plain `TEXT` will be used instead.');
this._length = undefined;
}
return 'TEXT';
}n/a
query_interface = function (sequelize) {
this.sequelize = sequelize;
this.QueryGenerator = this.sequelize.dialect.QueryGenerator;
}n/a
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);
}n/a
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;
}
options = Utils.cloneDeep(options);
options.fields = attributes;
var sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false }));
}n/a
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);
}n/a
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);
}n/a
bulkUpdate = function (tableName, values, identifier, options, attributes) {
options = Utils.cloneDeep(options);
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
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 });
options.model = model;
return this.sequelize.query(sql, options);
}n/a
changeColumn = function (tableName, attributeName, dataTypeOrOptions, options) {
var attributes = {};
options = options || {};
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 change a column
return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options);
} else {
var query = this.QueryGenerator.attributesToSQL(attributes)
, sql = this.QueryGenerator.changeColumnQuery(tableName, query);
return this.sequelize.query(sql, options);
}
}n/a
commitTransaction = function (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();
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction,
supportsSearchPath: false
});
var sql = this.QueryGenerator.commitTransactionQuery(transaction);
var promise = this.sequelize.query(sql, options);
transaction.finished = 'commit';
return promise;
}n/a
createFunction = function (functionName, params, returnType, language, body, options) {
var sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}...
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
};
QueryInterface.prototype.createFunction = function(functionName, params, returnType, language, body, options) {
var sql = this.QueryGenerator.createFunction(functionName, params, returnType, language
, body, options);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
...createSchema = function (schema, options) {
options = options || {};
var sql = this.QueryGenerator.createSchema(schema);
return this.sequelize.query(sql, options);
}...
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);
...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 })
));
}
}
return Promise.all(promises).then(function(results) {
var promises = []
, 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 = 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];
}
valueOptions.supportsSearchPath = false;
promises.push(self.sequelize.query(self.QueryGenerator.pgEnumAdd(tableName, keys[i], value, valueOptions), valueOptions
));
}
});
enumIdx++;
}
}
}
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 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
});
}
attributes = self.QueryGenerator.attributesToSQL(attributes, {
context: 'createTable'
});
sql = self.QueryGenerator.createTableQuery(tableName, attributes, options);
return self.sequelize.query(sql, options);
}
}n/a
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();
}
}...
}
return result;
});
};
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();
}
};
...databaseVersion = function (options) {
return this.sequelize.query(
this.QueryGenerator.versionQuery(),
_.assign({}, options, { type: QueryTypes.VERSION })
);
}n/a
deferConstraints = function (transaction, options) {
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
var sql = this.QueryGenerator.deferConstraintsQuery(options);
if (sql) {
return this.sequelize.query(sql, options);
}
return Promise.resolve();
}n/a
delete = function (instance, tableName, identifier, options) {
var self = this
, cascades = []
, sql = self.QueryGenerator.deleteQuery(tableName, identifier, null, instance.Model);
options = _.clone(options) || {};
// Check for a restrict field
if (!!instance.Model && !!instance.Model.associations) {
var keys = Object.keys(instance.Model.associations)
, length = keys.length
, association;
for (var i = 0; i < length; i++) {
association = instance.Model.associations[keys[i]];
if (association.options && association.options.onDelete &&
association.options.onDelete.toLowerCase() === 'cascade' &&
association.options.useHooks === true) {
cascades.push(association.accessors.get);
}
}
}
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();
}
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);
});
}n/a
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);
}
});
}...
return this.sequelize.query(sql, options);
}
};
QueryInterface.prototype.renameColumn = function(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
return this.describeTable(tableName, options).then(function(data) {
data = data[attrNameBefore] || {};
var _options = {};
_options[attrNameAfter] = {
attribute: attrNameAfter,
type: data.type,
...dropAllEnums = function (options) {
if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve();
}
options = options || {};
var self = this;
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 })
);
});
}n/a
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);
});
}
}n/a
dropAllTables = function (options) {
var self = this
, skip;
options = options || {};
skip = options.skip || [];
var dropAllTables = function(tableNames) {
return Promise.each(tableNames, function(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 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);
});
});
} 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(function() {
return dropAllTables(tableNames);
});
});
}
});
}n/a
dropFunction = function (functionName, params, options) {
var sql = this.QueryGenerator.dropFunction(functionName, params);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}...
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 || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
...dropSchema = function (schema, options) {
options = options || {};
var sql = this.QueryGenerator.dropSchema(schema);
return this.sequelize.query(sql, 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;
...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;
var sql = this.QueryGenerator.dropTableQuery(tableName, options)
, self = this;
return this.sequelize.query(sql, options).then(function() {
var 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' });
if (!!instanceTable) {
var getTableName = (!options || !options.schema || options.schema === 'public' ? '' : options.schema + '_') + tableName;
var keys = Object.keys(instanceTable.rawAttributes)
, keyLen = keys.length
, i = 0;
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 })));
}
}
}
}
return Promise.all(promises).get(0);
});
}...
options = options || {};
skip = options.skip || [];
var dropAllTables = function(tableNames) {
return Promise.each(tableNames, function(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 self.showAllTables(options).then(function(tableNames) {
if (self.sequelize.options.dialect === 'sqlite') {
return self.sequelize.query('PRAGMA foreign_keys;', options).then(function(result) {
...dropTrigger = function (tableName, triggerName, options) {
var sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}...
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
};
QueryInterface.prototype.dropTrigger = function(tableName, triggerName, options) {
var sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
...escape = function (value) {
return this.QueryGenerator.escape(value);
}...
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
};
/**
* Escape a value (e.g. a string, number or date)
*/
QueryInterface.prototype.escape = function(value) {
return this.QueryGenerator.escape(value);
};
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 (transaction.parent) {
...getForeignKeysForTables = function (tableNames, options) {
var self = this;
options = options || {};
if (tableNames.length === 0) {
return Promise.resolve({});
}
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 = {};
tableNames.forEach(function(tableName, i) {
if (Utils._.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
result[tableName] = Utils._.compact(results[i]).map(function(r) {
return r.constraint_name;
});
});
return result;
});
}...
});
});
} 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;
}
...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);
}n/a
insert = function (instance, tableName, values, options) {
options = Utils.cloneDeep(options);
options.hasTrigger = instance && instance.Model.options.hasTrigger;
var sql = this.QueryGenerator.insertQuery(tableName, values, instance && instance.Model.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;
});
}n/a
nameIndexes = function (indexes, rawTablename) {
return this.QueryGenerator.nameIndexes(indexes, rawTablename);
}...
QueryInterface.prototype.showIndex = function(tableName, options) {
var sql = this.QueryGenerator.showIndexesQuery(tableName, options);
return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
};
QueryInterface.prototype.nameIndexes = function(indexes, rawTablename) {
return this.QueryGenerator.nameIndexes(indexes, rawTablename);
};
QueryInterface.prototype.getForeignKeysForTables = function(tableNames, options) {
var self = this;
options = options || {};
if (tableNames.length === 0) {
...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 }));
}...
// 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 })
));
}
}
...quoteIdentifier = function (identifier, force) {
return this.QueryGenerator.quoteIdentifier(identifier, force);
}...
/**
* 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);
};
QueryInterface.prototype.quoteTable = function(identifier) {
return this.QueryGenerator.quoteTable(identifier);
};
/**
...quoteIdentifiers = function (identifiers, force) {
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
}...
/**
* 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);
};
/**
* Escape a value (e.g. a string, number or date)
*/
QueryInterface.prototype.escape = function(value) {
return this.QueryGenerator.escape(value);
...quoteTable = function (identifier) {
return this.QueryGenerator.quoteTable(identifier);
}...
* false.
*/
QueryInterface.prototype.quoteIdentifier = function(identifier, force) {
return this.QueryGenerator.quoteIdentifier(identifier, force);
};
QueryInterface.prototype.quoteTable = function(identifier) {
return this.QueryGenerator.quoteTable(identifier);
};
/**
* 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.
*/
...rawSelect = function (tableName, options, attributeSelector, Model) {
if (options.schema) {
tableName = this.QueryGenerator.addSchema({
tableName: tableName,
$schema: options.schema
});
}
options = Utils.cloneDeep(options);
options = _.defaults(options, {
raw: true,
plain: true,
type: QueryTypes.SELECT
});
var sql = this.QueryGenerator.selectQuery(tableName, options, Model);
if (attributeSelector === undefined) {
throw new Error('Please pass an attribute selector!');
}
return this.sequelize.query(sql, options).then(function(data) {
if (!options.plain) {
return data;
}
var result = data ? data[attributeSelector] : null;
if (options && options.dataType) {
var 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;
});
}n/a
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':
case 'mariadb':
// mysql/maria 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);
}
}n/a
removeIndex = function (tableName, indexNameOrAttributes, options) {
options = options || {};
var sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes);
return this.sequelize.query(sql, options);
}n/a
renameColumn = function (tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
return this.describeTable(tableName, options).then(function(data) {
data = data[attrNameBefore] || {};
var _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 {
var sql = this.QueryGenerator.renameColumnQuery(
tableName,
attrNameBefore,
this.QueryGenerator.attributesToSQL(_options)
);
return this.sequelize.query(sql, options);
}
}.bind(this));
}n/a
renameFunction = function (oldFunctionName, params, newFunctionName, options) {
var sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}...
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
};
QueryInterface.prototype.renameFunction = function(oldFunctionName, params, newFunctionName, options) {
var sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName
);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
...renameTable = function (before, after, options) {
options = options || {};
var sql = this.QueryGenerator.renameTableQuery(before, after);
return this.sequelize.query(sql, options);
}n/a
renameTrigger = function (tableName, oldTriggerName, newTriggerName, options) {
var sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}...
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 || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
...rollbackTransaction = function (transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to rollback a transaction without transaction object!');
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction,
supportsSearchPath: false
});
options.transaction.name = transaction.parent ? transaction.name : undefined;
var sql = this.QueryGenerator.rollbackTransactionQuery(transaction);
var promise = this.sequelize.query(sql, options);
transaction.finished = 'rollback';
return promise;
}n/a
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
);
}n/a
setAutocommit = function (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();
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
var sql = this.QueryGenerator.setAutocommitQuery(value, {
parent: transaction.parent
});
if (!sql) return Promise.resolve();
return this.sequelize.query(sql, options);
}n/a
setIsolationLevel = function (transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set isolation level for a transaction without transaction object!');
}
if (transaction.parent) {
// Not possible to set a seperate isolation level for savepoints
return Promise.resolve();
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
var sql = this.QueryGenerator.setIsolationLevelQuery(value, {
parent: transaction.parent
});
if (!sql) return Promise.resolve();
return this.sequelize.query(sql, options);
}n/a
showAllSchemas = function (options) {
var self = this;
options = _.assign({}, options, {
raw: true,
type: this.sequelize.QueryTypes.SELECT
});
var showSchemasSql = self.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);
})
);
});
}...
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);
});
}
};
QueryInterface.prototype.showAllSchemas = function(options) {
var self = this;
...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);
});
}...
// 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 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() {
...showIndex = function (tableName, options) {
var sql = this.QueryGenerator.showIndexesQuery(tableName, options);
return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
}n/a
startTransaction = function (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
});
options.transaction.name = transaction.parent ? transaction.name : undefined;
var sql = this.QueryGenerator.startTransactionQuery(transaction);
return this.sequelize.query(sql, options);
}n/a
update = function (instance, tableName, values, identifier, options) {
options = _.clone(options || {});
options.hasTrigger = !!(instance && instance.$modelOptions && instance.$modelOptions.hasTrigger);
var self = this
, restrict = false
, sql = self.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.Model.rawAttributes);
options.type = QueryTypes.UPDATE;
// Check for a restrict field
if (!!instance.Model && !!instance.Model.associations) {
var keys = Object.keys(instance.Model.associations)
, length = keys.length;
for (var i = 0; i < length; i++) {
if (instance.Model.associations[keys[i]].options && instance.Model.associations[keys[i]].options.onUpdate && instance.Model
.associations[keys[i]].options.onUpdate === 'restrict') {
restrict = true;
}
}
}
options.instance = instance;
return this.sequelize.query(sql, options);
}n/a
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) {
if (Utils._.intersection(attributes, index).length === index.length) {
where = {};
index.forEach(function (field) {
where[field] = valuesByField[field];
});
wheres.push(where);
}
});
where = { $or: wheres };
options.type = QueryTypes.UPSERT;
options.raw = true;
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;
}
// 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 rowCount === 1;
});
}n/a
escape = function (val, timeZone, dialect, format) {
var prependN = false;
if (val === undefined || val === null) {
return 'NULL';
}
switch (typeof val) {
case 'boolean':
// SQLite doesn't have true/false support. MySQL aliases true/false to 1/0
// for us. Postgres actually has a boolean type with true/false literals,
// but sequelize doesn't use it yet.
if (dialect === 'sqlite' || dialect === 'mssql') {
return +!!val;
}
return '' + !!val;
case 'number':
return val + '';
case 'string':
// In mssql, prepend N to all quoted vals which are originally a string (for
// unicode compatibility)
prependN = dialect === 'mssql';
break;
}
if (val instanceof Date) {
val = dataTypes[dialect].DATE.prototype.stringify(val, { timezone: timeZone });
}
if (Buffer.isBuffer(val)) {
if (dataTypes[dialect].BLOB) {
return dataTypes[dialect].BLOB.prototype.stringify(val);
}
return dataTypes.BLOB.prototype.stringify(val);
}
if (Array.isArray(val)) {
var escape = _.partial(SqlString.escape, _, timeZone, dialect, format);
if (dialect === 'postgres' && !format) {
return dataTypes.ARRAY.prototype.stringify(val, {escape: escape});
}
return val.map(escape);
}
if (dialect === 'postgres' || dialect === 'sqlite' || dialect === 'mssql') {
// http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
// http://stackoverflow.com/q/603572/130598
val = val.replace(/'/g, "''");
} else {
val = val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) {
switch (s) {
case '\0': return '\\0';
case '\n': return '\\n';
case '\r': return '\\r';
case '\b': return '\\b';
case '\t': return '\\t';
case '\x1a': return '\\Z';
default: return '\\' + s;
}
});
}
return (prependN ? "N'" : "'") + val + "'";
}...
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
};
/**
* Escape a value (e.g. a string, number or date)
*/
QueryInterface.prototype.escape = function(value) {
return this.QueryGenerator.escape(value);
};
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 (transaction.parent) {
...escapeId = function (val, forbidQualified) {
if (forbidQualified) {
return '`' + val.replace(/`/g, '``') + '`';
}
return '`' + val.replace(/`/g, '``').replace(/\./g, '`.`') + '`';
}n/a
format = function (sql, values, timeZone, dialect) {
values = [].concat(values);
return sql.replace(/\?/g, function(match) {
if (!values.length) {
return match;
}
return SqlString.escape(values.shift(), timeZone, dialect, true);
});
}n/a
formatNamedParameters = function (sql, values, timeZone, dialect) {
return sql.replace(/\:+(?!\d)(\w+)/g, function(value, key) {
if ('postgres' === dialect && '::' === value.slice(0, 2)) {
return value;
}
if (values[key] !== undefined) {
return SqlString.escape(values[key], timeZone, dialect, true);
} else {
throw new Error('Named parameter "' + value + '" has no value in the given object.');
}
});
}n/a
BIGINT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BIGINT)) return new BIGINT(options);
BaseTypes.BIGINT.call(this, options);
}n/a
CHAR = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
ENUM = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
FLOAT = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof FLOAT)) return new FLOAT(options);
BaseTypes.FLOAT.call(this, options);
}n/a
INTEGER = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof INTEGER)) return new INTEGER(options);
BaseTypes.INTEGER.call(this, options);
}n/a
NUMBER = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
REAL = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof REAL)) return new REAL(options);
BaseTypes.REAL.call(this, options);
}n/a
STRING = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
TEXT = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
BIGINT = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BIGINT)) return new BIGINT(options);
BaseTypes.BIGINT.call(this, options);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return NUMBER.prototype.toSql.call(this);
}n/a
CHAR = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
if (this._binary) {
return 'CHAR BINARY(' + this._length + ')';
} else {
return BaseTypes.CHAR.prototype.toSql.call(this);
}
}n/a
DATE = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (date, options) {
if (date.indexOf('+') === -1) {
// For backwards compat. Dates inserted by sequelize < 2.0dev12 will not have a timestamp set
return new Date(date + options.timezone);
} else {
return new Date(date); // We already have a timezone stored in the string
}
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
ENUM = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return 'TEXT';
}n/a
FLOAT = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof FLOAT)) return new FLOAT(options);
BaseTypes.FLOAT.call(this, options);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (value) {
if (_.isString(value)) {
if (value === 'NaN') {
return NaN;
} else if (value === 'Infinity') {
return Infinity;
} else if (value === '-Infinity') {
return -Infinity;
}
}
return value;
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return NUMBER.prototype.toSql.call(this);
}n/a
INTEGER = function (length) {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof INTEGER)) return new INTEGER(options);
BaseTypes.INTEGER.call(this, options);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return NUMBER.prototype.toSql.call(this);
}n/a
NUMBER = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
var result = this.key;
if (this._unsigned) {
result += ' UNSIGNED';
}
if (this._zerofill) {
result += ' ZEROFILL';
}
if (this._length) {
result += '(' + this._length;
if (typeof this._decimals === 'number') {
result += ',' + this._decimals;
}
result += ')';
}
return result;
}n/a
REAL = function (length, decimals) {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof REAL)) return new REAL(options);
BaseTypes.REAL.call(this, options);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...parse = function (value) {
if (_.isString(value)) {
if (value === 'NaN') {
return NaN;
} else if (value === 'Infinity') {
return Infinity;
} else if (value === '-Infinity') {
return -Infinity;
}
}
return value;
}n/a
super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
return NUMBER.prototype.toSql.call(this);
}n/a
STRING = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
if (this._binary) {
return 'VARCHAR BINARY(' + this._length + ')';
} else {
return BaseTypes.STRING.prototype.toSql.call(this);
}
}n/a
TEXT = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
}n/a
extend = function (oldType) {
return new DataType(oldType.options);
}n/a
inherits = function (Constructor) {
var baseType = this;
if (!Constructor) {
Constructor = function () {
if (!(this instanceof Constructor)) {
var args = [null].concat(arguments);
var FactoryFunction = Constructor.bind.apply(Constructor, args);
return new FactoryFunction();
}
baseType.apply(this, arguments);
};
}
util.inherits(Constructor, baseType); // Instance (prototype) methods
_.extend(Constructor, this); // Static methods
return Constructor;
}...
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
/**
* Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` property,
* which is an array with 1 or more ValidationErrorItems, one for each validation that failed.
*
* @param {string} message Error message
...super_ = function (options) {
}n/a
warn = function (link, text) {
if (!warnings[text]) {
warnings[text] = true;
console.warn('>> WARNING:', text, '\n>> Check:', link);
}
}n/a
toSql = function () {
if (this._length) {
warn('SQLite does not support TEXT with options. Plain `TEXT` will be used instead.');
this._length = undefined;
}
return 'TEXT';
}n/a