TypeORM中文文档 v1.1
版本发布 / 1.0 / 从 0.3 升级到 1.0
GitHub

从 0.3 升级到 1.0

Upgrading from 0.3 英文原文 Markdown

这是从 0.3.x 版本升级到 1.0 的升级指南。

自动化升级

@typeorm/codemod 包可以自动处理本指南中描述的大部分破坏性变更:

npx @typeorm/codemod v1 src/

它会就地更新你的代码——使用 --dry 可以预览改动而不写入文件。该 codemod 会处理导入重命名、API 替换、查找选项语法、依赖升级等。无法自动化的改动会留作 TODO 注释,供人工审阅。

完整的用法和选项请参阅 codemod README。

平台要求

Node.js 20+

最低 JavaScript 目标现在是 ES2023,这要求 Node.js 20 或更高版本。如果你使用的是更旧的 Node.js 版本,请先升级再更新 TypeORM。

非 Node 平台上 Buffer 被替换为 Uint8Array

浏览器端的 Buffer polyfill 已被移除。在非 Node 平台(浏览器、Deno、Bun)上,二进制数据现在表示为 Uint8Array。Node.js 用户不受影响——Node 的 Buffer 继承自 Uint8Array,继续照常工作。

驱动变更

MySQL / MariaDB

移除 connectorPackage 选项

connectorPackage 选项已随对旧版 mysql 客户端的支持一起被移除。现在唯一受支持的数据库客户端是 mysql2,TypeORM 会默认尝试加载它。如果你的项目中用的是 mysql,只需把它换成 mysql2。

legacySpatialSupport 默认值改为 false

legacySpatialSupport 选项现在默认为 false,这意味着 TypeORM 会使用 MySQL 5.7 引入、MySQL 8.0+ 要求的标准兼容 ST_GeomFromText 和 ST_AsText 空间函数。旧版的 GeomFromText 和 AsText 函数已在 MySQL 8.0 中被移除。

如果你运行的是 MySQL 5.6 或更早版本并且依赖空间类型,请显式设置 legacySpatialSupport: true:

new DataSource({
    type: "mysql",
    legacySpatialSupport: true,
    // ...
})

移除 width 和 zerofill 列选项

MySQL 8.0.17 弃用了整数类型的显示宽度和 ZEROFILL 属性,MySQL 8.4 则彻底移除了它们。TypeORM 不再支持 width 和 zerofill 列选项。如果你用过这些选项,请把它们从列定义中移除:

// 之前
@Column({ type: "int", width: 9, zerofill: true })
postCode: number

// 之后
@Column({ type: "int" })
postCode: number

如果你需要补零的显示格式,请在应用层用 String.prototype.padStart() 处理,或在原生查询中使用 MySQL 的 LPAD() 函数。整数类型的 unsigned 选项 不 受此变更影响。

QueryBuilder.useIndex 签名变更

指定 USE INDEX 查询提示时,QueryBuilder.useIndex() 方法不再接受原生 SQL,而是接受一个索引名或索引名数组。

// 之前
qb.useIndex("index1, `index#2`")

// 之后
qb.useIndex(["index1", "index#2"])

SQLite

sqlite3 包已被弃用。请改用 better-sqlite3:

// 之前
new DataSource({
    type: "sqlite",
    database: "db.sqlite",
})

// 之后
new DataSource({
    type: "better-sqlite3",
    database: "db.sqlite",
})

移除 flags 选项

sqlite3 包接受 C 层的打开标志(OPEN_URI、OPEN_SHAREDCACHE 等)。better-sqlite3 不支持这个——请改用专门的选项:

  • 只读模式用 readonly
  • WAL 日志模式用 enableWAL

busyTimeout 选项更名为 timeout

sqlite3 包用 busyTimeout 配置 SQLite 的忙等待超时。better-sqlite3 改用 timeout(默认:5000ms):

// 之前
new DataSource({
    type: "sqlite",
    database: "db.sqlite",
    busyTimeout: 2000,
})

// 之后
new DataSource({
    type: "better-sqlite3",
    database: "db.sqlite",
    timeout: 2000,
})

MongoDB

TypeORM 现在要求 mongodb Node.js 驱动 v7 或更高版本(^7.0.0)。对 mongodb 驱动 v5/v6 的支持已被移除。

移除已弃用的连接选项

