Prisma
以下为严格遵循规则的翻译结果:
这里快速展示了如何将您的 Prisma 应用连接到 Supabase Postgres。如果遇到任何问题,请参考 Prisma 故障排除文档。
如果您计划完全使用 Prisma 而非 Supabase 数据 API (PostgREST),请在 API 设置 中关闭它。
1
为 Prisma 创建自定义用户
- 在 SQL 编辑器 中,创建一个对 public 模式拥有完全权限的 Prisma 数据库用户
- 这样可以更好地控制 Prisma 的访问权限,并更容易通过 Supabase 工具如 查询性能仪表盘 和 日志浏览器 进行监控
密码管理器
出于安全考虑,建议使用 密码生成器 为 Prisma 角色生成密码
123456789101112131415-- 创建自定义用户create user "prisma" with password 'custom_password' bypassrls createdb;-- 将 prisma 的权限扩展到 postgres(必要以便在仪表盘中查看变更)grant "prisma" to "postgres";-- 授予相关模式(public)的必要权限grant usage on schema public to prisma;grant create on schema public to prisma;grant all on all tables in schema public to prisma;grant all on all routines in schema public to prisma;grant all on all sequences in schema public to prisma;alter default privileges for role postgres in schema public grant all on tables to prisma;alter default privileges for role postgres in schema public grant all on routines to prisma;alter default privileges for role postgres in schema public grant all on sequences to prisma;
12-- 如需修改 prisma 密码alter user "prisma" with password 'new_password';
2
创建 Prisma 项目
在您的计算机上创建一个新的 Prisma 项目
创建新目录
12mkdir hello-prismacd hello-prisma
初始化新的 Prisma 项目
123456npm init -ynpm install prisma typescript ts-node @types/node --save-devnpx tsc --initnpx prisma init
3
将连接信息添加到 .env 文件
- 在项目仪表盘中点击 连接
- 找到您的 Supavisor 会话模式连接字符串(应以 5432 结尾),它将用于您的
.env
文件
如果您处于 IPv6 环境 或拥有 IPv4 附加组件,可以直接使用连接字符串而非 Supavisor 会话模式
- 如果计划将 Prisma 部署到无服务器或自动扩展环境,还需要 Supavisor 事务模式字符串
- 该字符串与会话模式字符串相同,但使用端口 6543
在 .env 文件中设置 DATABASE_URL 变量为您的连接字符串
12# 用于 Prisma 迁移和应用程序内部DATABASE_URL="postgres://[DB-USER].[PROJECT-REF]:[PRISMA-PASSWORD]@[DB-REGION].pooler.supabase.com:5432/postgres"
将字符串中的 [DB-USER]
改为 prisma
并添加第一步创建的密码
1postgres://prisma.[PROJECT-REF]...
4
创建迁移
如果已修改过 Supabase 数据库,请将其与迁移文件同步。否则为数据库创建新表
在 prisma.schema 文件中创建新表
123456789101112131415model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int?}model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[]}
提交迁移
1npx prisma migrate dev --name first_prisma_migration
5
安装 prisma 客户端
安装 Prisma 客户端并生成其模型
12npm install @prisma/clientnpx prisma generate
6
测试 API
创建 index.ts 文件并运行以测试连接
123456789101112131415161718192021const { PrismaClient } = require('@prisma/client');const prisma = new PrismaClient();async function main() { //更改为引用您模式中的表 const val = await prisma.<SOME_TABLE_NAME>.findMany({ take: 10, }); console.log(val);}main() .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); await prisma.$disconnect(); process.exit(1);});