TypeORM: Dynamically set database schema for EntityManager (or repositories) at runtime?

Solution 1:

To answer my own question:

At the moment there is no way to instantiate TypeORM repositories with different schemas at runtime without creating new connections.

So the only two options that a developer is left with for schema-based multi tenancy are:

  1. Setting up new connections to connect with different schemas within the same db at runtime. E.g. see NestJS Request Scoped Multitenancy for Multiple Databases. However, one should definitely strive for reusing connections and and be aware of connection limits.
  2. Abandoning the idea of working with the RepositoryApi and reverting to using createQueryBuilder (or executing SQL queries via query()).

For further research, here are some TypeORM GitHub issues that track the idea of changing the schema for a existing connections or repositories at runtime (similar to what is requested in the OP):

  • Multi-tenant architecture using schema. #4786 proposes something like this.photoRepository.useSchema('customer1').find()
  • Handling of database schemas #3067 proposes something like getConnection().changeDefaultSchema('myschema')
  • Run-time change of schema #4473
  • Add an ability to set postgresql schema per call #2439

P.S. If TypeORM decides to support the idea discussed in the OP, I will try to update this answer.