Skip to content

fix(drizzle): exceeding bound parameter limit of d1 in polymorphic and joined queries - #19243

Open
digitalwerber wants to merge 5 commits into
payloadcms:mainfrom
digitalwerber:fix/drizzle-limited-bound-parameters
Open

digitalwerber wants to merge 5 commits into
payloadcms:mainfrom
digitalwerber:fix/drizzle-limited-bound-parameters

Conversation

@digitalwerber

Copy link
Copy Markdown

What?

With limitedBoundParameters (set by @payloadcms/db-d1-sqlite), the Drizzle adapter now also writes in / not_in values into the statement for polymorphic relationships and other fields, and for the IDs that findMany and deleteMany load after resolving a join.

Why?

Only in / not_in on id were written into the statement. Everything else was bound, so Cloudflare D1 (100 bound parameters per statement) failed with "too many SQL variables":

  • in on a polymorphic relationship binds the values once per related collection. Bulk delete hits this when it looks up the locks of the deleted documents with document.value: { in: ids }.
  • Queries with joins first resolve the matching IDs and then load them with inArray(id, ids), in findMany and in deleteMany.
  • in on other fields binds every value. Bulk delete hits this when it deletes the document preferences with key: { in: [...] }.

As a result, a bulk delete of about 100 documents failed on D1, both at the lock cleanup and at the preference cleanup.

How?

A small helper, buildInlinedInConstraint, writes the values into the statement when all of them are numbers, null or strings in the format of an ID, the same check the id case already used. It is used for the existing id case, the polymorphic columns, other fields, and the ID lookups in findMany and deleteMany. It also covers not_in on relationship and upload fields that are not hasMany, which has its own branch that binds every ID twice. Values that don't pass the check stay bound as before; only id keeps throwing on invalid values. null in in keeps matching through the existing IS NULL condition, and values are only inlined when no operator handler applies, so custom handlers keep building the comparison (this also fixes the existing id case, which discarded the handler's comparison).

Tests are added to test/database/sqlite-bound-parameters-limit.int.spec.ts: each limit test fails with limitedBoundParameters: false and passes with true. They cover in on a polymorphic relationship, in on a text field, not_in on a relationship, a join with more than 100 matches and deleteMany with a join and more than 100 matches, plus null in in and operator handlers with limitedBoundParameters: true. Verified locally against D1 (Miniflare): bulk deleting 120 locked documents with preferences fails before and passes after, including the preference cleanup, with no changes to the core.

Closes #19233

…d joined queries

With `limitedBoundParameters`, only `id` values of `in` and `not_in`
were written into the statement. Other queries still bound every value:

- `in` on a polymorphic relationship binds the values once per related
  collection, e.g. the lock lookup of bulk delete on `document.value`
- queries with joins load the matched rows by binding all of their ids,
  in `findMany` and `deleteMany`
- `in` on other fields, e.g. the preference keys removed by bulk delete

Cloudflare D1 allows 100 bound parameters per statement, so bulk deletes
and other queries over about 100 documents failed with "too many SQL
variables".

Write these values into the statement as well when all of them are
numbers or have the format of an ID. Other values stay bound as before.
- Inline the values without `null` and combine them with the IS NULL
  condition, so `in: [null, ...]` matches the same rows as when the
  values are bound. This also applies to the existing `id` case.
- Only inline when no operator handler applies to `in` / `not_in`, so
  custom handlers keep building the comparison. This also applies to
  the existing `id` case, which built the handler's comparison and then
  discarded it.
- Take object parameters in `canInlineValues` and order the exports
  before the helper.
`not_in` on a relationship or upload field that is not `hasMany` is
handled by its own branch, which bound the values with `notInArray`
before the inlining applied. The values hold every ID twice, as a
number and as a string, so 50 IDs already exceeded the bound parameter
limit of D1. Inline them there as well, within the existing IS NULL
condition.
@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between ec35164 and 97c4235.

Files selected for processing: 6
  • packages/drizzle/src/deleteMany.ts
  • packages/drizzle/src/find/findMany.ts
  • packages/drizzle/src/queries/buildOperatorConstraint.ts
  • packages/drizzle/src/queries/parseParams.ts
  • packages/drizzle/src/utilities/buildInlinedInConstraint.ts
  • test/database/sqlite-bound-parameters-limit.int.spec.ts

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

Walkthrough

Drizzle now inlines eligible values in IN and NOT IN constraints when bound parameters are limited and no matching operator handler applies. Joined read and delete paths also inline eligible selected IDs. SQLite integration tests cover these query and mutation paths.

Changes: Limited-parameter query handling

