Files
aiapply/DATABASE_SETUP.md
2025-09-06 08:28:47 +08:00

206 lines
3.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# PromptForge 数据库设置指南
## 🗄️ 数据库配置
PromptForge 使用 **腾讯云数据库** 作为后端数据存储,支持完整的用户系统、模板管理和社区功能。
### 📋 当前配置
- **数据库类型**: MySQL
- **云服务商**: 腾讯云
- **连接地址**: `gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com:24936`
- **数据库名**: `pronode_db`
- **用户名**: `root`
## 🚀 快速开始
### 1. 安装依赖
```bash
npm install
```
### 2. 设置环境变量
创建 `.env.local` 文件:
```env
# 数据库配置
DATABASE_URL="mysql://root:!Rjb12191@gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com:24936/pronode_db?charset=utf8mb4"
# Next.js 配置
NEXTAUTH_SECRET="your-secret-key-here"
NEXTAUTH_URL="http://localhost:3000"
# 应用配置
NODE_ENV="development"
```
### 3. 生成 Prisma 客户端
```bash
npm run db:generate
```
### 4. 推送数据库模式
```bash
npm run db:push
```
### 5. 初始化示例数据
```bash
npm run db:seed
```
### 6. 启动开发服务器
```bash
npm run dev
```
## 📊 数据库结构
### 主要数据表
1. **users** - 用户信息
2. **templates** - 提示词模板
3. **favorites** - 用户收藏
4. **comments** - 模板评论
5. **tests** - 测试记录
6. **system_configs** - 系统配置
### 表关系
```
User (1) ←→ (N) Template
User (1) ←→ (N) Favorite
User (1) ←→ (N) Comment
Template (1) ←→ (N) Test
```
## 🛠️ 数据库管理命令
```bash
# 生成 Prisma 客户端
npm run db:generate
# 推送模式到数据库
npm run db:push
# 创建迁移文件
npm run db:migrate
# 打开 Prisma Studio数据库管理界面
npm run db:studio
# 初始化示例数据
npm run db:seed
```
## 🔧 开发工具
### Prisma Studio
Prisma Studio 是一个可视化的数据库管理工具:
```bash
npm run db:studio
```
访问 `http://localhost:5555` 查看数据库内容。
### 数据库连接测试
```typescript
import { testDatabaseConnection } from '@/lib/database'
// 测试连接
const isConnected = await testDatabaseConnection()
console.log('数据库连接状态:', isConnected)
```
## 🔒 安全配置
### 环境变量
- 生产环境请使用环境变量存储敏感信息
- 不要在代码中硬编码数据库密码
- 定期更换数据库密码
### 访问控制
- 限制数据库访问IP
- 使用最小权限原则
- 定期备份数据
## 📈 性能优化
### 索引优化
```sql
-- 为常用查询添加索引
CREATE INDEX idx_templates_category ON templates(category);
CREATE INDEX idx_templates_author ON templates(authorId);
CREATE INDEX idx_templates_public ON templates(isPublic);
```
### 连接池配置
```typescript
const prisma = new PrismaClient({
datasources: {
db: {
url: databaseUrl,
},
},
// 连接池配置
log: ['query', 'error', 'warn'],
})
```
## 🚨 故障排除
### 常见问题
1. **连接超时**
- 检查网络连接
- 验证数据库地址和端口
- 确认防火墙设置
2. **认证失败**
- 验证用户名和密码
- 检查用户权限
- 确认数据库存在
3. **模式同步失败**
- 检查数据库权限
- 验证表结构
- 查看错误日志
### 日志查看
```bash
# 查看 Prisma 日志
npm run db:studio
# 查看应用日志
npm run dev
```
## 📚 相关文档
- [Prisma 官方文档](https://www.prisma.io/docs)
- [腾讯云数据库文档](https://cloud.tencent.com/document/product/236)
- [Next.js 数据库集成](https://nextjs.org/docs/app/building-your-application/data-fetching)
## 🤝 支持
如果遇到数据库相关问题,请:
1. 查看错误日志
2. 检查网络连接
3. 验证配置信息
4. 联系技术支持