Neon 是一個完全託管的無伺服器 Postgres,分離運算和儲存,以提供諸如自動擴展、分支和無限儲存等功能。Neon 可以直接從 Bun 使用 @neondatabase/serverless
驅動程式或透過像 Drizzle
這樣的 ORM 來使用。
Drizzle ORM 支援類似 SQL 的「查詢建構器」API 和類似 ORM 的 Queries API。首先建立一個專案目錄,使用 bun init
初始化目錄,並安裝 Drizzle 和 Neon 無伺服器驅動程式。
mkdir bun-drizzle-neon
cd bun-drizzle-neon
bun init -y
bun add drizzle-orm @neondatabase/serverless
bun add -D drizzle-kit
建立一個 .env.local
檔案,並將您的 Neon Postgres 連接字串新增到其中。
DATABASE_URL=postgresql://username:password@ep-adj-noun-guid.us-east-1.aws.neon.tech/neondb?sslmode=require
我們將使用 Neon 無伺服器驅動程式連接到 Neon 資料庫,並將其封裝在 Drizzle 資料庫實例中。
import { neon } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-http';
// Bun automatically loads the DATABASE_URL from .env.local
// Refer to: https://bun.dev.org.tw/docs/runtime/env for more information
const sql = neon(process.env.DATABASE_URL!);
export const db = drizzle(sql);
要查看資料庫的運作情況,請將這些行新增到 index.ts
。
import { db } from "./db";
import { sql } from "drizzle-orm";
const query = sql`select 'hello world' as text`;
const result = await db.execute(query);
console.log(result.rows);
然後使用 Bun 執行 index.ts
。
bun run index.ts
[
{
text: "hello world",
}
]
我們可以使用 Drizzle ORM 原語為我們的資料庫定義結構描述。建立一個 schema.ts
檔案並新增此程式碼。
import { pgTable, integer, serial, text, timestamp } from "drizzle-orm/pg-core";
export const authors = pgTable("authors", {
id: serial("id").primaryKey(),
name: text("name").notNull(),
bio: text("bio"),
createdAt: timestamp("created_at").notNull().defaultNow(),
});
然後我們使用 drizzle-kit
CLI 來產生初始 SQL 遷移。
bunx drizzle-kit generate --dialect postgresql --schema ./schema.ts --out ./drizzle
這會建立一個新的 drizzle
目錄,其中包含 .sql
遷移檔案和 meta
目錄。
drizzle
├── 0000_aspiring_post.sql
└── meta
├── 0000_snapshot.json
└── _journal.json
我們可以使用一個簡單的 migrate.ts
腳本來執行這些遷移。此腳本會建立一個到 Neon 資料庫的新連線,並執行 drizzle
目錄中所有未執行的遷移。
import { db } from './db';
import { migrate } from "drizzle-orm/neon-http/migrator";
const main = async () => {
try {
await migrate(db, { migrationsFolder: "drizzle" });
console.log("Migration completed");
} catch (error) {
console.error("Error during migration:", error);
process.exit(1);
}
};
main();
我們可以使用 bun
執行此腳本來執行遷移。
bun run migrate.ts
Migration completed
我們現在可以將一些資料新增到我們的資料庫。建立一個包含以下內容的 seed.ts
檔案。
import { db } from "./db";
import * as schema from "./schema";
async function seed() {
await db.insert(schema.authors).values([
{
name: "J.R.R. Tolkien",
bio: "The creator of Middle-earth and author of The Lord of the Rings.",
},
{
name: "George R.R. Martin",
bio: "The author of the epic fantasy series A Song of Ice and Fire.",
},
{
name: "J.K. Rowling",
bio: "The creator of the Harry Potter series.",
},
]);
}
async function main() {
try {
await seed();
console.log("Seeding completed");
} catch (error) {
console.error("Error during seeding:", error);
process.exit(1);
}
}
main();
然後執行此檔案。
bun run seed.ts
Seeding completed
我們現在有一個具有結構描述和範例資料的資料庫。我們可以使用 Drizzle 來查詢它。將 index.ts
的內容替換為以下內容。
import * as schema from "./schema";
import { db } from "./db";
const result = await db.select().from(schema.authors);
console.log(result);
然後執行該檔案。您應該會看到我們插入的三位作者。
bun run index.ts
[
{
id: 1,
name: "J.R.R. Tolkien",
bio: "The creator of Middle-earth and author of The Lord of the Rings.",
createdAt: 2024-05-11T10:28:46.029Z,
}, {
id: 2,
name: "George R.R. Martin",
bio: "The author of the epic fantasy series A Song of Ice and Fire.",
createdAt: 2024-05-11T10:28:46.029Z,
}, {
id: 3,
name: "J.K. Rowling",
bio: "The creator of the Harry Potter series.",
createdAt: 2024-05-11T10:28:46.029Z,
}
]
此範例使用了 Neon 無伺服器驅動程式的 SQL-over-HTTP 功能。Neon 的無伺服器驅動程式還公開了 Client
和 Pool
建構函式,以啟用會話、互動式交易和 node-postgres 相容性。有關完整概述,請參閱 Neon 的文件。
有關使用 Drizzle ORM 的更多文件,請參閱 Drizzle 網站。