以下 MongoDB 连接选项已被移除:

被移除的选项 处理方式
appname 改用 appName(驼峰命名)
fsync 改用 writeConcern: { journal: true }
j 改用 writeConcern: { journal: true }
keepAlive 移除——自 MongoDB 驱动 v6.0 起始终启用
keepAliveInitialDelay 移除——自 MongoDB 驱动 v6.0 起不可配置
ssl 改用 tls
sslCA 改用 tlsCAFile
sslCRL 移除——现代驱动中没有替代品
sslCert 改用 tlsCertificateKeyFile
sslKey 改用 tlsCertificateKeyFile
sslPass 改用 tlsCertificateKeyFilePassword
sslValidate 改用 tlsAllowInvalidCertificates(取反)
useNewUrlParser 移除——自 MongoDB 驱动 v4.0 起是空操作
useUnifiedTopology 移除——自 MongoDB 驱动 v4.0 起是空操作
w 改用 writeConcern: { w: 1 }
wtimeout 改用 writeConcern: { wtimeoutMS: 2500 }
wtimeoutMS 改用 writeConcern: { wtimeoutMS: 2500 }

移除 stats() 方法

stats() 方法已从 MongoQueryRunner、MongoEntityManager 和 MongoRepository 中移除。底层的 collStats 命令在 MongoDB 服务器 6.2 中被弃用,Collection.stats() 方法在 MongoDB 驱动 v7 中被移除。

请改用 $collStats 聚合阶段。注意响应结构不同——count、size、storageSize 这类属性嵌套在 storageStats 下,而不是在顶层。

// 之前
const stats = await mongoRepository.stats()
console.log(stats.count)
console.log(stats.size)
console.log(stats.totalIndexSize)

// 之后——使用 $collStats 聚合阶段
const [stats] = await dataSource.mongoManager
    .aggregate(MyEntity, [{ $collStats: { storageStats: {} } }])
    .toArray()
console.log(stats.storageStats.count)
console.log(stats.storageStats.size)
console.log(stats.storageStats.totalIndexSize)

移除 getMongoRepository 和 getMongoManager 全局函数

已弃用的全局函数 getMongoRepository() 和 getMongoManager() 已被移除。请改用 DataSource 或 EntityManager 上对应的实例方法:

// 之前
import { getMongoManager, getMongoRepository } from "typeorm"

const manager = getMongoManager()
const repository = getMongoRepository(User)

// 之后
const manager = dataSource.mongoManager
const repository = dataSource.getMongoRepository(User)

类型

内部的 MongoDB 类型(ObjectId 等)不再从 typeorm 重新导出。请直接从 mongodb 导入它们:

// 之前
import { ObjectId } from "typeorm"

// 之后
import { ObjectId } from "mongodb"

MS SQL Server

移除 domain 连接选项

SqlServerConnectionCredentialsOptions 上已弃用的 domain 选项已被移除。请改用 NTLM 类型的 authentication 选项:

// 之前
new DataSource({
    type: "mssql",
    domain: "MYDOMAIN",
    username: "user",
    password: "pass",
    // ...
})

// 之后
new DataSource({
    type: "mssql",
    authentication: {
        type: "ntlm",
        options: {
            domain: "MYDOMAIN",
            userName: "user",
            password: "pass",
        },
    },
    // ...
})

options.isolation 和 options.connectionIsolationLevel

SqlServerDataSourceOptions 上的 options.isolation 选项已更名为 options.isolationLevel,因为它本来就不是正确的选项。另外请注意,值格式已从 READ_COMMITTED 改为 READ COMMITTED(下划线换成空格),以匹配 TypeORM 整个代码库中所使用的预期格式。请相应地更新你的 DataSource 选项:

// 之前
new DataSource({
    type: "mssql",
    options: {
        isolation: "READ_COMMITTED",
        connectionIsolationLevel: "READ_COMMITTED",
        // ...
    },
    // ...
})

// 之后
new DataSource({
    type: "mssql",
    options: {
        isolationLevel: "READ COMMITTED",
        connectionIsolationLevel: "READ COMMITTED",
        // ...
    },
    // ...
})

Oracle

LegacyOracleNamingStrategy 不再从 TypeORM 主包中导出。如果你仍然需要它,可以从 @typeorm/legacy-naming-strategies 导入。

// 之前
import { LegacyOracleNamingStrategy } from "typeorm"

