Skip to content

upsert with return functionality #1090

Closed

Description

@EvaLok

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 loaded

at 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;
}

Activity

  1. added this to the 0.2.0 milestone on Nov 20, 2017
  2. self-assigned this
    on Nov 20, 2017
  3. pleerock commented on Nov 22, 2017

    @pleerock
    Member

    I added onConflict method to insert 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:

            await connection.createQueryBuilder()
                .insert()
                .into(Post)
                .values(post2)
                .onConflict(`("id") DO NOTHING`)
                .execute();
    
            await connection.createQueryBuilder()
                .insert()
                .into(Post)
                .values(post2)
                .onConflict(`("id") DO UPDATE SET "title" = :title`)
                .setParameter("title", post2.title)
                .execute();

    For now upsert method 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 save method instead.

    Will be released in 0.1.6

  4. added a commit that references this issue on Nov 22, 2017
  5. landon9720 commented on Apr 26, 2019

    @landon9720

    The above examples show using onConflict to set the DO UPDATE SET ... clause with a single input record to values. But values also supports an array of input records. How can the DO UPDATE SET parameters be set per record passed to values?

  6. ajayvardhan commented on May 23, 2019

    @ajayvardhan

    @pleerock @Kononnable any word on support on array of inputs?

    also, is this only for postgres or does it work for mysql as well?

  7. rsbh commented on May 28, 2019

    @rsbh

    can we update row on conflict?

  8. matiasdelgado commented on Jul 9, 2019

    @matiasdelgado

    @landon9720 in postgres you can use the excluded key, like this:

    await connection.createQueryBuilder()
        .insert()
        .into(Post)
        .values([post1, post2, ...])
        .onConflict(`("id") DO UPDATE SET "title" = excluded.title`)
        .execute();
  9. mschuttt commented on Jul 23, 2019

    @mschuttt

    What's the status on this issue?

  10. EvaLok commented on Jul 25, 2019

    @EvaLok
    Author

    @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

  11. danielmhanover commented on Aug 3, 2019

    @danielmhanover
  12. 35 remaining items

  13. added 2 commits that reference this issue on Jan 27, 2021
    33e20fe
    c878820
  14. added 4 commits that reference this issue on Feb 25, 2021
    ca56381
    bfa55aa
    aeab403
    eeb1063
  15. DedaDev commented on Mar 9, 2021

    @DedaDev

    Is there a plausible method of using this to use a constraint for the conflict target?

    this worked for me,
    #4122 (comment)

  16. conoremclaughlin commented on Jan 24, 2022

    @conoremclaughlin

    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:

    orUpdate(overwrite: string[], conflictTarget?: string | string[]): this;
    

    So for @ahmadalfy's solution, you'll now need:

    await getConnection()
      .createQueryBuilder()
      .insert()
      .into(GroupEntity)
      .values(updatedGroups)
      .orUpdate(
        ['name', 'parentId', 'web', 'avatar', 'description'],
        ['id']
      )
      .execute();

    And you can find the current implementation of orUpdate here:

    if (this.connection.driver.supportedUpsertType === "on-conflict-do-update") {

  17. LuisOfCourse commented on Feb 14, 2022

    @LuisOfCourse

    What about unique set of colums? I have the following example

    @Entity()
    @Unique('dayofweek-pickuppoint', ['pickuppoint', 'dayOfWeek'])
    export class WorkDays {
    	@PrimaryGeneratedColumn({ type: 'bigint' })
    	id: string;
    
    	@ManyToOne(() => Pickuppoint, (pickuppoint) => pickuppoint.workhours)
    	pickuppoint: Pickuppoint;
    
    	@Column({ type: 'enum', enum: DayOfWeekEnum })
    	dayOfWeek: DayOfWeekEnum;
    
    	@Column({ type: 'time' })
    	startMorning: string;
    
    	@Column({ type: 'time' })
    	endMorning: string;
    
    	@Column({ type: 'time' })
    	startAfternoon: string;
    
    	@Column({ type: 'time' })
    	endAfternoon: string;
    }
    
    this.workHourRepository
    			.createQueryBuilder()
    			.insert()
    			.values(plaindays)
    			.orUpdate(
    				[
    					'dayOfWeek',
    					'startMorning',
    					'startAfternoon',
    					'endMorning',
    					'endAfternoon',
    				],
    				[ 'dayofweek-pickuppoint'],
    			)
    			.execute();
    
    

    This example here gives the following errror: "QueryFailedError: column "dayofweek-pickuppoint" does not exist". So you cant use Unique set of columns?

  18. CNLHC commented on Mar 7, 2022

    @CNLHC

    What about unique set of colums? I have the following example

    @Entity()
    @Unique('dayofweek-pickuppoint', ['pickuppoint', 'dayOfWeek'])
    export class WorkDays {
    	@PrimaryGeneratedColumn({ type: 'bigint' })
    	id: string;
    
    	@ManyToOne(() => Pickuppoint, (pickuppoint) => pickuppoint.workhours)
    	pickuppoint: Pickuppoint;
    
    	@Column({ type: 'enum', enum: DayOfWeekEnum })
    	dayOfWeek: DayOfWeekEnum;
    
    	@Column({ type: 'time' })
    	startMorning: string;
    
    	@Column({ type: 'time' })
    	endMorning: string;
    
    	@Column({ type: 'time' })
    	startAfternoon: string;
    
    	@Column({ type: 'time' })
    	endAfternoon: string;
    }
    
    this.workHourRepository
    			.createQueryBuilder()
    			.insert()
    			.values(plaindays)
    			.orUpdate(
    				[
    					'dayOfWeek',
    					'startMorning',
    					'startAfternoon',
    					'endMorning',
    					'endAfternoon',
    				],
    				[ 'dayofweek-pickuppoint'],
    			)
    			.execute();
    

    This example here gives the following errror: "QueryFailedError: column "dayofweek-pickuppoint" does not exist". So you cant use Unique set of columns?

    Same problem here. I am looking for how to achieve INSERT ... ON CONFLICT CONSTRAINT 'foo' DO UPDATE ...

  19. omerd-cyera commented on Sep 19, 2022

    @omerd-cyera
    Contributor

    @LuisOfCourse @CNLHC Did you find a solution/workaround?

  20. JE-Zenarosa commented on Oct 13, 2022

    @JE-Zenarosa

    upsert typeorm function not working.... still inserting even i defined the column that should be unique

  21. mlevkovsky commented on Mar 4, 2023

    @mlevkovsky

    upsert typeorm function not working.... still inserting even i defined the column that should be unique

    is you're column nullable? In Mysql null values can't be used for a constraint

  22. ajangidm commented on Sep 29, 2023

    @ajangidm

    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:

    orUpdate(overwrite: string[], conflictTarget?: string | string[]): this;
    

    So for @ahmadalfy's solution, you'll now need:

    await getConnection()
      .createQueryBuilder()
      .insert()
      .into(GroupEntity)
      .values(updatedGroups)
      .orUpdate(
        ['name', 'parentId', 'web', 'avatar', 'description'],
        ['id']
      )
      .execute();

    And you can find the current implementation of orUpdate here:

    if (this.connection.driver.supportedUpsertType === "on-conflict-do-update") {

    Does this solution work for

    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:

    orUpdate(overwrite: string[], conflictTarget?: string | string[]): this;
    

    So for @ahmadalfy's solution, you'll now need:

    await getConnection()
      .createQueryBuilder()
      .insert()
      .into(GroupEntity)
      .values(updatedGroups)
      .orUpdate(
        ['name', 'parentId', 'web', 'avatar', 'description'],
        ['id']
      )
      .execute();

    And you can find the current implementation of orUpdate here:

    if (this.connection.driver.supportedUpsertType === "on-conflict-do-update") {

    @conoremclaughlin, does this work for postgres?

    await getConnection()
      .createQueryBuilder()
      .insert()
      .into(GroupEntity)
      .values(updatedGroups)
      .orUpdate(
        ['name', 'parentId', 'web', 'avatar', 'description'],
        ['id']
      )
      .execute();
    

    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

  23. erBhushanPawar commented on Jan 25, 2024

    @erBhushanPawar

    I know I'm too late to catch on this but here is my solution

    
    async upsertRecord(createDtoGeneric, read: boolean = true) {
            const pk = createDtoGeneric.getPK()
            // enable below if pk is not auto-generated column
            // if (!createDtoGeneric[createDtoGeneric.getPK()])
            //     createDtoGeneric.initPK()
            const upsertResponse = await this._repo.upsert(createDtoGeneric, { conflictPaths: createDtoGeneric.getConflictPaths(), skipUpdateIfNoValuesChanged: true, upsertType: 'on-conflict-do-update' })
            if (read) {
                delete createDtoGeneric[pk]
                return await this.findOneByQuery(createDtoGeneric)
            }
            else
                return upsertResponse;
        }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions