DrizzleORM v0.29.0 发布
Nov 9, 2023

Drizzle ORM 0.29.0 版本要求 Drizzle Kit 的最低版本为 0.20.0,反之亦然。因此,升级到 Drizzle ORM 的较新版本时,你还需要升级 Drizzle Kit。这可能会导致不同版本之间出现一些重大变更,尤其是在你需要升级 Drizzle Kit 并且你的 Drizzle ORM 版本早于 <0.28.0 的情况下。

新功能

🎉 用于 bigint 的 MySQL unsigned 选项

你现在可以指定 bigint unsigned 类型了

const table = mysqlTable('table', {
  id: bigint('id', { mode: 'number', unsigned: true }),
});

docs 中阅读更多内容

🎉 改进了查询构建器类型

默认情况下,从 0.29.0 开始,由于 Drizzle 中的所有查询构建器都尽可能遵循 SQL,因此大多数方法只能调用一次。例如,在 SELECT 语句中可能只有一个 WHERE 子句,因此你只能调用 .where() 一次:

const query = db
  .select()
  .from(users)
  .where(eq(users.id, 1))
  .where(eq(users.name, 'John')); // ❌ Type error - where() can only be invoked once

此行为对于常规查询构建非常有用,例如,当你一次创建整个查询时。但是,当你想要动态构建查询时,例如,如果你有一个共享函数,它接受查询构建器并对其进行增强,就会出现问题。为了解决这个问题,Drizzle 为查询构建器提供了一种特殊的 ‘dynamic’ 模式,它消除了只能调用一次方法的限制。要启用它,你需要在查询构建器上调用 .$dynamic()。

让我们通过实现一个简单的 withPagination 函数来了解它的工作原理,该函数根据提供的页码和可选的页面大小,将 LIMIT 和 OFFSET 子句添加到查询中:

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

const query = db.select().from(users).where(eq(users.id, 1));
withPagination(query, 1); // ❌ Type error - the query builder is not in dynamic mode

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

请注意,withPagination 函数也是通用函数,它允许你修改其中查询构建器的结果类型,例如通过添加连接:

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);

docs 中阅读更多内容

🎉 可以指定主键和外键的名称

当约束名称超过数据库的 64 个字符限制时,会出现问题。这会导致数据库引擎截断名称,从而可能导致问题。从 0.29.0 开始,你可以选择为 primaryKey()foreignKey() 指定自定义名称。我们还弃用了旧的 primaryKey() 语法,该语法仍然可以使用,但将在未来版本中移除。

const table = pgTable('table', {
  id: integer('id'),
  name: text('name'),
}, (table) => ({
  cpk: primaryKey({ name: 'composite_key', columns: [table.id, table.name] }),
  cfk: foreignKey({
    name: 'fkName',
    columns: [table.id],
    foreignColumns: [table.name],
  }),
}));

docs 中阅读更多内容

🎉 只读副本支持

你现在可以使用 Drizzle withReplica 函数来指定不同的数据库。用于读取副本的连接以及用于写入操作的主实例的连接。默认情况下,withReplicas 将使用随机读取副本执行读取操作,并使用主实例执行所有其他数据修改操作。你还可以指定自定义逻辑来选择要使用的只读副本连接。你可以自由地为此做出任何加权的自定义决策。以下是一些使用示例:

const primaryDb = drizzle({ client });
const read1 = drizzle({ client });
const read2 = drizzle({ client });

const db = withReplicas(primaryDb, [read1, read2]);

// read from primary
db.$primary.select().from(usersTable);

// read from either read1 connection or read2 connection
db.select().from(usersTable)

// use primary database for delete operation
db.delete(usersTable).where(eq(usersTable.id, 1))

用于选择只读副本的自定义逻辑的实现示例,其中第一个副本被选中的概率为 70%,第二个副本被选中的概率为 30%。请注意,你可以为只读副本实现任何类型的随机选择。

const db = withReplicas(primaryDb, [read1, read2], (replicas) => {
    const weight = [0.7, 0.3];
    let cumulativeProbability = 0;
    const rand = Math.random();

    for (const [i, replica] of replicas.entries()) {
      cumulativeProbability += weight[i]!;
      if (rand < cumulativeProbability) return replica;
    }
    return replicas[0]!
});

withReplicas 函数适用于 Drizzle ORM 中的所有方言

docs 中阅读更多内容

🎉 集合运算符支持 (UNION、UNION ALL、INTERSECT、INTERSECT ALL、EXCEPT、EXCEPT ALL)

非常感谢 @Angelelz 做出的重大贡献,从 API 讨论到正确的类型检查和运行时逻辑,以及大量的测试。这极大地帮助我们在此版本中实现此功能。

使用示例:所有集合运算符都可以通过两种方式使用:import approachbuilder approach

// Import approach
import { union } from 'drizzle-orm/pg-core'

const allUsersQuery = db.select().from(users);
const allCustomersQuery = db.select().from(customers);

const result = await union(allUsersQuery, allCustomersQuery)
// Builder approach
const result = await db.select().from(users).union(db.select().from(customers));

docs 中阅读更多内容

🎉 新的 MySQL 代理驱动程序

我们发布了一个新的驱动程序,允许你使用 MySQL 数据库创建自己的 HTTP 驱动程序实现。你可以在 ./examples/mysql-proxy 文件夹中找到使用示例。