// 之后
import { LegacyOracleNamingStrategy } from "@typeorm/legacy-naming-strategies"

SAP HANA

若干已弃用的 SAP HANA 连接别名已被移除。

  • hanaClientDriver 已移除。请使用 driver。
  • pool.max 已移除。请使用 pool.maxConnectedOrPooled。
  • pool.requestTimeout 已移除。请使用 pool.maxWaitTimeoutIfPoolExhausted。
  • pool.idleTimeout 已移除。请使用 pool.maxPooledIdleTime(秒)。
  • pool.min、pool.maxWaitingRequests 和 pool.checkInterval 已移除,没有替代品。

另外请注意连接池配置的默认行为变化:

  • pool.maxPooledIdleTime 现在默认为 30 秒,不再回退到 pool.idleTimeout。
  • pool.maxWaitTimeoutIfPoolExhausted 现在默认为 0,不再回退到 pool.requestTimeout。

Expo

最低受支持的 Expo SDK 版本是 52,它带来了现代的异步 SQLite API。TypeORM 现在会自动加载 expo-sqlite,因此 driver 选项不再是必需的:

// 之前
new DataSource({
    type: "expo",
    driver: require("expo-sqlite"),
    database: "db.sqlite",
})

// 之后
new DataSource({
    type: "expo",
    database: "db.sqlite",
})

Redis(缓存)

RedisQueryResultCache 中对旧版(v3)Redis 客户端的支持已移除。请升级到 Redis 客户端 v4 或更高版本(redis、ioredis):

// 之前——redis v3
import { createClient } from "redis"
const client = createClient()

// 之后——redis v4+
import { createClient } from "redis"
const client = createClient()
await client.connect()

数据源

Connection → DataSource

DataSource 在 v0.3 中取代了 Connection。向后兼容的别名现在已被移除:

// 之前
import { Connection, ConnectionOptions } from "typeorm"

const connection = await createConnection(options)
await connection.close()

// 之后
import { DataSource, DataSourceOptions } from "typeorm"

const dataSource = new DataSource(options)
await dataSource.initialize()
await dataSource.destroy()

以下重命名全局适用:

之前 之后
Connection DataSource
ConnectionOptions DataSourceOptions
BaseConnectionOptions BaseDataSourceOptions
MysqlConnectionOptions MysqlDataSourceOptions
(所有驱动都遵循同样的模式)
connection.connect() dataSource.initialize()
connection.close() dataSource.destroy()
connection.isConnected dataSource.isInitialized

移除 name 属性

DataSource 和 BaseDataSourceOptions 上已弃用的 name 属性已被移除。命名连接在 v0.3 移除 ConnectionManager 时就已被弃用。如果你曾用 name 来标识连接,请改为直接管理你的 DataSource 实例。

注意:读取 dataSource.name 的代码现在会得到 undefined 而不是 "default"。如果你在日志或多租户逻辑中使用了这个值,请相应更新。

各类中的 .connection 属性现在是 .dataSource

Driver、QueryRunner、EntityManager、QueryBuilder、EntityMetadata 和 *Event 类中的 connection 属性已更名为 dataSource。对 EntityManager 而言,这一变更在 0.3 中就已公布,但当时并未真正实现。为便于过渡,这里加了一个已弃用的 getter,它返回与 dataSource 相同的值。

杂项

ConnectionManager 类已被移除。如果你曾用它管理多个连接,请改为直接创建并管理你的 DataSource 实例。

ConnectionOptionsReader 也被简化了:all() 更名为 get()(以数组形式返回所有配置),旧的 get(name) 和 has(name) 方法已被移除。它现在会在 process.cwd() 而不是应用路径中搜索 ormconfig 文件。你可以用 root 选项改变搜索位置。

const reader = new ConnectionOptionsReader({ root: "/path/to/config/" })

// 当你的 ormconfig 只有一个数据源时
const [options] = await reader.get()

// 当你需要从多个数据源中取某个特定配置时
const allOptions = await reader.get()
const postgresOptions = allOptions.find((o) => o.type === "postgres")

移除全局便捷函数

以下已弃用的全局函数已被移除:

  • createConnection / createConnections
  • getConnection
  • getConnectionManager
  • getConnectionOptions
  • getManager
  • getSqljsManager
  • getRepository
  • getTreeRepository
  • createQueryBuilder

