Repository navigation
Closed
Description
proposing the following functionality (essentially insert... on conflict.. returning..):
const result = model.upsert({
id: 123,
someValue: "test"
}, {
returnAll: true
});
console.log(result); // outputs entire updated model, including preexisting fields, auto-updated fields
const result = model.upsert({
id: 123,
someValue: "test"
});
console.log(result); // outputs some indicator as to whether or not an insert or an update occurred
const result = model.upsert({
id: 123,
someValue: "test"
}, {
returnPartial: [
'id',
'someValue',
'someOtherValue'
]
);
console.log(result); // outputs a partial object with specified fields loadedat least in postgres, this is possible in a single operation, but it's not currently possible in a single operation with TypeORM (example not tested, just for showing a current rough solution..):
import { Column, PrimaryColumn, Repository, UpdateDateColumn } from "typeorm";
import { Entity } from "typeorm/decorator/entity/Entity";
export class SomeServiceClass {
constructor(
private repo: Repository<SomeAggregate>
) {}
public async handleSomeEventWithTypeORMMethods( event: ISomeEvent ): Promise<SomeAggregate> {
let model = await this.repo.findOne({
id: event.id,
});
if ( ! model ) {
model = new SomeAggregate();
}
model.valueToUpdate = event.valueToUpdate;
await this.repo.persist(model);
const updatedModel = await this.repo.findOne({
id: event.id,
});
return updatedModel;
}
public async handleSomeEventWithRawQuery( event: ISomeEvent ): Promise<SomeAggregate> {
const results = await this.repo.query(`
INSERT INTO
some_table
(
"id",
"valueToUpdate"
)
VALUES
(
$1,
$2
)
ON CONFLICT( "id" )
DO UPDATE
SET
"valueToUpdate" = $2
WHERE
"some_table"."id" = $1
RETURNING *
`, [
event.id,
event.valueToUpdate
]);
return results[0];
}
}
@Entity()
export class SomeAggregate {
@PrimaryColumn("uuid")
public id: string;
@Column("text")
public valueToUpdate ?: string;
@Column("text")
public anotherValue ?: string;
@UpdateDateColumn({type: "timestamp with time zone"})
public modifiedAt ?: Date;
}
export interface ISomeEvent {
id: string;
valueToUpdate: string;
}Reacted by Tino Butz, Stefan Hipfel, Daniel Heffter, user3587412, Ludwik Trammer, Kris Kaczor, Ivan Wang, Mariusz Kujawski, Park Hee Chan, Mantz and 26 more
Activity
added "ON CONFLICT" cause support for #1090
pleerock commentedon Nov 22, 2017
I added
onConflictmethod toinsert query builder.This functionality was made just to support onConflict clause inside InsertQueryBuilder and it only appends given ON CONFLICT statement into insertion query, no more then that.
It has such limited functionality due to complexity and flexibility of "on conflict" statement.
You can use it this way:
For now
upsertmethod will not be implemented repository/entity manager.If you need a single query you have to use a bit inconvenient query and build onConflict on your own as in example above. If you simply want to a update an entity use regular
savemethod instead.Will be released in
0.1.6Merge branch 'master' into next
landon9720 commentedon Apr 26, 2019
The above examples show using
onConflictto set theDO UPDATE SET ...clause with a single input record tovalues. Butvaluesalso supports an array of input records. How can theDO UPDATE SETparameters be set per record passed tovalues?ajayvardhan commentedon May 23, 2019
@pleerock @Kononnable any word on support on array of inputs?
also, is this only for postgres or does it work for mysql as well?
rsbh commentedon May 28, 2019
can we update row on conflict?
matiasdelgado commentedon Jul 9, 2019
@landon9720 in postgres you can use the
excludedkey, like this:mschuttt commentedon Jul 23, 2019
What's the status on this issue?
EvaLok commentedon Jul 25, 2019
@mschuttt i haven't been following this project for years, however, i ended up using another library instead which is based on sequelize. it has (user-friendly) upsert functionality and the typescript features are fairly similar if you're used to typeorm
https://github.com/RobinBuschmann/sequelize-typescript
danielmhanover commentedon Aug 3, 2019
For those who do not want to finagle with onConflict themselves:
https://github.com/danielmhanover/typeorm-upsert
35 remaining items
feat: upsert/query-builder insert or update all columns
feat: upsert/query-builder insert or update all columns
feat: upsert/query-builder insert or update all columns
feat: upsert/query-builder insert or update all columns
feat: upsert/query-builder insert or update all columns
feat: upsert/query-builder insert or update all columns
DedaDev commentedon Mar 9, 2021
this worked for me,
#4122 (comment)
conoremclaughlin commentedon Jan 24, 2022
For anyone that stumbles upon this from Google, upsert is directly supported in
^0.2.40. Thanks to the hard work of of the TypeORM folks:#8104
Which closed:
#2363
The new method signature is:
So for @ahmadalfy's solution, you'll now need:
And you can find the current implementation of orUpdate here:
typeorm/src/query-builder/InsertQueryBuilder.ts
Line 356 in 26581d0
LuisOfCourse commentedon Feb 14, 2022
What about unique set of colums? I have the following example
This example here gives the following errror: "QueryFailedError: column "dayofweek-pickuppoint" does not exist". So you cant use Unique set of columns?
CNLHC commentedon Mar 7, 2022
Same problem here. I am looking for how to achieve
INSERT ... ON CONFLICT CONSTRAINT 'foo' DO UPDATE ...omerd-cyera commentedon Sep 19, 2022
@LuisOfCourse @CNLHC Did you find a solution/workaround?
JE-Zenarosa commentedon Oct 13, 2022
upsert typeorm function not working.... still inserting even i defined the column that should be unique
mlevkovsky commentedon Mar 4, 2023
is you're column nullable? In Mysql null values can't be used for a constraint
ajangidm commentedon Sep 29, 2023
Does this solution work for
@conoremclaughlin, does this work for postgres?
In my case it is inserting new rows for all the entities, while I am trying to update entities which have PK property set.
I am using following versions:
node: 18.16.0
typeorm: 0.3.17
postgres: 12.1
erBhushanPawar commentedon Jan 25, 2024
I know I'm too late to catch on this but here is my solution