Repository navigation
Description
Issue description
insert().orIgnore() writes the returned rows back onto the wrong entities when a row is skipped
Expected Behavior
After insert().values(entities).orIgnore().execute(), each entity either gets the generated values of its own row, or is left alone if its row was skipped. InsertResult.identifiers and generatedMaps line up with the entities in the same way.
Actual Behavior
ReturningResultsEntityUpdator.insert matches the RETURNING rows to the entities by array position (insertResult.raw[entityIndex]). ON CONFLICT DO NOTHING returns no row for a skipped entity, so every row after it moves up one place onto the previous entity:
raw: [ { id: '0b0b5887-2622-4430-9eb2-d914ea4cf528' } ]
tags: [
Tag { id: '0b0b5887-2622-4430-9eb2-d914ea4cf528', name: 'a' }, // <- this is b's id
Tag { id: undefined, name: 'b' } // <- b's id is lost
]
identifiers: [ { id: '0b0b5887-2622-4430-9eb2-d914ea4cf528' }, undefined ]
in db: [
Tag { id: '4dedf6d6-b9af-40e0-a048-52d78b0ad777', name: 'a' },
Tag { id: '0b0b5887-2622-4430-9eb2-d914ea4cf528', name: 'b' }
]
Entity a was skipped but now carries b's id. b was inserted but has no id. The same thing happens to every column TypeORM adds to RETURNING (create/update dates, columns with a default, and columns passed to .returning()), while the other fields stay on the original entity. If you set the id before the insert (e.g. a uuid you generate yourself), a ends up with b's id and b keeps its own, so two entities share the same id.
This silently breaks the common pattern "insert, ignore duplicates, then act on what was inserted". In our case it sent "blocked" notifications for records that already existed.
Steps to reproduce
import "reflect-metadata"
import { Column, DataSource, Entity, PrimaryGeneratedColumn } from "typeorm"
@Entity()
class Tag {
@PrimaryGeneratedColumn("uuid")
id: string
@Column({ type: "varchar", unique: true })
name: string
}
const dataSource = new DataSource({
type: "postgres",
url: "postgres://postgres:pw@localhost:5432/postgres",
entities: [Tag],
synchronize: true,
dropSchema: true,
})
async function main() {
await dataSource.initialize()
const repo = dataSource.getRepository(Tag)
// "a" already exists, so the insert below skips it
await repo.insert({ name: "a" })
const tags = [repo.create({ name: "a" }), repo.create({ name: "b" })]
const result = await repo
.createQueryBuilder()
.insert()
.values(tags)
.orIgnore()
.execute()
console.log("raw:", result.raw)
console.log("tags:", tags)
console.log("identifiers:", result.identifiers)
console.log("in db:", await repo.find({ order: { name: "ASC" } }))
await dataSource.destroy()
}
main()The workaround is .updateEntity(false), then reading result.raw and matching it back by a natural key yourself.
My Environment
| Dependency | Version |
|---|---|
| Operating System | Linux (Ubuntu, kernel 6.8) |
| Node.js version | 24.21.0 |
| Typescript version | 5.9.3 |
| TypeORM version | 1.1.2 |
| pg | 8.23.1 |
| PostgreSQL | 16.14 |
Additional Context
This is the same bug as #5226. That issue had a failing test case, but it was closed as stale in the 2025 backlog cleanup without a fix. It still happens on 1.1.2, and master still uses raw[entityIndex].
Related, but not covering this case:
- upsert() with MySQL mutates input entity objects in-place with wrong auto-increment IDs after ON DUPLICATE KEY UPDATE #12094 / PR fix(upsert): prevent input entity mutation during upsert result merge #12155 stop the write-back for upserts (
expressionMap.onUpdate), not fororIgnore(). - ReturningResultsEntityUpdator assigning incorrect uuids to entities after upsert #10574 and upsert incorrectly modified entities #11083 are about the order of the re-select used on drivers without
RETURNING.
A possible fix: when onIgnore is set (or RETURNING returns fewer rows than entities), match the returned rows to entities by primary key or by the conflict columns instead of by position. If an entity can't be matched, leave it alone rather than giving it another row's values.
Relevant Database Driver(s)
- aurora-mysql
- aurora-postgres
- better-sqlite3
- capacitor
- cockroachdb
- cordova
- expo
- mongodb
- mysql
- nativescript
- oracle
- postgres
- react-native
- sap
- spanner
- sqlite
- sqljs
- sqlserver
Are you willing to resolve this issue by submitting a Pull Request?
Yes, I have the time, and I know how to start.
Activity
fix(query-builder): map orIgnore/orUpdate returning rows to entities …
fix(query-builder): map orIgnore/orUpdate returning rows to entities …