Layer / File(s) Summary
Inline constraint and handler detection
packages/drizzle/src/utilities/buildInlinedInConstraint.ts, packages/drizzle/src/queries/buildOperatorConstraint.ts
Adds eligibility checks and SQL construction for inline IN and NOT IN constraints. Adds a check for matching adapter operator handlers.
Operator parsing and validation
packages/drizzle/src/queries/parseParams.ts, test/database/sqlite-bound-parameters-limit.int.spec.ts
Query parsing inlines eligible relationship and general IN/NOT IN values when bound parameters are limited and no matching handler applies. Tests cover value types, null matching, parameter limits, and custom handlers.
Joined read and delete ID filters
packages/drizzle/src/find/findMany.ts, packages/drizzle/src/deleteMany.ts, test/database/sqlite-bound-parameters-limit.int.spec.ts
Joined read and delete paths inline eligible selected IDs in qualified table ID constraints. Tests cover both paths.

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

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant QueryParser
  participant hasOperatorHandler
  participant buildInlinedInConstraint
  participant SQLite
  QueryParser->>hasOperatorHandler: Check for a matching operator handler
  hasOperatorHandler-->>QueryParser: Return handler match result
  QueryParser->>buildInlinedInConstraint: Build constraint for eligible values
  buildInlinedInConstraint-->>QueryParser: Return inline SQL constraint
  QueryParser->>SQLite: Execute query with inline constraint
Loading

Possibly related PRs

  • payloadcms/payload#15423: Changes relationship filters to use in and not_in, which are also handled by this PR’s limited-parameter logic.
  • payloadcms/payload#19236: Addresses the same D1 bound-parameter failure during bulk-delete lock queries.

Suggested reviewers: alessiogr, r1tsuu, paulpopus

Merge Risk: Minimal · up to 97c42

The reviewed query paths have no established merge-blocking issue; the change is ready for normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the Drizzle fix for bound-parameter limit failures in polymorphic and joined queries.
Description check Passed The description directly explains the bound-parameter issue, the inlining changes, affected query paths, and test coverage.
Linked Issues check Passed Issue #19233 requires bulk delete on Cloudflare D1 to avoid "too many SQL variables". The failing lock lookup uses document.value: { in: ids } on a polymorphic relationship. In parseParams.ts, the…
Out of Scope Changes check Passed All changes support one objective: write eligible in / not_in values into the statement when limitedBoundParameters is enabled. parseParams.ts covers polymorphic columns for #19233, other fiel…
Full details: Linked Issues check

Explanation

Issue #19233 requires bulk delete on Cloudflare D1 to avoid "too many SQL variables". The failing lock lookup uses document.value: { in: ids } on a polymorphic relationship. In parseParams.ts, the polymorphic branch now calls buildInlinedInConstraint for in and not_in when adapter.limitedBoundParameters is true, the values pass canInlineValues, and no operator handler applies. Each per-collection column then writes the values into the statement, so the bound-parameter count no longer scales with collections multiplied by IDs. The PR description reports a local D1 (Miniflare) run. Bulk deleting 120 locked documents with preferences fails before the change and passes after it. The PR also adds a polymorphic in test in test/database/sqlite-bound-parameters-limit.int.spec.ts, per the description and summary. I did not read that test file or run the tests, so this rests on the code diff and the reported verification. The reproduction test linked in the issue lives on a fork branch and is not part of this PR. It is not a requirement of this PR. Values that fail the format check stay bound. Numeric and ID-format values, which the issue's case uses, pass the check.

Full details: Out of Scope Changes check

Explanation

All changes support one objective: write eligible in / not_in values into the statement when limitedBoundParameters is enabled. parseParams.ts covers polymorphic columns for #19233, other fields, not_in on non-hasMany relationship and upload fields, and the existing id case. findMany.ts and deleteMany.ts cover the ID lookup after join resolution, which hits the same D1 limit. The PR description ties deleteMany to the bulk delete path. The issue cites #17493 and #14766, which describe the same limitedBoundParameters gap. buildOperatorConstraint.ts narrows handlerMatches and adds hasOperatorHandler, which the inlining check needs. buildInlinedInConstraint.ts adds the helper. Inlined values are limited to finite numbers, null, and strings matching /^[\w-]+$/, so the inlined SQL does not admit quote or injection characters. I found no unrelated changes. Two behavior notes apply. First, in and not_in on other fields are inlined too, which broadens the change beyond the issue's polymorphic case. The PR ties this to the same D1 limit. Second, for id with a custom operator handler, inlining is skipped, so invalid ID values no longer raise APIError in that case. Both notes are connected to the change and do not fail scope. I assessed deleteMany.ts and the tests from the PR summary and description, not from a full diff read.

Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. 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 1 functions across 6 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
🧪 Generate unit tests (beta)
  • 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

Comment @coderabbitai help to get the list of available commands.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bulk delete fails on Cloudflare D1 with "too many SQL variables" (document lock query binds collections × ids parameters)

1 participant