注意 — 目前 Prisma 需要安裝 Node.js 才能執行某些生成程式碼。請確保在您執行 bunx prisma
命令的環境中已安裝 Node.js。
Prisma 與 Bun 開箱即用。首先,建立一個目錄並使用 bun init
初始化它。
mkdir prisma-app
cd prisma-app
bun init
然後安裝 Prisma CLI (prisma
) 和 Prisma Client (@prisma/client
) 作為依賴項。
bun add -d prisma
bun add @prisma/client
我們將使用 Prisma CLI 與 bunx
來初始化我們的 schema 和 migration 目錄。為了簡化,我們將使用記憶體中的 SQLite 資料庫。
bunx prisma init --datasource-provider sqlite
開啟 prisma/schema.prisma
並新增一個簡單的 User
模型。
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
然後生成並執行初始 migration。
這將在 prisma/migrations
中生成一個 .sql
migration 檔案,建立一個新的 SQLite 實例,並針對新實例執行 migration。
bunx prisma migrate dev --name init
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": SQLite database "dev.db" at "file:./dev.db"
SQLite database dev.db created at file:./dev.db
Applying migration `20230928182242_init`
The following migration(s) have been created and applied from new schema changes:
migrations/
└─ 20230928182242_init/
└─ migration.sql
Your database is now in sync with your schema.
✔ Generated Prisma Client (v5.3.1) to ./node_modules/@prisma/client in 41ms
如輸出所示,每當我們執行新的 migration 時,Prisma 都會重新生成我們的 *Prisma client*。該 client 提供了一個完全類型化的 API,用於從我們的資料庫讀取和寫入。您可以使用 Prisma CLI 手動重新生成 client。
bunx prisma generate
我們可以從 @prisma/client
導入生成的 client。
import {PrismaClient} from "@prisma/client";
讓我們編寫一個簡單的腳本來建立一個新使用者,然後計算資料庫中使用者數量。
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
// create a new user
await prisma.user.create({
data: {
name: "John Dough",
email: `john-${Math.random()}@example.com`,
},
});
// count the number of users
const count = await prisma.user.count();
console.log(`There are ${count} users in the database.`);
讓我們使用 bun run
執行此腳本。每次我們執行它,都會建立一個新使用者。
bun run index.ts
Created john-0.12802932895402364@example.com
There are 1 users in the database.
bun run index.ts
Created john-0.8671308799782803@example.com
There are 2 users in the database.
bun run index.ts
Created john-0.4465968383115295@example.com
There are 3 users in the database.
就是這樣!現在您已經使用 Bun 設定了 Prisma,我們建議您在繼續開發應用程式時參考 官方 Prisma 文件。