From e5cc9153aadf9aed1572d4fa63deaff9ce06a11e Mon Sep 17 00:00:00 2001 From: Sasha <64744993+r1tsuu@users.noreply.github.com> Date: Mon, 25 Nov 2024 18:15:19 +0200 Subject: [PATCH] fix(db-postgres): allow to clear select fields with `hasMany: true` (#9464) ### What? Previously, using Postgres, select fields with `hasMany: true` weren't clearable. Meaning, you couldn't pass an empty array: ```ts const updatedDoc = await payload.update({ id, collection: 'select-fields', data: { selectHasMany: [], }, }) ``` ### Why? To achieve the same behavior with MongoDB. ### How? Modifies logic in `packages/drizzle/src/upsertRow/index.ts` to include empty arrays. --- packages/drizzle/src/upsertRow/index.ts | 19 +++++++++++-------- test/fields/int.spec.ts | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/packages/drizzle/src/upsertRow/index.ts b/packages/drizzle/src/upsertRow/index.ts index ec9f20e3d1..07d7a365f7 100644 --- a/packages/drizzle/src/upsertRow/index.ts +++ b/packages/drizzle/src/upsertRow/index.ts @@ -114,13 +114,13 @@ export const upsertRow = async | TypeWithID>( // store by table name and rows if (Object.keys(rowToInsert.selects).length > 0) { Object.entries(rowToInsert.selects).forEach(([selectTableName, selectRows]) => { + selectsToInsert[selectTableName] = [] + selectRows.forEach((row) => { if (typeof row.parent === 'undefined') { row.parent = insertedRow.id } - if (!selectsToInsert[selectTableName]) { - selectsToInsert[selectTableName] = [] - } + selectsToInsert[selectTableName].push(row) }) }) @@ -343,11 +343,14 @@ export const upsertRow = async | TypeWithID>( where: eq(selectTable.parent, insertedRow.id), }) } - await adapter.insert({ - db, - tableName: selectTableName, - values: tableRows, - }) + + if (tableRows.length) { + await adapter.insert({ + db, + tableName: selectTableName, + values: tableRows, + }) + } } // ////////////////////////////////// diff --git a/test/fields/int.spec.ts b/test/fields/int.spec.ts index 8b9afda3fc..9f349a33fa 100644 --- a/test/fields/int.spec.ts +++ b/test/fields/int.spec.ts @@ -521,6 +521,25 @@ describe('Fields', () => { expect(updatedDoc.selectHasMany).toEqual(['one', 'two']) }) + it('should clear select hasMany field', async () => { + const { id } = await payload.create({ + collection: 'select-fields', + data: { + selectHasMany: ['one', 'two'], + }, + }) + + const updatedDoc = await payload.update({ + id, + collection: 'select-fields', + data: { + selectHasMany: [], + }, + }) + + expect(updatedDoc.selectHasMany).toHaveLength(0) + }) + it('should query hasMany in', async () => { const hit = await payload.create({ collection: 'select-fields',