简体   繁体   中英

How to properly treat deletions in a Postgres SQL database

I'm working on setting up a SQL database for tracking workouts, and I'm unsure how to handle deletions. Here are a few relevant tables from my schema:

Template A template is a type of workout (eg "Leg Workout")

id serial PRIMARY KEY
user_id integer
   REFERENCES User(id)
   NOT NULL
   ON DELETE CASCADE
name varchar(255) NOT NULL
UNIQUE(user_id, name)

Movement A movement is a specific exercise (like a Squat)

id serial PRIMARY KEY
user_id
   REFERENCES User(id)
   NOT NULL
   ON DELETE CASCADE
name UNIQUE NOT NULL
UNIQUE(user_id, name)

CompletedWorkout A completed workout is exactly what it sounds like — a workout that someone completed based on a template

id serial PRIMARY KEY
date DATE NOT NULL DEFAULT CURRENT_DATE
template_id integer
    REFERENCES Template(id)
    NOT NULL
comment varchar(1536)

Completed Exercise A completed exercise is a specific exercise (with reps and weights) inside of a completed workout. For example, a Squat on Leg day with 5 reps of 200lbs would be one completed exercise.

id serial PRIMARY KEY
completed_workout_id integer
    REFERENCES CompletedWorkout(id)
    NOT NULL
movement_id integer
    REFERENCES Movement(id)
    NOT NULL
reps integer
weight_lbs integer DEFAULT 0

So here's my question — what should I do when someone deletes a Template or a Movement?

I still want the CompletedWorkout table to know the name of the template before it was deleted. For example, someone might delete their "Leg Workout" template, but if they had already completed a "Leg Workout", the database record in the "CompletedWorkout" table should know that.

I'm not quite sure about the right way to make this happens. Since with the current setup deleting a record inside of the Template table would leave a row inside of the CompletedWorkout table that has a template_id that doesn't exist.

Any idea on the right way to implement this? Appreciate the help!

If you want to retain the basic information, you should do what is called a "soft delete": include a column in the table called "Active" or "Deleted", and merely update the value of that column. Then you must also account for this new column in various retrieval operations.

Often, for this type of data you also want to know the date of the deletion, so the column might be named "DeletedDate", where a NULL value means the item was not deleted yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM