TypeORM中文文档 v1.1
数据源 / where 条件中 null 与 undefined 的处理
GitHub

where 条件中 null 与 undefined 的处理

Handling null and undefined values in where conditions 英文原文 Markdown

在 'WHERE' 条件中,null 和 undefined 这两个值在 TypeORM 里并不是严格合法的值。

传入一个已知的 null 值会在编译期被 TypeScript 禁止(当你在 tsconfig.json 中启用了 strictNullChecks 时)。默认行为是:运行时遇到的 null 与 undefined 值会抛出错误。

null 与 undefined 值的处理方式可以通过数据源选项中的 invalidWhereValuesBehavior 配置项自定义。它适用于查找操作、repository 方法以及 EntityManager 方法(update、delete、softDelete、restore)等高层操作。

注意

该设置 不会 影响 QueryBuilder 的 .where()、.andWhere() 或 .orWhere() 方法。QueryBuilder 是底层 API,null/undefined 值会原样透传。在 QueryBuilder 中请使用 IsNull() 操作符或参数化条件来显式处理 null。

默认行为

默认情况下,当 where 条件中出现 null 或 undefined 值时,TypeORM 会抛出错误。这能避免意外结果,并帮助你尽早发现潜在 bug:

// 两条查询都会抛出错误
const posts1 = await repository.find({
    where: {
        text: null,
    },
})
// Error: Null value encountered in property 'text' of a where condition.

const posts2 = await repository.find({
    where: {
        text: undefined,
    },
})
// Error: Undefined value encountered in property 'text' of a where condition.

要在 where 条件中匹配 null 值,请使用 IsNull 操作符(详见查找选项):

const posts = await repository.find({
    where: {
        text: IsNull(),
    },
})

配置

你可以在数据源配置中用 invalidWhereValuesBehavior 选项自定义 null 与 undefined 值的处理方式:

const dataSource = new DataSource({
    // ... 其他选项
    invalidWhereValuesBehavior: {
        null: "ignore" | "sql-null" | "throw",
        undefined: "ignore" | "throw",
    },
})

null 行为选项

null 的行为可以设为以下三个值之一:

'ignore'

where 条件中的 JavaScript null 值会被忽略,该属性被跳过:

const dataSource = new DataSource({
    // ... 其他选项
    invalidWhereValuesBehavior: {
        null: "ignore",
    },
})

// 这会返回所有帖子,忽略 text 属性
const posts = await repository.find({
    where: {
        text: null,
    },
})

'sql-null'

JavaScript 的 null 值会被转换为 SQL 的 NULL 条件:

const dataSource = new DataSource({
    // ... 其他选项
    invalidWhereValuesBehavior: {
        null: "sql-null",
    },
})

// 这只会返回数据库中 text 列为 NULL 的帖子
const posts = await repository.find({
    where: {
        text: null,
    },
})

'throw'(默认)

JavaScript 的 null 值会导致抛出 TypeORMError:

const dataSource = new DataSource({
    // ... 其他选项
    invalidWhereValuesBehavior: {
        null: "throw",
    },
})

// 这会抛出错误
const posts = await repository.find({
    where: {
        text: null,
    },
})
// Error: Null value encountered in property 'text' of a where condition.
// To match with SQL NULL, the IsNull() operator must be used.
// Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in data source options to skip or handle null values.

undefined 行为选项

undefined 的行为可以设为以下两个值之一:

'ignore'

where 条件中的 JavaScript undefined 值会被忽略,该属性被跳过:

const dataSource = new DataSource({
    // ... 其他选项
    invalidWhereValuesBehavior: {
        undefined: "ignore",
    },
})

// 这会返回所有帖子,忽略 text 属性
const posts = await repository.find({
    where: {
        text: undefined,
    },
})

'throw'(默认)

JavaScript 的 undefined 值会导致抛出 TypeORMError:

const dataSource = new DataSource({
    // ... 其他选项
    invalidWhereValuesBehavior: {
        undefined: "throw",
    },
})

// 这会抛出错误
const posts = await repository.find({
    where: {
        text: undefined,
    },
})
// Error: Undefined value encountered in property 'text' of a where condition.
// Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in data source options to skip properties with undefined values.

注意,这只适用于被显式设置为 undefined 的值,不适用于被省略的属性。

同时使用两个选项

你可以分别配置两种行为,以获得全面的控制:

const dataSource = new DataSource({
    // ... 其他选项
    invalidWhereValuesBehavior: {
        null: "sql-null",
        undefined: "throw",
    },
})

该配置会:

  1. 把 where 条件中的 JavaScript null 值转换为 SQL NULL
  2. 一旦遇到任何 undefined 值就抛出错误
  3. 仍然忽略 where 子句中未提供的属性

当你想要做到以下几点时,这种组合很有用:

  • 明确地表达"在数据库中查找 NULL 值"
  • 捕获那些 undefined 值可能悄悄混入查询的潜在编程错误

受支持的操作

invalidWhereValuesBehavior 配置适用于 TypeORM 的高层操作,不适用于 QueryBuilder 直接调用的 .where() 方法:

查找操作

// Repository.find() / findOne() / findBy() / findOneBy()
await repository.find({ where: { text: null } }) // 遵循 invalidWhereValuesBehavior

