widelands / wl_addons_server

Provides the add-ons server and all add-ons for the Widelands game.
https://www.widelands.org
Other
6 stars 4 forks source link

Add foreign key constraints #122

Open frankystone opened 2 years ago

frankystone commented 2 years ago

The tables uploaders, uservotes and usercomments are tied to the table addons through the column addon. To add a bit of security related to database integrity i would recommend to add foreign keys to those tables. This can be done inside the mysql console (as root), e.g.:

ALTER TABLE uservotes           # change table
ADD CONSTRAINT fk_addon_votes   # use 'fk_addon_votes' as a name for this foreign key
FOREIGN KEY (addon)             # the column 'addon' in uservotes will get a foreign key to
REFERENCES addons(id)           # the column addons.id
ON DELETE CASCADE;              # delete each each row in uservotes where addon = addons.id if addons.id get deleted

ON DELETE CASCADE make parts of this code superfluous (only line 737 will be needed, the other deletions are done by mysql): https://github.com/widelands/wl_addons_server/blob/d85cb452756d4c9b9ec593d9261ae49d11f2239f/wl/server/HandleCommand.java#L735-L738

The thing one has to pay attention to: You have to be sure to add the entry in the addons table first, before adding entries in the other tables. But as i can see you did it like that already: https://github.com/widelands/wl_addons_server/blob/d85cb452756d4c9b9ec593d9261ae49d11f2239f/wl/server/HandleCommand.java#L997-L1003

Reference: https://dev.mysql.com/doc/mysql-tutorial-excerpt/5.7/en/example-foreign-keys.html

Optionally it should also be considered to rename the column addon in those tables to something like addon_id. This has to be done before the foreign keys will be applied because the statement FOREIGN KEY (addon) has to be changed to reflect the renaming, e.g. FOREIGN KEY (addon_id).