动态查询构建

默认情况下,由于 Drizzle 中的所有查询构建器都尽量符合 SQL 规范,你只能对大多数方法调用一次。
例如,在 SELECT 语句中可能只有一个 WHERE 子句,因此你只能调用一次 .where()

const query = db
	.select()
	.from(users)
	.where(eq(users.id, 1))
	.where(eq(users.name, 'John')); // ❌ 类型错误 - where() 只能被调用一次

在之前的 ORM 版本中,由于没有实现这种限制,这个特定示例常常让许多用户感到困惑,因为他们期望查询构建器会将多次 .where() 调用“合并”为一个条件。

这种行为对于常规的查询构建是有用的,也就是当你一次性创建整个查询时。
然而,当你想要动态构建查询时,这就成了一个问题,也就是当你有一个共享函数接收查询构建器并对其进行增强时。
为了解决这个问题,Drizzle 为查询构建器提供了一种特殊的“动态”模式,它移除了方法只能调用一次的限制。
要启用它,你需要在查询构建器上调用 .$dynamic()

让我们通过实现一个简单的 withPagination 函数来看看它是如何工作的。这个函数会根据提供的页码和可选的页面大小,为查询添加 LIMITOFFSET 子句:

function withPagination<T extends PgSelect>(
	qb: T,
	page: number = 1,
	pageSize: number = 10,
) {
	return qb.limit(pageSize).offset((page - 1) * pageSize);
}

const query = db.select().from(users).where(eq(users.id, 1));
withPagination(query, 1); // ❌ 类型错误 - 查询构建器不处于动态模式

const dynamicQuery = query.$dynamic();
withPagination(dynamicQuery, 1); // ✅ 正确

请注意,withPagination 函数是泛型的,这使你可以修改其中查询构建器的结果类型,例如通过添加一个 join:

function withFriends<T extends PgSelect>(qb: T) {
	return qb.leftJoin(friends, eq(friends.userId, users.id));
}

let query = db.select().from(users).where(eq(users.id, 1)).$dynamic();
query = withFriends(query);

这是可行的,因为 PgSelect 和其他类似类型是专门为动态查询构建而设计的。它们只能在动态模式下使用。

以下是可在动态查询构建中作为泛型参数使用的所有类型列表:

DialectType
QuerySelectInsertUpdateDelete
PostgresPgSelectPgInsertPgUpdatePgDelete
PgSelectQueryBuilder
MySQLMySqlSelectMySqlInsertMySqlUpdateMySqlDelete
MySqlSelectQueryBuilder
SQLiteSQLiteSelectSQLiteInsertSQLiteUpdateSQLiteDelete
SQLiteSelectQueryBuilder

...QueryBuilder 类型用于 独立查询构建器实例。DB 查询构建器是它们的子类,因此你也可以将它们一起使用。

	import { QueryBuilder } from 'drizzle-orm/pg-core';

	function withFriends<T extends PgSelectQueryBuilder>(qb: T) {
		return qb.leftJoin(friends, eq(friends.userId, users.id));
	}

	const qb = new QueryBuilder();
	let query = qb.select().from(users).where(eq(users.id, 1)).$dynamic();
	query = withFriends(query);