# 从 0.3 升级

> 英文标题：Upgrading from 0.3
> 官网原文：https://typeorm.io/docs/releases/1.0/upgrading-from-0.3
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 231 块

---

<!-- EN -->
# Upgrading from 0.3 to 1.0

<!-- ZH -->
# 从 0.3 升级到 1.0

<!-- EN -->
This is the upgrading guide from version `0.3.x` to `1.0`.

<!-- ZH -->
这是从 `0.3.x` 版本升级到 `1.0` 的升级指南。

<!-- EN -->
## Automated upgrade

<!-- ZH -->
## 自动化升级

<!-- EN -->
The `@typeorm/codemod` package can automate most of the breaking changes described in this guide:

<!-- ZH -->
`@typeorm/codemod` 包可以自动处理本指南中描述的大部分破坏性变更：

<!-- EN -->
```bash
npx @typeorm/codemod v1 src/
```

<!-- ZH -->
```bash
npx @typeorm/codemod v1 src/
```

<!-- EN -->
This will update your code in place — use `--dry` to preview changes without writing. The codemod handles import renames, API replacements, find option syntax, dependency upgrades, and more. Changes that cannot be automated are left as `TODO` comments for manual review.

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

<!-- EN -->
See the [codemod README](https://github.com/typeorm/typeorm/tree/master/packages/codemod) for full usage and options.

<!-- ZH -->
完整的用法和选项请参阅 [codemod README](https://github.com/typeorm/typeorm/tree/master/packages/codemod)。

<!-- EN -->
## Platform requirements

<!-- ZH -->
## 平台要求

<!-- EN -->
### Node.js 20+

<!-- ZH -->
### Node.js 20+

<!-- EN -->
The minimum JavaScript target is now `ES2023`, which requires **Node.js 20 or later**. If you are using an older Node.js version, upgrade before updating TypeORM.

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

<!-- EN -->
### `Buffer` replaced with `Uint8Array` on non-Node platforms

<!-- ZH -->
### 非 Node 平台上 `Buffer` 被替换为 `Uint8Array`

<!-- EN -->
The browser `Buffer` polyfill has been removed. On non-Node platforms (browser, Deno, Bun), binary data is now represented as `Uint8Array`. Node.js users are not affected — Node's `Buffer` extends `Uint8Array` and continues to work as before.

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

<!-- EN -->
## Driver changes

<!-- ZH -->
## 驱动变更

<!-- EN -->
### MySQL / MariaDB

<!-- ZH -->
### MySQL / MariaDB

<!-- EN -->
#### `connectorPackage` option removed

<!-- ZH -->
#### 移除 `connectorPackage` 选项

<!-- EN -->
The `connectorPackage` option was removed, together with the support for the old `mysql` client. The only database client supported is now `mysql2`, which TypeORM will try to load by default. If you were using `mysql` in your project, simply replace it with `mysql2`.

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

<!-- EN -->
#### `legacySpatialSupport` default changed to `false`

<!-- ZH -->
#### `legacySpatialSupport` 默认值改为 `false`

<!-- EN -->
The `legacySpatialSupport` option now defaults to `false`, meaning TypeORM uses the standard-compliant `ST_GeomFromText` and `ST_AsText` spatial functions introduced in MySQL 5.7 and required by MySQL 8.0+. The legacy `GeomFromText` and `AsText` functions were removed in MySQL 8.0.

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

<!-- EN -->
If you are running MySQL 5.6 or earlier and rely on spatial types, set `legacySpatialSupport: true` explicitly:

<!-- ZH -->
如果你运行的是 MySQL 5.6 或更早版本并且依赖空间类型，请显式设置 `legacySpatialSupport: true`：

<!-- EN -->
```typescript
new DataSource({
    type: "mysql",
    legacySpatialSupport: true,
    // ...
})
```

<!-- ZH -->
```typescript
new DataSource({
    type: "mysql",
    legacySpatialSupport: true,
    // ...
})
```

<!-- EN -->
#### `width` and `zerofill` column options removed

<!-- ZH -->
#### 移除 `width` 和 `zerofill` 列选项

<!-- EN -->
MySQL 8.0.17 deprecated display width for integer types and the `ZEROFILL` attribute, and MySQL 8.4 removed them entirely. TypeORM no longer supports the `width` and `zerofill` column options. If you were using these options, remove them from your column definitions:

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

<!-- EN -->
```typescript
// Before
@Column({ type: "int", width: 9, zerofill: true })
postCode: number

// After
@Column({ type: "int" })
postCode: number
```

<!-- ZH -->
```typescript
// 之前
@Column({ type: "int", width: 9, zerofill: true })
postCode: number

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

<!-- EN -->
If you need zero-padded display formatting, handle it in your application layer using `String.prototype.padStart()` or the MySQL `LPAD()` function in a raw query. The `unsigned` option for integer types is **not** affected by this change.

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

<!-- EN -->
#### `QueryBuilder.useIndex` signature changed

<!-- ZH -->
#### `QueryBuilder.useIndex` 签名变更

<!-- EN -->
When specifying the `USE INDEX` query hint, the `QueryBuilder.useIndex()` method no longer accepts raw SQL, but either an index name or an array of index names.

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

<!-- EN -->
```typescript
// Before
qb.useIndex("index1, `index#2`")

// After
qb.useIndex(["index1", "index#2"])
```

<!-- ZH -->
```typescript
// 之前
qb.useIndex("index1, `index#2`")

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

<!-- EN -->
### SQLite

<!-- ZH -->
### SQLite

<!-- EN -->
The `sqlite3` package has been dropped. Use `better-sqlite3` instead:

<!-- ZH -->
`sqlite3` 包已被弃用。请改用 `better-sqlite3`：

<!-- EN -->
```typescript
// Before
new DataSource({
    type: "sqlite",
    database: "db.sqlite",
})

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

<!-- ZH -->
```typescript
// 之前
new DataSource({
    type: "sqlite",
    database: "db.sqlite",
})

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

<!-- EN -->
#### `flags` option removed

<!-- ZH -->
#### 移除 `flags` 选项

<!-- EN -->
The `sqlite3` package accepted C-level open flags (`OPEN_URI`, `OPEN_SHAREDCACHE`, etc.). `better-sqlite3` does not support this — use the dedicated options instead:

<!-- ZH -->
`sqlite3` 包接受 C 层的打开标志（`OPEN_URI`、`OPEN_SHAREDCACHE` 等）。`better-sqlite3` 不支持这个——请改用专门的选项：

<!-- EN -->
* `readonly` for read-only mode
* `enableWAL` for WAL journal mode

<!-- ZH -->
* 只读模式用 `readonly`
* WAL 日志模式用 `enableWAL`

<!-- EN -->
#### `busyTimeout` option renamed to `timeout`

<!-- ZH -->
#### `busyTimeout` 选项更名为 `timeout`

<!-- EN -->
The `sqlite3` package used `busyTimeout` to configure SQLite's busy timeout. `better-sqlite3` uses `timeout` instead (default: 5000ms):

<!-- ZH -->
`sqlite3` 包用 `busyTimeout` 配置 SQLite 的忙等待超时。`better-sqlite3` 改用 `timeout`（默认：5000ms）：

<!-- EN -->
```typescript
// Before
new DataSource({
    type: "sqlite",
    database: "db.sqlite",
    busyTimeout: 2000,
})

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

<!-- ZH -->
```typescript
// 之前
new DataSource({
    type: "sqlite",
    database: "db.sqlite",
    busyTimeout: 2000,
})

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

<!-- EN -->
### MongoDB

<!-- ZH -->
### MongoDB

<!-- EN -->
TypeORM now requires the **`mongodb` Node.js driver v7 or later** (`^7.0.0`). Support for the `mongodb` driver v5/v6 has been dropped.

<!-- ZH -->
TypeORM 现在要求 **`mongodb` Node.js 驱动 v7 或更高版本**（`^7.0.0`）。对 `mongodb` 驱动 v5/v6 的支持已被移除。

<!-- EN -->
#### Deprecated connection options removed

<!-- ZH -->
#### 移除已弃用的连接选项

<!-- EN -->
The following MongoDB connection options have been removed:

<!-- ZH -->
以下 MongoDB 连接选项已被移除：

<!-- EN -->
| Removed option          | Action                                               |
| ----------------------- | ---------------------------------------------------- |
| `appname`               | Use `appName` (camelCase) instead                    |
| `fsync`                 | Use `writeConcern: { journal: true }` instead        |
| `j`                     | Use `writeConcern: { journal: true }` instead        |
| `keepAlive`             | Remove — always enabled since MongoDB Driver v6.0    |
| `keepAliveInitialDelay` | Remove — not configurable since MongoDB Driver v6.0  |
| `ssl`                   | Use `tls` instead                                    |
| `sslCA`                 | Use `tlsCAFile` instead                              |
| `sslCRL`                | Remove — no replacement in modern driver             |
| `sslCert`               | Use `tlsCertificateKeyFile` instead                  |
| `sslKey`                | Use `tlsCertificateKeyFile` instead                  |
| `sslPass`               | Use `tlsCertificateKeyFilePassword` instead          |
| `sslValidate`           | Use `tlsAllowInvalidCertificates` (inverted) instead |
| `useNewUrlParser`       | Remove — no-op since MongoDB Driver v4.0             |
| `useUnifiedTopology`    | Remove — no-op since MongoDB Driver v4.0             |
| `w`                     | Use `writeConcern: { w: 1 }` instead                 |
| `wtimeout`              | Use `writeConcern: { wtimeoutMS: 2500 }` instead     |
| `wtimeoutMS`            | Use `writeConcern: { wtimeoutMS: 2500 }` instead     |

<!-- ZH -->
| 被移除的选项            | 处理方式                                             |
| ----------------------- | ---------------------------------------------------- |
| `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 }`            |

<!-- EN -->
#### `stats()` method removed

<!-- ZH -->
#### 移除 `stats()` 方法

<!-- EN -->
The `stats()` method has been removed from `MongoQueryRunner`, `MongoEntityManager`, and `MongoRepository`. The underlying `collStats` command was deprecated in MongoDB server 6.2 and the `Collection.stats()` method was removed in MongoDB Driver v7.

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

<!-- EN -->
Use the [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/) aggregation stage instead. Note that the response shape is different — properties like `count`, `size`, and `storageSize` are nested under `storageStats` rather than at the top level.

<!-- ZH -->
请改用 [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/) 聚合阶段。注意响应结构不同——`count`、`size`、`storageSize` 这类属性嵌套在 `storageStats` 下，而不是在顶层。

<!-- EN -->
```typescript
// Before
const stats = await mongoRepository.stats()
console.log(stats.count)
console.log(stats.size)
console.log(stats.totalIndexSize)

// After — use $collStats aggregation stage
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)
```

<!-- ZH -->
```typescript
// 之前
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)
```

<!-- EN -->
#### `getMongoRepository` and `getMongoManager` globals removed

<!-- ZH -->
#### 移除 `getMongoRepository` 和 `getMongoManager` 全局函数

<!-- EN -->
The deprecated global functions `getMongoRepository()` and `getMongoManager()` have been removed. Use the corresponding instance methods on `DataSource` or `EntityManager` instead:

<!-- ZH -->
已弃用的全局函数 `getMongoRepository()` 和 `getMongoManager()` 已被移除。请改用 `DataSource` 或 `EntityManager` 上对应的实例方法：

<!-- EN -->
```typescript
// Before
import { getMongoManager, getMongoRepository } from "typeorm"

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

// After
const manager = dataSource.mongoManager
const repository = dataSource.getMongoRepository(User)
```

<!-- ZH -->
```typescript
// 之前
import { getMongoManager, getMongoRepository } from "typeorm"

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

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

<!-- EN -->
#### Types

<!-- ZH -->
#### 类型

<!-- EN -->
The internal MongoDB types (`ObjectId`, etc.) are no longer re-exported from `typeorm`. Import them directly from `mongodb`:

<!-- ZH -->
内部的 MongoDB 类型（`ObjectId` 等）不再从 `typeorm` 重新导出。请直接从 `mongodb` 导入它们：

<!-- EN -->
```typescript
// Before
import { ObjectId } from "typeorm"

// After
import { ObjectId } from "mongodb"
```

<!-- ZH -->
```typescript
// 之前
import { ObjectId } from "typeorm"

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

<!-- EN -->
### MS SQL Server

<!-- ZH -->
### MS SQL Server

<!-- EN -->
#### `domain` connection option removed

<!-- ZH -->
#### 移除 `domain` 连接选项

<!-- EN -->
The deprecated `domain` option on `SqlServerConnectionCredentialsOptions` has been removed. Use the `authentication` option with NTLM type instead:

<!-- ZH -->
`SqlServerConnectionCredentialsOptions` 上已弃用的 `domain` 选项已被移除。请改用 NTLM 类型的 `authentication` 选项：

<!-- EN -->
```typescript
// Before
new DataSource({
    type: "mssql",
    domain: "MYDOMAIN",
    username: "user",
    password: "pass",
    // ...
})

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

<!-- ZH -->
```typescript
// 之前
new DataSource({
    type: "mssql",
    domain: "MYDOMAIN",
    username: "user",
    password: "pass",
    // ...
})

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

<!-- EN -->
#### `options.isolation` and `options.connectionIsolationLevel`

<!-- ZH -->
#### `options.isolation` 和 `options.connectionIsolationLevel`

<!-- EN -->
The `options.isolation` option on `SqlServerDataSourceOptions` was renamed to `options.isolationLevel` as was not the correct option in the first place. Also note that the value format has changed from `READ_COMMITTED` to `READ COMMITTED` (underscore replaced with space) to match the expected format used by the TypeORM throughout the codebase. Update your DataSource options accordingly:

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

<!-- EN -->
```typescript
// Before
new DataSource({
    type: "mssql",
    options: {
        isolation: "READ_COMMITTED",
        connectionIsolationLevel: "READ_COMMITTED",
        // ...
    },
    // ...
})

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

<!-- ZH -->
```typescript
// 之前
new DataSource({
    type: "mssql",
    options: {
        isolation: "READ_COMMITTED",
        connectionIsolationLevel: "READ_COMMITTED",
        // ...
    },
    // ...
})

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

<!-- EN -->
### Oracle

<!-- ZH -->
### Oracle

<!-- EN -->
The `LegacyOracleNamingStrategy` is no longer exported in the main TypeORM package. You can import it from `@typeorm/legacy-naming-strategies` if you still need it.

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

<!-- EN -->
```typescript
// Before
import { LegacyOracleNamingStrategy } from "typeorm"

// After
import { LegacyOracleNamingStrategy } from "@typeorm/legacy-naming-strategies"
```

<!-- ZH -->
```typescript
// 之前
import { LegacyOracleNamingStrategy } from "typeorm"

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

<!-- EN -->
### SAP HANA

<!-- ZH -->
### SAP HANA

<!-- EN -->
Several deprecated SAP HANA connection aliases were removed.

<!-- ZH -->
若干已弃用的 SAP HANA 连接别名已被移除。

<!-- EN -->
* `hanaClientDriver` was removed. Use `driver`.
* `pool.max` was removed. Use `pool.maxConnectedOrPooled`.
* `pool.requestTimeout` was removed. Use `pool.maxWaitTimeoutIfPoolExhausted`.
* `pool.idleTimeout` was removed. Use `pool.maxPooledIdleTime` (seconds).
* `pool.min`, `pool.maxWaitingRequests`, and `pool.checkInterval` were removed with no replacement.

<!-- ZH -->
* `hanaClientDriver` 已移除。请使用 `driver`。
* `pool.max` 已移除。请使用 `pool.maxConnectedOrPooled`。
* `pool.requestTimeout` 已移除。请使用 `pool.maxWaitTimeoutIfPoolExhausted`。
* `pool.idleTimeout` 已移除。请使用 `pool.maxPooledIdleTime`（秒）。
* `pool.min`、`pool.maxWaitingRequests` 和 `pool.checkInterval` 已移除，没有替代品。

<!-- EN -->
Also note the default behavior changes in pool configuration:

<!-- ZH -->
另外请注意连接池配置的默认行为变化：

<!-- EN -->
* `pool.maxPooledIdleTime` now defaults to `30` seconds and no longer falls back to `pool.idleTimeout`.
* `pool.maxWaitTimeoutIfPoolExhausted` now defaults to `0` and no longer falls back to `pool.requestTimeout`.

<!-- ZH -->
* `pool.maxPooledIdleTime` 现在默认为 `30` 秒，不再回退到 `pool.idleTimeout`。
* `pool.maxWaitTimeoutIfPoolExhausted` 现在默认为 `0`，不再回退到 `pool.requestTimeout`。

<!-- EN -->
### Expo

<!-- ZH -->
### Expo

<!-- EN -->
The minimum supported Expo SDK version is 52, which comes with a modern async SQLite API. TypeORM now loads `expo-sqlite` automatically, so the `driver` option is no longer required:

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

<!-- EN -->
```typescript
// Before
new DataSource({
    type: "expo",
    driver: require("expo-sqlite"),
    database: "db.sqlite",
})

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

<!-- ZH -->
```typescript
// 之前
new DataSource({
    type: "expo",
    driver: require("expo-sqlite"),
    database: "db.sqlite",
})

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

<!-- EN -->
### Redis (cache)

<!-- ZH -->
### Redis（缓存）

<!-- EN -->
Removed support for legacy (v3) Redis clients in `RedisQueryResultCache`. Upgrade to **Redis client v4 or later** (`redis`, `ioredis`):

<!-- ZH -->
`RedisQueryResultCache` 中对旧版（v3）Redis 客户端的支持已移除。请升级到 **Redis 客户端 v4 或更高版本**（`redis`、`ioredis`）：

<!-- EN -->
```typescript
// Before — redis v3
import { createClient } from "redis"
const client = createClient()

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

<!-- ZH -->
```typescript
// 之前——redis v3
import { createClient } from "redis"
const client = createClient()

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

<!-- EN -->
## Data Source

<!-- ZH -->
## 数据源

<!-- EN -->
### `Connection` → `DataSource`

<!-- ZH -->
### `Connection` → `DataSource`

<!-- EN -->
`DataSource` replaced `Connection` in v0.3. The backward-compatible alias has now been removed:

<!-- ZH -->
`DataSource` 在 v0.3 中取代了 `Connection`。向后兼容的别名现在已被移除：

<!-- EN -->
```typescript
// Before
import { Connection, ConnectionOptions } from "typeorm"

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

// After
import { DataSource, DataSourceOptions } from "typeorm"

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

<!-- ZH -->
```typescript
// 之前
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()
```

<!-- EN -->
The following renames apply throughout:

<!-- ZH -->
以下重命名全局适用：

<!-- EN -->
| Before                           | After                      |
| -------------------------------- | -------------------------- |
| `Connection`                     | `DataSource`               |
| `ConnectionOptions`              | `DataSourceOptions`        |
| `BaseConnectionOptions`          | `BaseDataSourceOptions`    |
| `MysqlConnectionOptions`         | `MysqlDataSourceOptions`   |
| *(same pattern for all drivers)* |                            |
| `connection.connect()`           | `dataSource.initialize()`  |
| `connection.close()`             | `dataSource.destroy()`     |
| `connection.isConnected`         | `dataSource.isInitialized` |

<!-- ZH -->
| 之前                             | 之后                       |
| -------------------------------- | -------------------------- |
| `Connection`                     | `DataSource`               |
| `ConnectionOptions`              | `DataSourceOptions`        |
| `BaseConnectionOptions`          | `BaseDataSourceOptions`    |
| `MysqlConnectionOptions`         | `MysqlDataSourceOptions`   |
| *（所有驱动都遵循同样的模式）*   |                            |
| `connection.connect()`           | `dataSource.initialize()`  |
| `connection.close()`             | `dataSource.destroy()`     |
| `connection.isConnected`         | `dataSource.isInitialized` |

<!-- EN -->
### `name` property removed

<!-- ZH -->
### 移除 `name` 属性

<!-- EN -->
The deprecated `name` property on `DataSource` and `BaseDataSourceOptions` has been removed. Named connections were deprecated in v0.3 when `ConnectionManager` was removed. If you were using `name` to identify connections, manage your `DataSource` instances directly instead.

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

<!-- EN -->
Note: code that reads `dataSource.name` will now receive `undefined` instead of `"default"`. If you use this value in logging or multi-tenancy logic, update accordingly.

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

<!-- EN -->
### `.connection` property in various classes is now `.dataSource`

<!-- ZH -->
### 各类中的 `.connection` 属性现在是 `.dataSource`

<!-- EN -->
The `connection` property in the `Driver`, `QueryRunner`, `EntityManager`, `QueryBuilder`, `EntityMetadata` and `*Event` classes was renamed to `dataSource`. For `EntityManager`, this change was announced in 0.3, but it was not actually implemented. To ease the transition, a deprecated getter was added that returns the same value as `dataSource`.

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

<!-- EN -->
### Miscellaneous

<!-- ZH -->
### 杂项

<!-- EN -->
The `ConnectionManager` class has been removed. If you were using it to manage multiple connections, create and manage your `DataSource` instances directly instead.

<!-- ZH -->
`ConnectionManager` 类已被移除。如果你曾用它管理多个连接，请改为直接创建并管理你的 `DataSource` 实例。

<!-- EN -->
`ConnectionOptionsReader` has also been simplified: `all()` was renamed to `get()` (returning all configs as an array), and the old `get(name)` and `has(name)` methods were removed. It will now search for the `ormconfig` file in `process.cwd()` instead of the application path. You can use the `root` option to change the search location.

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

<!-- EN -->
```typescript
const reader = new ConnectionOptionsReader({ root: "/path/to/config/" })

// when your ormconfig has a single data source
const [options] = await reader.get()

// when you need a specific config from multiple data sources
const allOptions = await reader.get()
const postgresOptions = allOptions.find((o) => o.type === "postgres")
```

<!-- ZH -->
```typescript
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")
```

<!-- EN -->
### Global convenience functions removed

<!-- ZH -->
### 移除全局便捷函数

<!-- EN -->
The following deprecated global functions have been removed:

<!-- ZH -->
以下已弃用的全局函数已被移除：

<!-- EN -->
* `createConnection` / `createConnections`
* `getConnection`
* `getConnectionManager`
* `getConnectionOptions`
* `getManager`
* `getSqljsManager`
* `getRepository`
* `getTreeRepository`
* `createQueryBuilder`

<!-- ZH -->
* `createConnection` / `createConnections`
* `getConnection`
* `getConnectionManager`
* `getConnectionOptions`
* `getManager`
* `getSqljsManager`
* `getRepository`
* `getTreeRepository`
* `createQueryBuilder`

<!-- EN -->
Use the equivalent methods on your `DataSource` instance:

<!-- ZH -->
请使用你的 `DataSource` 实例上的等价方法：

<!-- EN -->
```typescript
// Before
const repo = getRepository(User)
const qb = createQueryBuilder("user")

// After
const repo = dataSource.getRepository(User)
const qb = dataSource.createQueryBuilder("user")
```

<!-- ZH -->
```typescript
// 之前
const repo = getRepository(User)
const qb = createQueryBuilder("user")

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

<!-- EN -->
### Configuration via environment variables removed

<!-- ZH -->
### 移除通过环境变量配置的方式

<!-- EN -->
The deprecated `ConnectionOptionsEnvReader` class and the ability to configure connections via `TYPEORM_CONNECTION`, `TYPEORM_URL`, and other `TYPEORM_*` environment variables has been removed. The `ormconfig.env` file format is also no longer supported. TypeORM no longer auto-loads `.env` files or depends on `dotenv`.

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

<!-- EN -->
Use a TypeScript or JavaScript configuration file instead:

<!-- ZH -->
请改用 TypeScript 或 JavaScript 配置文件：

<!-- EN -->
```typescript
// ormconfig.ts
export default {
    type: process.env.DB_TYPE,
    url: process.env.DB_URL,
    // ...
}
```

<!-- ZH -->
```typescript
// ormconfig.ts
export default {
    type: process.env.DB_TYPE,
    url: process.env.DB_URL,
    // ...
}
```

<!-- EN -->
## Behavioral changes

<!-- ZH -->
## 行为变更

<!-- EN -->
### `invalidWhereValuesBehavior` default changed to `throw`

<!-- ZH -->
### `invalidWhereValuesBehavior` 默认值改为 `throw`

<!-- EN -->
**This is a significant behavioral change that may break existing applications at runtime.**

<!-- ZH -->
**这是一项重大的行为变更，可能在运行时破坏现有应用。**

<!-- EN -->
The default behavior for null and undefined values in where conditions has changed. Previously, null and undefined values were silently ignored (the property was skipped). Now, both **throw an error by default**.

<!-- ZH -->
where 条件中 null 与 undefined 值的默认行为发生了变化。此前，null 和 undefined 值会被静默忽略（该属性被跳过）。现在，两者**默认都会抛出错误**。

<!-- EN -->
This change prevents subtle bugs where queries like `findBy({ id: undefined })` would silently return all rows instead of failing.

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

<!-- EN -->
```typescript
// v0.3: silently returns all posts (null is ignored)
// v1.0: throws TypeORMError
await repository.find({ where: { text: null } })

// v0.3: silently returns all posts (undefined is ignored)
// v1.0: throws TypeORMError
await repository.find({ where: { text: undefined } })
```

<!-- ZH -->
```typescript
// v0.3：静默返回所有帖子（null 被忽略）
// v1.0：抛出 TypeORMError
await repository.find({ where: { text: null } })

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

<!-- EN -->
To match null values, use the `IsNull()` operator:

<!-- ZH -->
要匹配 null 值，请使用 `IsNull()` 运算符：

<!-- EN -->
```typescript
import { IsNull } from "typeorm"

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

<!-- ZH -->
```typescript
import { IsNull } from "typeorm"

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

<!-- EN -->
To restore the previous behavior, set `invalidWhereValuesBehavior` in your data source options:

<!-- ZH -->
要恢复之前的行为，请在数据源选项中设置 `invalidWhereValuesBehavior`：

<!-- EN -->
```typescript
new DataSource({
    // ...
    invalidWhereValuesBehavior: {
        null: "ignore",
        undefined: "ignore",
    },
})
```

<!-- ZH -->
```typescript
new DataSource({
    // ...
    invalidWhereValuesBehavior: {
        null: "ignore",
        undefined: "ignore",
    },
})
```

<!-- EN -->
This setting guards all high-level APIs — find operations, repository/manager mutation methods, and `queryBuilder.setFindOptions()` (the only QueryBuilder method that is affected). The rest of the QueryBuilder methods (`.where()`, `.andWhere()`, `.orWhere()`) are **not** affected — null and undefined values pass through as-is. See [Null and undefined handling](https://typeorm.io/docs/data-source/null-and-undefined-handling) for full details.

<!-- ZH -->
该设置守护所有高层 API——查找操作、repository/manager 的变更方法，以及 `queryBuilder.setFindOptions()`（唯一受影响的 QueryBuilder 方法）。QueryBuilder 的其余方法（`.where()`、`.andWhere()`、`.orWhere()`）**不**受影响——null 和 undefined 值会原样透传。完整细节参见 [null 与 undefined 的处理](https://typeorm.io/docs/data-source/null-and-undefined-handling)。

<!-- EN -->
### Hashing

<!-- ZH -->
### 哈希

<!-- EN -->
In TypeORM v1, the SHA1 hashing algorithm used for hashing is applied directly to the input. In the previous versions (v0.3), the input was first encoded using [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent).

<!-- ZH -->
在 TypeORM v1 中，用于哈希的 SHA1 算法会直接作用于输入。在之前的版本（v0.3）中，输入会先用 [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) 编码。

<!-- EN -->
If you use TypeORM's query result cache, existing cached entries will be invalidated after upgrading because the hash function produces different output. Caches will be rebuilt automatically — you may see a brief increase in cache misses.

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

<!-- EN -->
If you have table and columns names containing special characters, you can use `@typeorm/legacy-naming-strategies` to avoid changes in the database:

<!-- ZH -->
如果你的表名和列名包含特殊字符，可以使用 `@typeorm/legacy-naming-strategies` 来避免数据库发生变化：

<!-- EN -->
```typescript
import { NamingStrategyV03 } from "@typeorm/legacy-naming-strategies"

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

<!-- ZH -->
```typescript
import { NamingStrategyV03 } from "@typeorm/legacy-naming-strategies"

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

<!-- EN -->
### Glob patterns

<!-- ZH -->
### Glob 模式

<!-- EN -->
Glob patterns (used in entity/migration file discovery) are now handled by `tinyglobby` instead of `glob`. This is a drop-in replacement for most projects.

<!-- ZH -->
Glob 模式（用于实体/迁移文件的发现）现在由 `tinyglobby` 而不是 `glob` 处理。对大多数项目来说这是无缝替换。

<!-- EN -->
### `orphanedRowAction: "nullify"` with non-nullable foreign keys

<!-- ZH -->
### 带非空外键的 `orphanedRowAction: "nullify"`

<!-- EN -->
When `orphanedRowAction` is `"nullify"` (the default) and the foreign key column is non-nullable, orphaned children are now **deleted** instead of throwing a database constraint violation. Previously, TypeORM would attempt to set the FK to `null`, which failed on non-nullable columns.

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

<!-- EN -->
This only applies when the relation is loaded on the entity instance. TypeORM does not automatically load relations — it only traverses relation values that are already populated on the object. To ensure orphaned children are handled, load the relation before calling `remove` or `save`:

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

<!-- EN -->
```typescript
const parent = await manager.findOne(Parent, {
    where: { id: 1 },
    relations: { children: true },
})
await manager.remove(parent)
```

<!-- ZH -->
```typescript
const parent = await manager.findOne(Parent, {
    where: { id: 1 },
    relations: { children: true },
})
await manager.remove(parent)
```

<!-- EN -->
If the relation is not loaded (i.e. the property is `undefined`), TypeORM will not detect or delete orphaned children, which may result in foreign key constraint violations.

<!-- ZH -->
如果关系未被加载（即该属性为 `undefined`），TypeORM 不会检测或删除孤儿子对象，这可能导致外键约束冲突。

<!-- EN -->
If you were relying on the error to prevent accidental child deletion, set `orphanedRowAction: "disable"` on the relation to preserve the old behavior.

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

<!-- EN -->
### Cascade remove now works for one-to-many relations

<!-- ZH -->
### 级联删除现在对一对多关系生效

<!-- EN -->
Calling `manager.remove(entity)` with `cascade: true` or `cascade: ["remove"]` on a one-to-many relation now correctly deletes child entities before the parent. Previously, the child entities were not cascade-removed, causing the DELETE to fail with a foreign key constraint violation. Additionally, cascade operations are now scoped to the matching operation type — for example, `save()` only follows `insert`/`update` cascades and no longer traverses `remove`-only relations.

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

<!-- EN -->
### Many-to-many junction rows and soft-deleted entities

<!-- ZH -->
### 多对多中间表行与软删除实体

<!-- EN -->
Calling `recover()` on a soft-deleted entity with many-to-many relations no longer throws a duplicate key violation. Junction table rows are not touched by `softRemove`, but TypeORM previously couldn't see them when loading the entity for recovery, causing it to attempt duplicate inserts.

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

<!-- EN -->
As a side effect, many-to-many junction comparisons during `save()` now include soft-deleted related entities. If you explicitly set a relation array that excludes a soft-deleted entity, its junction row will be removed:

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

<!-- EN -->
```typescript
// photo2 was independently soft-deleted but its junction row exists
user.manyToManyPhotos = [photo1] // photo2 excluded
await manager.save(user) // junction row for photo2 is now removed
```

<!-- ZH -->
```typescript
// photo2 被独立软删除了，但它的中间表行仍然存在
user.manyToManyPhotos = [photo1] // photo2 被排除
await manager.save(user) // photo2 的中间表行现在被移除了
```

<!-- EN -->
This only applies when the relation property is explicitly set. If it is `undefined`, no comparison is performed and junction rows are left intact.

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

<!-- EN -->
### Logger

<!-- ZH -->
### 日志记录器

<!-- EN -->
`FileLogger` lets the underlying platform (e.g. NodeJS) handle the paths instead of determining the path relative to the app root. You can provide an absolute path (or a path relative to `process.cwd()`) if the app is not started from its root folder:

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

<!-- EN -->
```typescript
const dataSource = new DataSource({
    logger: new FileLogger("all", { logPath: "/path/to/file.log" }),
})
```

<!-- ZH -->
```typescript
const dataSource = new DataSource({
    logger: new FileLogger("all", { logPath: "/path/to/file.log" }),
})
```

<!-- EN -->
## Columns

<!-- ZH -->
## 列

<!-- EN -->
### `readonly` option removed

<!-- ZH -->
### 移除 `readonly` 选项

<!-- EN -->
The deprecated `readonly` column option has been removed. Use the `update` option instead — note that it takes the **opposite** value:

<!-- ZH -->
已弃用的 `readonly` 列选项已被移除。请改用 `update` 选项——注意它取的是 **相反** 的值：

<!-- EN -->
```typescript
// Before
@Column({ readonly: true })
authorName: string

// After
@Column({ update: false })
authorName: string
```

<!-- ZH -->
```typescript
// 之前
@Column({ readonly: true })
authorName: string

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

<!-- EN -->
### `unsigned` on `ColumnNumericOptions` removed

<!-- ZH -->
### 移除 `ColumnNumericOptions` 上的 `unsigned`

<!-- EN -->
The deprecated `unsigned` property on `ColumnNumericOptions` (used with decimal/float column type overloads like `@Column("decimal", { unsigned: true })`) has been removed, as MySQL deprecated `UNSIGNED` for non-integer numeric types. The `unsigned` option on `ColumnOptions` for integer types is **not** affected.

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

<!-- EN -->
## Relations

<!-- ZH -->
## 关系

<!-- EN -->
### `nullable: false` now uses INNER JOIN

<!-- ZH -->
### `nullable: false` 现在使用 INNER JOIN

<!-- EN -->
Relations marked with `nullable: false` now use `INNER JOIN` instead of `LEFT JOIN` when loaded via `relations`, eager loading, or find options. This applies only to relation types that own the join column (`ManyToOne` and owning-side `OneToOne`).

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

<!-- EN -->
This is semantically correct since a non-nullable foreign key guarantees the related entity exists, and allows the database optimizer to produce more efficient query plans.

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

<!-- EN -->
**Potentially breaking:** If your database contains rows that violate the `NOT NULL` constraint (e.g. orphaned foreign keys, or `nullable: false` was set but the column is actually nullable in the DB), those rows will be excluded from query results. Verify your data integrity or change the relation to `nullable: true` if needed.

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

<!-- EN -->
```typescript
// INNER JOIN — related entity is guaranteed to exist
@ManyToOne(() => User, { nullable: false })
author: User

// LEFT JOIN — related entity may not exist (default)
@ManyToOne(() => User)
optionalEditor: User
```

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

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

<!-- EN -->
`OneToMany`, `ManyToMany`, and inverse `OneToOne` relations always use `LEFT JOIN` regardless of the `nullable` setting, since these relation types do not have a join column on the current table.

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

<!-- EN -->
**Soft-delete exception:** If the related entity has a `@DeleteDateColumn`, `LEFT JOIN` is used even for `nullable: false` relations (unless `withDeleted: true` is set). This prevents soft-deleted related entities from filtering out their parent rows.

<!-- ZH -->
**软删除例外：** 如果关联实体有 `@DeleteDateColumn`，即使是 `nullable: false` 的关系也会使用 `LEFT JOIN`（除非设置了 `withDeleted: true`）。这能防止软删除的关联实体把它们的父行过滤掉。

<!-- EN -->
## Repository

<!-- ZH -->
## Repository

<!-- EN -->
### `findOneById`

<!-- ZH -->
### `findOneById`

<!-- EN -->
The deprecated `findOneById` method has been removed from `EntityManager`, `Repository`, `BaseEntity`, `MongoEntityManager`, and `MongoRepository`. Use `findOneBy` instead:

<!-- ZH -->
已弃用的 `findOneById` 方法已从 `EntityManager`、`Repository`、`BaseEntity`、`MongoEntityManager` 和 `MongoRepository` 中移除。请改用 `findOneBy`：

<!-- EN -->
```typescript
// Before
const user = await manager.findOneById(User, 1)
const user = await repository.findOneById(1)
const user = await User.findOneById(1)

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

<!-- ZH -->
```typescript
// 之前
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 })
```

<!-- EN -->
For MongoDB entities with `@ObjectIdColumn()`, `findOneBy` works the same way — TypeORM automatically translates the property name to `_id`.

<!-- ZH -->
对带 `@ObjectIdColumn()` 的 MongoDB 实体，`findOneBy` 的用法相同——TypeORM 会自动把属性名转换为 `_id`。

<!-- EN -->
### `findByIds` removed

<!-- ZH -->
### 移除 `findByIds`

<!-- EN -->
The deprecated `findByIds` method has been removed from `EntityManager`, `Repository`, and `BaseEntity`. Use `findBy` with the `In` operator instead:

<!-- ZH -->
已弃用的 `findByIds` 方法已从 `EntityManager`、`Repository` 和 `BaseEntity` 中移除。请改用带 `In` 运算符的 `findBy`：

<!-- EN -->
```typescript
// Before
const users = await repository.findByIds([1, 2, 3])

// After
import { In } from "typeorm"

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

<!-- ZH -->
```typescript
// 之前
const users = await repository.findByIds([1, 2, 3])

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

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

<!-- EN -->
### `exist` renamed to `exists`

<!-- ZH -->
### `exist` 更名为 `exists`

<!-- EN -->
The deprecated `Repository.exist()` method has been removed. Use `exists()` instead — the behavior is identical:

<!-- ZH -->
已弃用的 `Repository.exist()` 方法已被移除。请改用 `exists()`——行为完全一致：

<!-- EN -->
```typescript
// Before
const hasUsers = await userRepository.exist({ where: { isActive: true } })

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

<!-- ZH -->
```typescript
// 之前
const hasUsers = await userRepository.exist({ where: { isActive: true } })

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

<!-- EN -->
### `AbstractRepository`, `@EntityRepository`, and `getCustomRepository` removed

<!-- ZH -->
### 移除 `AbstractRepository`、`@EntityRepository` 和 `getCustomRepository`

<!-- EN -->
The `AbstractRepository` class, `@EntityRepository` decorator, and `getCustomRepository()` method have been removed. These were deprecated in v0.3 in favor of `Repository.extend()`:

<!-- ZH -->
`AbstractRepository` 类、`@EntityRepository` 装饰器和 `getCustomRepository()` 方法已被移除。它们在 v0.3 中就已弃用，推荐使用 `Repository.extend()`：

<!-- EN -->
```typescript
// Before
@EntityRepository(User)
class UserRepository extends AbstractRepository<User> {
    findByName(name: string) {
        return this.repository.findOneBy({ name })
    }
}
const userRepo = dataSource.getCustomRepository(UserRepository)

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

<!-- ZH -->
```typescript
// 之前
@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 })
    },
})
```

<!-- EN -->
The following error classes were also removed: `CustomRepositoryDoesNotHaveEntityError`, `CustomRepositoryCannotInheritRepositoryError`, `CustomRepositoryNotFoundError`.

<!-- ZH -->
以下错误类也已被移除：`CustomRepositoryDoesNotHaveEntityError`、`CustomRepositoryCannotInheritRepositoryError`、`CustomRepositoryNotFoundError`。

<!-- EN -->
### `@RelationCount` decorator and `loadRelationCountAndMap` removed

<!-- ZH -->
### 移除 `@RelationCount` 装饰器和 `loadRelationCountAndMap`

<!-- EN -->
The `@RelationCount` decorator and `SelectQueryBuilder.loadRelationCountAndMap()` method have been removed. Use `@VirtualColumn` or a sub-query in your query builder instead:

<!-- ZH -->
`@RelationCount` 装饰器和 `SelectQueryBuilder.loadRelationCountAndMap()` 方法已被移除。请改用 `@VirtualColumn` 或在 query builder 中使用子查询：

<!-- EN -->
```typescript
// Before
@RelationCount((post: Post) => post.categories)
categoryCount: number