请使用你的 DataSource 实例上的等价方法:

// 之前
const repo = getRepository(User)
const qb = createQueryBuilder("user")

// 之后
const repo = dataSource.getRepository(User)
const qb = dataSource.createQueryBuilder("user")

移除通过环境变量配置的方式

已弃用的 ConnectionOptionsEnvReader 类,以及通过 TYPEORM_CONNECTION、TYPEORM_URL 和其他 TYPEORM_* 环境变量配置连接的能力已被移除。ormconfig.env 文件格式也不再受支持。TypeORM 不再自动加载 .env 文件,也不再依赖 dotenv。

请改用 TypeScript 或 JavaScript 配置文件:

// ormconfig.ts
export default {
    type: process.env.DB_TYPE,
    url: process.env.DB_URL,
    // ...
}

行为变更

invalidWhereValuesBehavior 默认值改为 throw

这是一项重大的行为变更,可能在运行时破坏现有应用。

where 条件中 null 与 undefined 值的默认行为发生了变化。此前,null 和 undefined 值会被静默忽略(该属性被跳过)。现在,两者默认都会抛出错误。

这一变更避免了那些隐蔽的 bug——比如 findBy({ id: undefined }) 会静默返回所有行而不是失败。

// v0.3:静默返回所有帖子(null 被忽略)
// v1.0:抛出 TypeORMError
await repository.find({ where: { text: null } })

// v0.3:静默返回所有帖子(undefined 被忽略)
// v1.0:抛出 TypeORMError
await repository.find({ where: { text: undefined } })

要匹配 null 值,请使用 IsNull() 运算符:

import { IsNull } from "typeorm"

await repository.find({ where: { text: IsNull() } })

要恢复之前的行为,请在数据源选项中设置 invalidWhereValuesBehavior:

new DataSource({
    // ...
    invalidWhereValuesBehavior: {
        null: "ignore",
        undefined: "ignore",
    },
})

该设置守护所有高层 API——查找操作、repository/manager 的变更方法,以及 queryBuilder.setFindOptions()(唯一受影响的 QueryBuilder 方法)。QueryBuilder 的其余方法(.where()、.andWhere()、.orWhere())不受影响——null 和 undefined 值会原样透传。完整细节参见 null 与 undefined 的处理。

哈希

在 TypeORM v1 中,用于哈希的 SHA1 算法会直接作用于输入。在之前的版本(v0.3)中,输入会先用 encodeURIComponent 编码。

如果你使用 TypeORM 的查询结果缓存,升级后已有的缓存条目会失效,因为哈希函数产生的输出不同。缓存会自动重建——你可能会看到缓存未命中短暂增加。

如果你的表名和列名包含特殊字符,可以使用 @typeorm/legacy-naming-strategies 来避免数据库发生变化:

import { NamingStrategyV03 } from "@typeorm/legacy-naming-strategies"

const dataSource = new DataSource({
    ...
    namingStrategy: new NamingStrategyV03(),
    ...
})

Glob 模式

Glob 模式(用于实体/迁移文件的发现)现在由 tinyglobby 而不是 glob 处理。对大多数项目来说这是无缝替换。

带非空外键的 orphanedRowAction: "nullify"

当 orphanedRowAction 为 "nullify"(默认值)且外键列不可空时,孤儿子对象现在会被删除,而不是抛出数据库约束冲突。此前,TypeORM 会尝试把外键设为 null,这在非空列上会失败。

这仅在关系已加载到实体实例上时适用。TypeORM 不会自动加载关系——它只遍历对象上已经填充的关系值。为确保孤儿子对象被处理,请在调用 remove 或 save 之前先加载该关系:

const parent = await manager.findOne(Parent, {
    where: { id: 1 },
    relations: { children: true },
})
await manager.remove(parent)

如果关系未被加载(即该属性为 undefined),TypeORM 不会检测或删除孤儿子对象,这可能导致外键约束冲突。

如果你依赖那个错误来防止意外删除子对象,请在关系上设置 orphanedRowAction: "disable" 以保留旧行为。

级联删除现在对一对多关系生效

在一对多关系上使用 cascade: true 或 cascade: ["remove"] 时调用 manager.remove(entity),现在会正确地在删除父对象之前先删除子实体。此前子实体不会被级联删除,导致 DELETE 因外键约束冲突而失败。此外,级联操作现在限定在匹配的操作类型范围内——例如 save() 只遵循 insert/update 级联,不再遍历仅 remove 的关系。

