Neon 是一个完全托管的无服务器 Postgres。Neon 分离了计算和存储,提供了自动扩展、分支、无底存储等现代开发人员功能。
通过创建一个项目目录,使用 bun init 初始化目录,并将 Neon serverless driver 添加为项目依赖项来开始。
mkdir bun-neon-postgrescd bun-neon-postgresbun init -ybun add @neondatabase/serverless创建一个 .env.local 文件,并将你的 Neon Postgres 连接字符串 添加到其中。
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.net.cn/docs/runtime/env 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 版本将打印到控制台。
bun ./index.tsPostgreSQL 16.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit此示例使用了 Neon serverless driver 的 SQL-over-HTTP 功能。Neon 的 serverless driver 还公开了 Client 和 Pool 构造函数,以支持会话、交互式事务和 node-postgres 兼容性。
有关 serverless driver 的完整概述,请参阅 Neon 的文档。