使用多个 Schema
在 MySQL、PostgreSQL 与 SQLite(通过 ATTACH DATABASE)中,你可以把实体定义在多个 schema 中。在 MySQL 的术语里它叫 database,但从实现角度看它就是一个 schema。
要使用多个 schema,你的连接需要能访问它们全部(单个 MikroORM 实例中不支持多个连接)。
你只需要通过 schema 选项定义 schema 名称,或者在 tableName 选项中带上 schema 名的表名即可:
@Entity({ schema: 'first_schema' })
export class Foo { ... }
// 或者我们也可以在自定义表名中指定它
@Entity({ tableName: 'second_schema.bar' })
export class Bar { ... }然后像平常一样使用这些实体。生成的 SQL 查询会把该 tableName 值用作表名,因此只要你的连接能访问给定的 schema,一切都应该如预期工作。
你也可以通过 EntityManager、EntityRepository 或 QueryBuilder 查询特定 schema 中的实体:
const user = await em.findOne(User, { ... }, { schema: 'client-123' });要在特定 schema 中创建实体,你需要使用 QueryBuilder:
const qb = em.createQueryBuilder(User);
await qb.insert({ email: 'foo@bar.com' }).withSchema('client-123');EntityManager 上的默认 schema
除了按实体或按操作定义 schema,你还可以 .fork() EntityManger 并定义一个默认 schema,它会与通配符 schema 一起使用。
const fork = em.fork({ schema: 'client-123' });
await fork.findOne(User, { ... });
// 与下面这段代码结果相同
const user = await em.findOne(User, { ... }, { schema: 'client-123' });创建实体时,该 fork 会设置默认 schema
const fork = em.fork({ schema: 'client-123' });
const user = new User();
user.email = 'foo@bar.com';
await fork.persist(user).flush();
// 与下面这段代码结果相同
const qb = em.createQueryBuilder(User);
await qb.insert({ email: 'foo@bar.com' }).withSchema('client-123');你也可以设置或清除 schema
em.schema = 'client-123';
const fork = em.fork({ schema: 'client-1234' });
fork.schema = null;EntityManager.schema 遵循上下文,因此如果在请求上下文处理器内部执行,全局 EM 会给出上下文中的 schema。
通配符 Schema
MikroORM 还支持定义可以存在于多个 schema 中的实体。要做到这一点,你只需指定通配符 schema:
@Entity({ schema: '*' })
export class Book {
@PrimaryKey()
id!: number;
@Property({ nullable: true })
name?: string;
@ManyToOne(() => Author, { nullable: true, deleteRule: 'cascade' })
author?: Author;
@ManyToOne(() => Book, { nullable: true })
basedOn?: Book;
}使用 SchemaGenerator 时,这类实体默认会被忽略,因为你需要指定使用哪个 schema。为此你需要使用 create/update/drop 方法的 schema 选项,或 CLI 的 --schema 参数。
在运行时,通配符 schema 会被 FindOptions.schema、EntityManager.schema 或 ORM 配置中的 schema 选项替换。
关于迁移的说明
默认情况下,migration:create 会忽略通配符 schema 实体——你需要回退到 SchemaGenerator(例如在创建新租户的 API 端点中),或者手写动态 schema 查询。
对于每个租户共享相同 schema 结构的多租户扇出场景,可以用 migrations.includeWildcardSchema: true 让通配符实体进入 migration:create。生成的 DDL 是未限定的,因此同一个迁移文件可以在运行时通过 migrator.up({ schema }) 应用到任意 schema。完整流程请参见运行时 schema 上下文。
SQLite ATTACH DATABASE
SQLite 通过 ATTACH DATABASE 命令支持多个 schema,该命令允许把额外的数据库文件附加到单个连接上。每个被附加的数据库都充当一个独立的 schema,表通过 schema.table_name 语法访问。
配置
使用 attachDatabases 选项指定连接时要附加的数据库:
import { MikroORM } from '@mikro-orm/sqlite'; // 或 @mikro-orm/libsql
const orm = await MikroORM.init({
dbName: './main.db',
entities: [Author, Book, UserProfile, LogEntry],
attachDatabases: [
{ name: 'users_db', path: './users.db' },
{ name: 'logs_db', path: '/var/data/logs.db' },
],
});相对路径会基于 baseDir 选项解析(未设置时则基于当前工作目录)。
实体定义
使用 schema 选项引用被附加的数据库:
import { defineEntity, p } from '@mikro-orm/core';
// 位于主数据库中的实体(对 main 而言 schema 是可选的)
const AuthorSchema = defineEntity({
name: 'Author',
schema: 'main',
properties: {
id: p.number().primary(),
name: p.string(),
},
});
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);
// 位于被附加数据库中的实体
const UserProfileSchema = defineEntity({
name: 'UserProfile',
schema: 'users_db',
properties: {
id: p.number().primary(),
username: p.string(),
},
});
export class UserProfile extends UserProfileSchema.class {}
UserProfileSchema.setClass(UserProfile);import { defineEntity, p } from '@mikro-orm/core';
// 位于主数据库中的实体(对 main 而言 schema 是可选的)
export const Author = defineEntity({
name: 'Author',
schema: 'main',
properties: {
id: p.number().primary(),
name: p.string(),
},
});
// 位于被附加数据库中的实体
export const UserProfile = defineEntity({
name: 'UserProfile',
schema: 'users_db',
properties: {
id: p.number().primary(),
username: p.string(),
},
});// 位于主数据库中的实体(对 main 而言 schema 是可选的)
@Entity({ schema: 'main' })
class Author {
@PrimaryKey()
id!: number;
@Property()
name!: string;
}
// 位于被附加数据库中的实体
@Entity({ schema: 'users_db' })
class UserProfile {
@PrimaryKey()
id!: number;
@Property()
username!: string;
}// 位于主数据库中的实体(对 main 而言 schema 是可选的)
@Entity({ schema: 'main' })
class Author {
@PrimaryKey()
id!: number;
@Property()
name!: string;
}
// 位于被附加数据库中的实体
@Entity({ schema: 'users_db' })
class UserProfile {
@PrimaryKey()
id!: number;
@Property()
username!: string;
}Schema 生成器支持
schema 生成器完全支持被附加的数据库。它会:
- 依据实体的
schema选项在正确的被附加数据库中创建表 - 检测并 diff 所有被附加数据库中的表
- 为每个数据库生成正确的迁移 SQL
// 在所有数据库(主库与被附加库)中创建表
await orm.schema.create();
// 更新所有数据库的 schema
await orm.schema.update();限制
- libSQL 远程连接:使用远程 libSQL URL(
libsql://、https://)时不支持 ATTACH DATABASE。只能附加基于本地文件的数据库。 - sql.js:
@mikro-orm/sql-js驱动完全在内存中运行、没有文件系统,因此attachDatabases在那里会抛出错误。 - 跨数据库外键:虽然 SQLite 允许在同一连接内的被附加数据库之间建立外键,但 SQL 语法中被引用的表名不能包含 schema 前缀。MikroORM 会自动处理这一点。
- 事务:同一连接内的所有被附加数据库共享同一个事务范围。