// EntityManager.find() / findOne() / findBy() / findOneBy()
await manager.find(Post, { where: { text: null } }) // 遵循 invalidWhereValuesBehavior

Repository 与 EntityManager 方法

// Repository.update()
await repository.update({ text: null }, { title: "Updated" }) // 遵循 invalidWhereValuesBehavior

// Repository.delete()
await repository.delete({ text: null }) // 遵循 invalidWhereValuesBehavior

// EntityManager.update()
await manager.update(Post, { text: null }, { title: "Updated" }) // 遵循 invalidWhereValuesBehavior

// EntityManager.delete()
await manager.delete(Post, { text: null }) // 遵循 invalidWhereValuesBehavior

// EntityManager.softDelete()
await manager.softDelete(Post, { text: null }) // 遵循 invalidWhereValuesBehavior
注意

空条件会被拒绝。 update、delete、softDelete 和 restore 要求条件非空——空条件会渲染成 WHERE 1=1 并影响 每一 行。由于 "ignore" 会剥离值为 null/undefined 的属性,一个所有键都被剥离的条件就会变成空条件。此时该操作会被拒绝,而不是作为无过滤的写操作执行:

const dataSource = new DataSource({
    // ... 其他选项
    invalidWhereValuesBehavior: { null: "ignore", undefined: "ignore" },
})

// { text: null } 剥离后变成 {} -> 被拒绝;表不会被清空
await manager.delete(Post, { text: null })
// Error: Empty criteria(s) are not allowed for the delete method.

当你确实想影响每一行时,请使用专门的 updateAll() / deleteAll() 方法。

只有普通对象条件会被规范化

invalidWhereValuesBehavior 只规范化普通的 FindOptionsWhere 对象。传给 update / delete / softDelete / restore 的任何其他条件值——实体类实例、FindOperator、数组、Date、Buffer,或原始类型的 id——都会原样透传,不会被校验。因此,一个可空列为 null 的实体实例会渲染成 col = NULL(匹配不到任何行),而不是抛出错误或被转换。如果你需要 null 处理,请传入一个带 IsNull() 操作符的普通对象(例如 { text: IsNull() })。

对实体实例条件做深度校验需要实体元数据,不在此处讨论范围内;当你希望 invalidWhereValuesBehavior 生效时,请使用普通的 FindOptionsWhere 对象。

配合 setFindOptions 的 QueryBuilder

// setFindOptions 走的是查找选项路径,因此遵循该设置
await dataSource
    .createQueryBuilder(Post, "post")
    .setFindOptions({ where: { text: null } }) // 遵循 invalidWhereValuesBehavior
    .getMany()

不受影响:QueryBuilder 的 .where()

QueryBuilder 的 .where()、.andWhere() 和 .orWhere() 是底层 API,不受该设置影响。null 与 undefined 值会原样透传:

// 这不遵循 invalidWhereValuesBehavior —— null 原样透传
await dataSource
    .createQueryBuilder()
    .update(Post)
    .set({ title: "Updated" })
    .where({ text: null })
    .execute()

null 与 undefined 在 QueryBuilder .where() 中的行为

由于 QueryBuilder 是底层 API,null 与 undefined 值 不会 被校验或转换。理解它们的行为对避免意外结果很重要。

QueryBuilder .where() 中的 null

当在对象风格的 .where() 中把 null 作为值传入时,它会生成一个针对 NULL 的 SQL 等值判断:

await dataSource
    .createQueryBuilder(Post, "post")
    .where({ text: null })
    .getMany()
// 生成:WHERE post.text = NULL

在 SQL 中,column = NULL 永远为假 ——没有任何值等于 NULL。这条查询会 返回零条结果,这几乎肯定不是你的本意。要匹配 NULL 值,请使用 IsNull() 操作符:

import { IsNull } from "typeorm"

await dataSource
    .createQueryBuilder(Post, "post")
    .where({ text: IsNull() })
    .getMany()
// 生成:WHERE post.text IS NULL

或者使用字符串条件:

await dataSource
    .createQueryBuilder(Post, "post")
    .where("post.text IS NULL")
    .getMany()

QueryBuilder .where() 中的 undefined

当把 undefined 作为值传入时,行为相同——它会生成 WHERE column = NULL,永远为假:

await dataSource
    .createQueryBuilder(Post, "post")
    .where({ text: undefined })
    .getMany()
// 生成:WHERE post.text = NULL
// 返回:零条结果

汇总表

值 高层 API(find/repository/manager) QueryBuilder .where()
null 配 "ignore" 属性被跳过——不加过滤 WHERE col = NULL——零条结果
null 配 "sql-null" WHERE col IS NULL WHERE col = NULL——零条结果
null 配 "throw"(默认) 抛出错误 WHERE col = NULL——零条结果
undefined 配 "ignore" 属性被跳过——不加过滤 WHERE col = NULL——零条结果
undefined 配 "throw"(默认) 抛出错误 WHERE col = NULL——零条结果
IsNull() WHERE col IS NULL WHERE col IS NULL
提示

无论使用哪个 API,只要你想匹配 SQL 的 NULL 值,就始终使用 IsNull()。它在高层 API 和 QueryBuilder 上下文中都能正确工作。