// After — use @VirtualColumn with a sub-query
// Replace the junction table name and column names to match your schema
@VirtualColumn({
    query: (alias) =>
        `SELECT COUNT(*) FROM post_categories_category WHERE postId = ${alias}.id`,
})
categoryCount: number
```

<!-- ZH -->
```typescript
// 之前
@RelationCount((post: Post) => post.categories)
categoryCount: number

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

<!-- EN -->
## Find Options

<!-- ZH -->
## 查找选项

<!-- EN -->
### `join` option removed

<!-- ZH -->
### 移除 `join` 选项

<!-- EN -->
The deprecated `join` property on `FindOneOptions` and `FindManyOptions` has been removed, along with the `JoinOptions` interface.

<!-- ZH -->
`FindOneOptions` 和 `FindManyOptions` 上已弃用的 `join` 属性已被移除，`JoinOptions` 接口也一并移除。

<!-- EN -->
#### `leftJoinAndSelect` → `relations`

<!-- ZH -->
#### `leftJoinAndSelect` → `relations`

<!-- EN -->
If you were using `leftJoinAndSelect`, replace it with the `relations` object syntax — `relations` always performs LEFT JOINs with selection, which is equivalent:

<!-- ZH -->
如果你曾使用 `leftJoinAndSelect`，请把它替换为 `relations` 对象语法——`relations` 总是执行带选取的 LEFT JOIN，两者等价：