多对多中间表行与软删除实体

对带多对多关系的软删除实体调用 recover() 不再抛出重复键冲突。softRemove 不会触碰中间表行,但 TypeORM 此前在为恢复而加载实体时看不到它们,导致它尝试重复插入。

副作用是,save() 期间的多对多中间表比较现在会包含软删除的关联实体。如果你显式设置了一个排除某软删除实体的关系数组,它的中间表行会被移除:

// photo2 被独立软删除了,但它的中间表行仍然存在
user.manyToManyPhotos = [photo1] // photo2 被排除
await manager.save(user) // photo2 的中间表行现在被移除了

这仅在关系属性被显式设置时适用。如果它是 undefined,则不会执行比较,中间表行保持原样。

日志记录器

FileLogger 让底层平台(例如 NodeJS)处理路径,而不是相对于应用根目录来确定路径。如果应用不是从其根文件夹启动的,你可以提供一个绝对路径(或相对于 process.cwd() 的路径):

const dataSource = new DataSource({
    logger: new FileLogger("all", { logPath: "/path/to/file.log" }),
})

列

移除 readonly 选项

已弃用的 readonly 列选项已被移除。请改用 update 选项——注意它取的是 相反 的值:

// 之前
@Column({ readonly: true })
authorName: string

// 之后
@Column({ update: false })
authorName: string

移除 ColumnNumericOptions 上的 unsigned

ColumnNumericOptions 上已弃用的 unsigned 属性(用于 decimal/float 列类型重载,如 @Column("decimal", { unsigned: true }))已被移除,因为 MySQL 已弃用非整数数值类型的 UNSIGNED。整数类型的 ColumnOptions 上的 unsigned 选项 不 受影响。

关系

nullable: false 现在使用 INNER JOIN

标记为 nullable: false 的关系,在通过 relations、急加载或查找选项加载时,现在使用 INNER JOIN 而不是 LEFT JOIN。这仅适用于持有连接列的关系类型(ManyToOne 和拥有方 OneToOne)。

这在语义上是正确的,因为非空外键保证了关联实体必然存在,并让数据库优化器能产生更高效的查询计划。

潜在破坏性: 如果你的数据库中包含违反 NOT NULL 约束的行(例如孤儿外键,或设置了 nullable: false 但该列在数据库中实际可空),这些行会被排除在查询结果之外。请验证你的数据完整性,或在需要时把关系改为 nullable: true。

// INNER JOIN——关联实体必然存在
@ManyToOne(() => User, { nullable: false })
author: User

// LEFT JOIN——关联实体可能不存在(默认)
@ManyToOne(() => User)
optionalEditor: User

OneToMany、ManyToMany 和反向 OneToOne 关系无论 nullable 设置如何都始终使用 LEFT JOIN,因为这些关系类型在当前表上没有连接列。

软删除例外: 如果关联实体有 @DeleteDateColumn,即使是 nullable: false 的关系也会使用 LEFT JOIN(除非设置了 withDeleted: true)。这能防止软删除的关联实体把它们的父行过滤掉。

Repository

findOneById

已弃用的 findOneById 方法已从 EntityManager、Repository、BaseEntity、MongoEntityManager 和 MongoRepository 中移除。请改用 findOneBy:

// 之前
const user = await manager.findOneById(User, 1)
const user = await repository.findOneById(1)
const user = await User.findOneById(1)

// 之后
const user = await manager.findOneBy(User, { id: 1 })
const user = await repository.findOneBy({ id: 1 })
const user = await User.findOneBy({ id: 1 })

对带 @ObjectIdColumn() 的 MongoDB 实体,findOneBy 的用法相同——TypeORM 会自动把属性名转换为 _id。

移除 findByIds

已弃用的 findByIds 方法已从 EntityManager、Repository 和 BaseEntity 中移除。请改用带 In 运算符的 findBy:

// 之前
const users = await repository.findByIds([1, 2, 3])

// 之后
import { In } from "typeorm"

const users = await repository.findBy({ id: In([1, 2, 3]) })

exist 更名为 exists

已弃用的 Repository.exist() 方法已被移除。请改用 exists()——行为完全一致:

