Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
185 changes: 185 additions & 0 deletions src/content/docs/zh-cn/guides/backend/prisma-postgres.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
---
title: Prisma Postgres & Astro
description: Add a serverless Postgres database to your Astro project with Prisma Postgres
sidebar:
label: Prisma Postgres
type: backend
service: Prisma Postgres
stub: false
i18nReady: true
---

import ReadMore from '~/components/ReadMore.astro';

[Prisma Postgres](https://www.prisma.io/) 是专为现代 Web 应用构建的完全托管、无服务器的 Postgres 数据库。

## Connect via Prisma ORM (Recommended)

推荐使用 [Prisma ORM](https://www.prisma.io/orm) 连接你的 Prisma Postgres 数据库。它提供类型安全查询、迁移和全局性能优化。

### 前提条件
- 一个已安装适配器并支持按需渲染(SSR)的 Astro 项目。

### 安装依赖并初始化 Prisma

运行以下命令安装所需的 Prisma 依赖项:

Run the following commands to install the necessary Prisma dependencies:

```bash
npm install prisma tsx --save-dev
npm install @prisma/extension-accelerate @prisma/client
```

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

```bash
npx prisma init --db --output ../src/generated/prisma
```

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

这将创建:
- 一个包含 `schema.prisma` 文件的 `prisma/` 目录
- 一个已设置好 `DATABASE_URL` 的 `.env` 文件

### 定义模型

即使你现在不需要任何特定的数据模型,Prisma 仍然需要在模式中至少定义一个模型,以便生成客户端并应用迁移。

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.

Update the generator provider from `prisma-client-js` to `prisma-client` in your `prisma/schema.prisma` file:

```prisma title="prisma/schema.prisma" {2} ins={11-16}
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
}
```

Learn more about configuring your Prisma ORM setup in the [Prisma schema reference](https://www.prisma.io/docs/concepts/components/prisma-schema).

### Generate migration files

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.

```bash
npx prisma migrate dev --name init
```

### Create a Prisma Client

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.

```typescript title="src/lib/prisma.ts"
import { PrismaClient } from "../generated/prisma/client";
import { withAccelerate } from "@prisma/extension-accelerate";

const prisma = new PrismaClient({
datasourceUrl: import.meta.env.DATABASE_URL,
}).$extends(withAccelerate());

export default prisma;
```

### Querying and displaying data

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:

```astro title="src/pages/posts.astro" {2, 4-7}
---
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>
```

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](https://www.prisma.io/docs/guides/astro).

## Direct TCP connection
To connect to Prisma Postgres via direct TCP, you can create a direct connection string in your Prisma Console. This allows you to connect any other ORM, database library, or tool of your choice.

### Prerequisites
- A [Prisma Postgres](https://pris.ly/ppg) database with a TCP enabled connection string

### Install dependencies

This example will make a direct TCP connection using [`pg`, a PostgreSQL client for Node.js](https://github.com/brianc/node-postgres).

Run the following command to install the `pg` package:

```bash
npm install pg
```

### Query your database client

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

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

```astro title="src/pages/index.astro" {2-19}
---
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>
```

## 官方资源

- [Astro + Prisma ORM 指南](https://www.prisma.io/docs/guides/astro)