<!-- EN -->
```typescript
// Before
const posts = await repository.find({
    join: {
        alias: "post",
        leftJoinAndSelect: {
            categories: "post.categories",
            author: "post.author",
        },
    },
})

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

<!-- ZH -->
```typescript
// 之前
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 },
})
```

<!-- EN -->
#### All other join types → QueryBuilder

<!-- ZH -->
#### 所有其他连接类型 → QueryBuilder

<!-- EN -->
The `relations` option only supports LEFT JOINs with selection. If you were using `innerJoinAndSelect`, `innerJoin`, or `leftJoin` (without select), switch to the QueryBuilder API:

<!-- ZH -->
`relations` 选项只支持带选取的 LEFT JOIN。如果你曾使用 `innerJoinAndSelect`、`innerJoin` 或 `leftJoin`（不选取），请改用 QueryBuilder API：

<!-- EN -->
```typescript
// Before — innerJoinAndSelect
const posts = await repository.find({
    join: {
        alias: "post",
        innerJoinAndSelect: {
            categories: "post.categories",
        },
    },
})

// After — QueryBuilder with innerJoinAndSelect
const posts = await repository
    .createQueryBuilder("post")
    .innerJoinAndSelect("post.categories", "categories")
    .getMany()

// Before — leftJoin (without select)
const posts = await repository.find({
    join: {
        alias: "post",
        leftJoin: {
            categories: "post.categories",
        },
    },
    where: { categories: { isRemoved: false } },
})

