Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(postgres, sqlite): map conflictFields to column names in Model.upsert #17211

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/core/src/model.js
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
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