MySQL with Soft-Deletion, Unique Key and Foreign Key Constraints

好久不见. 提交于 2019-12-02 20:47:15

Add unique constraint on fields(username, deleted) Change field type for 'deleted' to INTEGER.

During delete operation (it can be done in trigger, or in part of code where you need actually delete user) copy value of id field to deleted field.

This approach allow you:

  • keep unique names for active users (deleted = 0)
  • allow delete users with same username several times

Field 'Deleted' can't have only 2 value because the following scenario will not work:

  1. you create user 'Sam'
  2. User Sam is deleted
  3. You create new user witn userName 'Sam'
  4. You try delete user with userName 'Sam' - fail. You already have record userName = 'Sam' and deleted = '1'

Just keep the unique index or contraint on username. You do not want new users to be able to use the deleted name, as not only could there be general confusion about identity, but if you are still showing the old posts from the deleted user, then they will mistakenly be understood to be posted by the new user with the same name.

When a new user registers, you would normally check to see if the name is in use before allowing registration to complete, so there should be no conflict here.

.

My practical solution for soft-delete is archiving by creating a new table with following columns: original_id, table_name, payload, (and an optional primary key `id).

Where original_id is the original id of deleted record, table_name is the table name of the deleted record ("user" in your case), payload is JSON-stringified string from all columns of the deleted record.

I also suggest making an index on the column original_id for latter data retrievement.

By this way of archiving data. You will have these advantages

  • Keep track of all data in history
  • Have only one place to archive records from any table, regardless of the deleted record's table structure
  • No worry of unique index in the original table
  • No worry of checking foreign index in the original table

The is already a discussion here explaining why soft-deletion is not a good idea in practice. Soft-delete introduces some potential troubles in future such as counting records, ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!