// After — QueryBuilder with leftJoin
const posts = await repository
    .createQueryBuilder("post")
    .leftJoin("post.categories", "categories")
    .where("categories.isRemoved = :isRemoved", { isRemoved: false })
    .getMany()
```

<!-- ZH -->
```typescript
// 之前——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()
```

<!-- EN -->
This distinction matters in practice. For example, PostgreSQL and CockroachDB do not allow `FOR UPDATE` on the nullable side of an outer join, so queries that combine locking with joined relations may need INNER JOINs:

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

<!-- EN -->
```typescript
// Before — innerJoinAndSelect + lock
const post = await repository.findOne({
    join: {
        alias: "post",
        innerJoinAndSelect: {
            categories: "post.categories",
        },
    },
    lock: { mode: "pessimistic_write", tables: ["category"] },
})

// After — QueryBuilder with innerJoinAndSelect + lock
const post = await repository
    .createQueryBuilder("post")
    .innerJoinAndSelect("post.categories", "categories")
    .setLock("pessimistic_write", undefined, ["categories"])
    .getOne()
```

<!-- ZH -->
```typescript
// 之前——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()
```

<!-- EN -->
#### Locking with nested relations → QueryBuilder

<!-- ZH -->
#### 带嵌套关系的锁 → QueryBuilder

<!-- EN -->
The `relations` option cannot be used with pessimistic locking on joined tables because `relations` always uses LEFT JOINs, and PostgreSQL/CockroachDB reject `FOR UPDATE` on the nullable side of outer joins. Use QueryBuilder with `innerJoinAndSelect` instead:

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

<!-- EN -->
```typescript
// Before — nested relations + lock via find options
const post = await repository.findOne({
    where: { id: 1 },
    join: {
        alias: "post",
        innerJoinAndSelect: {
            categories: "post.categories",
            images: "categories.images",
        },
    },
    lock: { mode: "pessimistic_write", tables: ["images"] },
})

