無伺服器驅動
適用於 Prisma Postgres 的無伺服器驅動是一個輕量級、精簡的客戶端庫,可以使用原始 SQL 與 Prisma Postgres 通訊。你可以透過 @prisma/ppg npm 包使用它。
警告
Prisma Postgres 無伺服器驅動目前處於早期訪問階段,暫不建議用於生產環境。
安裝
透過 npm 安裝無伺服器驅動
npm install @prisma/ppg
使用方法
對於大多數使用者來說,推薦的 API 是 ppg 函式,它返回一個以模板字面量標籤函式實現的 SQL 高階客戶端
import { ppg } from "@prisma/ppg";
type Post = {
id: number;
title: string;
content: string | null;
published: boolean;
authorId: number | null;
}
const sql = ppg("prisma+postgres://accelerate.prisma-data.net/?api_key=...");
const authorId = 1;
const posts = await sql<Post>`SELECT * FROM "Post" WHERE "authorId" = ${authorId}`;
API 參考
ppg
ppg 函式返回一個以模板字面量標籤函式實現的 SQL 高階客戶端
function ppg(connectionString: string, deserialize?: Deserialize): Sql;
interface Sql {
<Record = unknown>(strings: TemplateStringsArray, ...values: unknown[]): Promise<Record[]>;
/**
* Executes a raw query defined as a string with placeholders and the list
* of parameters.
*
* ```ts
* const [user] = await sql.query<User>("SELECT * FROM users WHERE id = $1", [id]);
* ```
*/
query<Record>(query: string, ...params: unknown[]): Promise<Record[]>;
}
type Deserialize = (value: unknown, oid: unknown) => unknown;
返回的 Sql 物件
- 接受 SQL 語句作為模板字面量。如果其中包含任何插值,這些值會自動轉換為 SQL 引數,以防止 SQL 注入攻擊(請參閱下面的示例)。
- 將資料作為物件陣列返回,這些物件反映了你的 Prisma 模型的結構。
- 提供一個
query函式,它- 單獨接受原始字串和引數列表,允許你自行控制 SQL 引數,或者在需要時不安全地拼接查詢。
- 返回列型別和原始資料,而不將行轉換為物件陣列。
引數
ppg 函式接受以下引數
| 名稱 | 型別 | 必需 | 描述 |
|---|---|---|---|
connectionString | string | 是 | 你的 Prisma Postgres 例項的連線字串。 |
deserialize | Deserialize | 否 | 自定義反序列化函式,接受列型別 OID 和原始值,並返回對映後的值。其型別定義為 type Deserialize = (value: unknown, oid: unknown) => unknown |
使用方法
import { ppg } from "@prisma/ppg";
type Post = {
id: number;
title: string;
content: string | null;
published: boolean;
authorId: number | null;
}
type User = {
id: number;
email: string
}
const sql = ppg("prisma+postgres://accelerate.prisma-data.net/?api_key=...");
const posts: Post[] = await sql<Post>`SELECT * FROM "Post"`
const userId = 42;
const user: User[] = await sql<User>`SELECT * FROM "User" WHERE "id" = ${userId}`
Client
Client 類提供了更底層的控制,使用時應更加謹慎
class Client implements Queryable {
constructor(options: ClientOptions);
/**
* Executes a query against the Prisma Postgres database.
*/
query(query: string, parameters: unknown[]): Promise<QueryResponse>;
}
它暴露的 query 函式
- 單獨接受原始字串和引數列表,允許你自行控制 SQL 引數,或者在需要時不安全地拼接查詢。
- 返回列型別和原始資料,而不將行轉換為物件陣列。
使用方法
import { Client } from "@prisma/ppg";
const client = new Client({
connectionString: "prisma+postgres://accelerate.prisma-data.net/?api_key=...",
});
const posts = await client.query('SELECT * FROM "Post" WHERE "authorId" = $1', [1]);
此查詢返回一個具有以下結構的物件
{
columns: [
{ name: 'id', oid: 23 },
{ name: 'title', oid: 25 },
{ name: 'content', oid: 25 },
{ name: 'published', oid: 16 },
{ name: 'authorId', oid: 23 }
],
rows: [ [ 1, 'Hello World', 'This is the content of the post', true, 1 ] ]
}
限制
- 不支援事務。
- 不支援本地 Prisma Postgres。