PSQL typeorm upsert with where on update

35 views Asked by At

How do make a typeorm query cmd as below

INSERT INTO t1 (id, data, createdAt)  
VALUES 
(1, 'data3', '2022-01-03'), 
(2, 'data3', '2022-01-02')  
ON CONFLICT (id) DO UPDATE SET  
  data = CASE  
           WHEN EXCLUDED.createdAt > t1.createdAt THEN EXCLUDED.data  
           ELSE t1.data  
         END,  
  createdAt = CASE  
             WHEN EXCLUDED.createdAt > t1.createdAt THEN EXCLUDED.createdAt  
             ELSE t1.createdAt  
           END;  

the goal is to upsert the data, but only update if the createdAt > than before, else ignore

use 2 query can do the same, but it may not strong consistency

1

There are 1 answers

1
r_dmr On

TypeORM provides support for raw queries as well. If you want, you can use the raw query, or a query builder. Here is an example from the docs where it tackles same kind of issue