// After — QueryBuilder with 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()
```

<!-- ZH -->
```typescript
// 之前——通过查找选项使用嵌套关系 + 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()
```

<!-- EN -->
Note that locking the *main* table still works with `relations` — only locking *joined* tables requires QueryBuilder with inner joins.

<!-- ZH -->
注意，锁定*主*表仍然可以与 `relations` 一起使用——只有锁定*被连接的*表才需要 QueryBuilder 配合内连接。

<!-- EN -->
### String-based `select` removed

<!-- ZH -->
### 移除基于字符串的 `select`

<!-- EN -->
The deprecated string-array syntax for `select` find options has been removed. Use the object syntax instead:

<!-- ZH -->
`select` 查找选项中已弃用的字符串数组语法已被移除。请改用对象语法：

<!-- EN -->
```typescript
// Before
const users = await repository.find({
    select: ["id", "name"],
})

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

<!-- ZH -->
```typescript
// 之前
const users = await repository.find({
    select: ["id", "name"],
})

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

<!-- EN -->
The removed type is `FindOptionsSelectByString`.

<!-- ZH -->
被移除的类型是 `FindOptionsSelectByString`。

<!-- EN -->
### String-based `relations` removed

<!-- ZH -->
### 移除基于字符串的 `relations`

<!-- EN -->
The deprecated string-array syntax for `relations` find options has been removed. Use the object syntax instead:

<!-- ZH -->
`relations` 查找选项中已弃用的字符串数组语法已被移除。请改用对象语法：

<!-- EN -->
```typescript
// Before
const users = await repository.find({
    relations: ["profile", "posts"],
})

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

