System code has a feature that relies on the field tenant_id to ensure that a record in the database is not leaked to another tenant.
This field is set upon INSERT statement through a DATABASE trigger.
Goal
As INSERT triggers are executed inside the same transaction, and some of them are buggy, it might be better to set this tenant_id by code instead.
Pros:
- Modifying the code is easier than modifying a database trigger
- Usage of DDL statement does not need to deactivate a trigger, which will be much more safe for operations
- It can have better tests per model
Sub-goals
- ability to delete records from the database really reliably. Using only the tenant_id as the source of truth. That will simplify background deletion
- All logic should be readable and testable.