diff --git a/plugin-server/src/utils/db/db.ts b/plugin-server/src/utils/db/db.ts index 9501f5a58cbf5..89f9b060e268c 100644 --- a/plugin-server/src/utils/db/db.ts +++ b/plugin-server/src/utils/db/db.ts @@ -862,7 +862,23 @@ export class DB { 'addPersonlessDistinctId' ) - return result.rows[0]['is_merged'] + if (result.rows.length === 1) { + return result.rows[0]['is_merged'] + } + + // ON CONFLICT ... DO NOTHING won't give us our RETURNING, so we have to do another SELECT + const existingResult = await this.postgres.query( + PostgresUse.COMMON_WRITE, + ` + SELECT is_merged + FROM posthog_personlessdistinctid + WHERE team_id = $1 AND distinct_id = $2 + `, + [teamId, distinctId], + 'addPersonlessDistinctId' + ) + + return existingResult.rows[0]['is_merged'] } public async addPersonlessDistinctIdForMerge( diff --git a/plugin-server/tests/main/db.test.ts b/plugin-server/tests/main/db.test.ts index 670685f445ddc..1ff74e418f20d 100644 --- a/plugin-server/tests/main/db.test.ts +++ b/plugin-server/tests/main/db.test.ts @@ -284,6 +284,23 @@ describe('DB', () => { return selectResult.rows[0] } + test('addPersonlessDistinctId', async () => { + const team = await getFirstTeam(hub) + await db.addPersonlessDistinctId(team.id, 'addPersonlessDistinctId') + + // This will conflict, but shouldn't throw an error + await db.addPersonlessDistinctId(team.id, 'addPersonlessDistinctId') + + const result = await db.postgres.query( + PostgresUse.COMMON_WRITE, + 'SELECT id FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2', + [team.id, 'addPersonlessDistinctId'], + 'addPersonlessDistinctId' + ) + + expect(result.rows.length).toEqual(1) + }) + describe('createPerson', () => { let team: Team const uuid = new UUIDT().toString()