<!-- ZH -->
```typescript
// 之前
const users = await repository.find({
    relations: ["profile", "posts"],
})

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

<!-- EN -->
The removed type is `FindOptionsRelationByString`.

<!-- ZH -->
被移除的类型是 `FindOptionsRelationByString`。

<!-- EN -->
## QueryBuilder

<!-- ZH -->
## QueryBuilder

<!-- EN -->
### `printSql` removed

<!-- ZH -->
### 移除 `printSql`

<!-- EN -->
The `printSql()` method on query builders has been removed. It was redundant because all executed queries are already automatically logged through the configured logger when query logging is enabled. Use `getSql()` or `getQueryAndParameters()` to inspect the generated SQL instead:

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

<!-- EN -->
```typescript
// Before
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .printSql()
    .getMany()

// After — inspect SQL before executing
const qb = dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })

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

const users = await qb.getMany()
```

<!-- ZH -->
```typescript
// 之前
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()
```

<!-- EN -->
To log all executed queries automatically, enable query logging in your DataSource:

<!-- ZH -->
要自动记录所有已执行的查询，请在你的 DataSource 中启用查询日志：

<!-- EN -->
```typescript
new DataSource({
    // ...
    logging: ["query"],
})
```

<!-- ZH -->
```typescript
new DataSource({
    // ...
    logging: ["query"],
})
```

<!-- EN -->
### `onConflict` removed

<!-- ZH -->
### 移除 `onConflict`

<!-- EN -->
The `onConflict()` method on `InsertQueryBuilder` has been removed. It accepted raw SQL strings which were driver-specific and error-prone. Use `orIgnore()` or `orUpdate()` instead:

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

<!-- EN -->
```typescript
// Before
await dataSource
    .createQueryBuilder()
    .insert()
    .into(Post)
    .values(post)
    .onConflict(`("id") DO NOTHING`)
    .execute()

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

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

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

