Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composite keys in a Multi-tenant database

I'm designing a database for pure multi-tenancy (one database, one schema) and I'd like to keep a Tenant_Id in most of my tables as a security measure to ensure that data doesn't fall into the wrong tenant's hands. It seems like this would require a composite key on every table.

Example:

Under single-tenant circumstances, I would have a single primary key:

Animal_Id (PK)  
Animal_Type  
Animal_Name  

Under Multi-tenant circumstances, I would add another primary key for Tenant_Id:

Animal_Id (PK)  
Tenant_Id (PK)  
Animal_Type  
Animal_Name  

Does adding a Tenant_Id column to every table mean that I will need to have a composite key in every table, or is there a secure way to avoid this? Composite keys are ok, but I'd like to avoid them if I can.

like image 555
awright Avatar asked Dec 28 '22 23:12

awright


1 Answers

If all your ids are autoincremented integers, you can add tenant_id which is not a part of the primary key and just check for it in all your queries.

However, this has several side effects which you may or may not see as drawbacks:

  • You can possibly link two entities from different tenants in a many-to-many link table and the FOREIGN KEY constraint won't prevent you from doing this (as it would in case tenant_id were a part of the PRIMARY KEY)
  • Your users can evaluate how many other tenants are there from the ids
  • You will have to additionally join the entity tables to the searches which could possibly be done only from many-to-many link tables (to check the tenant)

In other words, if you really don't like composite keys for entities, it is possible to design the database without them.

like image 150
Quassnoi Avatar answered Jan 27 '23 10:01

Quassnoi