只读副本

当你的项目涉及一组只读副本实例,并且你需要一种便捷的方法来管理从只读副本执行的 SELECT 查询,以及在主实例上执行创建、删除和更新操作时,你可以利用 Drizzle 中的 withReplicas() 函数。

PostgreSQL
MySQL
SQLite
SingleStore
import { sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { boolean, jsonb, pgTable, serial, text, timestamp, withReplicas } from 'drizzle-orm/pg-core';

const usersTable = pgTable('users', {
	id: serial('id' as string).primaryKey(),
	name: text('name').notNull(),
	verified: boolean('verified').notNull().default(false),
	jsonb: jsonb('jsonb').$type<string[]>(),
	createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});

const primaryDb = drizzle("postgres://user:password@host:port/primary_db");
const read1 = drizzle("postgres://user:password@host:port/read_replica_1");
const read2 = drizzle("postgres://user:password@host:port/read_replica_2");

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

你现在可以像以前一样使用 db 实例。Drizzle 将自动处理只读副本和主实例之间的选择。

// Read from either the read1 connection or the read2 connection
await db.select().from(usersTable)

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

你可以使用 $primary 键强制使用主实例,即使对于读取操作也是如此。

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

使用 Drizzle,你还可以指定用于选择只读副本的自定义逻辑。你可以对随机读取副本的选择进行加权决策或任何其他自定义选择方法。以下是用于选择只读副本的自定义逻辑的实现示例,其中第一个副本被选中的概率为 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]!
});

await db.select().from(usersTable)