Repository navigation
fix(drizzle): exceeding bound parameter limit of d1 in polymorphic and joined queries - #19243
digitalwerber wants to merge 5 commits into
Conversation
…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.
|
No actionable comments were generated in the recent review.
|
| 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
Possibly related PRs
- payloadcms/payload#15423: Changes relationship filters to use
inandnot_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: 
4 · 
1
-
Failed checks: 1 warning Passed checks: 4 passed-
Full details: Linked Issues check
-
Explanation
Issue
#19233requires bulk delete on Cloudflare D1 to avoid "too many SQL variables". The failing lock lookup usesdocument.value: { in: ids }on a polymorphic relationship. InparseParams.ts, the polymorphic branch now callsbuildInlinedInConstraintforinandnot_inwhenadapter.limitedBoundParametersis true, the values passcanInlineValues, 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 polymorphicintest intest/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_invalues into the statement whenlimitedBoundParametersis enabled.parseParams.tscovers polymorphic columns for#19233, other fields,not_inon non-hasManyrelationship and upload fields, and the existingidcase.findMany.tsanddeleteMany.tscover the ID lookup after join resolution, which hits the same D1 limit. The PR description tiesdeleteManyto the bulk delete path. The issue cites#17493and#14766, which describe the samelimitedBoundParametersgap.buildOperatorConstraint.tsnarrowshandlerMatchesand addshasOperatorHandler, which the inlining check needs.buildInlinedInConstraint.tsadds 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,inandnot_inon 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, foridwith a custom operator handler, inlining is skipped, so invalid ID values no longer raiseAPIErrorin that case. Both notes are connected to the change and do not fail scope. I assesseddeleteMany.tsand 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.
Comment @coderabbitai help to get the list of available commands.
What?
With
limitedBoundParameters(set by@payloadcms/db-d1-sqlite), the Drizzle adapter now also writesin/not_invalues into the statement for polymorphic relationships and other fields, and for the IDs thatfindManyanddeleteManyload after resolving a join.Why?
Only
in/not_inonidwere written into the statement. Everything else was bound, so Cloudflare D1 (100 bound parameters per statement) failed with "too many SQL variables":inon a polymorphic relationship binds the values once per related collection. Bulk delete hits this when it looks up the locks of the deleted documents withdocument.value: { in: ids }.inArray(id, ids), infindManyand indeleteMany.inon other fields binds every value. Bulk delete hits this when it deletes the document preferences withkey: { 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,nullor strings in the format of an ID, the same check theidcase already used. It is used for the existingidcase, the polymorphic columns, other fields, and the ID lookups infindManyanddeleteMany. It also coversnot_inon relationship and upload fields that are nothasMany, which has its own branch that binds every ID twice. Values that don't pass the check stay bound as before; onlyidkeeps throwing on invalid values.nullininkeeps 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 existingidcase, which discarded the handler's comparison).Tests are added to
test/database/sqlite-bound-parameters-limit.int.spec.ts: each limit test fails withlimitedBoundParameters: falseand passes withtrue. They coverinon a polymorphic relationship,inon a text field,not_inon a relationship, a join with more than 100 matches anddeleteManywith a join and more than 100 matches, plusnullininand operator handlers withlimitedBoundParameters: 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