Skip to content

fix(drizzle): limit atomic updates with a locking subquery - #19214

Merged
DanRibbens merged 2 commits into
mainfrom
fix/atomic-update-one-subquery
Nov 10, 2026
Merged

DanRibbens merged 2 commits into
mainfrom
fix/atomic-update-one-subquery

Conversation

@DanRibbens

Copy link
Copy Markdown
Contributor

Written with AI

Description

Atomic updateOne predicates can update every matching SQL row while returning only the first. Limit the write to one matching primary key using a subquery inside the UPDATE, retaining the original predicate on the outer write.

Supersedes #19156 and addresses the subquery review suggestion. This replaces the separate candidate lookup and application retry loop with one SQL statement. PostgreSQL locks the candidate with FOR UPDATE, allowing a waiting caller to continue to another matching row if a competing write makes the first candidate ineligible. SQLite uses the same subquery without a locking clause because it serializes writers.

Changes

  • Keep the single-statement path behind options.atomic === true, preserving main-table write validation and rejecting predicates requiring joins.
  • Return at most one updated document, or null when no document qualifies.
  • Add coverage for multiple matches, concurrent claims, no match, unsupported predicates/writes, and PostgreSQL contention with competing commits and rollbacks.
  • Verify that rolling back the caller's transaction also rolls back its atomic update.

This remains an independent prerequisite extracted from #19101. Branch-specific physical row-ID resolution and visibility remain in the content branching stack.

Test Plan

  • Focused PostgreSQL integration suite: 8 passed.
  • Focused SQLite integration suite: 6 passed; 2 PostgreSQL-only tests skipped.
  • Changed-file oxlint, formatting, and git diff --check passed.
  • Drizzle package typecheck passed on the reviewed draft. The broader database-test typecheck reports repository errors; the changed test file has no diagnostics.
  • D1 adapter execution remains unverified.

@coderabbitai

coderabbitai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Atomic updateOne now selects one matching row ID before writing. PostgreSQL locks the candidate; other databases use an unlocked selection. Integration tests cover update outcomes, validation, SQLite parameter counts, and PostgreSQL transaction behavior.

Changes: Atomic conditional updates

Layer / File(s) Summary
Candidate selection and update
packages/drizzle/src/updateOne.ts
Atomic updates reject predicates that require joins and select one matching row ID before writing. PostgreSQL locks the candidate with FOR NO KEY UPDATE; other databases select without that lock.
Conditional update outcomes and validation
test/database/conditional-update.int.spec.ts
Tests cover no matches, concurrent updates, updating at most one row, rejected predicates and complex-field writes, and SQLite parameter counts for a non-ID predicate.
PostgreSQL transaction behavior
test/database/conditional-update.int.spec.ts
Tests cover a category update while another transaction inserts a referencing post. Other cases check candidate selection after a competing transaction commits or rolls back, and verify rollback restores the claimed post to pending.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant updateOne
  participant PostgreSQL
  Caller->>updateOne: atomic update with predicate
  updateOne->>PostgreSQL: select matching row ID and lock candidate
  PostgreSQL-->>updateOne: candidate row ID
  updateOne->>PostgreSQL: update selected row
  PostgreSQL-->>updateOne: update result
  updateOne-->>Caller: return result
Loading

Possibly related PRs

Suggested reviewers: paulpopus, alessiogr

Merge Risk: Minimal · up to df87f

Atomic updates now claim at most one row through a locking subquery. The built-in PostgreSQL adapters take the locking path, and no concrete merge-blocking issue remains.

Pre-merge checks: Passed 5

Check name Status Explanation
Title check Passed The title relates to limiting atomic updates and locking the candidate, though the change summary describes a separate ID lookup rather than a locking subquery inside the UPDATE.
Description check Passed The description discusses atomic updateOne behavior and its tests, so it is related to the changeset.
Docstring Coverage Passed No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 0 functions across 2 files.

Finishing Touches

Generate docstrings

  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 6dfaa6e and df87fc0.

Files selected for processing: 2

  • packages/drizzle/src/updateOne.ts
  • test/database/conditional-update.int.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@github-actions

Copy link
Copy Markdown
Contributor

📦 esbuild Bundle Analysis for payload

This analysis was generated by esbuild-bundle-analyzer. 🤖
This PR introduced no changes to the esbuild bundle! 🙌

@AlessioGr AlessioGr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review:

1. FOR UPDATE takes a stronger lock than the UPDATE needs

packages/drizzle/src/updateOne.ts:86

On main, the atomic path is a plain UPDATE … WHERE <where>. Postgres takes FOR NO KEY UPDATE row locks for that. The new candidate subquery uses .for('update'), which also conflicts with the FOR KEY SHARE lock that a foreign-key check takes when a row referencing the locked row is inserted.

This can hang a request in forgotPassword. The reservation runs on a separate autocommit connection (reservationReq.transactionID = undefined), while req keeps its own transaction open. If that transaction has already inserted a row with an FK to the user (from a beforeOperation hook, an outer caller transaction, a *_rels row, payload_preferences_rels, etc.), the reservation's SELECT … FOR UPDATE waits on req, and req waits on the reservation. Both are on the same Node request, so Postgres can't detect the deadlock and the request hangs.

In confirmOrder the stronger lock is held until the settlement commits. Concurrent inserts that reference the ecommerce transaction row block for that whole time.

Fix: match the lock the UPDATE takes anyway:

this.name === 'postgres' ? matchingRowQuery.for('no key update') : matchingRowQuery

2. The where condition is sent twice

packages/drizzle/src/updateOne.ts:93

.where(and(eq(table.id, matchingRow), where))

where is now in both the candidate subquery and the outer UPDATE. Every bound parameter is sent twice, and the database evaluates the condition twice.

On D1 (100 bound-parameter limit) and other SQLite builds with low limits, a condition with roughly 50+ parameters (e.g. an in list on a non-id column) fit on main but now fails.

The outer where looks redundant:

  • Postgres (READ COMMITTED): FOR UPDATE/FOR NO KEY UPDATE re-checks where against the latest row version before it locks the row, so the locked row already matches.
  • SQLite: writers are serialized and this is one statement, so the subquery and the UPDATE see the same data.

Fix: drop the outer where:

.where(eq(table.id, matchingRow))

@github-actions

Copy link
Copy Markdown
Contributor

🚀 This is included in version v4.0.0-beta.9

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants