Repository navigation
fix(sql-orm-client): createAndCount returns the database count - #30364
wmadden-electric wants to merge 3 commits into
Conversation
Unit tests stub the runtime execute statistics so the reported affectedRows differs from the number of rows passed, on both the single-statement path and the SQLite split path. The Postgres integration test installs a BEFORE INSERT trigger that drops one row, so the database inserts two of the three rows passed. All three fail on the current implementation, which returns data.length. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
createAndCount returned data.length on both the single-statement path and the SQLite split path, so it reported how many rows were passed rather than how many the database inserted. It now returns stats.affectedRows from the execute statistics, summed across the per-group statements on the split path, the way updateAndCount and deleteAndCount already do. The empty-input early return of 0 is unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The create function and create trigger statements ran before the try block, so a failure while creating the trigger would leave the function behind for the rest of the run. Both now run inside the try, so the finally cleanup covers them. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
|
Understand this PR’s impact Explore downstream dependencies and potential security impact with Blast Radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository: prisma/orm/.coderabbit.yml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (4)
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthrough
ChangesCreate count reporting
Priority: ⬇️ Low Estimated code review effort: 2 (Simple) | ~15 minutes Change: Bug fix Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
@prisma/orm-extension-arktype-json
@prisma/orm-extension-middleware-cache
@prisma/orm-extension-paradedb
@prisma/orm-extension-pgvector
@prisma/orm-extension-postgis
@prisma/orm-extension-supabase
@prisma/orm-family-mongo
@prisma/orm-family-sql
@prisma/orm-framework
@prisma/orm-mongo
@prisma/orm-postgres
@prisma/orm-sqlite
@prisma/orm-target-mongo
@prisma/orm-target-postgres
@prisma/orm-target-sqlite
@prisma/orm-toolchain
commit: |
size-limit report 📦
|
|
Folded into #30365 as a single PR. |
…que constraint (#30365) ```ts const rows = [ { id: 1, email: '[email protected]' }, { id: 2, email: '[email protected]' }, // same email as row 1 { id: 3, email: '[email protected]' }, ]; const inserted = await db.User.createAll(rows, { onConflict: 'skip' }); // [{ id: 1, ... }, { id: 3, ... }] row 2 was skipped by the database const count = await db.User.createAndCount(rows, { onConflict: 'skip' }); // 2 ``` Before this PR, that call threw a unique violation and inserted nothing. Now the database skips the colliding row and the ORM returns only what was actually written. ## The decision `createAll` and `createAndCount` accept an options object. Its only option is `onConflict: 'skip'`, optionally with `conflictOn: ['email']` to name which unique constraint counts as "a conflict". The SQL is `INSERT ... ON CONFLICT DO NOTHING`, or `ON CONFLICT ("email") DO NOTHING` when a target is named. Prisma 7 called this `createMany({ skipDuplicates: true })`. We promised a user in `#prisma-8` on 2026-09-09 that Prisma 8 would get an equivalent. The scorecard listed it as deliberately absent, which contradicted that promise. ## How it works, from the SQL up **The SQL layer already knew how to do this, almost.** `upsert` uses `ON CONFLICT` today, so the SQL AST has an `InsertOnConflict` node and both renderers emit the clause. The one restriction was that a conflict clause had to name at least one column. Postgres and SQLite both accept `ON CONFLICT DO NOTHING` with no target, meaning "skip on any unique constraint", and that is what `skipDuplicates` did. So the AST gains a targetless form that is valid only with `DO NOTHING`. A targetless `DO UPDATE SET` makes no sense and both renderers still reject it. **What comes back.** `createAll` uses `RETURNING`, so it naturally yields only the rows the database inserted. `createAndCount` was a different story: it returned the length of the input array, not anything the database said. That was already a bug (a trigger could drop a row and the count would lie), and it would have made the count wrong for every skipped row. It now reads the driver's affected-row count, the way `updateAndCount` and `deleteAndCount` always have. That fix is the second commit and stands on its own. **Why SQLite needs a little more.** SQLite cannot take `DEFAULT` as a value in a multi-row insert, so when rows have different column sets the ORM already splits one `createAll` into one statement per column signature. The conflict clause goes on every one of those statements, and `createAndCount` sums the counts. **Why this is behind capabilities.** Prisma 8 never asks "which database is this". Instead, adapters report what they can do, the emitted `contract.json` records those capabilities, and features check for a capability key at the point of use. Two new keys: - `sql.insertOnConflictSkip`: the adapter can skip rows on a unique conflict at all. - `sql.insertOnConflictWithoutTarget`: it can do so without naming the constraint. Postgres and SQLite report both. The split exists for targets we plan to add. MySQL has no `ON CONFLICT` but can skip with `INSERT IGNORE`. SQL Server has neither and can only express "skip" as a `MERGE` or `WHERE NOT EXISTS` on an explicit key, so it will report the first key and not the second. Without the first key the option is refused with `ORM.CAPABILITY_MISSING`; without the second, only the untargeted form is refused. That is also why `conflictOn` is part of the API from day one rather than something bolted on when SQL Server arrives. **What is refused on purpose.** Multi-table inheritance variants: a variant row is a base-table insert followed by a variant-table insert per row, and a skipped variant insert would leave an orphan base row. Refused with `ORM.OPERATION_UNSUPPORTED` until we do savepoint-per-row. `create()` does not take the option; a single row that may or may not be inserted is `upsert` with an empty update, which already exists. Mongo is untouched. ## What is in the diff - `packages/2-sql/4-lanes/relational-core`: `InsertOnConflict.doNothing()` for the targetless form. - `packages/3-targets/6-adapters/{postgres,sqlite}`: render the targetless clause; report the two capability keys in the runtime profile and in the map that the emitter copies into `contract.json`. - `packages/3-extensions/sql-orm-client`: the option on `createAll` and `createAndCount`, the capability and MTI checks, `conflictOn` field-to-column mapping through the same path `upsert` uses, and the `createAndCount` count fix. - `docs/reference/capabilities.md`, the sql-orm-client README, JSDoc on both methods, the scorecard row, and an upgrade note. - `projects/createall-conflict-skip/`: the spec, design notes, and plan this was built from. Transient; deleted at close-out per the projects convention. - 473 regenerated `contract.json` / `contract.d.ts` fixtures. See the next section before you scroll through them. ## About the regenerated contracts Every emitted contract carries the adapter's capability map, so adding two keys touches every fixture in the repo. I checked all 473 files mechanically: the only change in any of them is the two added keys, and no hash moved. Eighteen of them are migration snapshots under `migrations/snapshots/`. Our convention says snapshots are written once, but the regen scripts that `pnpm fixtures:check` runs rewrite snapshot contracts unconditionally, so leaving them out fails the check. They are included; a contract without the keys still loads fine and simply refuses the option. Making the regen scripts leave existing snapshots alone is a separate follow-up. Users on an existing contract must re-emit it before they can use the option. The upgrade note under `upgrade-instructions/pending/` says so. ## How it is tested - Postgres integration, `test/integration/test/sql-orm-client/create-on-conflict.test.ts`: collision against an existing row, targeted and untargeted, every row colliding, a collision on a constraint other than the named one still raising, both capability refusals, and a batch whose rows collide with each other. Each goes red if the clause is dropped. - SQLite end to end: the split path with a collision in one of two statements, and the within-batch case. - Two Prisma engine cases (`create_many_no_error_skip_dup` and its `createManyAndReturn` variant) ported faithfully under `test/integration/test/ports/engines/writes/top_level_mutations/create_many/` and ticked in the port checklist. - Unit tier: the AST node, both renderers with exact SQL strings, plan compilation, collection behaviour including the old callback-in-second-position call form, and every structured error code. - The `createAndCount` fix: a `BEFORE INSERT` trigger drops one of three rows on Postgres and the count comes back as 2. ## Alternatives considered - **`skipDuplicates: true`, the Prisma 7 name.** Familiar, but a boolean cannot carry a conflict target, and SQL Server needs one. Rejected. - **`onConflict: 'doNothing'`.** Serhii's suggestion; matches the SQL. Kept `'skip'` because it is target-neutral: MySQL spells this `INSERT IGNORE` and SQL Server `MERGE`, and `'skip'` names what the caller observes. Neither of us felt strongly. - **Letting `onConflict` grow an `update` value later.** No. `upsert` owns update-on-conflict; a batch form would be its own method. - **A separate method such as `createAllIgnoringConflicts`.** Doubles with `createAndCount`. Rejected. - **A chained modifier, `db.User.onConflict('skip').createAll(rows)`.** Puts a write-only flag into builder state that `find`, `select`, and `include` share. Rejected. - **Always requiring `conflictOn`.** Most portable, but forces every Postgres and SQLite user to name a constraint for the common case. The second capability key makes the requirement target-specific instead. - **Supporting MTI variants with a savepoint per row.** Correct but a second transaction concern inside an experimental surface. Deferred. Supersedes #30363 and #30364, which were these commits split for stacked review. No Linear issue exists for this work yet. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]>
Decision
createAndCountnow returns the number of rows the database reports inserting, read from the execute statistics the wayupdateAndCountanddeleteAndCountalready do. On the SQLite split path the per-statement counts are summed. It used to returndata.length, the input length, which is wrong whenever the database inserts fewer rows than it was given.Why now
This is slice 1 of the createAll conflict-skip project (#30363). The next slice adds an
onConflict: 'skip'option that makes the database drop colliding rows, so the count must already be the database's before that lands. It is a bug on its own regardless.Evidence
collection.state.test.tsstub the execute statistics to report fewer rows than passed, on the single-statement path and the split path. Both failed against the old code.BEFORE INSERTtrigger drops one of three rows;createAndCountreturns 2 and the table holds the two surviving rows. Failed against the old code withexpected 3 to be 2.Gates
pnpm --filter @internal/sql-orm-client test(920 tests), that package'slint, and thesql-orm-client/createintegration file in both vitest projects all pass.pnpm typecheckhas five pre-existing errors in the packaging tarball tests that reproduce on the base commit.Stacking
Based on the shaping branch so the slice spec is reviewable alongside. Retarget to
mainonce #30363 merges. No Linear issue exists yet.🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
createAndCount()now reports the number of rows actually inserted by the database, rather than the number of rows provided as input.Tests