// 之前
const hasUsers = await userRepository.exist({ where: { isActive: true } })

// 之后
const hasUsers = await userRepository.exists({ where: { isActive: true } })

移除 AbstractRepository、@EntityRepository 和 getCustomRepository

AbstractRepository 类、@EntityRepository 装饰器和 getCustomRepository() 方法已被移除。它们在 v0.3 中就已弃用,推荐使用 Repository.extend():

// 之前
@EntityRepository(User)
class UserRepository extends AbstractRepository<User> {
    findByName(name: string) {
        return this.repository.findOneBy({ name })
    }
}
const userRepo = dataSource.getCustomRepository(UserRepository)

// 之后
const UserRepository = dataSource.getRepository(User).extend({
    findByName(name: string) {
        return this.findOneBy({ name })
    },
})

以下错误类也已被移除:CustomRepositoryDoesNotHaveEntityError、CustomRepositoryCannotInheritRepositoryError、CustomRepositoryNotFoundError。

移除 @RelationCount 装饰器和 loadRelationCountAndMap

@RelationCount 装饰器和 SelectQueryBuilder.loadRelationCountAndMap() 方法已被移除。请改用 @VirtualColumn 或在 query builder 中使用子查询:

// 之前
@RelationCount((post: Post) => post.categories)
categoryCount: number

// 之后——使用带子查询的 @VirtualColumn
// 把中间表名和列名替换为与你的结构匹配的名字
@VirtualColumn({
    query: (alias) =>
        `SELECT COUNT(*) FROM post_categories_category WHERE postId = ${alias}.id`,
})
categoryCount: number

查找选项

移除 join 选项

FindOneOptions 和 FindManyOptions 上已弃用的 join 属性已被移除,JoinOptions 接口也一并移除。

leftJoinAndSelect → relations

如果你曾使用 leftJoinAndSelect,请把它替换为 relations 对象语法——relations 总是执行带选取的 LEFT JOIN,两者等价:

// 之前
const posts = await repository.find({
    join: {
        alias: "post",
        leftJoinAndSelect: {
            categories: "post.categories",
            author: "post.author",
        },
    },
})

// 之后
const posts = await repository.find({
    relations: { categories: true, author: true },
})

所有其他连接类型 → QueryBuilder

relations 选项只支持带选取的 LEFT JOIN。如果你曾使用 innerJoinAndSelect、innerJoin 或 leftJoin(不选取),请改用 QueryBuilder API:

// 之前——innerJoinAndSelect
const posts = await repository.find({
    join: {
        alias: "post",
        innerJoinAndSelect: {
            categories: "post.categories",
        },
    },
})

// 之后——QueryBuilder 配合 innerJoinAndSelect
const posts = await repository
    .createQueryBuilder("post")
    .innerJoinAndSelect("post.categories", "categories")
    .getMany()

// 之前——leftJoin(不选取)
const posts = await repository.find({
    join: {
        alias: "post",
        leftJoin: {
            categories: "post.categories",
        },
    },
    where: { categories: { isRemoved: false } },
})

// 之后——QueryBuilder 配合 leftJoin
const posts = await repository
    .createQueryBuilder("post")
    .leftJoin("post.categories", "categories")
    .where("categories.isRemoved = :isRemoved", { isRemoved: false })
    .getMany()

这一区别在实践中很重要。例如,PostgreSQL 和 CockroachDB 不允许在外连接的可空一侧使用 FOR UPDATE,因此把锁与连接关系结合的查询可能需要 INNER JOIN:

// 之前——innerJoinAndSelect + lock
const post = await repository.findOne({
    join: {
        alias: "post",
        innerJoinAndSelect: {
            categories: "post.categories",
        },
    },
    lock: { mode: "pessimistic_write", tables: ["category"] },
})

// 之后——QueryBuilder 配合 innerJoinAndSelect + lock
const post = await repository
    .createQueryBuilder("post")
    .innerJoinAndSelect("post.categories", "categories")
    .setLock("pessimistic_write", undefined, ["categories"])
    .getOne()

带嵌套关系的锁 → QueryBuilder

relations 选项无法与针对被连接表的悲观锁一起使用,因为 relations 总是使用 LEFT JOIN,而 PostgreSQL/CockroachDB 拒绝在外连接的可空一侧使用 FOR UPDATE。请改用 QueryBuilder 配合 innerJoinAndSelect:

