使用 Query Builder 查询
什么是 QueryBuilder?
QueryBuilder 是 TypeORM 最强大的特性之一——它让你能用优雅而便捷的语法构建 SQL 查询、执行它们,并拿到自动转换好的实体。
QueryBuilder 的简单示例:
const firstUser = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.getOne()它会构建如下 SQL 查询:
SELECT
user.id as userId,
user.firstName as userFirstName,
user.lastName as userLastName
FROM users user
WHERE user.id = 1并返回一个 User 实例:
User {
id: 1,
firstName: "Timber",
lastName: "Saw"
}使用 QueryBuilder 时的重要注意事项
使用 QueryBuilder 时,你需要在 WHERE 表达式中提供各不相同的参数名。下面这样是不行的:
const result = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.linkedSheep", "linkedSheep")
.leftJoinAndSelect("user.linkedCow", "linkedCow")
.where("user.linkedSheep = :id", { id: sheepId })
.andWhere("user.linkedCow = :id", { id: cowId })……但这样可以:
const result = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.linkedSheep", "linkedSheep")
.leftJoinAndSelect("user.linkedCow", "linkedCow")
.where("user.linkedSheep = :sheepId", { sheepId })
.andWhere("user.linkedCow = :cowId", { cowId })注意,我们给 :sheepId 和 :cowId 取了不同的名字,而不是对不同参数两次使用 :id。
如何创建并使用 QueryBuilder?
创建 Query Builder 有几种方式:
- 使用 DataSource:
const user = await dataSource
.createQueryBuilder()
.select("user")
.from(User, "user")
.where("user.id = :id", { id: 1 })
.getOne()- 使用 entity manager:
const user = await dataSource.manager
.createQueryBuilder(User, "user")
.where("user.id = :id", { id: 1 })
.getOne()- 使用 repository:
const user = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.getOne()共有 5 种不同的 QueryBuilder 类型可用:
SelectQueryBuilder- 用于构建并执行SELECT查询。示例:
const user = await dataSource
.createQueryBuilder()
.select("user")
.from(User, "user")
.where("user.id = :id", { id: 1 })
.getOne()InsertQueryBuilder- 用于构建并执行INSERT查询。示例:
await dataSource
.createQueryBuilder()
.insert()
.into(User)
.values([
{ firstName: "Timber", lastName: "Saw" },
{ firstName: "Phantom", lastName: "Lancer" },
])
.execute()UpdateQueryBuilder- 用于构建并执行UPDATE查询。示例:
await dataSource
.createQueryBuilder()
.update(User)
.set({ firstName: "Timber", lastName: "Saw" })
.where("id = :id", { id: 1 })
.execute()DeleteQueryBuilder- 用于构建并执行DELETE查询。示例:
await dataSource
.createQueryBuilder()
.delete()
.from(User)
.where("id = :id", { id: 1 })
.execute()RelationQueryBuilder- 用于构建并执行关系专属操作 [TBD]。示例:
await dataSource
.createQueryBuilder()
.relation(User, "photos")
.of(id)
.loadMany()你可以在任意一种 query builder 中切换到其他类型,一旦切换就会得到一个新的 query builder 实例(与其他所有方法不同)。
用 QueryBuilder 获取值
要从数据库获取单条结果,例如按 id 或名字获取一个用户,你必须使用 getOne:
const timber = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" })
.getOne()getOneOrFail 也会从数据库获取单条结果,但如果不存在任何结果,它会抛出 EntityNotFoundError:
const timber = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" })
.getOneOrFail()要从数据库获取多条结果,例如获取数据库中的所有用户,请使用 getMany:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.getMany()使用 select query builder 你可以得到两类结果:实体 或 原生结果。大多数时候,你需要从数据库中选取真正的实体,例如用户。为此你使用 getOne 和 getMany。但有时你需要选取某些特定数据,比如所有用户照片的总和。这类数据不是实体,它被称为原生数据。要获取原生数据,你使用 getRawOne 和 getRawMany。示例:
const { sum } = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("SUM(user.photosCount)", "sum")
.where("user.id = :id", { id: 1 })
.getRawOne()const photosSums = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.id")
.addSelect("SUM(user.photosCount)", "sum")
.groupBy("user.id")
.getRawMany()
// 结果会像这样:[{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]获取数量
你可以用 getCount() 获取一条查询将返回的行数。它返回的是数字而不是实体结果。
const count = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.name = :name", { name: "Timber" })
.getCount()它会生成如下 SQL 查询:
SELECT count(*) FROM users user WHERE user.name = 'Timber'别名是做什么用的?
我们用了 createQueryBuilder("user")。但 "user" 是什么?它就是一个普通的 SQL 别名。除了处理被选中的数据之外,我们到处都在使用别名。
createQueryBuilder("user") 等价于:
createQueryBuilder().select("user").from(User, "user")它会生成如下 SQL 查询:
SELECT ... FROM users user在这条 SQL 查询中,users 是表名,user 是我们给这张表起的别名。之后我们用这个别名来访问这张表:
createQueryBuilder()
.select("user")
.from(User, "user")
.where("user.name = :name", { name: "Timber" })它会生成如下 SQL 查询:
SELECT ... FROM users user WHERE user.name = 'Timber'看,我们通过创建 query builder 时指定的 user 别名用到了 users 表。
一个 query builder 并不局限于一个别名,它可以拥有多个别名。每个 select 都可以有自己的别名,你可以从多张表中选取、每张表各有别名,也可以连接多张表、每张表各有别名。你可以用这些别名访问正在选取的表(或正在选取的数据)。
用参数转义数据
我们用了 where("user.name = :name", { name: "Timber" })。{ name: "Timber" } 代表什么?它是我们用来防止 SQL 注入的参数。我们本可以写成:where("user.name = '" + name + "'),但这不安全,因为它让代码暴露在 SQL 注入风险之下。安全的做法是使用这种特殊语法:where("user.name = :name", { name: "Timber" }),其中 :name 是参数名,值在一个对象中给出:{ name: "Timber" }。
.where("user.name = :name", { name: "Timber" })是下面写法的简写:
.where("user.name = :name")
.setParameter("name", "Timber")注意:不要在整个 query builder 中对不同的值使用相同的参数名。如果你多次设置同一个参数,先前的值会被覆盖。
你也可以提供一个值数组,并用特殊的展开语法把它们转换成 SQL 语句中的值列表:
.where("user.name IN (:...names)", { names: [ "Timber", "Crystal", "Lina" ] })它会变成:
WHERE user.name IN ('Timber', 'Crystal', 'Lina')添加 WHERE 表达式
添加 WHERE 表达式非常简单:
createQueryBuilder("user").where("user.name = :name", { name: "Timber" })它会生成:
SELECT ... FROM users user WHERE user.name = 'Timber'你可以在已有的 WHERE 表达式中加入 AND:
createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName: "Timber" })
.andWhere("user.lastName = :lastName", { lastName: "Saw" })它会生成如下 SQL 查询:
SELECT ... FROM users user WHERE user.firstName = 'Timber' AND user.lastName = 'Saw'你可以在已有的 WHERE 表达式中加入 OR:
createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName: "Timber" })
.orWhere("user.lastName = :lastName", { lastName: "Saw" })它会生成如下 SQL 查询:
SELECT ... FROM users user WHERE user.firstName = 'Timber' OR user.lastName = 'Saw'你可以用 WHERE 表达式做 IN 查询:
createQueryBuilder("user").where("user.id IN (:...ids)", { ids: [1, 2, 3, 4] })它会生成如下 SQL 查询:
SELECT ... FROM users user WHERE user.id IN (1, 2, 3, 4)你可以用 Brackets 在已有的 WHERE 中加入复杂的 WHERE 表达式
createQueryBuilder("user")
.where("user.registered = :registered", { registered: true })
.andWhere(
new Brackets((qb) => {
qb.where("user.firstName = :firstName", {
firstName: "Timber",
}).orWhere("user.lastName = :lastName", { lastName: "Saw" })
}),
)它会生成如下 SQL 查询:
SELECT ... FROM users user WHERE user.registered = true AND (user.firstName = 'Timber' OR user.lastName = 'Saw')你可以用 NotBrackets 在已有的 WHERE 中加入取反的复杂 WHERE 表达式
createQueryBuilder("user")
.where("user.registered = :registered", { registered: true })
.andWhere(
new NotBrackets((qb) => {
qb.where("user.firstName = :firstName", {
firstName: "Timber",
}).orWhere("user.lastName = :lastName", { lastName: "Saw" })
}),
)它会生成如下 SQL 查询:
SELECT ... FROM users user WHERE user.registered = true AND NOT((user.firstName = 'Timber' OR user.lastName = 'Saw'))你可以按需组合任意多的 AND 与 OR 表达式。如果你多次使用 .where,之前所有的 WHERE 表达式都会被覆盖。
注意:使用 orWhere 时要小心——如果你同时用了含 AND 与 OR 的复杂表达式,请记住它们是毫无修饰地层层堆叠的。有时你需要自己拼一个 where 字符串,并避免使用 orWhere。
添加 HAVING 表达式
添加 HAVING 表达式很简单:
createQueryBuilder("user").having("user.name = :name", { name: "Timber" })它会生成如下 SQL 查询:
SELECT ... FROM users user HAVING user.name = 'Timber'你可以在已有的 HAVING 表达式中加入 AND:
createQueryBuilder("user")
.having("user.firstName = :firstName", { firstName: "Timber" })
.andHaving("user.lastName = :lastName", { lastName: "Saw" })它会生成如下 SQL 查询:
SELECT ... FROM users user HAVING user.firstName = 'Timber' AND user.lastName = 'Saw'你可以在已有的 HAVING 表达式中加入 OR:
createQueryBuilder("user")
.having("user.firstName = :firstName", { firstName: "Timber" })
.orHaving("user.lastName = :lastName", { lastName: "Saw" })它会生成如下 SQL 查询:
SELECT ... FROM users user HAVING user.firstName = 'Timber' OR user.lastName = 'Saw'你可以按需组合任意多的 AND 与 OR 表达式。如果你多次使用 .having,之前所有的 HAVING 表达式都会被覆盖。
添加 ORDER BY 表达式
添加 ORDER BY 表达式很简单:
createQueryBuilder("user").orderBy("user.id")它会生成:
SELECT ... FROM users user ORDER BY user.id你可以把排序方向从升序改为降序(或反过来):
createQueryBuilder("user").orderBy("user.id", "DESC")
createQueryBuilder("user").orderBy("user.id", "ASC")你可以添加多个排序条件:
createQueryBuilder("user").orderBy("user.name").addOrderBy("user.id")你也可以使用排序字段的映射:
createQueryBuilder("user").orderBy({
"user.name": "ASC",
"user.id": "DESC",
})如果你多次使用 .orderBy,之前所有的 ORDER BY 表达式都会被覆盖。
添加 DISTINCT ON 表达式(仅 Postgres)
当同时使用 distinct-on 与 order-by 表达式时,distinct-on 表达式必须与最左侧的 order-by 相匹配。distinct-on 表达式的解释规则与 order-by 相同。请注意,在没有 order-by 表达式的情况下使用 distinct-on,意味着每个分组中取到哪一行是不可预测的。
添加 DISTINCT ON 表达式很简单:
createQueryBuilder("user").distinctOn(["user.id"]).orderBy("user.id")它会生成:
SELECT DISTINCT ON (user.id) ... FROM users user ORDER BY user.id添加 GROUP BY 表达式
添加 GROUP BY 表达式很简单:
createQueryBuilder("user").groupBy("user.id")它会生成如下 SQL 查询:
SELECT ... FROM users user GROUP BY user.id要添加更多分组条件,请使用 addGroupBy:
createQueryBuilder("user").groupBy("user.name").addGroupBy("user.id")如果你多次使用 .groupBy,之前所有的 GROUP BY 表达式都会被覆盖。
添加 LIMIT 表达式
添加 LIMIT 表达式很简单:
createQueryBuilder("user").limit(10)它会生成如下 SQL 查询:
SELECT ... FROM users user LIMIT 10最终生成的 SQL 查询取决于数据库类型(SQL、mySQL、Postgres 等)。注意:如果你使用的是带连接或子查询的复杂查询,LIMIT 的表现可能与预期不符。如果你做的是分页,建议改用 take。
添加 OFFSET 表达式
添加 SQL OFFSET 表达式很简单:
createQueryBuilder("user").offset(10)它会生成如下 SQL 查询:
SELECT ... FROM users user OFFSET 10最终生成的 SQL 查询取决于数据库类型(SQL、mySQL、Postgres 等)。注意:如果你使用的是带连接或子查询的复杂查询,OFFSET 的表现可能与预期不符。如果你做的是分页,建议改用 skip。
连接关系
假设你有以下实体:
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"
import { Photo } from "./Photo"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToMany((type) => Photo, (photo) => photo.user)
photos: Photo[]
}import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"
import { User } from "./User"
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number
@Column()
url: string
@ManyToOne((type) => User, (user) => user.photos)
user: User
}现在假设你想加载用户 "Timber" 以及他的所有照片:
const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.where("user.name = :name", { name: "Timber" })
.getOne()你会得到如下结果:
{
id: 1,
name: "Timber",
photos: [{
id: 1,
url: "me-with-chakram.jpg"
}, {
id: 2,
url: "me-with-trees.jpg"
}]
}如你所见,leftJoinAndSelect 自动加载了 Timber 的所有照片。第一个参数是你想加载的关系,第二个参数是你给该关系的表起的别名。你可以在 query builder 中的任何地方使用这个别名。例如,我们来取出 Timber 所有未被移除的照片。
const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.where("user.name = :name", { name: "Timber" })
.andWhere("photo.isRemoved = :isRemoved", { isRemoved: false })
.getOne()这会生成如下 SQL 查询:
SELECT user.*, photo.* FROM users user
LEFT JOIN photos photo ON photo.user = user.id
WHERE user.name = 'Timber' AND photo.isRemoved = FALSE你也可以把条件加到连接表达式上,而不是用 "where":
const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo", "photo.isRemoved = :isRemoved", {
isRemoved: false,
})
.where("user.name = :name", { name: "Timber" })
.getOne()这会生成如下 SQL 查询:
SELECT user.*, photo.* FROM users user
LEFT JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
WHERE user.name = 'Timber'内连接与左连接
如果你想用 INNER JOIN 而不是 LEFT JOIN,只需改用 innerJoinAndSelect:
const user = await dataSource
.createQueryBuilder("user")
.innerJoinAndSelect(
"user.photos",
"photo",
"photo.isRemoved = :isRemoved",
{ isRemoved: false },
)
.where("user.name = :name", { name: "Timber" })
.getOne()这会生成:
SELECT user.*, photo.* FROM users user
INNER JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
WHERE user.name = 'Timber'LEFT JOIN 与 INNER JOIN 的区别在于:如果一个用户没有任何照片,INNER JOIN 不会返回该用户;而 LEFT JOIN 即使他没有照片也会返回该用户。要进一步了解不同的连接类型,请参阅 SQL 文档。
连接但不选取
你可以连接数据而不选取它。要做到这一点,请使用 leftJoin 或 innerJoin:
const user = await dataSource
.createQueryBuilder("user")
.innerJoin("user.photos", "photo")
.where("user.name = :name", { name: "Timber" })
.getOne()这会生成:
SELECT user.* FROM users user
INNER JOIN photos photo ON photo.user = user.id
WHERE user.name = 'Timber'这会在 Timber 有照片时选中他,但不会返回他的照片。
连接任意实体或表
你不仅能连接关系,还能连接其他不相关的实体或表。示例:
const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndSelect(Photo, "photo", "photo.userId = user.id")
.getMany()const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndSelect("photos", "photo", "photo.userId = user.id")
.getMany()连接与映射功能
给 User 实体加上 profilePhoto,你就可以用 QueryBuilder 把任意数据映射到该属性上:
export class User {
/// ...
profilePhoto: Photo
}const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndMapOne(
"user.profilePhoto",
"user.photos",
"photo",
"photo.isForProfile = TRUE",
)
.where("user.name = :name", { name: "Timber" })
.getOne()这会加载 Timber 的头像照片并把它设置到 user.profilePhoto。如果你想加载并映射单个实体,请使用 leftJoinAndMapOne。如果你想加载并映射多个实体,请使用 leftJoinAndMapMany。
获取生成的查询
有时你可能想拿到 QueryBuilder 生成的 SQL 查询。要做到这一点,请使用 getSql:
const sql = dataSource
.createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName: "Timber" })
.orWhere("user.lastName = :lastName", { lastName: "Saw" })
.getSql()出于调试目的,你可以用 getSql() 或 getQuery() 查看生成的 SQL:
const qb = dataSource
.createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName: "Timber" })
.orWhere("user.lastName = :lastName", { lastName: "Saw" })
console.log(qb.getSql())
// SELECT ... WHERE "user"."firstName" = $1 OR "user"."lastName" = $2
const users = await qb.getMany()getSql() 返回带参数占位符的 SQL。getQuery() 返回同样的 SQL 字符串。如果还想看到参数值,请使用 getQueryAndParameters(),它返回一个 [sql, parameters] 元组。
当你在 DataSource 选项中启用查询日志时,所有已执行的查询也都会通过所配置的日志记录器自动记录:
new DataSource({
// ...
logging: ["query"],
})获取原生结果
使用 select query builder 你可以得到两类结果:实体 和 原生结果。大多数时候,你需要从数据库中选取真正的实体,例如用户。为此你使用 getOne 和 getMany。不过,有时你需要选取特定数据,比如所有用户照片的总和。这类数据不是实体,它被称为原生数据。要获取原生数据,你使用 getRawOne 和 getRawMany。示例:
const { sum } = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("SUM(user.photosCount)", "sum")
.where("user.id = :id", { id: 1 })
.getRawOne()const photosSums = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.id")
.addSelect("SUM(user.photosCount)", "sum")
.groupBy("user.id")
.getRawMany()
// 结果会像这样:[{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]流式处理结果数据
你可以使用 stream,它会返回一个流。流式处理返回的是原生数据,你必须手动处理实体转换:
const stream = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.stream()使用分页
开发应用时,大多数时候你都需要分页功能。当你的应用中有分页、页面滑块或无限滚动组件时就会用到它。
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.take(10)
.getMany()这会给你前 10 个用户及其照片。
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.skip(10)
.getMany()这会给你除前 10 个用户之外的所有用户及其照片。你可以组合这两个方法:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.skip(5)
.take(10)
.getMany()这会跳过前 5 个用户,然后取其后的 10 个用户。
take 和 skip 看起来像是我们在用 limit 和 offset,但其实不是。一旦你有更复杂的、带连接或子查询的查询,limit 和 offset 的表现就可能与预期不符。使用 take 和 skip 能避免这些问题。
设置锁
QueryBuilder 同时支持乐观锁和悲观锁。
锁模式
下表列出了各锁模式的支持情况以及它们被转换成的 SQL 语句(空白单元格表示不支持)。当指定的锁模式不被支持时,会抛出 LockNotSupportedOnGivenDriverError 错误。
| pessimistic_read | pessimistic_write | dirty_read | for_no_key_update | for_key_share | |
|---|---|---|---|---|---|
| MySQL, MariaDB | FOR SHARE (MySQL 8+), LOCK IN SHARE MODE |
FOR UPDATE |
(nothing) | ||
| Oracle | FOR UPDATE |
FOR UPDATE |
(nothing) | ||
| Postgres, CockroachDB | FOR SHARE |
FOR UPDATE |
(nothing) | FOR NO KEY UPDATE |
FOR KEY SHARE |
| SAP HANA | FOR SHARE LOCK |
FOR UPDATE |
(nothing) | ||
| SQL Server | WITH (HOLDLOCK, ROWLOCK) |
WITH (UPDLOCK, ROWLOCK) |
WITH (NOLOCK) |
要使用悲观读锁,请使用以下方法:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("pessimistic_read")
.getMany()要使用悲观写锁,请使用以下方法:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("pessimistic_write")
.getMany()要使用脏读锁,请使用以下方法:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("dirty_read")
.getMany()要使用乐观锁,请使用以下方法:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("optimistic", existUser.version)
.getMany()乐观锁与 @Version 和 @UpdatedDate 装饰器配合使用。
锁表
你也可以用以下方法锁表:
const users = await dataSource
.getRepository(Post)
.createQueryBuilder("post")
.leftJoin("post.author", "user")
.setLock("pessimistic_write", undefined, ["post"])
.getMany()如果提供了 Lock Tables 参数,那么 FOR UPDATE OF 子句中只会指定被锁的那张表。锁表仅在 PostgreSQL / CockroachDB 上受支持。
setOnLocked
它让你可以控制某行被锁定时会发生什么。默认情况下,数据库会等待锁。你可以用 setOnLocked 控制这一行为
不等待:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("pessimistic_write")
.setOnLocked("nowait")
.getMany()跳过该行:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("pessimistic_write")
.setOnLocked("skip_locked")
.getMany()各数据库基于锁模式对 setOnLocked 的支持情况:
- MySQL < 8、Maria DB:
pessimistic_write - MySQL 8+:
pessimistic_read、pessimistic_write - Oracle:
pessimistic_write - Postgres、Cockroach:
pessimistic_read、pessimistic_write、for_no_key_update、for_key_share - SAP HANA:
pessimistic_read、pessimistic_write
使用自定义索引
在某些情况下,你可以指定数据库服务器使用某个特定索引。该特性仅在 MySQL 上受支持。
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.useIndex("my_index") // 索引名
.getMany()最大执行时间
我们可以丢弃慢查询,以避免服务器崩溃。
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.maxExecutionTime(1000) // 毫秒。
.getMany()部分选取
如果你只想选取实体的部分属性,可以使用以下语法:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select(["user.id", "user.name"])
.getMany()这只会选取 User 的 id 和 name。
使用子查询
你可以轻松创建子查询。子查询在 FROM、WHERE 和 JOIN 表达式中都受支持。示例:
const qb = await dataSource.getRepository(Post).createQueryBuilder("post")
const posts = qb
.where(
"post.title IN " +
qb
.subQuery()
.select("user.name")
.from(User, "user")
.where("user.registered = :registered")
.getQuery(),
)
.setParameter("registered", true)
.getMany()更优雅的等价写法:
const posts = await dataSource
.getRepository(Post)
.createQueryBuilder("post")
.where((qb) => {
const subQuery = qb
.subQuery()
.select("user.name")
.from(User, "user")
.where("user.registered = :registered")
.getQuery()
return "post.title IN " + subQuery
})
.setParameter("registered", true)
.getMany()另外,你也可以创建一个独立的 query builder 并使用它生成的 SQL:
const userQb = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.name")
.where("user.registered = :registered", { registered: true })
const posts = await dataSource
.getRepository(Post)
.createQueryBuilder("post")
.where("post.title IN (" + userQb.getQuery() + ")")
.setParameters(userQb.getParameters())
.getMany()你可以这样在 FROM 中创建子查询:
const userQb = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.name", "name")
.where("user.registered = :registered", { registered: true })
const posts = await dataSource
.createQueryBuilder()
.select("user.name", "name")
.from("(" + userQb.getQuery() + ")", "user")
.setParameters(userQb.getParameters())
.getRawMany()或者使用更优雅的语法:
const posts = await dataSource
.createQueryBuilder()
.select("user.name", "name")
.from((subQuery) => {
return subQuery
.select("user.name", "name")
.from(User, "user")
.where("user.registered = :registered", { registered: true })
}, "user")
.getRawMany()如果你想添加一个子查询作为"第二个 from",请使用 addFrom。
你也可以在 SELECT 语句中使用子查询:
const posts = await dataSource
.createQueryBuilder()
.select("post.id", "id")
.addSelect((subQuery) => {
return subQuery.select("user.name", "name").from(User, "user").limit(1)
}, "name")
.from(Post, "post")
.getRawMany()隐藏列
如果你查询的模型中有 select: false 的列,你必须使用 addSelect 函数才能取回该列的信息。
假设你有以下实体:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@Column({ select: false })
password: string
}使用标准的 find 或查询时,你不会收到该模型的 password 属性。不过,如果你这样做:
const users = await dataSource
.getRepository(User)
.createQueryBuilder()
.select("user.id", "id")
.addSelect("user.password")
.getMany()你就会在查询结果中得到 password 属性。
select: false 只控制读取时从数据库加载什么。repository.save() 返回的内存中实体不受影响——你为 select: false 列提供的任何值都会保留在返回的实体以及传给 save() 的原始引用上。之后若要从数据库重新读取这些列,请再执行一次带 addSelect 的查询。
查询已删除的行
如果你查询的模型中有带 @DeleteDateColumn 属性的列,query builder 会自动把"软删除"的行也查出来。
假设你有以下实体:
import {
Entity,
PrimaryGeneratedColumn,
Column,
DeleteDateColumn,
} from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@DeleteDateColumn()
deletedAt?: Date
}使用标准的 find 或查询时,你不会收到该列有值的那些行。不过,如果你这样做:
const users = await dataSource
.getRepository(User)
.createQueryBuilder()
.select("user.id", "id")
.withDeleted()
.getMany()你就会得到所有行,包括已被删除的那些。
公共表表达式
如果你的数据库受支持的最低版本支持公共表表达式,QueryBuilder 实例也支持它们。Oracle 目前还不支持公共表表达式。
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.id", "id")
.addCommonTableExpression(
`
SELECT "userId" FROM "post"
`,
"post_users_ids",
)
.where(`user.id IN (SELECT "userId" FROM 'post_users_ids')`)
.getMany()InsertQueryBuilder 或 UpdateQueryBuilder 的结果值可以在 Postgres 中使用:
const insertQueryBuilder = dataSource
.getRepository(User)
.createQueryBuilder()
.insert({
name: "John Smith",
})
.returning(["id"])
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.addCommonTableExpression(insertQueryBuilder, "insert_results")
.where(`user.id IN (SELECT "id" FROM 'insert_results')`)
.getMany()时间旅行查询
时间旅行查询目前仅在 CockroachDB 数据库中受支持。
const repository = dataSource.getRepository(Account)
// 创建一个新账户
const account = new Account()
account.name = "John Smith"
account.balance = 100
await repository.save(account)
// 假设我们在创建 1 小时后更新了账户余额
account.balance = 200
await repository.save(account)
// 输出 { name: "John Smith", balance: "200" }
console.log(account)
// 加载 1 小时前的账户状态
account = await repository
.createQueryBuilder("account")
.timeTravelQuery(`'-1h'`)
.getOneOrFail()
// 输出 { name: "John Smith", balance: "100" }
console.log(account)默认情况下,如果不传参数,timeTravelQuery() 会使用 follower_read_timestamp() 函数。关于其他受支持的时间戳参数及更多信息,请参阅 CockroachDB 文档。
调试
你可以通过调用 getQuery() 或 getQueryAndParameters() 从 query builder 拿到生成的 SQL。
如果你只想要查询本身,可以使用 getQuery()
const sql = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.getQuery()结果是:
SELECT `user`.`id` as `userId`, `user`.`firstName` as `userFirstName`, `user`.`lastName` as `userLastName` FROM `users` `user` WHERE `user`.`id` = ?或者,如果你既想要查询又想要参数,可以用 getQueryAndParameters() 拿回一个数组
const queryAndParams = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.getQueryAndParameters()结果是:
;[
"SELECT `user`.`id` as `userId`, `user`.`firstName` as `userFirstName`, `user`.`lastName` as `userLastName` FROM `users` `user` WHERE `user`.`id` = ?",
[1],
]What is a QueryBuilder?
QueryBuilder is one of the most powerful features of TypeORM - it allows you to build SQL queries using elegant and convenient syntax, execute them and get automatically transformed entities.
Simple example of QueryBuilder:
const firstUser = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.getOne()It builds the following SQL query:
SELECT
user.id as userId,
user.firstName as userFirstName,
user.lastName as userLastName
FROM users user
WHERE user.id = 1and returns you an instance of User:
User {
id: 1,
firstName: "Timber",
lastName: "Saw"
}Important note when using the QueryBuilder
When using the QueryBuilder, you need to provide unique parameters in your WHERE expressions. This will not work:
const result = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.linkedSheep", "linkedSheep")
.leftJoinAndSelect("user.linkedCow", "linkedCow")
.where("user.linkedSheep = :id", { id: sheepId })
.andWhere("user.linkedCow = :id", { id: cowId })... but this will:
const result = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.linkedSheep", "linkedSheep")
.leftJoinAndSelect("user.linkedCow", "linkedCow")
.where("user.linkedSheep = :sheepId", { sheepId })
.andWhere("user.linkedCow = :cowId", { cowId })Note that we uniquely named :sheepId and :cowId instead of using :id twice for different parameters.
How to create and use a QueryBuilder?
There are several ways how you can create a Query Builder:
- Using DataSource:
const user = await dataSource
.createQueryBuilder()
.select("user")
.from(User, "user")
.where("user.id = :id", { id: 1 })
.getOne()- Using entity manager:
const user = await dataSource.manager
.createQueryBuilder(User, "user")
.where("user.id = :id", { id: 1 })
.getOne()- Using repository:
const user = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.getOne()There are 5 different QueryBuilder types available:
SelectQueryBuilder- used to build and executeSELECTqueries. Example:
const user = await dataSource
.createQueryBuilder()
.select("user")
.from(User, "user")
.where("user.id = :id", { id: 1 })
.getOne()InsertQueryBuilder- used to build and executeINSERTqueries. Example:
await dataSource
.createQueryBuilder()
.insert()
.into(User)
.values([
{ firstName: "Timber", lastName: "Saw" },
{ firstName: "Phantom", lastName: "Lancer" },
])
.execute()UpdateQueryBuilder- used to build and executeUPDATEqueries. Example:
await dataSource
.createQueryBuilder()
.update(User)
.set({ firstName: "Timber", lastName: "Saw" })
.where("id = :id", { id: 1 })
.execute()DeleteQueryBuilder- used to build and executeDELETEqueries. Example:
await dataSource
.createQueryBuilder()
.delete()
.from(User)
.where("id = :id", { id: 1 })
.execute()RelationQueryBuilder- used to build and execute relation-specific operations [TBD]. Example:
await dataSource
.createQueryBuilder()
.relation(User, "photos")
.of(id)
.loadMany()You can switch between different types of query builder within any of them, once you do, you will get a new instance of query builder (unlike all other methods).
Getting values using QueryBuilder
To get a single result from the database, for example to get a user by id or name, you must use getOne:
const timber = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" })
.getOne()getOneOrFail will get a single result from the database, but if no result exists it will throw an EntityNotFoundError:
const timber = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" })
.getOneOrFail()To get multiple results from the database, for example, to get all users from the database, use getMany:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.getMany()There are two types of results you can get using select query builder: entities or raw results. Most of the time, you need to select real entities from your database, for example, users. For this purpose, you use getOne and getMany. But sometimes you need to select some specific data, let's say the sum of all user photos. This data is not an entity, it's called raw data. To get raw data, you use getRawOne and getRawMany. Examples:
const { sum } = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("SUM(user.photosCount)", "sum")
.where("user.id = :id", { id: 1 })
.getRawOne()const photosSums = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.id")
.addSelect("SUM(user.photosCount)", "sum")
.groupBy("user.id")
.getRawMany()
// result will be like this: [{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]Getting a count
You can get the count on the number of rows a query will return by using getCount(). This will return the count as a number rather than an Entity result.
const count = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.name = :name", { name: "Timber" })
.getCount()Which produces the following SQL query:
SELECT count(*) FROM users user WHERE user.name = 'Timber'What are aliases for?
We used createQueryBuilder("user"). But what is "user"? It's just a regular SQL alias. We use aliases everywhere, except when we work with selected data.
createQueryBuilder("user") is equivalent to:
createQueryBuilder().select("user").from(User, "user")Which will result in the following SQL query:
SELECT ... FROM users userIn this SQL query, users is the table name, and user is an alias we assign to this table. Later we use this alias to access the table:
createQueryBuilder()
.select("user")
.from(User, "user")
.where("user.name = :name", { name: "Timber" })Which produces the following SQL query:
SELECT ... FROM users user WHERE user.name = 'Timber'See, we used the users table by using the user alias we assigned when we created a query builder.
One query builder is not limited to one alias, they can have multiple aliases. Each select can have its own alias, you can select from multiple tables each with its own alias, you can join multiple tables each with its own alias. You can use those aliases to access tables you are selecting (or data you are selecting).
Using parameters to escape data
We used where("user.name = :name", { name: "Timber" }). What does { name: "Timber" } stand for? It's a parameter we used to prevent SQL injection. We could have written: where("user.name = '" + name + "'), however this is not safe, as it opens the code to SQL injections. The safe way is to use this special syntax: where("user.name = :name", { name: "Timber" }), where :name is a parameter name and the value is specified in an object: { name: "Timber" }.
.where("user.name = :name", { name: "Timber" })is a shortcut for:
.where("user.name = :name")
.setParameter("name", "Timber")Note: do not use the same parameter name for different values across the query builder. Values will be overridden if you set them multiple times.
You can also supply an array of values, and have them transformed into a list of values in the SQL statement, by using the special expansion syntax:
.where("user.name IN (:...names)", { names: [ "Timber", "Crystal", "Lina" ] })Which becomes:
WHERE user.name IN ('Timber', 'Crystal', 'Lina')Adding WHERE expression
Adding a WHERE expression is as easy as:
createQueryBuilder("user").where("user.name = :name", { name: "Timber" })Which will produce:
SELECT ... FROM users user WHERE user.name = 'Timber'You can add AND into an existing WHERE expression:
createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName: "Timber" })
.andWhere("user.lastName = :lastName", { lastName: "Saw" })Which will produce the following SQL query:
SELECT ... FROM users user WHERE user.firstName = 'Timber' AND user.lastName = 'Saw'You can add OR into an existing WHERE expression:
createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName: "Timber" })
.orWhere("user.lastName = :lastName", { lastName: "Saw" })Which will produce the following SQL query:
SELECT ... FROM users user WHERE user.firstName = 'Timber' OR user.lastName = 'Saw'You can do an IN query with the WHERE expression:
createQueryBuilder("user").where("user.id IN (:...ids)", { ids: [1, 2, 3, 4] })Which will produce the following SQL query:
SELECT ... FROM users user WHERE user.id IN (1, 2, 3, 4)You can add a complex WHERE expression into an existing WHERE using Brackets
createQueryBuilder("user")
.where("user.registered = :registered", { registered: true })
.andWhere(
new Brackets((qb) => {
qb.where("user.firstName = :firstName", {
firstName: "Timber",
}).orWhere("user.lastName = :lastName", { lastName: "Saw" })
}),
)Which will produce the following SQL query:
SELECT ... FROM users user WHERE user.registered = true AND (user.firstName = 'Timber' OR user.lastName = 'Saw')You can add a negated complex WHERE expression into an existing WHERE using NotBrackets
createQueryBuilder("user")
.where("user.registered = :registered", { registered: true })
.andWhere(
new NotBrackets((qb) => {
qb.where("user.firstName = :firstName", {
firstName: "Timber",
}).orWhere("user.lastName = :lastName", { lastName: "Saw" })
}),
)Which will produce the following SQL query:
SELECT ... FROM users user WHERE user.registered = true AND NOT((user.firstName = 'Timber' OR user.lastName = 'Saw'))You can combine as many AND and OR expressions as you need. If you use .where more than once you'll override all previous WHERE expressions.
Note: be careful with orWhere - if you use complex expressions with both AND and OR expressions, keep in mind that they are stacked without any pretences. Sometimes you'll need to create a where string instead, and avoid using orWhere.
Adding HAVING expression
Adding a HAVING expression is easy as:
createQueryBuilder("user").having("user.name = :name", { name: "Timber" })Which will produce following SQL query:
SELECT ... FROM users user HAVING user.name = 'Timber'You can add AND into an exist HAVING expression:
createQueryBuilder("user")
.having("user.firstName = :firstName", { firstName: "Timber" })
.andHaving("user.lastName = :lastName", { lastName: "Saw" })Which will produce the following SQL query:
SELECT ... FROM users user HAVING user.firstName = 'Timber' AND user.lastName = 'Saw'You can add OR into a exist HAVING expression:
createQueryBuilder("user")
.having("user.firstName = :firstName", { firstName: "Timber" })
.orHaving("user.lastName = :lastName", { lastName: "Saw" })Which will produce the following SQL query:
SELECT ... FROM users user HAVING user.firstName = 'Timber' OR user.lastName = 'Saw'You can combine as many AND and OR expressions as you need. If you use .having more than once you'll override all previous HAVING expressions.
Adding ORDER BY expression
Adding an ORDER BY expression is easy as:
createQueryBuilder("user").orderBy("user.id")Which will produce:
SELECT ... FROM users user ORDER BY user.idYou can change the ordering direction from ascending to descending (or versa):
createQueryBuilder("user").orderBy("user.id", "DESC")
createQueryBuilder("user").orderBy("user.id", "ASC")You can add multiple order-by criteria:
createQueryBuilder("user").orderBy("user.name").addOrderBy("user.id")You can also use a map of order-by fields:
createQueryBuilder("user").orderBy({
"user.name": "ASC",
"user.id": "DESC",
})If you use .orderBy more than once you'll override all previous ORDER BY expressions.
Adding DISTINCT ON expression (Postgres only)
When using both distinct-on with an order-by expression, the distinct-on expression must match the leftmost order-by. The distinct-on expressions are interpreted using the same rules as order-by. Please note that, using distinct-on without an order-by expression means that the first row of each set is unpredictable.
Adding a DISTINCT ON expression is easy as:
createQueryBuilder("user").distinctOn(["user.id"]).orderBy("user.id")Which will produce:
SELECT DISTINCT ON (user.id) ... FROM users user ORDER BY user.idAdding GROUP BY expression
Adding a GROUP BY expression is easy as:
createQueryBuilder("user").groupBy("user.id")Which will produce the following SQL query:
SELECT ... FROM users user GROUP BY user.idTo add more group-by criteria use addGroupBy:
createQueryBuilder("user").groupBy("user.name").addGroupBy("user.id")If you use .groupBy more than once you'll override all previous GROUP BY expressions.
Adding LIMIT expression
Adding a LIMIT expression is easy as:
createQueryBuilder("user").limit(10)Which will produce the following SQL query:
SELECT ... FROM users user LIMIT 10The resulting SQL query depends on the type of database (SQL, mySQL, Postgres, etc). Note: LIMIT may not work as you may expect if you are using complex queries with joins or subqueries. If you are using pagination, it's recommended to use take instead.
Adding OFFSET expression
Adding an SQL OFFSET expression is easy as:
createQueryBuilder("user").offset(10)Which will produce the following SQL query:
SELECT ... FROM users user OFFSET 10The resulting SQL query depends on the type of database (SQL, mySQL, Postgres, etc). Note: OFFSET may not work as you may expect if you are using complex queries with joins or subqueries. If you are using pagination, it's recommended to use skip instead.
Joining relations
Let's say you have the following entities:
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"
import { Photo } from "./Photo"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToMany((type) => Photo, (photo) => photo.user)
photos: Photo[]
}import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"
import { User } from "./User"
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number
@Column()
url: string
@ManyToOne((type) => User, (user) => user.photos)
user: User
}Now let's say you want to load user "Timber" with all of his photos:
const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.where("user.name = :name", { name: "Timber" })
.getOne()You'll get the following result:
{
id: 1,
name: "Timber",
photos: [{
id: 1,
url: "me-with-chakram.jpg"
}, {
id: 2,
url: "me-with-trees.jpg"
}]
}As you can see leftJoinAndSelect automatically loaded all of Timber's photos. The first argument is the relation you want to load and the second argument is an alias you assign to this relation's table. You can use this alias anywhere in query builder. For example, let's take all Timber's photos which aren't removed.
const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.where("user.name = :name", { name: "Timber" })
.andWhere("photo.isRemoved = :isRemoved", { isRemoved: false })
.getOne()This will generate following SQL query:
SELECT user.*, photo.* FROM users user
LEFT JOIN photos photo ON photo.user = user.id
WHERE user.name = 'Timber' AND photo.isRemoved = FALSEYou can also add conditions to the join expression instead of using "where":
const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo", "photo.isRemoved = :isRemoved", {
isRemoved: false,
})
.where("user.name = :name", { name: "Timber" })
.getOne()This will generate the following SQL query:
SELECT user.*, photo.* FROM users user
LEFT JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
WHERE user.name = 'Timber'Inner and left joins
If you want to use INNER JOIN instead of LEFT JOIN just use innerJoinAndSelect instead:
const user = await dataSource
.createQueryBuilder("user")
.innerJoinAndSelect(
"user.photos",
"photo",
"photo.isRemoved = :isRemoved",
{ isRemoved: false },
)
.where("user.name = :name", { name: "Timber" })
.getOne()This will generate:
SELECT user.*, photo.* FROM users user
INNER JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
WHERE user.name = 'Timber'The difference between LEFT JOIN and INNER JOIN is that INNER JOIN won't return a user if it does not have any photos. LEFT JOIN will return you the user even if it doesn't have photos. To learn more about different join types, refer to the SQL documentation.
Join without selection
You can join data without its selection. To do that, use leftJoin or innerJoin:
const user = await dataSource
.createQueryBuilder("user")
.innerJoin("user.photos", "photo")
.where("user.name = :name", { name: "Timber" })
.getOne()This will generate:
SELECT user.* FROM users user
INNER JOIN photos photo ON photo.user = user.id
WHERE user.name = 'Timber'This will select Timber if he has photos, but won't return his photos.
Joining any entity or table
You can join not only relations, but also other unrelated entities or tables. Examples:
const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndSelect(Photo, "photo", "photo.userId = user.id")
.getMany()const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndSelect("photos", "photo", "photo.userId = user.id")
.getMany()Joining and mapping functionality
Add profilePhoto to User entity, and you can map any data into that property using QueryBuilder:
export class User {
/// ...
profilePhoto: Photo
}const user = await dataSource
.createQueryBuilder("user")
.leftJoinAndMapOne(
"user.profilePhoto",
"user.photos",
"photo",
"photo.isForProfile = TRUE",
)
.where("user.name = :name", { name: "Timber" })
.getOne()This will load Timber's profile photo and set it to user.profilePhoto. If you want to load and map a single entity use leftJoinAndMapOne. If you want to load and map multiple entities use leftJoinAndMapMany.
Getting the generated query
Sometimes you may want to get the SQL query generated by QueryBuilder. To do so, use getSql:
const sql = dataSource
.createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName: "Timber" })
.orWhere("user.lastName = :lastName", { lastName: "Saw" })
.getSql()For debugging purposes you can inspect the generated SQL using getSql() or getQuery():
const qb = dataSource
.createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName: "Timber" })
.orWhere("user.lastName = :lastName", { lastName: "Saw" })
console.log(qb.getSql())
// SELECT ... WHERE "user"."firstName" = $1 OR "user"."lastName" = $2
const users = await qb.getMany()getSql() returns the SQL with parameter placeholders. getQuery() returns the same SQL string. To also see the parameter values, use getQueryAndParameters() which returns a [sql, parameters] tuple.
All executed queries are also automatically logged through the configured logger when you enable query logging in your DataSource options:
new DataSource({
// ...
logging: ["query"],
})Getting raw results
There are two types of results you can get using select query builder: entities and raw results. Most of the time, you need to select real entities from your database, for example, users. For this purpose, you use getOne and getMany. However, sometimes you need to select specific data, like the sum of all user photos. Such data is not an entity, it's called raw data. To get raw data, you use getRawOne and getRawMany. Examples:
const { sum } = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("SUM(user.photosCount)", "sum")
.where("user.id = :id", { id: 1 })
.getRawOne()const photosSums = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.id")
.addSelect("SUM(user.photosCount)", "sum")
.groupBy("user.id")
.getRawMany()
// result will be like this: [{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]Streaming result data
You can use stream which returns you a stream. Streaming returns you raw data, and you must handle entity transformation manually:
const stream = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.stream()Using pagination
Most of the time when you develop an application, you need pagination functionality. This is used if you have pagination, page slider, or infinite scroll components in your application.
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.take(10)
.getMany()This will give you the first 10 users with their photos.
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.skip(10)
.getMany()This will give you all except the first 10 users with their photos. You can combine those methods:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.skip(5)
.take(10)
.getMany()This will skip the first 5 users and take 10 users after them.
take and skip may look like we are using limit and offset, but they aren't. limit and offset may not work as you expect once you have more complicated queries with joins or subqueries. Using take and skip will prevent those issues.
Set locking
QueryBuilder supports both optimistic and pessimistic locking.
Lock modes
Support of lock modes, and SQL statements they translate to, are listed in the table below (blank cell denotes unsupported). When specified lock mode is not supported, a LockNotSupportedOnGivenDriverError error will be thrown.
| pessimistic_read | pessimistic_write | dirty_read | for_no_key_update | for_key_share | |
|---|---|---|---|---|---|
| MySQL, MariaDB | FOR SHARE (MySQL 8+), LOCK IN SHARE MODE |
FOR UPDATE |
(nothing) | ||
| Oracle | FOR UPDATE |
FOR UPDATE |
(nothing) | ||
| Postgres, CockroachDB | FOR SHARE |
FOR UPDATE |
(nothing) | FOR NO KEY UPDATE |
FOR KEY SHARE |
| SAP HANA | FOR SHARE LOCK |
FOR UPDATE |
(nothing) | ||
| SQL Server | WITH (HOLDLOCK, ROWLOCK) |
WITH (UPDLOCK, ROWLOCK) |
WITH (NOLOCK) |
To use pessimistic read locking use the following method:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("pessimistic_read")
.getMany()To use pessimistic write locking use the following method:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("pessimistic_write")
.getMany()To use dirty read locking use the following method:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("dirty_read")
.getMany()To use optimistic locking use the following method:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("optimistic", existUser.version)
.getMany()Optimistic locking works in conjunction with both @Version and @UpdatedDate decorators.
Lock tables
You can also lock tables using the following method:
const users = await dataSource
.getRepository(Post)
.createQueryBuilder("post")
.leftJoin("post.author", "user")
.setLock("pessimistic_write", undefined, ["post"])
.getMany()If the Lock Tables argument is provided, only the table that is locked in the FOR UPDATE OF clause is specified. Lock tables are supported in PostgreSQL / CockroachDB only.
setOnLocked
Allows you to control what happens when a row is locked. By default, the database will wait for the lock. You can control that behavior by using setOnLocked
To not wait:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("pessimistic_write")
.setOnLocked("nowait")
.getMany()To skip the row:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.setLock("pessimistic_write")
.setOnLocked("skip_locked")
.getMany()Database support for setOnLocked based on lock mode:
- MySQL < 8, Maria DB:
pessimistic_write - MySQL 8+:
pessimistic_read,pessimistic_write - Oracle:
pessimistic_write - Postgres, Cockroach:
pessimistic_read,pessimistic_write,for_no_key_update,for_key_share - SAP HANA:
pessimistic_read,pessimistic_write
Use custom index
You can provide a certain index for database server to use in some cases. This feature is only supported in MySQL.
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.useIndex("my_index") // name of index
.getMany()Max execution time
We can drop slow query to avoid crashing the server.
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.maxExecutionTime(1000) // milliseconds.
.getMany()Partial selection
If you want to select only some entity properties, you can use the following syntax:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select(["user.id", "user.name"])
.getMany()This will only select the id and name of User.
Using subqueries
You can easily create subqueries. Subqueries are supported in FROM, WHERE and JOIN expressions. Example:
const qb = await dataSource.getRepository(Post).createQueryBuilder("post")
const posts = qb
.where(
"post.title IN " +
qb
.subQuery()
.select("user.name")
.from(User, "user")
.where("user.registered = :registered")
.getQuery(),
)
.setParameter("registered", true)
.getMany()A more elegant way to do the same:
const posts = await dataSource
.getRepository(Post)
.createQueryBuilder("post")
.where((qb) => {
const subQuery = qb
.subQuery()
.select("user.name")
.from(User, "user")
.where("user.registered = :registered")
.getQuery()
return "post.title IN " + subQuery
})
.setParameter("registered", true)
.getMany()Alternatively, you can create a separate query builder and use its generated SQL:
const userQb = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.name")
.where("user.registered = :registered", { registered: true })
const posts = await dataSource
.getRepository(Post)
.createQueryBuilder("post")
.where("post.title IN (" + userQb.getQuery() + ")")
.setParameters(userQb.getParameters())
.getMany()You can create subqueries in FROM like this:
const userQb = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.name", "name")
.where("user.registered = :registered", { registered: true })
const posts = await dataSource
.createQueryBuilder()
.select("user.name", "name")
.from("(" + userQb.getQuery() + ")", "user")
.setParameters(userQb.getParameters())
.getRawMany()or using a more elegant syntax:
const posts = await dataSource
.createQueryBuilder()
.select("user.name", "name")
.from((subQuery) => {
return subQuery
.select("user.name", "name")
.from(User, "user")
.where("user.registered = :registered", { registered: true })
}, "user")
.getRawMany()If you want to add a subselect as a "second from" use addFrom.
You can use subselects in SELECT statements as well:
const posts = await dataSource
.createQueryBuilder()
.select("post.id", "id")
.addSelect((subQuery) => {
return subQuery.select("user.name", "name").from(User, "user").limit(1)
}, "name")
.from(Post, "post")
.getRawMany()Hidden Columns
If the model you are querying has a column with a select: false column, you must use the addSelect function in order to retrieve the information from the column.
Let's say you have the following entity:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@Column({ select: false })
password: string
}Using a standard find or query, you will not receive the password property for the model. However, if you do the following:
const users = await dataSource
.getRepository(User)
.createQueryBuilder()
.select("user.id", "id")
.addSelect("user.password")
.getMany()You will get the property password in your query.
select: false only controls what is loaded from the database on a read. The in-memory entity returned by repository.save() is not affected — any value you supply for a select: false column is preserved on both the returned entity and the original reference passed to save(). To re-read those columns from the database afterwards, run a subsequent query with addSelect.
Querying Deleted rows
If the model you are querying has a column with the attribute @DeleteDateColumn set, the query builder will automatically query rows which are 'soft deleted'.
Let's say you have the following entity:
import {
Entity,
PrimaryGeneratedColumn,
Column,
DeleteDateColumn,
} from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@DeleteDateColumn()
deletedAt?: Date
}Using a standard find or query, you will not receive the rows which have a value in that column. However, if you do the following:
const users = await dataSource
.getRepository(User)
.createQueryBuilder()
.select("user.id", "id")
.withDeleted()
.getMany()You will get all the rows, including the ones which are deleted.
Common table expressions
QueryBuilder instances support common table expressions , if minimal supported version of your database supports them. Common table expressions aren't supported for Oracle yet.
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.id", "id")
.addCommonTableExpression(
`
SELECT "userId" FROM "post"
`,
"post_users_ids",
)
.where(`user.id IN (SELECT "userId" FROM 'post_users_ids')`)
.getMany()Result values of InsertQueryBuilder or UpdateQueryBuilder can be used in Postgres:
const insertQueryBuilder = dataSource
.getRepository(User)
.createQueryBuilder()
.insert({
name: "John Smith",
})
.returning(["id"])
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.addCommonTableExpression(insertQueryBuilder, "insert_results")
.where(`user.id IN (SELECT "id" FROM 'insert_results')`)
.getMany()Time Travel Queries
Time Travel Queries currently supported only in CockroachDB database.
const repository = dataSource.getRepository(Account)
// create a new account
const account = new Account()
account.name = "John Smith"
account.balance = 100
await repository.save(account)
// imagine we update the account balance 1 hour after creation
account.balance = 200
await repository.save(account)
// outputs { name: "John Smith", balance: "200" }
console.log(account)
// load account state on 1 hour back
account = await repository
.createQueryBuilder("account")
.timeTravelQuery(`'-1h'`)
.getOneOrFail()
// outputs { name: "John Smith", balance: "100" }
console.log(account)By default timeTravelQuery() uses follower_read_timestamp() function if no arguments passed. For another supported timestamp arguments and additional information please refer to CockroachDB docs.
Debugging
You can get the generated SQL from the query builder by calling getQuery() or getQueryAndParameters().
If you just want the query you can use getQuery()
const sql = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.getQuery()Which results in:
SELECT `user`.`id` as `userId`, `user`.`firstName` as `userFirstName`, `user`.`lastName` as `userLastName` FROM `users` `user` WHERE `user`.`id` = ?Or if you want the query and the parameters you can get an array back using getQueryAndParameters()
const queryAndParams = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.getQueryAndParameters()Which results in:
;[
"SELECT `user`.`id` as `userId`, `user`.`firstName` as `userFirstName`, `user`.`lastName` as `userLastName` FROM `users` `user` WHERE `user`.`id` = ?",
[1],
]