diff --git a/server/models/base/Model.test.ts b/server/models/base/Model.test.ts index 544c9e1f80..bd62015dcb 100644 --- a/server/models/base/Model.test.ts +++ b/server/models/base/Model.test.ts @@ -2,12 +2,16 @@ import { faker } from "@faker-js/faker"; import { randomUUID } from "node:crypto"; import { CommentingAccess, TeamPreference } from "@shared/types"; import { createContext } from "@server/context"; +import { sequelize } from "@server/storage/database"; import { buildDocument, + buildGroup, + buildGroupUser, buildSearchQuery, buildTeam, buildUser, } from "@server/test/factories"; +import GroupUser from "../GroupUser"; import SearchQuery from "../SearchQuery"; import User from "../User"; @@ -92,6 +96,33 @@ describe("Model", () => { }); }); + describe("findOrCreateWithCtx", () => { + it("should return the existing row when another request creates it first", async () => { + const user = await buildUser(); + const group = await buildGroup({ teamId: user.teamId }); + const existing = await buildGroupUser({ + groupId: group.id, + userId: user.id, + teamId: user.teamId, + }); + + // Simulate the race: the first lookup misses the row created concurrently. + vi.spyOn(GroupUser, "findOne").mockResolvedValueOnce(null); + + const [groupUser, created] = await sequelize.transaction( + async (transaction) => + GroupUser.findOrCreateWithCtx(createContext({ user, transaction }), { + where: { groupId: group.id, userId: user.id }, + defaults: { createdById: user.id }, + }) + ); + + expect(created).toBe(false); + expect(groupUser.groupId).toEqual(existing.groupId); + expect(groupUser.userId).toEqual(existing.userId); + }); + }); + describe("batch load", () => { it("should return data in batches", async () => { const team = await buildTeam(); diff --git a/server/models/base/Model.ts b/server/models/base/Model.ts index 399ac551f3..652af07ac5 100644 --- a/server/models/base/Model.ts +++ b/server/models/base/Model.ts @@ -188,16 +188,23 @@ class Model< return [existing as M, false]; } - // Record not found, try to create it + const attributes = Object.assign( + {}, + options.defaults, + options.where + ) as CreationAttributes; + + // Record not found, try to create it. A savepoint keeps the outer + // transaction usable if the insert fails on a unique constraint. try { - const created = await this.create( - Object.assign( - {}, - options.defaults, - options.where - ) as CreationAttributes, - { ...hookContext, transaction } - ); + const created = transaction + ? await this.sequelize!.transaction({ transaction }, (savepoint) => + this.create(attributes, { + ...hookContext, + transaction: savepoint, + }) + ) + : await this.create(attributes, hookContext); return [created as M, true]; } catch (err) { // Handle race condition: another request created the record first