// 之前——通过查找选项使用嵌套关系 + lock
const post = await repository.findOne({
    where: { id: 1 },
    join: {
        alias: "post",
        innerJoinAndSelect: {
            categories: "post.categories",
            images: "categories.images",
        },
    },
    lock: { mode: "pessimistic_write", tables: ["images"] },
})

// 之后——QueryBuilder 配合 innerJoinAndSelect + lock
const post = await repository
    .createQueryBuilder("post")
    .innerJoinAndSelect("post.categories", "categories")
    .innerJoinAndSelect("categories.images", "images")
    .where("post.id = :id", { id: 1 })
    .setLock("pessimistic_write", undefined, ["images"])
    .getOne()

注意,锁定主表仍然可以与 relations 一起使用——只有锁定被连接的表才需要 QueryBuilder 配合内连接。

移除基于字符串的 select

select 查找选项中已弃用的字符串数组语法已被移除。请改用对象语法:

// 之前
const users = await repository.find({
    select: ["id", "name"],
})

// 之后
const users = await repository.find({
    select: { id: true, name: true },
})

被移除的类型是 FindOptionsSelectByString。

移除基于字符串的 relations

relations 查找选项中已弃用的字符串数组语法已被移除。请改用对象语法:

// 之前
const users = await repository.find({
    relations: ["profile", "posts"],
})

// 之后
const users = await repository.find({
    relations: { profile: true, posts: true },
})

被移除的类型是 FindOptionsRelationByString。

QueryBuilder

移除 printSql

query builder 上的 printSql() 方法已被移除。它是多余的,因为启用查询日志后,所有已执行的查询都已经通过所配置的日志记录器自动记录。请改用 getSql() 或 getQueryAndParameters() 来查看生成的 SQL:

// 之前
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .printSql()
    .getMany()

// 之后——执行前查看 SQL
const qb = dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })

console.log(qb.getSql())
// 或者:const [sql, params] = qb.getQueryAndParameters()

const users = await qb.getMany()

要自动记录所有已执行的查询,请在你的 DataSource 中启用查询日志:

new DataSource({
    // ...
    logging: ["query"],
})

移除 onConflict

InsertQueryBuilder 上的 onConflict() 方法已被移除。它接受原生 SQL 字符串,而那些字符串是驱动专属且容易出错的。请改用 orIgnore() 或 orUpdate():

// 之前
await dataSource
    .createQueryBuilder()
    .insert()
    .into(Post)
    .values(post)
    .onConflict(`("id") DO NOTHING`)
    .execute()

// 之后
await dataSource
    .createQueryBuilder()
    .insert()
    .into(Post)
    .values(post)
    .orIgnore()
    .execute()

// 之前
await dataSource
    .createQueryBuilder()
    .insert()
    .into(Post)
    .values(post)
    .onConflict(`("id") DO UPDATE SET "title" = :title`)
    .setParameter("title", post.title)
    .execute()

// 之后
await dataSource
    .createQueryBuilder()
    .insert()
    .into(Post)
    .values(post)
    .orUpdate(["title"], ["id"])
    .execute()

移除 orUpdate 的对象重载

接受 { columns?, overwrite?, conflict_target? } 的对象式 orUpdate() 重载已被移除。请改用基于数组的签名:

// 之前
.orUpdate({ conflict_target: ["date"], overwrite: ["title"] })

// 之后
.orUpdate(["title"], ["date"])

移除 setNativeParameters

// 之前
qb.setNativeParameters({ key: "value" })

// 之后
qb.setParameters({ key: "value" })

移除 WhereExpression 类型别名

// 之前
import { WhereExpression } from "typeorm"

// 之后
import { WhereExpressionBuilder } from "typeorm"

移除 replacePropertyNames

QueryBuilder 上已弃用的受保护方法 replacePropertyNames() 已被移除。如果你在自定义子类中重写了它,该重写不会再被调用。

移除已弃用的锁模式

// 之前
.setLock("pessimistic_partial_write")

// 之后
.setLock("pessimistic_write")
.setOnLocked("skip_locked")

// 之前
.setLock("pessimistic_write_or_fail")

// 之后
.setLock("pessimistic_write")
.setOnLocked("nowait")

查找选项同理:

// 之前
{ lock: { mode: "pessimistic_partial_write" } }

