Multi-tenant architecture using schema.
Issue type:
[X] question [ ] bug report [ ] feature request [ ] documentation issue
Database system/driver:
[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql / mariadb
[ ] oracle
[X] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo
TypeORM version:
[X] latest
[ ] @next
[ ] 0.x.x (or put your version here)
Steps to reproduce or a small repository showing the problem:
We are using TypeORM trough NestJS framework, currently trying to resolve issue with multi-tenancy. Currently what we see for PostgreSQL there are 3 different options to handle multi-tenant architecture in Single server/cluster mode.
- Single server/cluster, single database, tenant column in each table.
- Single server/cluster, single database, multi schema per customer.
- Single server/cluster, multi database per customer.
While the 1st one could work the best, first of all for some security reasons we cannot go with it, especially when data grow over time the query performance will drop down, the 3rd one would require opening new connection for each of the database, as Google Cloud SQL (ref. https://cloud.google.com/sql/docs/quotas) has limits with max concurrent connections at time, this one could make some issues also.
We decided that we will go with option 2, so for each customer we have scripts which copy all tables from template schema into newly created schema.
E.g. customer1, customer2, customer3, customer4, customer5... so all tables and entities looks exactly the same as in the others (during schema change we are using migration tool/custom script to update schema in each customer schema).
Currently as far as we get there is no multi-tenant supported in TypeORM within Schemas (there is an option but it is using QueryBuilder on top, but we want to use all functionality of TypeORM which saves us a lot of time with development ref. https://stackoverflow.com/questions/57459643/typeorm-dynamically-set-database-schema-for-entitymanager-or-repositories-at-ru) in some sort of dynamic way, there are however Entities which we can mark as specific schema, but having this for 100+ customers in one database would be overkill to add new classes per every customer that is coming to our software (ref. https://github.com/typeorm/typeorm/issues/1019).
What would be the best option to go trough TypeORM in dynamic schema?
E.g.
import { Injectable, Inject } from '@nestjs/common';
import { Repository } from 'typeorm';
import { Photo } from './photo.entity';
@Injectable()
export class PhotoService {
constructor(
@Inject('PHOTO_REPOSITORY')
private readonly photoRepository: Repository<Photo>,
) {}
async findAll(): Promise<Photo[]> {
return await this.photoRepository.useSchema('customer1').find();
}
}
While the .useSchema could basically do query schema based like this:
SELECT * FROM customer1.photoRepository LIMIT 1;
I see there might be one workaround to basically create copy of tables with different prefix, but while PostgreSQL has schema supported i don't think this is an option. Having multiple connections in configuration using createConnections isn't option also, as the customer's instances can be created on fly.
There is also another option but it is on the database level to set search schema per user on the database level, but we want to avoid any miss-configuration there (it also require to create multiple connections at the init of an app while it has to be dynamic, this is not an option too).
ALTER USER customer1 SET search_path = customer1;
Kind request to provide some help or examples in this area.
I'm reviewing the same problem, it would be much better having support from TypeORM to select the schema as you says to use it easily instead of create the same class for every tenant
I make it working with NestJS middleware which manages the connections. Before each request I am validating if connection is opened in "Connections Manager" if not, opens it.
@wintertime-inc can you show the code about changing the schema based on the http request ?
is there a way to incject the schema name to Entity class or repository class when I need to query same table in multiple schemas ? i.e change the schema in query without change the name of the table to query.
the context is multi-tenant app
If you use getRawOne/Many, you don't need to have one entity class per schema. If you use raw then it wont throw metadata error even if you dont create seperate entity class. Note: Updated comment
Hi @asmimo , thanks for sharing your code, however, you could also just use the normal querybuilder syntax instead of query() and add your schema to e.g. the from() part in your command:
const orders = await this.entityManager
.createQueryBuilder()
.select()
.from(`${tenantId}.orders`, 'order') // <--- setting schema-prefix here
.where("order.priority = 4")
.getMany();
Moreover, this ticket is about asking for a way that does not involve the querybuilder but the repo-style for querying entities as far as I understood it:
there is an option but it is using QueryBuilder on top, but we want to use all functionality of TypeORM which saves us a lot of time with development https://github.com/typeorm/typeorm/issues/4786#issue-496226382
@felixhayashi , according to my knowledge this only works when u have created a seperate entity classes for each schema otherwise you get a metadata error. this is what happened in my case. And with one entity for a schema, it would be hard to maintain like if you decided to add something in that entity you would have to do it for every single entity there like mentioned here:
there are however Entities which we can mark as specific schema, but having this for 100+ customers in one database would be overkill to add new classes per every customer that is coming to our software (ref. #1019).
So in this context my workaround is cleaner as you need only single class.
any update on this issue/feature?
@asmimo I managed to create a new connection and register all entities which are replicated across schemas. The workaround that I found was to provide all these entities in the entities property from ConnectionOptions. Therefore, I wasn't forced to declare a new entity per schema/tenant that I want to have in my app.
Having achived that, I now can use my repositories (simple and customs) and not only the queryBuilder as you proposed in this comment.
Honestly, I don't know the cost of performance implementing that, but I suspect that is very little and only when the connection is made.
Does someone knows if this feature will be implemented soon/one day?
@asmimo I managed to create a new connection and register all entities which are replicated across schemas. The workaround that I found was to provide all these entities in the
entitiesproperty from ConnectionOptions. Therefore, I wasn't forced to declare a new entity per schema/tenant that I want to have in my app.Having achived that, I now can use my repositories (simple and customs) and not only the queryBuilder as you proposed in this comment.
Honestly, I don't know the cost of performance implementing that, but I suspect that is very little and only when the connection is made.
@manuelnucci How do you handle migrations with this approach?
@VictorLandim I haven't figured that out yet but there's an interesting issue that can give you a boost.
Does someone knows if this feature will be implemented soon/one day?
There's no actual feature being requested except generalized wishful outcomes, unfortunately.
This is more of a vague question than an actionable feature request. Unless I've missed it somewhere, that is. Not that I'm against any feature that comes out of this, but general discussion, questions, and support fits better on the slack.
Technically, schemas in the @Entity() may be a function. With that you can switch the schema however you want. Does that solve your issue?
Sorry guys, didn't see this thread for a while, so what you can achieve is to manage your own connection, while this is not schema based, you can make request base connections using createConnection and getConnection (I used option 3).
What I have done in NestJS, was that I introduced data separation by just creating exact copy with synchronization (even on production), and then based on request I check whether the connection with the DB already exists or not, if not I am adding it using createConnection, and then library itself keeps the state of the databases by the name, so when you create provider e.g.: https://docs.nestjs.com/providers you can then inject this to your service like this:
private readonly rolesRepository: Repository<Roles>;
constructor (
@Inject('POSTGRES') private readonly postgresConnection: Connection,
) {
this.rolesRepository = this.postgresConnection.manager.getRepository(Roles);
}
public async findAll (): Promise<Roles[]> {
return this.rolesRepository.find({ order: { category: 'ASC', name: 'ASC' } });
}
To open the connection I have many complicated middlewares, guards and interceptors before it even reaches that far but long story short I use some modified request to open new connections, so in this way I can access any database based on request.
const instance = req.headers['instance'];
if (getConnection(instance).isConnected) {
return getConnection(instance);
}
await createConnection({
type: 'postgres',
url: `${ process.env.DATABASE_URL }/${ instance }`,
name: instance,
synchronize: true,
logging: false,
cache: {
type: 'ioredis',
options: {
host: process.env.REDIS,
port: process.env.REDIS_PORT,
db: process.env.REDIS_NO
}
},
entities: [ process.env.APP_PATH + '/**/**/**/*.entity{.ts,.js}' ],
migrations: [ process.env.APP_PATH + '/**/**/**/*.migration{.ts,.js}' ],
migrationsRun: true,
extra: {
min: 10,
max: 100,
connectionTimeoutMillis: 5000,
},
});
return getConnection(instance);
To handle multiple schemas you can do exactly the same, just add 'schema' variable to the configuration.
export interface PostgresConnectionOptions extends BaseConnectionOptions, PostgresConnectionCredentialsOptions {
/**
* Database type.
*/
readonly type: "postgres";
/**
* Schema name.
*/
readonly schema?: string;
/**
* Replication setup.
*/
readonly replication?: {
/**
* Master server used by orm to perform writes.
*/
readonly master: PostgresConnectionCredentialsOptions;
/**
* List of read-from severs (slaves).
*/
readonly slaves: PostgresConnectionCredentialsOptions[];
};
/**
* The Postgres extension to use to generate UUID columns. Defaults to uuid-ossp.
* If pgcrypto is selected, TypeORM will use the gen_random_uuid() function from this extension.
* If uuid-ossp is selected, TypeORM will use the uuid_generate_v4() function from this extension.
*/
readonly uuidExtension?: "pgcrypto" | "uuid-ossp";
readonly poolErrorHandler?: (err: any) => any;
}
I hope it helps, you can simply achieve it in other NodeJS frameworks or even core itself on request based without any further additions of TypeORM, while they support this already.
@wintertime-inc And how many connections can be created simultaneously? If I have 1000 users, each with its own database, can TypeORM support 1000 connections at the same time?
@KleinMaximus This is dependent on your backend and architecture and how you handle it.
I find something works in my case. I've got only One connection on my Postgresql database, with multiple schemas. One Schema per SOCIETY One table named ECRITURE in all schemas I use NestJS with TypeOrm All queries on ecritureRepository after this code works with the id_schema specified.
CODE
let find_meta=this.ecritureRepository.manager.connection.entityMetadatas.find(e=>e.tableName=='ECRITURE')
find_meta.schema=schema_${id_schema}
find_meta.tablePath=schema_${id_schema}.ECRITURE
I find something works in my case. I've got only One connection on my Postgresql database, with multiple schemas. One Schema per SOCIETY One table named ECRITURE in all schemas I use NestJS with TypeOrm All queries on ecritureRepository after this code works with the id_schema specified.
CODElet find_meta=this.ecritureRepository.manager.connection.entityMetadatas.find(e=>e.tableName=='ECRITURE') find_meta.schema=schema_${id_schema}find_meta.tablePath=schema_${id_schema}.ECRITURE
Could you be more specific?
Hello there I research how to resolve this issue, did you know have a solution better for this moment? Or I still should to create new connection for every request like:
const connectionMap = new Map<string, DataSource>()
export default async (tenantSchema: string): Promise<DataSource> => {
const connection = connectionMap.get(tenantSchema)
if (connection !== undefined) {
return connection
}
return await new DataSource({
...connectionOptions,
schema: tenantSchema
}).initialize().then(source => {
connectionMap.set(tenantSchema, source)
return source
})
}
P.S. Sorry my english is bad
With new changes in Typeorm, the connection manager function is not available anymore.