Skip to content

support for ON CONFLICT ON CONSTRAINT clause in PostgreSQL-like database #8731

Closed

Description

@CNLHC

Feature Description

The Problem

In #1090, TypeORM supported orUpdate in its query builder to support upsert. But currently, it is only possible to perform an upsert when the single column violation happens. It seems not possible now to perform an upsert when a key constraint violation happens.

Assume that one has this DDL in the PostgreSQL database:

create table issue_synced_items
(
    id          uuid      default uuid_generate_v4() not null
        constraint issue_synced_items_pk
            primary key,
    created_at  timestamp default (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'::text),
    updated_at  timestamp,
    instance_id uuid,
    left_id     varchar(128),
    right_id    varchar(128),
    constraint unique_pair
        unique (left_id, right_id)
);

it is possible to do an upsert on primary key violations by

      await getConnection().createQueryBuilder(SyncedItems, "synced_items")
                .insert()
                .into(SyncedItems)
                .values(item)
                .orUpdate(['updated_at'],['id'])
                .setParameter("t", new Date())
                .execute()

But if one wants to update on unique_pair constraint violation, a.k.a (left_id,right_id) already exists in the table, there is no way to achieve this by using orUpdate since the update will treat its' second parameter as a column.

The Solution

A Possible solution may be to add a third parameter for the orUpdate method so that it can properly handle the ON CONSTRAINT clause in the PostgreSQL-like database.

Considered Alternatives

Another possible solution for this problem is using

          await getConnection().createQueryBuilder(SyncedItems, "synced_items")
                .insert()
                .into(SyncedItems)
                .values(item)
                .onConflict("ON CONSTRAINT unique_pair DO UPDATE SET updated_at = :t")
                .setParameter("t", new Date())
                .execute()

If #8168 is solved, I believe this problem can be solved ( in some way ).

Additional Context

document for on conflict clause in PostgreSQL

Relevant Database Driver(s)

DB Type Relevant
aurora-data-api no
aurora-data-api-pg no
better-sqlite3 no
cockroachdb no
cordova no
expo no
mongodb no
mysql no
nativescript no
oracle no
postgres yes
react-native no
sap no
sqlite no
sqlite-abstract no
sqljs no
sqlserver no

Are you willing to resolve this issue by submitting a Pull Request?

  • ✖️ Yes, I have the time, but I don't know how to start. I would need guidance.

Activity

  1. Ginden commented on Mar 8, 2022

    @Ginden
    Contributor

    You can use onConflict method of InsertQueryBuilder right now (though, it's deprecated).

  2. kristijanhusak commented on Sep 2, 2022

    @kristijanhusak

    You can use onConflict method of InsertQueryBuilder right now (though, it's deprecated).

    Do you know if there will be some alternative for this once it gets removed?

  3. sylvainar commented on Sep 10, 2025

    @sylvainar

    Adding to this thread, I have this usecase that I don't think I can do any other way than with an onConflict, I want to be able to do a merge operation between the previous version of the line and the new one (here adding new planIds in the list everytime I get a new one):

    const query = this.metricMetadataRepository
            .createQueryBuilder()
            .insert()
            .into(MetricMetadata)
            .values({
              ...md,
              // In case of insert, put the current plan.
              planIds: [planId],
            })
             // In case of update, add the current planId to the list (will remove doubles)
            .onConflict(
              `
                ("key")
                DO UPDATE
                    SET "planIds" = case when EXCLUDED."planIds" @> :planId = true then EXCLUDED."planIds" else EXCLUDED."planIds" || :planId end
            `.replaceAll('\n', ''),
            )
            .setParameters({ planId });
    
          return query.execute();
  4. Cprakhar commented on Jan 10, 2026

    @Cprakhar
    Collaborator

    @CNLHC I think the requested feature has been successfully implemented.

  5. gioboa commented on Jan 10, 2026

    @gioboa
    Collaborator

    #11908 confirms that it working fine now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions