Bun

指南生態系統

使用 Prisma 搭配 Bun

注意 — 目前 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

我們將使用 bunx 搭配 Prisma CLI 來初始化我們的架構和遷移目錄。為簡化起見,我們將使用內建式 SQLite 資料庫。

bunx prisma init --datasource-provider sqlite

開啟 prisma/schema.prisma 並新增一個簡單的 User 模型。

prisma/schema.prisma
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?
}

然後產生並執行初始遷移。

這將在 prisma/migrations 中產生一個 .sql 遷移檔案,建立一個新的 SQLite 實例,並針對新的實例執行遷移。

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

如同輸出中所指示,Prisma 會在我們執行新的遷移時重新產生我們的 Prisma client。此 client 提供一個完全輸入的 API,用於從我們的資料庫中讀取和寫入。您可以使用 Prisma CLI 手動重新產生 client。

bunx prisma generate

我們可以從 @prisma/client 匯入產生的 client。

src/index.ts
import {PrismaClient} from "@prisma/client";

讓我們撰寫一個簡單的腳本來建立一個新使用者,然後計算資料庫中的使用者數量。

index.ts
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 文件