// 之后
{ lock: { mode: "pessimistic_write", onLocked: "skip_locked" } }

// 之前
{ lock: { mode: "pessimistic_write_or_fail" } }

// 之后
{ lock: { mode: "pessimistic_write", onLocked: "nowait" } }

迁移

移除 getAllMigrations

已弃用的 getAllMigrations() 方法已从 MigrationExecutor 中移除。请改用 getPendingMigrations() 或 getExecutedMigrations(),或直接访问 dataSource.migrations 来获取已注册的迁移类列表:

// 之前
const migrations = await migrationExecutor.getAllMigrations()

// 之后——取决于你需要什么
const pending = await migrationExecutor.getPendingMigrations()
const executed = await migrationExecutor.getExecutedMigrations()
const registered = dataSource.migrations

移除 QueryRunner.loadedTables 和 loadedViews

// 之前
const tables = queryRunner.loadedTables
const views = queryRunner.loadedViews

// 之后
const tables = await queryRunner.getTables()
const views = await queryRunner.getViews()

注意:替代品是异步方法,不是同步属性。

容器系统

已弃用的 IoC 容器集成已被移除:useContainer()、getFromContainer()、ContainerInterface、ContainedType 和 UseContainerOptions。

TypeORM 不再有内置的 IoC 容器支持。typeorm-typedi-extensions 和 typeorm-routing-controllers-extensions 包也不再兼容。下面几节介绍如何根据你的配置进行迁移。

带依赖的订阅者与迁移

TypeORM 始终在内部使用无参构造函数实例化订阅者和迁移,因此你无法传入预先构建好的实例。如果你的迁移需要访问服务,请在迁移内部使用 DataSource(可通过 queryRunner.dataSource 获取):

// 之前
import { useContainer } from "typeorm"
import { Container } from "typedi"
useContainer(Container)

// 之后——在迁移内部通过 DataSource 访问依赖
export class MyMigration1234 implements MigrationInterface {
    public async up(queryRunner: QueryRunner): Promise<void> {
        const repo = queryRunner.dataSource.getRepository(User)
        // ...
    }
}

访问 repository 与 entity manager

如果你之前用 typeorm-typedi-extensions 把 EntityManager 或 repository 注入到服务中,请改为直接使用 DataSource:

// 之前(配合 typeorm-typedi-extensions)
import { InjectManager, InjectRepository } from "typeorm-typedi-extensions"

class UserService {
    @InjectManager()
    private manager: EntityManager

    @InjectRepository(User)
    private userRepository: Repository<User>
}

// 之后——从 DataSource 实例获取
class UserService {
    private manager: EntityManager
    private userRepository: Repository<User>

    constructor(dataSource: DataSource) {
        this.manager = dataSource.manager
        this.userRepository = dataSource.getRepository(User)
    }
}

与 DI 框架一起使用

如果你使用 DI 框架,请把 DataSource(或它的 repository)注册为容器中的提供者:

// typedi 示例
import { DataSource } from "typeorm"
import { Container } from "typedi"

const dataSource = new DataSource({/* ... */})
await dataSource.initialize()
Container.set(DataSource, dataSource)
Container.set("UserRepository", dataSource.getRepository(User))

NestJS

NestJS 用户不受影响——@nestjs/typeorm 包有自己的集成,并不依赖 TypeORM 已被移除的容器系统。不过,@nestjs/typeorm v10 和 v11.0.0 会尝试注册已被移除的 Connection 类,并在启动时崩溃。要兼容 TypeORM v1,请升级到 @nestjs/typeorm v11.0.1 或更高版本。@typeorm/codemod 工具会自动为你提升版本。

其他内部移除

以下内部 API 已被移除。只有当你在构建自定义驱动、扩展 QueryBuilder 或使用底层元数据 API 时才会受影响:

被移除的 替代品
EntityMetadata.createPropertyPath()(静态) 已移除,没有公开替代品
EntityMetadata.getValueMap() 的 options 参数 移除第三个参数——它从未生效
DriverUtils.buildColumnAlias() 使用 DriverUtils.buildAlias()
Broadcaster.broadcastLoadEventsForAll() 没有替代品——请使用各个事件订阅者
QueryExpressionMap.nativeParameters 使用 QueryExpressionMap.parameters
RdbmsSchemaBuilder.renameTables() 已移除