简体   繁体   中英

How to manage a unique column across two tables

I have a Files table with a primary key file_id .

Users can upload all sorts of files that will be attached to a number of different tables. There is a possibility someone could manually post a request to my API with a unrelated file_id, which would technically allow them to access a file they shouldn't under very specific circumstances.

Unfortunately, there isn't a good way to refactor the way things were done in the past to prevent this from happening.

My logic was, simply make the file id unique across both tables. Problem solved. If anyone ever tries to send a request with a file_id they shouldn't, we'll see it already exists in another table and send back a 500.

However, I'm not certain what the best method of going about this would be...

My first thought was to add a constraint. Though I'm not certain how you would manage this. Most research I've done have offered weird work-arounds that weren't recommended. Though ideally, this is the way I would prefer to do it if there is a clean way to go about it.

My second was to add something like:

insert into table_a (file_id)
select file_id where not exists (select file_id from table_b where table_b.file_id = file_id);

And then do vice versa for table_b

This also seems kind of sloppy to me. Feels like this should be a solution in the schema itself, not the query used to insert.

If there are not too many tables, you could add foreign keys to each of them from the table than contains the files and model the association that way.

Let's call these columns tablea_id and tableb_id .

To make sure that a file cannot be associated to more than one table, add a check constraint:

ALTER TABLE files ADD CHECK ((tablea_id IS NULL AND tableb_id IS NOT NULL) OR 
                             (tablea_id IS NOT NULL AND tableb_id IS NULL));

If you want to ascertain that no more than one file is associated with any row in either table, place unique constraints on tablea_id and tableb_id .

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