Skip to content

NOTE

**注意** — 目前 Prisma 需要安裝 Node.js 才能運行某些生成代碼。確保在你運行 `bunx prisma` 命令的環境中 安裝了 Node.js。

創建新項目

首先,創建一個目錄並使用 bun init 初始化它。

bash
mkdir prisma-postgres-app
cd prisma-postgres-app
bun init

安裝 Prisma 依賴

然後安裝 Prisma CLI(prisma)、Prisma Client(@prisma/client)和 accelerate 擴展作為依賴。

bash
bun add -d prisma
bun add @prisma/client @prisma/extension-accelerate

使用 PostgreSQL 初始化 Prisma

我們將使用 bunx 運行 Prisma CLI 來初始化我們的模式和遷移目錄。我們將使用 PostgreSQL 作為數據庫。

bash
bunx --bun prisma init --db

這將創建一個基本模式。我們需要更新它以使用帶有 Bun 優化的新無 Rust 客戶端。打開 prisma/schema.prisma 並修改 generator 塊,然後添加一個簡單的 User 模型。

prisma
generator client {
	provider = "prisma-client"
	output = "./generated"
	engineType = "client"
	runtime = "bun"
}

datasource db {
	provider = "postgresql"
	url      = env("DATABASE_URL")
}

model User { 
	id    Int     @id @default(autoincrement()) 
	email String  @unique
	name  String?
} 

配置數據庫連接

.env 文件中設置你的 Postgres 數據庫 URL。

ini
DATABASE_URL="postgresql://username:password@localhost:5432/mydb?schema=public"

創建並運行數據庫遷移

然後生成並運行初始遷移。

這將在 prisma/migrations 中生成一個 .sql 遷移文件,並針對你的 Postgres 數據庫執行遷移。

bash
bunx --bun prisma migrate dev --name init
txt
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "mydb", schema "public" at "localhost:5432"

Applying migration `20250114141233_init`

The following migration(s) have been created and applied from new schema changes:

prisma/migrations/
  └─ 20250114141233_init/
    └─ migration.sql

Your database is now in sync with your schema.

✔ Generated Prisma Client (6.17.1) to ./generated in 18ms

生成 Prisma Client

如輸出所示,每當我們執行新遷移時,Prisma 會重新生成我們的 Prisma client。該客戶端提供了一個完全類型化的 API 用於從數據庫讀寫數據。你可以使用 Prisma CLI 手動重新生成客戶端。

sh
bunx --bun prisma generate

使用 Accelerate 初始化 Prisma Client

現在我們需要創建一個 Prisma 客戶端實例。創建一個新文件 prisma/db.ts 來使用 Postgres 適配器初始化 PrismaClient。

ts
import { PrismaClient } from "./generated/client";
import { withAccelerate } from '@prisma/extension-accelerate'

export const prisma = new PrismaClient().$extends(withAccelerate())

創建測試腳本

讓我們編寫一個簡單的腳本來創建一個新用戶,然後統計數據庫中的用戶數量。

ts
import { prisma } from "./prisma/db";

// 創建一個新用戶
await prisma.user.create({
  data: {
    name: "John Dough",
    email: `john-${Math.random()}@example.com`,
  },
});

// 統計用戶數量
const count = await prisma.user.count();
console.log(`There are ${count} users in the database.`);

運行和測試應用

讓我們使用 bun run 運行此腳本。每次運行它時,都會創建一個新用戶。

bash
bun run index.ts
txt
There are 1 users in the database.
bash
bun run index.ts
txt
There are 2 users in the database.
bash
bun run index.ts
txt
There are 3 users in the database.

就是這樣!現在你已經使用 Bun 設置了 Prisma Postgres,我們建議在繼續開發應用時參考 官方 Prisma Postgres 文檔

Bun學習網由www.bunjs.com.cn整理維護