Skip to content

Commit

Permalink
fix(postgres, sqlite): map conflictFields to column names in Model.up…
Browse files Browse the repository at this point in the history
…sert
  • Loading branch information
Murli Prajapati committed Mar 26, 2024
1 parent 21772a5 commit d76aba5
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/core/src/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2197,6 +2197,13 @@ ${associationOwner._getAssociationDebugList()}`);
await instance.validate(options);
}

// Map conflict fields to column names
if(options.conflictFields){
options.conflictFields = options.conflictFields.map(attrName => {
return modelDefinition.getColumnName(attrName);
});
}

// Map field names
const updatedDataValues = pick(instance.dataValues, changed);
const insertValues = mapValueFieldNames(
Expand Down
65 changes: 65 additions & 0 deletions packages/core/test/integration/model/upsert.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,71 @@ describe('Model', () => {
expect(otherMembership.permissions).to.eq('member');
expect(otherMembership.id).to.not.eq(originalMembership.id);
});

it('should map conflictFields to column names', async () => {
const Employees = sequelize.define('employees', {
employeeId: {
type: DataTypes.INTEGER,
field: 'Employee_ID',
},
departmentId: {
type: DataTypes.INTEGER,
field: 'Department_ID',
},
position: DataTypes.ENUM('junior', 'senior'),
});

await Employees.sync({ force: true });

await sequelize.queryInterface.addConstraint('employees', {
type: 'UNIQUE',
fields: ['Employee_ID', 'Department_ID'],
});

const [originalEmployee] = await Employees.upsert(
{
employeeId: 1,
departmentId: 1,
position: 'junior',
},
{
conflictFields: ['employeeId', 'departmentId'],
},
);

expect(originalEmployee).to.not.eq(null);
expect(originalEmployee.position).to.eq('junior');

const [updatedEmployee] = await Employees.upsert(
{
employeeId: 1,
departmentId: 1,
position: 'senior',
},
{
conflictFields: ['employeeId', 'departmentId'],
},
);

expect(updatedEmployee).to.not.eq(null);
expect(updatedEmployee.position).to.eq('senior');
expect(updatedEmployee.id).to.eq(originalEmployee.id);

const [otherEmployee] = await Employees.upsert(
{
employeeId: 2,
departmentId: 1,
position: 'senior',
},
{
conflictFields: ['employeeId', 'departmentId'],
},
);

expect(otherEmployee).to.not.eq(null);
expect(otherEmployee.position).to.eq('senior');
expect(otherEmployee.id).to.not.eq(originalEmployee.id);
});
});
}

Expand Down

0 comments on commit d76aba5

Please sign in to comment.