Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 53 additions & 60 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,54 @@ class Model {
return index;
}


static _uniqIncludes(options) {
if (!options.include) return;

options.include = _(options.include)
.groupBy(include => `${include.model && include.model.name}-${include.as}`)
.map(includes => this._assignOptions(...includes))
.value();
}

static _baseMerge(...args) {
_.assignWith(...args);
this._conformOptions(args[0]);
this._uniqIncludes(args[0]);
return args[0];
}

static _mergeFunction(objValue, srcValue, key) {
if (Array.isArray(objValue) && Array.isArray(srcValue)) {
return _.union(objValue, srcValue);
} else if (key === 'where') {
if (srcValue instanceof Utils.SequelizeMethod) {
srcValue = { [Op.and]: srcValue };
}
if (_.isPlainObject(objValue) && _.isPlainObject(srcValue)) {
return Object.assign(objValue, srcValue);
}
} else if (key === 'attributes' && _.isPlainObject(objValue) && _.isPlainObject(srcValue)) {
return _.assignWith(objValue, srcValue, (objValue, srcValue) => {
if (Array.isArray(objValue) && Array.isArray(srcValue)) {
return _.union(objValue, srcValue);
}
});
}
return srcValue === undefined ? objValue : srcValue;
}

static _assignOptions(...args) {
return this._baseMerge(...args, this._mergeFunction);
}

static _defaultsOptions(...args) {
return this._baseMerge(...args, (...cbArgs) => {
[cbArgs[0], cbArgs[1]] = [cbArgs[1], cbArgs[0]];
return this._mergeFunction(...cbArgs);
});
}

