widelands / wl_addons_server

Provides the add-ons server and all add-ons for the Widelands game.

Home Page:https://www.widelands.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add foreign key constraints

frankystone opened this issue · comments

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):

Utils.sql(Utils.Databases.kAddOns, "delete from uservotes where addon=?", id);
Utils.sql(Utils.Databases.kAddOns, "delete from usercomments where addon=?", id);
Utils.sql(Utils.Databases.kAddOns, "delete from addons where id=?", id);
Utils.sql(Utils.Databases.kAddOns, "delete from uploaders where addon=?", id);

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:

Utils.sql(
Utils.Databases.kAddOns,
"insert into addons (name,timestamp,edit_timestamp,i18n_version,security,quality,downloads) value(?,?,?,0,0,0,0)",
cmd[1], timestamp, timestamp);
Utils.sql(Utils.Databases.kAddOns,
"insert into uploaders (addon,user) value(?,?)",
Utils.getAddOnID(cmd[1]), userDatabaseID);

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).