你需要在服务器上实现两个用于查询和迁移的端点(迁移端点是可选的,仅当你要使用 Drizzle 迁移时才需要)。服务器和驱动程序的实现都由你决定,因此你不会受到任何限制。你可以添加自定义映射、日志记录等等。

你可以在 ./examples/mysql-proxy 文件夹中找到服务器和驱动程序的实现示例。

// Driver
import axios from 'axios';
import { eq } from 'drizzle-orm/expressions';
import { drizzle } from 'drizzle-orm/mysql-proxy';
import { migrate } from 'drizzle-orm/mysql-proxy/migrator';
import { cities, users } from './schema';

async function main() {
  const db = drizzle(async (sql, params, method) => {
    try {
      const rows = await axios.post(`${process.env.REMOTE_DRIVER}/query`, {
        sql,
        params,
        method,
      });

      return { rows: rows.data };
    } catch (e: any) {
      console.error('Error from pg proxy server:', e.response.data);
      return { rows: [] };
    }
  });

  await migrate(db, async (queries) => {
    try {
      await axios.post(`${process.env.REMOTE_DRIVER}/migrate`, { queries });
    } catch (e) {
      console.log(e);
      throw new Error('Proxy server cannot run migrations');
    }
  }, { migrationsFolder: 'drizzle' });

  await db.insert(cities).values({ id: 1, name: 'name' });

  await db.insert(users).values({
    id: 1,
    name: 'name',
    email: 'email',
    cityId: 1,
  });

  const usersToCityResponse = await db.select().from(users).leftJoin(
    cities,
    eq(users.cityId, cities.id),
  );
}

docs 中阅读更多内容

🎉 新的 PostgreSQL 代理驱动程序

与 MySQL 相同,你现在可以为 PostgreSQL 数据库实现自己的 http 驱动程序。你可以在 ./examples/pg-proxy 文件夹中找到使用示例。

你需要在服务器上实现两个用于查询和迁移的端点(迁移端点是可选的,仅当你想使用 Drizzle 迁移时才需要)。服务器和驱动程序的实现都由你决定,因此你不会受到任何限制。你可以添加自定义映射、日志记录等等。

你可以在 ./examples/pg-proxy 文件夹中找到服务器和驱动程序的实现示例。

import axios from 'axios';
import { eq } from 'drizzle-orm/expressions';
import { drizzle } from 'drizzle-orm/pg-proxy';
import { migrate } from 'drizzle-orm/pg-proxy/migrator';
import { cities, users } from './schema';

async function main() {
  const db = drizzle(async (sql, params, method) => {
    try {
      const rows = await axios.post(`${process.env.REMOTE_DRIVER}/query`, { sql, params, method });

      return { rows: rows.data };
    } catch (e: any) {
      console.error('Error from pg proxy server:', e.response.data);
      return { rows: [] };
    }
  });

  await migrate(db, async (queries) => {
    try {
      await axios.post(`${process.env.REMOTE_DRIVER}/query`, { queries });
    } catch (e) {
      console.log(e);
      throw new Error('Proxy server cannot run migrations');
    }
  }, { migrationsFolder: 'drizzle' });

  const insertedCity = await db.insert(cities).values({ id: 1, name: 'name' }).returning();
  const insertedUser = await db.insert(users).values({ id: 1, name: 'name', email: 'email', cityId: 1 });
  const usersToCityResponse = await db.select().from(users).leftJoin(cities, eq(users.cityId, cities.id));
}

docs 中阅读更多内容

🎉 D1 批处理 API 支持

参考:https://developers.cloudflare.com/d1/platform/client-api/#dbbatch

批处理 API 使用示例:

const batchResponse = await db.batch([
  db.insert(usersTable).values({ id: 1, name: 'John' }).returning({
    id: usersTable.id,
  }),
  db.update(usersTable).set({ name: 'Dan' }).where(eq(usersTable.id, 1)),
  db.query.usersTable.findMany({}),
  db.select().from(usersTable).where(eq(usersTable.id, 1)),
  db.select({ id: usersTable.id, invitedBy: usersTable.invitedBy }).from(
    usersTable,
  ),
]);
type BatchResponse = [
  {
    id: number;
  }[],
  D1Result,
  {
    id: number;
    name: string;
    verified: number;
    invitedBy: number | null;
  }[],
  {
    id: number;
    name: string;
    verified: number;
    invitedBy: number | null;
  }[],
  {
    id: number;
    invitedBy: number | null;
  }[],
];

所有可在 db.batch 中使用的构建器:

`db.all()`,
`db.get()`,
`db.values()`,
`db.run()`,
`db.query.<table>.findMany()`,
`db.query.<table>.findFirst()`,
`db.select()...`,
`db.update()...`,
`db.delete()...`,
`db.insert()...`,

更多使用示例:integration-tests/tests/d1-batch.test.tsdocs


Drizzle Kit 0.20.0

  1. 使用 defineConfig 函数定义 drizzle.config 的新方法
  2. 可以使用 wrangler.toml 文件通过 Drizzle Studio 访问 Cloudflare D1。
  3. Drizzle Studio 正在迁移到 https://local.drizzle.studio/
  4. bigint unsigned 支持
  5. primaryKeysforeignKeys 现在可以有自定义名称。
  6. 环境变量现在会自动获取
  7. 一些错误修复和改进

你可以阅读更多关于 drizzle-kit 更新的内容 此处