Drizzle <> Supabase

This guide assumes familiarity with:

根据 官方网站,Supabase 是一个开源的 Firebase 替代方案,用于以最低配置构建安全、高性能的 Postgres 后端。

查看官方 Supabase + Drizzle 文档。

步骤 1 - 安装软件包

npm
yarn
pnpm
bun
npm i drizzle-orm postgres -D drizzle-kit

步骤 2 - 初始化驱动程序并进行查询

index.ts
import { drizzle } from 'drizzle-orm/postgres-js'

const db = drizzle(process.env.DATABASE_URL);

const allUsers = await db.select().from(...);

如果你需要提供现有的驱动程序:

index.ts
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'

const client = postgres(process.env.DATABASE_URL)
const db = drizzle({ client });

const allUsers = await db.select().from(...);

如果你决定通过 Supabase 使用连接池(详见 此处),并启用了 “事务” 池模式,请确保关闭准备功能,因为不支持预处理语句。

index.ts
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'

// Disable prefetch as it is not supported for "Transaction" pool mode 
const client = postgres(process.env.DATABASE_URL, { prepare: false })
const db = drizzle({ client });

const allUsers = await db.select().from(...);

对于无服务器环境,使用连接池连接到数据库;对于长时间运行的服务器,使用直接连接连接到数据库。

下一步是什么?