activerecord-rescue_from_duplicate icon indicating copy to clipboard operation
activerecord-rescue_from_duplicate copied to clipboard

support composite primary keys

Open mkcny opened this issue 5 years ago • 4 comments

The function that was being used to find indexes explicitly ignores primary keys. The change in this PR will manually append the primary key to the list.

This will let us handle duplicate errors for composite primary keys in MySQL.

mkcny avatar Mar 03 '21 22:03 mkcny

The code looks ok, however it's been a very long while since I worked with this.

One thing I wonder is that normally you get this library working by setting a validator, e.g:

validates_uniqueness_of :name, scope: :shop_id, rescue_from_duplicate: true

How does that works with composite primary keys? Isn't it a bit weird to set a validator on them? That will generate an extra SELECT on insert, no?

casperisfine avatar Mar 08 '21 14:03 casperisfine

I might be misunderstanding, but won't validates_uniqueness_of do a select before an insert regardless of whether an index exists, or what kind of index might be there?

Are you referring to the extra query that will be run when we call klass.connection.primary_keys? It's true there's a new query there, but only upon hitting the race condition of a matching row being inserted by another thread. So I believe the impact should be minimal.

mkcny avatar Mar 08 '21 18:03 mkcny

but won't validates_uniqueness_of do a select before an insert regardless of whether an index exists, or what kind of index might be there?

Yes, I'm questioning wether you already have a uniqueness validator on that composite primary key, or if somehow you expect it to work without?

casperisfine avatar Mar 09 '21 07:03 casperisfine

Yeah, there is a preexisting uniqueness validator that used a composite unique key. We reindexed our table to make the primary key equivalent to that unique key and we saw new ActiveRecord::RecordNotUnique exceptions.

mkcny avatar Mar 10 '21 14:03 mkcny