typeorm-mtdb
is a CLI tool designed to facilitate the management of schema-based multi-tenant databases. This tool is built on TypeORM and provides a mechanism to efficiently manage multiple tenants.
typeorm-mtdb
manages databases using the following three concepts:
- Platform DB
- Tenant Class DB
- Tenant Instance DB
The Platform DB is treated as a standard TypeORM database. It is used for overall database management and holds common information such as the tenant list.
Tenant DBs are managed in a way that each tenant has its own schema. These are further divided into:
- Class Schema (Tenant Class DB)
- Instance Schema (Tenant Instance DB)
Tenant entities and migrations are initially executed on the Class Schema. Subsequently, the migration state of the Class Schema is reflected in each Tenant's Instance Schema. This mechanism allows for synchronization of multiple tenant schemas.
mtdb generate tenant
mtdb migrate tenant
mtdb spawn
mtdb distribute
mtdb generate platform
mtdb migrate platform
Set mtdb.config.json
in your project root.
{
// Configuration for the Platform DB
"platform": {
"database": "platform",
"entities": "src/db/entities/platform/*.ts",
"migrations": ["src/db/migrations/platform/*.ts"],
// `create` and `generate` commands will create files in this folder
"migrationOutDir": "src/db/migrations/platform"
},
// Configuration for the Tenant DB
"tenant": {
"classDbName": "tenant_class",
// The name of the Tenant Instance DB will be `#{relations.tenantTable[relation.keyColumn]}`.
// If the tenant ID is my_tenant, a schema named `#my_tenant` will be created.
"prefix": "#",
"entities": "src/db/entities/tenant/*.ts",
"migrations": ["src/db/migrations/tenant/*.ts"],
// `create` and `generate` commands will create files in this folder
"migrationOutDir": "src/db/migrations/tenant"
},
// Common settings
"common": {
// Specify the name of the TypeORM migration table
"migrationTableName": "typeorm_migrations"
},
// Define where the tenant information is located
// This setting means that `platform.tenants` is the list of tenants, and the `id` will be used as the name of the tenant instance schema.
"relation": {
"tenantTable": "tenants",
"keyColumn": "id"
}
}