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

Commit b5057239 by Sushant

fix(findOrCreate): warn and handle unknown attributes in defaults

1 parent a9cf4228
......@@ -2090,6 +2090,15 @@ class Model {
options = _.assign({}, options);
if (options.defaults) {
const defaults = Object.keys(options.defaults);
const unknownDefaults = defaults.filter(name => !this.rawAttributes[name]);
if (unknownDefaults.length) {
Utils.warn(`Unknown attributes (${unknownDefaults}) passed to defaults option of findOrCreate`);
}
}
if (options.transaction === undefined && this.sequelize.constructor._cls) {
const t = this.sequelize.constructor._cls.get('transaction');
if (t) {
......@@ -2130,7 +2139,9 @@ class Model {
const flattenedWhere = Utils.flattenObjectDeep(options.where);
const flattenedWhereKeys = _.map(_.keys(flattenedWhere), name => _.last(_.split(name, '.')));
const whereFields = flattenedWhereKeys.map(name => _.get(this.rawAttributes, `${name}.field`, name));
const defaultFields = options.defaults && Object.keys(options.defaults).map(name => this.rawAttributes[name].field || name);
const defaultFields = options.defaults && Object.keys(options.defaults)
.filter(name => this.rawAttributes[name])
.map(name => this.rawAttributes[name].field || name);
if (defaultFields) {
if (!_.intersection(Object.keys(err.fields), whereFields).length && _.intersection(Object.keys(err.fields), defaultFields).length) {
......
......@@ -104,6 +104,36 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
});
it('should error correctly when defaults contain a unique key and a non-existent field', function() {
const User = this.sequelize.define('user', {
objectId: {
type: DataTypes.STRING,
unique: true
},
username: {
type: DataTypes.STRING,
unique: true
}
});
return User.sync({force: true}).then(() => {
return User.create({
username: 'gottlieb'
});
}).then(() => {
return expect(User.findOrCreate({
where: {
objectId: 'asdasdasd'
},
defaults: {
username: 'gottlieb',
foo: 'bar', // field that's not a defined attribute
bar: 121
}
})).to.eventually.be.rejectedWith(Sequelize.UniqueConstraintError);
});
});
it('should error correctly when defaults contain a unique key and the where clause is complex', function() {
const User = this.sequelize.define('user', {
objectId: {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!