Drizzle 查询

WARNING

本页面解释的是 drizzle 版本 1.0.0-beta.1 及更高版本中可用的概念。

npm
yarn
pnpm
bun
npm i drizzle-orm@rc
npm i drizzle-kit@rc -D

Drizzle ORM 的设计目标是在 SQL 之上提供一个轻量且类型安全的层。
我们真心相信,我们已经设计出了从 TypeScript 操作 SQL 数据库的最佳方式,现在是时候把它变得更好了。

关系型查询旨在为你提供出色的开发者体验,用于从 SQL 数据库中查询嵌套的关系数据,避免多次连接和复杂的数据映射。

它是对现有 schema 定义和查询构建器的扩展。
你可以根据自己的需求选择启用它。
我们确保你同时拥有一流的开发者体验和性能。

index.ts
schema.ts
import { relations } from './schema';
import { drizzle } from 'drizzle-orm/...';

const db = drizzle({ relations });

const result = await db.query.users.findMany({
	with: {
		posts: true			
	},
});
[{
	id: 10,
	name: "Dan",
	posts: [
		{
			id: 1,
			content: "SQL is awesome",
			authorId: 10,
		},
		{
			id: 2,
			content: "But check relational queries",
			authorId: 10,
		}
	]
}]

关系型查询是 Drizzle 原始 query builder 的扩展。 你需要在 drizzle() 初始化时提供 schema 文件/文件中的所有 tablesrelations,然后直接使用 db.query API。

drizzle 的导入路径取决于你使用的 数据库驱动

index.ts
schema.ts
relations.ts
import { relations } from './relations';
import { drizzle } from 'drizzle-orm/...';

const db = drizzle({ relations });

await db.query.users.findMany(...);

Drizzle 提供 .findMany().findFirst() API。

查找多个

const users = await db.query.users.findMany();
// 结果类型
const result: {
	id: number;
	name: string;
	verified: boolean;
	invitedBy: number | null;
}[];

查找第一个

.findFirst() 会向查询中添加 limit 1

const user = await db.query.users.findFirst();
// 结果类型
const result: {
	id: number;
	name: string;
	verified: boolean;
	invitedBy: number | null;
};

包含关联关系

With 操作符允许你将来自多个相关表的数据组合起来,并正确聚合结果。

获取包含评论的所有帖子:

const posts = await db.query.posts.findMany({
	with: {
		comments: true,
	},
});

获取包含评论的第一条帖子:

const post = await db.query.posts.findFirst({
	with: {
		comments: true,
	},
});

你可以根据需要无限制地链式嵌套 with 语句。
对于任何嵌套的 with 查询,Drizzle 都会使用 Core Type API 推断类型。

获取所有带有帖子用户。每个帖子都应包含评论列表:

const users = await db.query.users.findMany({
	with: {
		posts: {
			with: {
				comments: true,
			},
		},
	},
});

部分字段选择

columns 参数让你可以包含或省略你想从数据库中获取的列。

Drizzle 在查询层执行部分选择,不会从数据库传输额外的数据。

请记住,Drizzle 只会输出一条 SQL 语句。

仅获取所有 posts 的 idcontent 并包含 comments

const posts = await db.query.posts.findMany({
	columns: {
		id: true,
		content: true,
	},
	with: {
		comments: true,
	}
});

获取所有 posts,但不包含 content

const posts = await db.query.posts.findMany({
	columns: {
		content: false,
	},
});

truefalse 选择选项同时存在时,所有 false 选项都会被忽略。

如果你包含 name 字段并排除 id 字段,id 的排除将是多余的,
除了 name 之外的所有字段本来就都会被排除。

在同一个查询中排除并包含字段:

const users = await db.query.users.findMany({
	columns: {
		name: true,
		id: false //忽略
	},
});
// 结果类型
const users: {
	name: string;
};

仅包含嵌套关系中的列:

const res = await db.query.users.findMany({
	columns: {},
	with: {
		posts: true
	}
});
// 结果类型
const res: {
	posts: {
		id: number,
		text: string
	}
}[];

嵌套部分字段选择

就像使用 部分选择 一样,你可以包含或排除嵌套关联的列:

const posts = await db.query.posts.findMany({
	columns: {
		id: true,
		content: true,
	},
	with: {
		comments: {
			columns: {
				authorId: false
			}
		}
	}
});

选择筛选器

就像在我们的类似 SQL 的查询构建器中一样,
关系查询 API 允许你使用我们的 operators 列表来定义筛选器和条件。

你可以从 drizzle-orm 中导入它们,也可以使用回调语法:

const users = await db.query.users.findMany({
	where: {
		id: 1
	}
});
select * from users where id = 1

查找 id=1 的帖子,以及在特定日期之前创建的评论:

await db.query.posts.findMany({
  where: {
    id: 1,
  },
  with: {
    comments: {
      where: {
        createdAt: { lt: new Date() },
      },
    },
  },
});

所有筛选运算符列表

where: {
    OR: [],
    AND: [],
    NOT: {},
    RAW: (table) => sql`${table.id} = 1`,

    // 按关系筛选
    [relation]: {},

	  // 按列筛选
    [column]: {
      OR: [],
      AND: [],
      NOT: {},
      eq: 1,
      ne: 1,
      gt: 1,
      gte: 1,
      lt: 1,
      lte: 1,
      in: [1],
      notIn: [1],
      like: "",
      notLike: "",
      isNull: true,
      isNotNull: true,
    },
},

示例