<!-- ZH -->
```typescript
// 之前
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()
```

<!-- EN -->
### `orUpdate` object overload removed

<!-- ZH -->
### 移除 `orUpdate` 的对象重载

<!-- EN -->
The object-based `orUpdate()` overload accepting `{ columns?, overwrite?, conflict_target? }` has been removed. Use the array-based signature instead:

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

<!-- EN -->
```typescript
// Before
.orUpdate({ conflict_target: ["date"], overwrite: ["title"] })

// After
.orUpdate(["title"], ["date"])
```

<!-- ZH -->
```typescript
// 之前
.orUpdate({ conflict_target: ["date"], overwrite: ["title"] })

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

<!-- EN -->
### `setNativeParameters` removed

<!-- ZH -->
### 移除 `setNativeParameters`

<!-- EN -->
```typescript
// Before
qb.setNativeParameters({ key: "value" })

// After
qb.setParameters({ key: "value" })
```

<!-- ZH -->
```typescript
// 之前
qb.setNativeParameters({ key: "value" })

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

<!-- EN -->
### `WhereExpression` type alias removed

<!-- ZH -->
### 移除 `WhereExpression` 类型别名

<!-- EN -->
```typescript
// Before
import { WhereExpression } from "typeorm"

// After
import { WhereExpressionBuilder } from "typeorm"
```

<!-- ZH -->
```typescript
// 之前
import { WhereExpression } from "typeorm"

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

<!-- EN -->
### `replacePropertyNames` removed

<!-- ZH -->
### 移除 `replacePropertyNames`

<!-- EN -->
The deprecated `replacePropertyNames()` protected method on QueryBuilder has been removed. If you were overriding it in a custom subclass, the override is no longer called.

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

<!-- EN -->
### Deprecated lock modes removed

<!-- ZH -->
### 移除已弃用的锁模式

<!-- EN -->
```typescript
// Before
.setLock("pessimistic_partial_write")

