prevent deadlocks in attachment deduplication
At Planio we encountered occasional deadlocks caused by the inner lock statement on the query selecting a potentially already existing identical attachment. Running the query without
lock first and locking the found record second solved the problem for us.
To account for the possible failure of the inner lock (i.e. when
existing was found but cannot be locked) this patch also adds a
rescue clause that silently ignores such errors. Deduplication did not happen in this case either because the duplicate was removed (then a retry would be useless) or the database aborted the transaction (deadlock or waited too long for the lock, a retry might work but I'm not sure it's worth it).