Skip to content

Prisma Postgres & Astro

Prisma Postgres 是一个完全托管的无服务器 Postgres 数据库,专为现代 Web 应用而构建。

¥Prisma Postgres is a fully managed, serverless Postgres database built for modern web apps.

¥Connect with Prisma ORM (Recommended)

Prisma ORM 是连接 Prisma Postgres 数据库的推荐方式。它提供类型安全的查询、迁移和全局性能。

¥Prisma ORM is the recommended way to connect to your Prisma Postgres database. It provides type-safe queries, migrations, and global performance.

¥Prerequisites

¥Install dependencies and initialize Prisma

运行以下命令安装必要的 Prisma 依赖:

¥Run the following commands to install the necessary Prisma dependencies:

终端窗口
npm install prisma tsx --save-dev
npm install @prisma/adapter-pg @prisma/client

安装完成后,使用以下命令在你的项目中初始化 Prisma:

¥Once installed, initialize Prisma in your project with the following command:

终端窗口
npx prisma init --db --output ./generated

在设置 Prisma Postgres 数据库时,你需要回答几个问题。选择离你最近的区域,并为你的数据库指定一个易于记忆的名称,例如 “我的 Astro 项目。”

¥You’ll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database, like “My Astro Project.”

这将创建:

¥This will create:

  • 一个包含 schema.prisma 文件的 prisma/ 目录

  • 一个已设置 DATABASE_URL.env 文件

¥Define a Model

即使你目前不需要任何特定的数据模型,Prisma 也要求模式中至少包含一个模型才能生成客户端并应用迁移。

¥Even if you don’t need any specific data models yet, Prisma requires at least one model in the schema in order to generate a client and apply migrations.

以下示例将 Post 模型定义为占位符。将此模型添加到你的 schema 中即可开始使用。你可以稍后安全地删除它或将其替换为反映实际数据的模型。

¥The following example defines a Post model as a placeholder. Add the model to your schema to get started. You can safely delete or replace it later with models that reflect your actual data.

prisma/schema.prisma
generator client {
provider = "prisma-client"
output = "./generated"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
}

了解更多关于在 Prisma schema 参考 中配置 Prisma ORM 设置的信息。

¥Learn more about configuring your Prisma ORM setup in the Prisma schema reference.

¥Generate client

运行以下命令以从你的模式生成 Prisma 客户端:

¥Run the following command to generate the Prisma Client from your schema:

终端窗口
npx prisma generate

¥Generate migration files

运行以下命令以创建数据库表并从你的模式生成 Prisma 客户端。这还会创建一个包含迁移历史记录文件的 prisma/migrations/ 目录。

¥Run the following command to create the database tables and generate the Prisma Client from your schema. This will also create a prisma/migrations/ directory with migration history files.

终端窗口
npx prisma migrate dev --name init

¥Create a Prisma Client

/src/lib 中,创建一个 prisma.ts 文件。此文件将初始化并导出你的 Prisma 客户端实例,以便你可以在整个 Astro 项目中查询数据库。

¥Inside of /src/lib, create a prisma.ts file. This file will initialize and export your Prisma Client instance so you can query your database throughout your Astro project.

src/lib/prisma.ts
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../../prisma/generated/client';
const connectionString = import.meta.env.DATABASE_URL;
const adapter = new PrismaPg({ connectionString });
const prisma = new PrismaClient({ adapter });
export default prisma;

¥Querying and displaying data

以下示例展示了如何使用 Prisma 客户端按 id 排序获取已发布的文章,然后在 Astro 模板中显示标题和文章内容:

¥The following example shows fetching only your published posts with the Prisma Client sorted by id, and then displaying titles and post content in your Astro template:

src/pages/posts.astro
---
import prisma from '../lib/prisma';
const posts = await prisma.post.findMany({
where: { published: true },
orderBy: { id: 'desc' }
});
---
<html>
<head>
<title>Published Posts</title>
</head>
<body>
<h1>Published Posts</h1>
<ul>
{posts.map((post) => (
<li>
<h2>{post.title}</h2>
{post.content && <p>{post.content}</p>}
</li>
))}
</ul>
</body>
</html>

最佳实践是在 API 路由中处理查询。有关如何在 Astro 项目中使用 Prisma ORM 的更多信息,请参阅 Astro + Prisma ORM 指南 文档。

¥It is best practice to handle queries in an API route. For more information on how to use Prisma ORM in your Astro project, see the Astro + Prisma ORM Guide.

¥Connect with Other ORMs and Libraries

你可以使用任何其他 ORM、数据库库或你选择的工具,通过直接 TCP 连接到 Prisma Postgres。在 Prisma 控制台中创建一个直接连接字符串以开始使用。

¥You can connect to Prisma Postgres via direct TCP using any other ORM, database library, or tool of your choice. Create a direct connection string in your Prisma Console to get started.

¥Prerequisites

¥Install dependencies

此示例使用 pg,一个适用于 Node.js 的 PostgreSQL 客户端 建立直接 TCP 连接。

¥This example uses pg, a PostgreSQL client for Node.js to make a direct TCP connection.

运行以下命令安装 pg 包:

¥Run the following command to install the pg package:

终端窗口
npm install pg

¥Query your database client

pg 客户端提供你的连接字符串,以便与你的 SQL 服务器通信并从数据库中获取数据。

¥Provide your connection string to the pg client to communicate with your SQL server and fetch data from your database.

以下示例创建了一个表并插入了数据,可用于验证查询 URL 和 TCP 连接:

¥The following example of creating a table and inserting data can be used to validate your query URL and TCP connection:

src/pages/index.astro
---
import { Client } from 'pg';
const client = new Client({
connectionString: import.meta.env.DATABASE_URL,
ssl: { rejectUnauthorized: false }
});
await client.connect();
await client.query(`
CREATE TABLE IF NOT EXISTS posts (
id SERIAL PRIMARY KEY,
title TEXT UNIQUE,
content TEXT
);
INSERT INTO posts (title, content)
VALUES ('Hello', 'World')
ON CONFLICT (title) DO NOTHING;
`);
const { rows } = await client.query('SELECT * FROM posts');
await client.end();
---
<h1>Posts</h1>
<p>{rows[0].title}: {rows[0].content}</p>

¥Official Resources

更多后端服务指南

Astro v5.16 中文网 - 粤ICP备13048890号