How to Build a SaaS Application Block by Block
blog.sentry.io
blog.sentry.io
Wat? Title should be: "How to do tenant isolation and audit logs"; this is in no way a sketch of how to build a SaaS application.
Is there a good solution for automatically scoping a query to a tenant at the database-level (perhaps using a custom extension or PL/PgSQL to rewrite the queries), assuming the tenant_id is in the SQL request?
I guess I'm asking if it's possible to move this functionality to the database layer with something like PL/pgSQL or the Postgres rule system... both of which I know very little about.
@db.event.listens_for(TenantQuery, 'before_compile', retval=True)
def ensure_tenant_constrained(query):
for desc in query.column_descriptions:
if hasattr(desc['type'], 'tenant') and \
query.current_tenant_constrained:
query = query.filter_by(tenant=get_current_tenant())
return query
Of course the only point in asking such a question is if there's a good reason to do it, and I can't remember why I looked into this in the first place (it's been more than a couple of years).You could use Postgres's partial indexes. (basically an index scoped per tenant).
Your 'WHERE' clauses would need to include the field indexed by those partial indexes.
https://devcenter.heroku.com/articles/postgresql-indexes#par...
I have not thought more though this, but may be combining that with the PG 11s partitioning, would get me even closer to tenant-specific archiving/backup and other admin tasks beyond query.