I'd like to build a multi-tenancy application using Flask + SQLAlchemy. The official SQLAlchemy docs suggest that, to use multi-tenancy the tables should be distributed over 1 scheme per tenant and handle the different tenants on engine level.
Maintaining multiple schemes seems a bit bloated to me and I'd like to know if the following approach using the same tables for all tenants is feasible if designed correctly and if not, why not:
- Those tables with tenant-owned records have a non-nullable column
tenant_id
that indicates which tenant "owns" the row. - Create/Update statements (
INSERT
andUPDATE
) automatically set the value of this column to the current tenant. - Reading/Deleting queries (
SELECT
orDELETE
) queries automatically add aWHERE tenant_id=:current tenant
clause/filter to the SQL. - The value of
tenant_id
could be derived from a JSON Web Token. - This automatically set value/where clause could be managed in the background, e.g. by a custom session like in this answer or using a pre-commit hook.
I barely find any information on this approach (excecpt for this one package called MultiAlchemy which seems to work similar to my description but has been archived and not updated for 7 years). My gut feeling says, there's a reason for it.
tl;dr: Why to not use shared schemes for multi-tenancy in SQLAlchemy?