/**
* Initialize a model, representing a table in the DB, with attributes and options.
*
Expand Down Expand Up @@ -980,16 +1028,6 @@ class Model {
this._scope = this.options.defaultScope;
this._scopeNames = ['defaultScope'];

if (_.isPlainObject(this._scope)) {
this._conformOptions(this._scope, this);
}

_.each(this.options.scopes, scope => {
if (_.isPlainObject(scope)) {
this._conformOptions(scope, this);
}
});

this.sequelize.modelManager.addModel(this);
this.sequelize.runHooks('afterDefine', this);

Expand Down Expand Up @@ -1428,8 +1466,6 @@ class Model {
throw new Error(`The scope ${name} already exists. Pass { override: true } as options to silence this error`);
}

this._conformOptions(scope, this);

if (name === 'defaultScope') {
this.options.defaultScope = this._scope = scope;
} else {
Expand Down Expand Up @@ -1525,29 +1561,12 @@ class Model {

if (_.isFunction(scope)) {
scope = scope();
this._conformOptions(scope, self);
}
}
}

if (scope) {
_.assignWith(self._scope, scope, (objectValue, sourceValue, key) => {
if (key === 'where') {
if (Array.isArray(sourceValue)) {
return sourceValue;
}
if (sourceValue instanceof Utils.SequelizeMethod) {
sourceValue = { [Op.and]: sourceValue };
}
return Object.assign(objectValue || {}, sourceValue);
}
if (['attributes', 'include', 'group'].includes(key) && Array.isArray(objectValue) && Array.isArray(sourceValue)) {
return objectValue.concat(sourceValue);
}

return objectValue ? objectValue : sourceValue;
});

this._assignOptions(self._scope, scope);
self._scopeNames.push(scopeName ? scopeName : 'defaultScope');
} else {
throw new sequelizeErrors.SequelizeScopeError(`Invalid scope ${scopeName} called.`);
Expand Down Expand Up @@ -1925,7 +1944,6 @@ class Model {
*/
static aggregate(attribute, aggregateFunction, options) {
options = Utils.cloneDeep(options);
options = _.defaults(options, { attributes: [] });

this._injectScope(options);
this._conformOptions(options, this);
Expand All @@ -1943,6 +1961,7 @@ class Model {
aggregateColumn = this.sequelize.fn('DISTINCT', aggregateColumn);
}

options.attributes = _.intersection(options.attributes, options.group);
options.attributes.push([this.sequelize.fn(aggregateFunction, aggregateColumn), aggregateFunction]);

if (!options.dataType) {
Expand Down Expand Up @@ -3058,36 +3077,10 @@ class Model {
}
}

// Inject _scope into options. Includes should have been conformed (conformOptions) before calling this
// Inject _scope into options.
static _injectScope(options) {
const scope = Utils.cloneDeep(this._scope);

const filteredScope = _.omit(scope, 'include'); // Includes need special treatment

Utils.defaults(options, filteredScope);
Utils.defaults(options.where, filteredScope.where);

if (scope.include) {
options.include = options.include || [];

// Reverse so we consider the latest include first.
// This is used if several scopes specify the same include - the last scope should take precedence
for (const scopeInclude of scope.include.reverse()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@u9r52sld u9r52sld Oct 25, 2018 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it's almost the same. I just updated for issues #9087,#6245

For example, current merge strategy is as follows.

Company.addScope('scopeA', {
  where: { name: 'A', something: true },
  attributes: {
    include: ['name']
  },
  include: [
    {
      model: Project,
      where: { name: 'A', something: true },
    },
    Project
  ],
  limit: 5,
  order: [
    ['name', 'DESC'],
  ]
})

Company.addScope('scopeB', {
  where: { name: 'B' },
  attributes: {
    exclude: ['something']
  },
  include: [
    {
      model: Project,
      as: 'Pj'
    },
    {
      model: Project,
      where: { name: 'B' }
    },
  ],
  limit: 10,
  order: [
    ['something', 'ASC'],
  ]
})

expect(Company.scope(['scopeA', 'scopeB'])._scope).to.deep.equal({
  where: { name: 'B', something: true }, // 'where' is shallowly merged
  attributes: { // just override
    exclude: ['something']
  },
  include: [ // 'include' is shallowly merged with the same model and alias(as)
    {
      model: Project,
      where: { name: 'B', something: true },
    },
    {
      model: Project,
      as: 'Pj'
    },
  ],
  limit: 10, // just override
  order: [ // Array is united
    ['name', 'DESC'],
    ['something', 'ASC']
  ]
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm I thought we discussed to have attributes.include / exclude merge #9735 (comment)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, i'm sorry. I fixed it. e31be36

Company.addScope('scopeA', {
  attributes: {
    include: ['name']
  }
})

Company.addScope('scopeB', {
  attributes: {
    include: ['something'],
    exclude: ['password']
  }
})

expect(Company.scope(['scopeA', 'scopeB'])._scope).to.deep.equal({
  attributes: { // merged
    include: ['name', 'something'],
    exclude: ['password']
  }
})

if (scopeInclude.all || !options.include.some(item => {
const isSameModel = item.model && item.model.name === scopeInclude.model.name;
if (!isSameModel || !item.as) return isSameModel;

if (scopeInclude.as) {
return item.as === scopeInclude.as;
} else {
const association = scopeInclude.association || this.getAssociationForAlias(scopeInclude.model, scopeInclude.as);
return association ? item.as === association.as : false;
}
})) {
options.include.push(scopeInclude);
}
}
}
this._defaultsOptions(options, scope);
}

static inspect() {
Expand Down Expand Up @@ -3832,7 +3825,7 @@ class Model {
const values = {};
values[include.association.foreignKey] = this.get(this.constructor.primaryKeyAttribute, {raw: true});
values[include.association.otherKey] = instance.get(instance.constructor.primaryKeyAttribute, {raw: true});

// Include values defined in the association
Object.assign(values, include.association.through.scope);
if (instance[include.association.through.model.name]) {
Expand Down
116 changes: 116 additions & 0 deletions test/integration/model/scope/associations.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,122 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(user.company.projects).to.have.length(1);
});
});

describe('with different format', () => {
it('should not throw error', function() {
const Child = this.sequelize.define('Child');
const Parent = this.sequelize.define('Parent', {}, {
defaultScope: {
include: [{ model: Child }]
},
scopes: {
children: {
include: [Child]
}
}
});
Parent.addScope('alsoChildren', {
include: [{ model: Child }]
});

Child.belongsTo(Parent);
Parent.hasOne(Child);

return this.sequelize.sync({ force: true }).then(() => {
return Promise.all([Child.create(), Parent.create()]);
}).then(([child, parent]) => {
return parent.setChild(child);
}).then(() => {
return Parent.scope('children', 'alsoChildren').findOne();
});
});
});

describe('with find options', () => {
it('should merge includes correctly', function() {
const Child = this.sequelize.define('Child', { name: Sequelize.STRING });
const Parent = this.sequelize.define('Parent', { name: Sequelize.STRING });
Parent.addScope('testScope1', {
include: [{
model: Child,
where: {
name: 'child2'
}
}]
});
Parent.hasMany(Child);

return this.sequelize.sync({ force: true })
.then(() => {
return Promise.all([
Parent.create({ name: 'parent1' }).then(parent => parent.createChild({ name: 'child1' })),
Parent.create({ name: 'parent2' }).then(parent => parent.createChild({ name: 'child2' }))
]);
})
.then(() => {
return Parent.scope('testScope1').findOne({
include: [{
model: Child,
attributes: { exclude: ['name'] }
}]
});
})
.then(parent => {
expect(parent.get('name')).to.equal('parent2');
expect(parent.Children).to.have.length(1);
expect(parent.Children[0].dataValues).not.to.have.property('name');
});
});
});
});

describe('scope with options', () => {
it('should return correct object included foreign_key', function() {
const Child = this.sequelize.define('Child', {
secret: Sequelize.STRING
}, {
scopes: {
public: {
attributes: {
exclude: ['secret']
}
}
}
});
const Parent = this.sequelize.define('Parent');
Child.belongsTo(Parent);
Parent.hasOne(Child);

return this.sequelize.sync({ force: true })
.then(() => Child.create({ secret: 'super secret' }))
.then(() => Child.scope('public').findOne())
.then(user => {
expect(user.dataValues).to.have.property('ParentId');
expect(user.dataValues).not.to.have.property('secret');
});
});

it('should return correct object included foreign_key with defaultScope', function() {
const Child = this.sequelize.define('Child', {
secret: Sequelize.STRING
}, {
defaultScope: {
attributes: {
exclude: ['secret']
}
}
});
const Parent = this.sequelize.define('Parent');
Child.belongsTo(Parent);

return this.sequelize.sync({ force: true })
.then(() => Child.create({ secret: 'super secret' }))
.then(() => Child.findOne())
.then(user => {
expect(user.dataValues).to.have.property('ParentId');
expect(user.dataValues).not.to.have.property('secret');
});
});
});
});
});
Expand Down
Loading