Skip to content

Row locking support in find*() queries (via FOR UPDATE) #17136

Open

Description

@thetminko

Problem

I just migrated from Sequelize and was quite a fan of Prisma for being type safe. Would Prisma be able to support SELECT FOR UPDATE row locking like Sequelize supports? Understand that Optimistic locking is preferred by Prisma but it would be great if we have the row locking mechanism too.
My problem: When multiple requests call this function concurrently, while first transaction is still processing, the subsequent transaction will see that the user is still active and do the processing again. If we could avoid it by locking the row, that would be great.

function deactivate() {
  const user = await prisma.$transaction(async tx => {
   const user = await tx.user.findUnique({ where: { id: user.id } });
   if (user.status !== 'ACTIVE') {
     throw new Error('User not active ...');
  }
  // some business processing (not long transaction)
  return tx.user.update({ where: { id: user.id } }, data: {  status: 'DELETED' });
 });

   await doAfterCommitProcessing(user);
}

Suggested solution

const user = await tx.user.findUnique({ where: { id: user.id }, lock: FOR_UPDATE });
So, the user record with specific id is locked till the transaction is completed.

Alternatives

Additional context

Activity

  1. gomain commented on Jan 23, 2023

    @gomain

    Yes, I too have a use case where I want racing reads to block.

  2. luxaritas commented on Mar 8, 2023

    @luxaritas
    Contributor

    Is this a duplicate of #5983?

  3. janpio commented on Mar 10, 2023

    @janpio
    Contributor

    Yep, sounds similar but a bit ore specific maybe. Will clean up when we look at the issue in depth.

  4. mweel1 commented on Mar 16, 2023

    @mweel1

    Same here.

      await prisma.$transaction(
          async (tx) => {
            let user = await tx.user.findFirst({
              where: {
                id: req.auth.userId,
              },
            });
    
            // update the user
            if (user) {
              const userWorkspace = await tx.userWorkspace.findFirstOrThrow({
                where: {
                  userId: req.auth.userId,
                  id: user.defaultWorkspaceId,
                },
              });
    
              workspaceId = userWorkspace.workspaceId;
    
              var updateUser = await tx.user.update({
                where: {
                  id: req.auth.userId,
                },
                data: {
                  fullName: req.body.fullName,
                  email: req.body.primaryEmailAddress.emailAddress,
                  auth_json: JSON.stringify(req.body),
                },
              });
            } else {
              workspaceId = "Personal";
              var userWorkspace = await tx.userWorkspace.create({
                data: {
                  userId: req.auth.userId,
                  label: "Personal",
                  workspaceId: "Personal",
                },
              });
    
              let newUser = await tx.user.create({
                data: {
                  id: req.auth.userId,
                  fullName: req.body.fullName,
                  email: req.body.primaryEmailAddress.emailAddress,
                  auth_json: JSON.stringify(req.body),
                  defaultWorkspaceId: userWorkspace.id,
                },
              });
            }
          },
          {
            isolationLevel: Prisma.Prisma.TransactionIsolationLevel.Serializable,
          }
    

    Getting this error when two threads are inserting the same user, the read should to see if the user exists if another transaction is working on it.

    image

  5. gomain commented on Mar 16, 2023

    @gomain

    The current work-around is to either use $rawQuery to place FOR UPDATE. Or artificially place a mutex field (typically a boolean) and select via updating the field to true (lock it) where it is false (not locked).

    This is important if the activities before updating the row involves other side effects that we definitely don't want to happen if the transaction would fail.

  6. KarolScibior commented on Mar 27, 2023

    @KarolScibior

    Any news / plans regarding this feature?

  7. AlejandroFrias commented on Jun 21, 2023

    @AlejandroFrias

    Another friendly ping. I have that exact user create error. But also am trying to avoid accruing interest on a loan multiple times in the same day on a background job that might retry randomly.

  8. changed the title [-]Row locking support in Find queries[/-] [+]Row locking support in `find*` queries[/+] on Jun 22, 2023
  9. added
    topic: findFirst()
    on Jun 22, 2023
  10. 1 remaining item

  11. changed the title [-]Row locking support in `find*` queries[/-] [+]Row locking support in `find*` queries (via `FOR UPDATE`)[/+] on Jun 22, 2023
  12. esmaeilzadeh commented on Oct 31, 2023

    @esmaeilzadeh

    Is there any plan to add "lock for update" feature to Prisma transactions?

  13. devSajan commented on Jan 11, 2024

    @devSajan

    yes, I have the same requirement, when deleting a record another request can access it which should not happen.

  14. changed the title [-]Row locking support in `find*` queries (via `FOR UPDATE`)[/-] [+]Row locking support in `find*()` queries (via `FOR UPDATE`)[/+] on Feb 21, 2024
  15. janpio commented on Mar 1, 2024

    @janpio
    Contributor

    Potentially related:
    #8580
    #5983

  16. easdkr commented on Apr 2, 2024

    @easdkr

    Is there any plan to add "lock" (shared, exclusive, update... etc lock) to findXXX method?

  17. crgold commented on Jul 6, 2024

    @crgold

    this would be lovely

  18. naylinnpkv commented on Jul 31, 2024

    @naylinnpkv

    Has somebody found a work around for that while this feature is not supported yet in Prisma?

  19. homoky commented on Jul 31, 2024

    @homoky

    From other issues I was part of, the roadmap of Prisma is not open, and we can dream about this for years, like people are dreaming for ears about enums in litesql.

  20. alexey-sh commented on Aug 6, 2024

    @alexey-sh

    Has somebody found a work around for that while this feature is not supported yet in Prisma?

    @naylinnpkv

     const payment = await prisma.payment.upsert(data);
     const fieldList = ['field1', 'field2'];
     await prisma.$transaction(async (tx) => {
            const payments = await tx.$queryRaw<RawPayment[]>`select ${fieldList} from payments where id = ${paymentId} for update`;
            if (!payments?.length) return null;
            const [payment] = payments;
            // code 
    });
    
  21. bilmatech commented on Feb 24, 2025

    @bilmatech

    Has somebody found a work around for that while this feature is not supported yet in Prisma?

    @naylinnpkv

     const payment = await prisma.payment.upsert(data);
     const fieldList = ['field1', 'field2'];
     await prisma.$transaction(async (tx) => {
            const payments = await tx.$queryRaw<RawPayment[]>`select ${fieldList} from payments where id = ${paymentId} for update`;
            if (!payments?.length) return null;
            const [payment] = payments;
            // code 
    });
    

    This will be a perfect work around.

  22. dimatakoy commented on Dec 11, 2025

    @dimatakoy

    I still need that feature. It's pretty common in my codebases to use SELECT FOR UPDATE (or, more specifically in PostgreSQL, SELECT FOR NO KEY UPDATE).

    The workaround is pretty painful for me because our app uses @map("snake_case_name")for better interoperability with other legacy systems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/featuretopic: database-functionalitytopic: findFirst()topic: findMany()topic: findUnique()topic: lockingtopic: transaction

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions