查詢資料庫
使用 Prisma Client 撰寫您的第一個查詢
現在您已經產生了 Prisma Client,您可以開始撰寫查詢,以在資料庫中讀取和寫入資料。為了本指南的目的,您將使用一個純 TypeScript 腳本來探索 Prisma Client 的一些基本功能。
建立一個名為 queries.ts
的新檔案,並將以下程式碼新增至其中
// 1
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'
// 2
const prisma = new PrismaClient()
.$extends(withAccelerate())
// 3
async function main() {
// ... you will write your Prisma Client queries here
}
// 4
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
// 5
await prisma.$disconnect()
process.exit(1)
})
以下是程式碼片段不同部分的快速概述
- 匯入
PrismaClient
建構函式和withAccelerate
擴充功能。 - 實例化
PrismaClient
並新增 Accelerate 擴充功能。 - 定義一個名為
main
的async
函式,以將查詢傳送至資料庫。 - 呼叫
main
函式。 - 在腳本終止時關閉資料庫連線。
在 main
函式內,新增以下查詢以從資料庫讀取所有 User
記錄並記錄結果
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
現在使用以下命令執行程式碼
npx tsx queries.ts
這應該會印出一個空陣列,因為資料庫中還沒有 User
記錄
[]
將資料寫入資料庫
您在前一節中使用的 findMany
查詢僅讀取資料庫中的資料(儘管它仍然是空的)。
在本節中,您將學習如何撰寫查詢,以一次性寫入新的記錄到 Post
、User
和 Profile
表格中。
調整 main
函式,移除之前的程式碼並新增以下內容
async function main() {
await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Hello World' },
},
profile: {
create: { bio: 'I like turtles' },
},
},
})
const allUsers = await prisma.user.findMany({
include: {
posts: true,
profile: true,
},
})
console.dir(allUsers, { depth: null })
}
此程式碼使用巢狀寫入查詢建立新的 User
記錄,以及新的 Post
和 Profile
記錄。
這些記錄透過您在 Prisma schema 中定義的關聯欄位連接。
請注意,您也將 include
選項傳遞給 findMany
,這告訴 Prisma Client 在傳回的 User
物件上包含 posts
和 profile
關聯。
使用以下命令執行程式碼
npx tsx queries.ts
輸出應如下所示
[
{
email: 'alice@prisma.io',
id: 1,
name: 'Alice',
posts: [
{
content: null,
createdAt: 2020-03-21T16:45:01.246Z,
updatedAt: 2020-03-21T16:45:01.246Z,
id: 1,
published: false,
title: 'Hello World',
authorId: 1,
}
],
profile: {
bio: 'I like turtles',
id: 1,
userId: 1,
}
}
]
另請注意,由於 Prisma Client 產生的類型,allUsers
變數是靜態類型。您可以透過將滑鼠懸停在編輯器中的 allUsers
變數上來觀察類型。它應該被輸入為如下
const allUsers: ({
posts: {
id: number;
createdAt: Date;
updatedAt: Date;
title: string;
content: string | null;
published: boolean;
authorId: number;
}[];
profile: {
id: number;
bio: string | null;
userId: number;
} | null;
} & {
...;
})[]
展開以視覺化檢視已建立的記錄
查詢在 User
、Post
和 Profile
表格中新增了新記錄
User
id | name | |
---|---|---|
1 | "alice@prisma.io" | "Alice" |
Post
id | createdAt | updatedAt | title | content | published | authorId |
---|---|---|---|---|---|---|
1 | 2020-03-21T16:45:01.246Z | 2020-03-21T16:45:01.246Z | "Hello World" | null | false | 1 |
Profile
id | bio | userId |
---|---|---|
1 | "I like turtles" | 1 |
Post
上的 authorId
欄位和 Profile
上的 userId
欄位中的數字都參考 User
表格的 id
欄位,這表示 id
值 1
欄位因此參考資料庫中的第一個(也是唯一一個)User
記錄。
在繼續下一節之前,您將使用 update
查詢「發布」您剛建立的 Post
記錄。如下調整 main
函式
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}
現在使用與之前相同的命令執行程式碼
npx tsx queries.ts
您將看到以下輸出
{
id: 1,
title: 'Hello World',
content: null,
published: true,
authorId: 1
}
id
為 1
的 Post
記錄現在已在資料庫中更新
Post
id | title | content | published | authorId |
---|---|---|---|---|
1 | "Hello World" | null | true | 1 |
太棒了,您剛剛使用 Prisma Client 🚀 第一次將新資料寫入資料庫
接收資料庫中資料變更時的即時更新
由於 Prisma Postgres 預設隨附 Prisma Pulse,因此您可以輕鬆地將資料庫中發生的任何變更串流到您的應用程式中,只需使用您現有的 PrismaClient
實例即可。讓我們看看它是如何運作的!
首先,在您的專案中安裝 Pulse Client 擴充功能
npm install @prisma/extension-pulse
接下來,建立一個名為 realtime.ts
的新檔案,並將以下程式碼新增至其中
// 1
import { PrismaClient } from '@prisma/client';
import { withPulse } from '@prisma/extension-pulse';
// 2
const apiKey: string = process.env.PULSE_API_KEY ?? '';
if (!apiKey || apiKey === "") {
console.log(`Please set the \`PULSE_API_KEY\` environment variable in the \`.env\` file.`);
process.exit(1);
}
// 3
const prisma = new PrismaClient().$extends(
withPulse({ apiKey: apiKey })
);
async function main() {
// 4
const stream = await prisma.user.stream();
process.on('exit', () => {
stream.stop();
});
// 5
console.log(`Waiting for an event on the \`User\` table ... `);
for await (const event of stream) {
console.log('Received an event:', event);
}
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
這裡發生了很多事情,讓我們仔細看看
- 匯入
PrismaClient
建構函式和withPulse
擴充功能。 - 讀取
PULSE_API_KEY
環境變數(在.env
檔案中設定)。 - 實例化
PrismaClient
並新增 Pulse 擴充功能(使用 Pulse API 金鑰)。 - 建立一個串流以擷取
User
表格上的任何 寫入事件。 - 啟動一個異步迭代器,該迭代器等待新事件並將它們記錄到您的終端機。
使用以下命令啟動腳本
npx tsx realtime.ts
您應該會看到以下輸出
Waiting for an event on the `User` table ...
在同一個終端機中,您現在會在以下情況發生時看到新的輸出被記錄
- 建立新的
User
記錄 - 更新現有的
User
記錄 - 刪除現有的
User
記錄
若要觸發其中一個事件,您可以使用 Prisma Studio。繼續並使用此命令開啟它(在新的終端機標籤或視窗中)
npx prisma studio
如果您在視覺化編輯器中建立新的 User
記錄,您應該會在先前的終端機標籤/視窗中看到類似以下的輸出
Received an event: {
action: 'create',
created: { id: @, email: 'bob@prisma.io', name: 'Bob' },
id: '01JAFNSZHQRDTW773BCAA9G7FJ'
}
當您使用 Prisma Client 寫入資料庫時,也會觸發這些變更事件。例如,您可以使用以下 update
查詢更新您的 queries.ts
檔案,將使用者從 "Alice"
重新命名為 "Alicia"
async function main() {
await prisma.user.update({
where: {
id: 1
},
data: {
name: 'Alicia',
email: 'alicia@prisma.io',
}
});
}
然後,您可以使用與之前相同的命令執行腳本(在新的終端機標籤或視窗中)
npx tsx queries.ts
您現在應該會在先前的終端機標籤/視窗中看到類似以下的輸出
{
action: 'update',
after: { id: 1, email: 'alicia@prisma.io', name: 'Alicia' },
before: null,
id: '0/2A5A248'
}
恭喜!您現在已經學會如何使用 Prisma Client 查詢 Prisma Postgres 資料庫,以及如何在您的應用程式中接收即時事件。如果您在過程中迷路了,想要了解更多查詢或探索 Prisma Accelerate 的快取功能,請查看完整的 Prisma 入門範本。