无服务器驱动
适用于 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。