使用 Neon 的无服务器 Postgres 结合 Bun
Neon 是一个完全托管的无服务器 Postgres。Neon 将计算和存储分离,以提供自动扩缩容、分支和无限存储等功能。
开始步骤:创建一个项目目录,使用 bun init 初始化该目录,并添加 Neon 无服务器驱动 作为项目依赖。
terminal
mkdir bun-neon-postgres
cd bun-neon-postgres
bun init -y
bun add @neondatabase/serverless
创建一个 .env.local 文件,并将你的 Neon Postgres 连接字符串 添加到其中。
.env.local
DATABASE_URL=postgresql://username:password@ep-adj-noun-guid.us-east-1.aws.neon.tech/neondb?sslmode=require
将以下代码粘贴到你项目的 index.ts 文件中。
import { neon } from "@neondatabase/serverless";
// Bun automatically loads the DATABASE_URL from .env.local
// Refer to: https://bun.sh/docs/runtime/environment-variables for more information
const sql = neon(process.env.DATABASE_URL!);
const rows = await sql`SELECT version()`;
console.log(rows[0]?.version);
使用 bun ./index.ts 启动程序。它会将 Postgres 版本输出到控制台。
terminal
bun ./index.ts
Text
PostgreSQL 16.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
此示例使用了 Neon 无服务器驱动的基于 HTTP 的 SQL 功能。Neon 的无服务器驱动还提供了 Client 和 Pool 构造函数,用于支持会话、交互式事务以及兼容 node-postgres。
请参阅 Neon 的文档,了解无服务器驱动的完整概览。