简体   繁体   中英

Postgres: use MAX in ON CONFLICT

I have the following table schema:

CREATE TABLE table (
   pk1 bigint,
   pk2 bigint,
   some_text varchar(4),
   valid_until bigint,
   PRIMARY KEY (pk1, pk2)

I want to insert into this table a record in a way that in case of conflict the final value of valid_until column is maximum of the old value and the new one.

Is it possible to achieve? If yes - is it possible to do it framework-friendly way (I'm using Scala Quill)?

It is at least possible to do through SQL, I'm not sure if you can do it in Quill without doing a separate select of data. The pure SQL version would look a bit like (pure memory, so there are likely mistakes):

INSERT INTO table (42, 84, 'some_text', 9000)
ON CONFLICT DO UPDATE
    SET some_text = 'some_text',
        valid_until = (SELECT GREATEST(9000, valid_until) FROM table WHERE pk1=42 AND pk2=84 LIMIT 1));

Hopefully this idea might get you moving forward :) You can probably imitate it somehow in Quill. Usually I actually try to avoid framworks that try to be clever with databases, it almost always ends up being the Hibernate-trap all over again, where the search for avoiding SQL ends up costing way more than just doing it. Maybe Scala framworks are better though, at least Scala is way better designed for designing such framworks, so maybe it works better there.

Updated the answer with ON CONFLICT as described here: Insert, on duplicate update in PostgreSQL?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM