Uploading the same file PDOException:SQLSTATE[23505]

Hi there, I try to upload a file with drupal7, when the file is uploaded, i rename it and check if the file exists, if it exists, i try to delete it, so I keep the same name (not file, file_01, etc), the uploading function allow us to update the file.

But I got a problem, when i upload the same uri like 10 times or less, I have a PDOException and “The website has encountered an unexpected error, try again later”

PDOException : SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint “d7_file_managed_uri_key” DETAIL: Key (uri)=(public://test.xlsx) already exists.: UPDATE d7_file_managed SET uid=:db_update_placeholder_0, filename=:db_update_placeholder_1, uri=:db_update_placeholder_2, filemime=:db_update_placeholder_3, filesize=:db_update_placeholder_4, status=:db_update_placeholder_5, timestamp=:db_update_placeholder_6, uuid=:db_update_placeholder_7 WHERE (fid = :db_condition_placeholder_0) ; Array ( [target] => default [return] => 2 [already_prepared] => 1 ) in drupal_write_record() (line 7387 in /includes/common.inc).

Do you guys have any idea ?

Source: https://www.drupal.org/taxonomy/term/4/feed