News for hackers. Stuff that matters.
Re:The Many Faces of Distinct in PostgreSQL by paulddraper on Monday May 22, 2023 @11:39AM (#36032854)
> You can’t target conflicts against multiple constraints,

I've never needed that, and it's not clear why I would.

Like, my new record is a duplicate of record A according to one constraint and record B according to another constraint, so it updates both A and B?

One "upsert" but two resulting records?

Can someone fill me in on when this would crop up?

Re:The Many Faces of Distinct in PostgreSQL by richbell on Monday May 22, 2023 @12:15PM (#36033316)
In my experience this tends to be an annoyance when you want to upsert against a table that has multiple unique constraints.

For example, let's say you're tracking GitHub repositories and have a table `repository(id, gh_id, gh_node_id, owner, name, description)` where `gh_id` and `gh_node_id` are both unique.

If you want to insert or update a repository you might want to do something like below, however, this is not a valid syntax and as you need to define a separate `DO UPDATE` for `gh_id` and `gh_node_id`:

    INSERT INTO repository (gh_id, gh_node_id, owner, name, description)
    VALUES (:id, :node_id, :owner, :name, :description)
    ON CONFLICT DO UPDATE
       SET name = excluded.name, 
           description = excluded.description;

------

To my knowledge there's no way to define a single constraint `UNIQUE(gh_id || gh_node_id)` instead of `UNIQUE(gh_id && gh_node_id)`.

Re:The Many Faces of Distinct in PostgreSQL by paulddraper on Monday May 22, 2023 @02:10PM (#36034668)
So....what is gh_id and gh_node_id?

Like, you have

    gh_id | gh_node_id
    ------------------
      1   |     2    
      2   |     1
And then you want to "upsert" (1, 1).

You want both records to be updated?

I'm still struggling to see why you would want to do a upsert relative to multiple unique constraints at once.

Re:The Many Faces of Distinct in PostgreSQL by cropcirclbureau on Monday May 22, 2023 @08:56PM (#36038565)
Ah, I'd run into the lack of multi constraint ON CONFLICT in postgres yesterday and was wondering about the omission. I'd not considered this case and GP's code smell comment makes sense now.

In my specific case, business logic dictates uniqueness of both columns is tied together i.e. if an incoming tuple has a value (1, 2) today, all subsequent expected tuples with `gh_id` 1 will also have `gh_node_id` of 2. What's the best practice to model this constraint?

Re:The Many Faces of Distinct in PostgreSQL by paulddraper on Monday May 22, 2023 @10:12PM (#36038987)
Then upsert based on gh_id.

I'm not saying that multiple unique identifiers is a code smell; I am claiming that an upsert is only sensibly done in the context of one constraint.