I want to make a part of my application reusable, and that warrants moving the corresponding tables into a separate database. So for the sake of an example, please consider the two imaginary databases in the list that follows. (More databases sharing the same logic may be added as the project grows.)
userscontaining tables related to user sign ups, login and e-mail history, password reset tokens etc., as well as the accounts themselves; andblogshaving tables for posts, media files, comments, etc.
Each table in the blogs database must obviously have an account_id column referring as a foreign key to users.accounts.id. (I do realise that to make it work both databases must use InnoDB and reside on the same server.)
My question is what would be a better practice:
- direct reference to another database:
- simply refer
blogs.posts.account_idtousers.accounts.id(repeat with all otherblogs.*tables), - make each reference CASCADE ON DELETE; or
- simply refer
- using an intermediary table:
- create an intermediary table
blogs.accountshaving only one column calledid; then - on one hand, refer every table inside the
blogsdatabase to that intermediary table (soblogs.posts.account_idtoblogs.accounts.id, CASCADE ON DELETE); and - on the other hand, finish by referring this
blogs.accounts.idto the 'upstream'users.accounts.id, make sure to CASCADE ON DELETE as well.
- create an intermediary table
The latter seems like an unnecessary complication. But the only advantage I can think of is this can make the setup future proof in case we end up having to still migrate one (or some) of the databases to another server:
- If we link the tables directly, after the migration the
blogsdatabase will have lots of disparateaccount_idcolumns that won't CASCADE ON DELETE - But if these intermediary tables get disconnected from the upstream
users.accounts.id, their neighbouring tables in each respective database are still linked to them. This way we can continue benefitting from at least somewhat integrity and CASCADEs. In other words, if a user gets deleted, all we have to do is have a script go through each of these*.accountsconnector tables and delete the id counterpart once, and CASCADE will take care of the rest of the tables inside of that database automatically.
Am I on the right track with this logic, or am I missing some other ways to handle this more effectively, and therefore reinventing the wheel?