Neon 是一个完全托管的无服务器 Postgres。Neon 将计算和存储分离,提供自动扩展、分支、无限存储等现代开发者功能。
首先创建一个项目目录,使用 bun init 初始化目录,然后将 Neon 无服务器驱动 添加为项目依赖。
sh
mkdir bun-neon-postgres
cd bun-neon-postgres
bun init -y
bun add @neondatabase/serverless创建一个 .env.local 文件并添加你的 Neon Postgres 连接字符串。
ini
DATABASE_URL=postgresql://usertitle:password@ep-adj-noun-guid.us-east-1.aws.neon.tech/neondb?sslmode=require将以下代码粘贴到项目的 index.ts 文件中。
ts
import { neon } from "@neondatabase/serverless";
// Bun 会自动从 .env.local 加载 DATABASE_URL
// 请参阅:https://bun.com/docs/runtime/environment-variables 获取更多信息
const sql = neon(process.env.DATABASE_URL);
const rows = await sql`SELECT version()`;
console.log(rows[0].version);使用 bun ./index.ts 启动程序。Postgres 版本应该会打印到控制台。
sh
bun ./index.tstxt
PostgreSQL 16.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit本示例使用了 Neon 无服务器驱动的 SQL-over-HTTP 功能。Neon 的无服务器驱动还提供了 Client 和 Pool 构造函数,以支持会话、交互式事务和 node-postgres 兼容性。
请参阅 Neon 文档 获取无服务器驱动的完整概述。