简单相等
使用 AND
使用 OR
使用 NOT
使用 RAW 的复杂示例
const response = db.query.users.findMany({
  where: {
    age: 15,
  },
});
select `users`.`id` as `id`, `users`.`name` as `name`
from `users` 
where (`users`.`age` = 15)

关系筛选

使用 Drizzle Relations,你不仅可以按正在查询的表进行筛选,还可以按查询中包含的任意表进行筛选。

示例: 获取所有 ID>10 且至少有一篇内容以 “M” 开头的帖子用户 users

const usersWithPosts = await db.query.usersTable.findMany({
  where: {
    id: {
      gt: 10
    },
    posts: {
      content: {
        like: 'M%'
      }
    }
  },
});

示例: 获取所有带有帖子 postsusers,仅当用户至少有 1 篇帖子时

const response = db.query.users.findMany({
  with: {
    posts: true,
  },
  where: {
    posts: true,
  },
});

Limit & Offset

Drizzle ORM 为查询以及嵌套实体提供了 limitoffset API。

查找 5 篇文章:

await db.query.posts.findMany({
	limit: 5,
});

查找文章并最多获取 3 条评论:

await db.query.posts.findMany({
	with: {
		comments: {
			limit: 3,
		},
	},
});
IMPORTANT

offset 现在也可以在 with 表中使用!

await db.query.posts.findMany({
	limit: 5,
	offset: 2, // 正确 ✅
	with: {
		comments: {
			offset: 3, // 正确 ✅
			limit: 3,
		},
	},
});

查找带有评论的文章,第 5 篇到第 10 篇文章:

await db.query.posts.findMany({
	with: {
		comments: true,
	},
  limit: 5,
  offset: 5,
});

排序

Drizzle 为关系型查询构建器提供了排序 API。

你可以使用相同的排序 核心 API,也可以在回调中直接使用
order by 操作符,无需导入。

重要

当你在同一张表上使用多个 orderBy 语句时,它们会按照你添加它们的相同顺序包含在查询中

await db.query.posts.findMany({
  orderBy: {
    id: "asc",
  },
});

asc + desc 排序:

  await db.query.posts.findMany({
    orderBy: { id: "asc" },
    with: {
      comments: {
        orderBy: { id: "desc" },
      },
    },
  });

你也可以在 order by 语句中使用自定义 sql

await db.query.posts.findMany({
  orderBy: (t) => sql`${t.id} asc`,
  with: {
    comments: {
      orderBy: (t, { desc }) => desc(t.id),
    },
  },
});

包含自定义字段

关系查询 API 允许你添加额外的自定义字段。 当你需要检索数据并对其应用额外函数时,这会非常有用。

IMPORTANT

截至目前,extras 中不支持聚合,请使用 core queries 来实现。

import { sql } from 'drizzle-orm';

await db.query.users.findMany({
	extras: {
		loweredName: sql`lower(${users.name})`,
	},
})
await db.query.users.findMany({
	extras: {
		loweredName: (users, { sql }) => sql`lower(${users.name})`,
	},
})

lowerName 作为键将被包含在返回对象的所有字段中。

IMPORTANT

如果你为任何 extras 字段指定 .as("<alias>") - drizzle 将会忽略它

要检索所有带有分组的用户,并包含 fullName 字段(它是 firstName 和 lastName 的拼接), 你可以使用 Drizzle 关系查询构建器执行以下查询。

const res = await db.query.users.findMany({
	extras: {
		fullName: (users, { sql }) => sql<string>`concat(${users.name}, " ", ${users.name})`,
	},
	with: {
		usersToGroups: {
			with: {
				group: true,
			},
		},
	},
});
// 结果类型
const res: {
	id: number;
	name: string;
	verified: boolean;
	invitedBy: number | null;
	fullName: string;
	usersToGroups: {
			group: {
					id: number;
					name: string;
					description: string | null;
			};
	}[];
}[];

要检索所有带有评论的帖子,并添加一个额外字段来计算帖子内容的大小以及每条评论内容的大小:

const res = await db.query.posts.findMany({
	extras: {
		contentLength: (table, { sql }) => sql<number>`length(${table.content})`,
	},
	with: {
		comments: {
			extras: {
				commentSize: (table, { sql }) => sql<number>`length(${table.content})`,
			},
		},
	},
});
// 结果类型
const res: {
	id: number;
	createdAt: Date;
	content: string;
	authorId: number | null;
	contentLength: number;
	comments: {
			id: number;
			createdAt: Date;
			content: string;
			creator: number | null;
			postId: number | null;
			commentSize: number;
	}[];
};

包含子查询

你也可以在关系查询中使用子查询,以利用自定义 SQL 语法的强大功能

获取包含帖子及每个用户帖子总数的用户

import { posts } from './schema';
import { eq } from 'drizzle-orm';

await db.query.users.findMany({
  with: {
    posts: true
  },
  extras: {
    totalPostsCount: (table) => db.$count(posts, eq(posts.authorId, table.id)),
  }
});
select `d0`.`id` as `id`, `d0`.`name` as `name`,
((select coalesce(json_arrayagg(json_object('id', `d1`.`id`, 'content', `d1`.`content`, 'authorId', `d1`.`author_id`)), json_array())
  from `posts` as `d1` where `d0`.`id` = `d1`.`author_id`)) as `posts`,
((select count(*) from `posts` where `posts`.`author_id` = `d0`.`id`)) as `totalPostsCount`
from `users` as `d0`

预处理语句

预处理语句旨在大幅提升查询性能——请看这里。

在本节中,你可以学习如何定义占位符,并使用 Drizzle 关系型查询构建器执行预处理语句。