Skip to content

fix(sql-orm-client): createAndCount returns the database count - #30364

Closed
wmadden-electric wants to merge 3 commits into
createall-conflict-skipfrom
createall-conflict-skip-01-create-and-count
Closed

wmadden-electric wants to merge 3 commits into
createall-conflict-skipfrom
createall-conflict-skip-01-create-and-count

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Decision

createAndCount now returns the number of rows the database reports inserting, read from the execute statistics the way updateAndCount and deleteAndCount already do. On the SQLite split path the per-statement counts are summed. It used to return data.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

  • Unit tier: two tests in collection.state.test.ts stub the execute statistics to report fewer rows than passed, on the single-statement path and the split path. Both failed against the old code.
  • Postgres integration: a BEFORE INSERT trigger drops one of three rows; createAndCount returns 2 and the table holds the two surviving rows. Failed against the old code with expected 3 to be 2.
  • Two pre-existing tests that happened to rely on the input length gained one statistics stub each; their assertions are unchanged.

Gates

pnpm --filter @internal/sql-orm-client test (920 tests), that package's lint, and the sql-orm-client/create integration file in both vitest projects all pass. pnpm typecheck has 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 main once #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.
    • Counts remain accurate when inserts are split into multiple operations or when database triggers skip rows.
  • Tests

    • Added coverage for database-reported counts, split inserts, and rows skipped by insert triggers.

wmadden-electric and others added 3 commits September 21, 2026 15:43
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]>
@wmadden-electric
wmadden-electric requested a review from a team as a code owner September 21, 2026 13:55
@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Understand this PR’s impact

Explore downstream dependencies and potential security impact with Blast Radius.

View blast radius →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: prisma/orm/.coderabbit.yml

Review profile: CHILL

Plan: Advanced

Run ID: 90f7154d-a083-4dbf-8d00-61e9ce19f742

📥 Commits

Reviewing files that changed from the base of the PR and between 1bea120 and 53b35e2.

📒 Files selected for processing (4)
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/test/collection.state.test.ts
  • packages/3-extensions/sql-orm-client/test/orm-namespace-crud.test.ts
  • test/integration/test/sql-orm-client/create.test.ts

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


📝 Walkthrough

Walkthrough

createAndCount() now returns database-reported affected-row counts. Split inserts sum counts from each execution. Tests cover single inserts, split inserts, namespace calls, and trigger-skipped rows.

Changes

Create count reporting

Layer / File(s) Summary
Affected-row count implementation
packages/3-extensions/sql-orm-client/src/collection.ts
createAndCount() returns stats.affectedRows for single inserts and sums it across split inserts. Its JSDoc describes the database-reported count.
Count behavior validation
packages/3-extensions/sql-orm-client/test/*, test/integration/test/sql-orm-client/create.test.ts
Tests cover affected-row values for single and split inserts, namespace calls, and a database trigger that skips one input row.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Bug fix

Suggested reviewers: tensordreams

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely identifies the main change: createAndCount now returns the database-reported count.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 4…
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.
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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

@pkg-pr-new

pkg-pr-new Bot commented Sep 21, 2026

Copy link
Copy Markdown

Open in StackBlitz

@prisma/orm-extension-arktype-json

npm i https://pkg.pr.new/@prisma/orm-extension-arktype-json@30364

@prisma/orm-extension-middleware-cache

npm i https://pkg.pr.new/@prisma/orm-extension-middleware-cache@30364

@prisma/orm-extension-paradedb

npm i https://pkg.pr.new/@prisma/orm-extension-paradedb@30364

@prisma/orm-extension-pgvector

npm i https://pkg.pr.new/@prisma/orm-extension-pgvector@30364

@prisma/orm-extension-postgis

npm i https://pkg.pr.new/@prisma/orm-extension-postgis@30364

@prisma/orm-extension-supabase

npm i https://pkg.pr.new/@prisma/orm-extension-supabase@30364

@prisma/orm-family-mongo

npm i https://pkg.pr.new/@prisma/orm-family-mongo@30364

@prisma/orm-family-sql

npm i https://pkg.pr.new/@prisma/orm-family-sql@30364

@prisma/orm-framework

npm i https://pkg.pr.new/@prisma/orm-framework@30364

@prisma/orm-mongo

npm i https://pkg.pr.new/@prisma/orm-mongo@30364

@prisma/orm-postgres

npm i https://pkg.pr.new/@prisma/orm-postgres@30364

@prisma/orm-sqlite

npm i https://pkg.pr.new/@prisma/orm-sqlite@30364

@prisma/orm-target-mongo

npm i https://pkg.pr.new/@prisma/orm-target-mongo@30364

@prisma/orm-target-postgres

npm i https://pkg.pr.new/@prisma/orm-target-postgres@30364

@prisma/orm-target-sqlite

npm i https://pkg.pr.new/@prisma/orm-target-sqlite@30364

@prisma/orm-toolchain

npm i https://pkg.pr.new/@prisma/orm-toolchain@30364

commit: 53b35e2

@github-actions

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size
postgres / no-emit 189.61 KB (+0.01% 🔺)
postgres / emit 159.96 KB (+0.01% 🔺)
mongo / no-emit 109.45 KB (0%)
mongo / emit 91.8 KB (0%)
cf-worker / no-emit 212.67 KB (0%)
cf-worker / emit 179.97 KB (0%)

@wmadden-electric

Copy link
Copy Markdown
Contributor Author

Folded into #30365 as a single PR.

wmadden-electric added a commit that referenced this pull request Sep 22, 2026
…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]>
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.

1 participant