// After
.setLock("pessimistic_write")
.setOnLocked("skip_locked")

// Before
.setLock("pessimistic_write_or_fail")

// After
.setLock("pessimistic_write")
.setOnLocked("nowait")
```

<!-- ZH -->
```typescript
// 之前
.setLock("pessimistic_partial_write")

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

// 之前
.setLock("pessimistic_write_or_fail")

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

<!-- EN -->
The same applies to find options:

<!-- ZH -->
查找选项同理：

<!-- EN -->
```typescript
// Before
{ lock: { mode: "pessimistic_partial_write" } }

// After
{ lock: { mode: "pessimistic_write", onLocked: "skip_locked" } }

// Before
{ lock: { mode: "pessimistic_write_or_fail" } }

// After
{ lock: { mode: "pessimistic_write", onLocked: "nowait" } }
```

<!-- ZH -->
```typescript
// 之前
{ lock: { mode: "pessimistic_partial_write" } }

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

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

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

<!-- EN -->
## Migrations

<!-- ZH -->
## 迁移

<!-- EN -->
### `getAllMigrations` removed

<!-- ZH -->
### 移除 `getAllMigrations`

<!-- EN -->
The deprecated `getAllMigrations()` method has been removed from `MigrationExecutor`. Use `getPendingMigrations()` or `getExecutedMigrations()` instead, or access `dataSource.migrations` directly for the list of registered migration classes:

<!-- ZH -->
已弃用的 `getAllMigrations()` 方法已从 `MigrationExecutor` 中移除。请改用 `getPendingMigrations()` 或 `getExecutedMigrations()`，或直接访问 `dataSource.migrations` 来获取已注册的迁移类列表：

<!-- EN -->
```typescript
// Before
const migrations = await migrationExecutor.getAllMigrations()

// After — depending on what you need
const pending = await migrationExecutor.getPendingMigrations()
const executed = await migrationExecutor.getExecutedMigrations()
const registered = dataSource.migrations
```

<!-- ZH -->
```typescript
// 之前
const migrations = await migrationExecutor.getAllMigrations()

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

<!-- EN -->
### `QueryRunner.loadedTables` and `loadedViews` removed

<!-- ZH -->
### 移除 `QueryRunner.loadedTables` 和 `loadedViews`

<!-- EN -->
```typescript
// Before
const tables = queryRunner.loadedTables
const views = queryRunner.loadedViews

// After
const tables = await queryRunner.getTables()
const views = await queryRunner.getViews()
```

<!-- ZH -->
```typescript
// 之前
const tables = queryRunner.loadedTables
const views = queryRunner.loadedViews

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

<!-- EN -->
Note: the replacements are async methods, not synchronous properties.

<!-- ZH -->
注意：替代品是异步方法，不是同步属性。

<!-- EN -->
## Container system

<!-- ZH -->
## 容器系统

<!-- EN -->
The deprecated IoC container integration has been removed: `useContainer()`, `getFromContainer()`, `ContainerInterface`, `ContainedType`, and `UseContainerOptions`.

<!-- ZH -->
已弃用的 IoC 容器集成已被移除：`useContainer()`、`getFromContainer()`、`ContainerInterface`、`ContainedType` 和 `UseContainerOptions`。

<!-- EN -->
TypeORM no longer has built-in IoC container support. The `typeorm-typedi-extensions` and `typeorm-routing-controllers-extensions` packages are also no longer compatible. The sections below cover how to migrate depending on your setup.

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

<!-- EN -->
### Subscribers and migrations with dependencies

<!-- ZH -->
### 带依赖的订阅者与迁移

<!-- EN -->
TypeORM always instantiates subscribers and migrations internally using a zero-argument constructor, so you cannot pass pre-built instances. If your migrations need access to services, use the `DataSource` (available via `queryRunner.dataSource`) inside the migration itself:

<!-- ZH -->
TypeORM 始终在内部使用无参构造函数实例化订阅者和迁移，因此你无法传入预先构建好的实例。如果你的迁移需要访问服务，请在迁移内部使用 `DataSource`（可通过 `queryRunner.dataSource` 获取）：

<!-- EN -->
```typescript
// Before
import { useContainer } from "typeorm"
import { Container } from "typedi"
useContainer(Container)

// After — access dependencies via the DataSource inside the migration
export class MyMigration1234 implements MigrationInterface {
    public async up(queryRunner: QueryRunner): Promise<void> {
        const repo = queryRunner.dataSource.getRepository(User)
        // ...
    }
}
```

<!-- ZH -->
```typescript
// 之前
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)
        // ...
    }
}
```

<!-- EN -->
### Accessing repositories and entity manager

<!-- ZH -->
### 访问 repository 与 entity manager

<!-- EN -->
If you previously used `typeorm-typedi-extensions` to inject `EntityManager` or repositories into your services, use the `DataSource` directly instead:

<!-- ZH -->
如果你之前用 `typeorm-typedi-extensions` 把 `EntityManager` 或 repository 注入到服务中，请改为直接使用 `DataSource`：

<!-- EN -->
```typescript
// Before (with typeorm-typedi-extensions)
import { InjectManager, InjectRepository } from "typeorm-typedi-extensions"

class UserService {
    @InjectManager()
    private manager: EntityManager

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

// After — access from the DataSource instance
class UserService {
    private manager: EntityManager
    private userRepository: Repository<User>

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

<!-- ZH -->
```typescript
// 之前（配合 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)
    }
}
```

<!-- EN -->
### Using with a DI framework

<!-- ZH -->
### 与 DI 框架一起使用

<!-- EN -->
If you use a DI framework, register the `DataSource` (or its repositories) as providers in your container:

<!-- ZH -->
如果你使用 DI 框架，请把 `DataSource`（或它的 repository）注册为容器中的提供者：

<!-- EN -->
```typescript
// typedi example
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))
```

<!-- ZH -->
```typescript
// 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))
```

<!-- EN -->
### NestJS

<!-- ZH -->
### NestJS

<!-- EN -->
NestJS users are not affected — the `@nestjs/typeorm` package has its own integration that does not depend on TypeORM's removed container system. However, `@nestjs/typeorm` v10 and v11.0.0 attempt to register the removed `Connection` class and will crash at startup. Upgrade to `@nestjs/typeorm` v11.0.1 or later for TypeORM v1 compatibility. The `@typeorm/codemod` tool will bump it for you automatically.

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

<!-- EN -->
## Other internal removals

<!-- ZH -->
## 其他内部移除

<!-- EN -->
The following internal APIs have been removed. These only affect you if you were building custom drivers, extending QueryBuilder, or using low-level metadata APIs:

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

<!-- EN -->
| Removed                                        | Replacement                                         |
| ---------------------------------------------- | --------------------------------------------------- |
| `EntityMetadata.createPropertyPath()` (static) | Removed with no public replacement                  |
| `EntityMetadata.getValueMap()` `options` param | Remove the third argument — it was never functional |
| `DriverUtils.buildColumnAlias()`               | Use `DriverUtils.buildAlias()`                      |
| `Broadcaster.broadcastLoadEventsForAll()`      | No replacement — use individual event subscribers   |
| `QueryExpressionMap.nativeParameters`          | Use `QueryExpressionMap.parameters`                 |
| `RdbmsSchemaBuilder.renameTables()`            | Removed                                             |

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