fix(db-postgres): payload.db.upsert inserts new rows instead of updating existing ones (#9916)

### What?
`payload.db.updateOne` (and so `payload.db.upsert`) with drizzle
adapters used incoming `where` incorrectly and worked properly only
either if you passed `id` or some where query path required table joins
(like `where: { 'array.title'`) which is also the reason why `upsert`
_worked_ with user preferences specifically, because we need to join the
`preferences_rels` table to query by `user.relationTo` and `user.value`

Fixes https://github.com/payloadcms/payload/issues/9915

This was found here - https://github.com/payloadcms/payload/pull/9913,
the database KV adapter uses `upsert` with `where` by unique fields.
This commit is contained in:
Sasha
2024-12-12 03:53:57 +02:00
committed by GitHub
parent d9efd192e7
commit 5e3963482e
2 changed files with 50 additions and 0 deletions

View File

@@ -1076,4 +1076,37 @@ describe('database', () => {
expect(relationBDocs.docs).toHaveLength(0)
})
it('should upsert', async () => {
const postShouldCreated = await payload.db.upsert({
req: {},
collection: 'posts',
data: {
title: 'some-title-here',
},
where: {
title: {
equals: 'some-title-here',
},
},
})
expect(postShouldCreated).toBeTruthy()
const postShouldUpdated = await payload.db.upsert({
req: {},
collection: 'posts',
data: {
title: 'some-title-here',
},
where: {
title: {
equals: 'some-title-here',
},
},
})
// Should stay the same ID
expect(postShouldCreated.id).toBe(postShouldUpdated.id)
})
})