Files
learn-ai/docs/tasks/02-database-setup.md
hughhuangandClaude Sonnet 4.5 830a17bf46 初始化项目结构和基础模块
完成内容:
- 创建前后端项目目录结构
- 初始化 Node.js + TypeScript 后端项目 (Fastify)
- 初始化 Vue 3 + TypeScript 前端项目 (Vite)
- 配置 Prisma ORM 和 MySQL 数据库
- 创建数据库 Schema 和种子数据
- 实现后端基础模块 (配置、日志、错误处理、验证)
- 创建基础服务类 (BaseService)
- 配置 Git 仓库和忽略文件

技术栈:
- 后端:Fastify + Prisma + MySQL + Winston
- 前端:Vue 3 + TypeScript + Element Plus + Pinia

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-03 12:11:57 +08:00

14 KiB
Raw Permalink Blame History

任务 02:数据库搭建

任务概述

使用 Prisma 创建数据库模型,执行数据库迁移,初始化数据库结构。

前置条件

  • 任务 01 已完成
  • MySQL 5.6 已安装并运行
  • 数据库连接信息已配置到 .env 文件

任务目标

  • 创建 Prisma Schema
  • 执行数据库迁移
  • 生成 Prisma Client
  • 创建种子数据脚本

详细步骤

1. 创建 Prisma Schema

创建 backend/prisma/schema.prisma:

generator client {
  provider = "prisma-client-js"
}

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

// LLM 配置表
model LlmConfig {
  id        Int      @id @default(autoincrement())
  name      String   @db.VarChar(100)
  baseUrl   String   @map("base_url") @db.VarChar(500)
  model     String   @db.VarChar(100)
  apiKey    String   @map("api_key") @db.VarChar(500)
  enabled   Boolean  @default(true) @db.TinyInt
  userId    Int?     @map("user_id")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  topics Topic[]

  @@index([userId, enabled], map: "idx_user_enabled")
  @@map("llm_configs")
}

// 数据源表
model Source {
  id              Int       @id @default(autoincrement())
  name            String    @db.VarChar(100)
  type            String    @db.VarChar(50) // api/playwright/rss
  config          Json
  cronExpression  String    @map("cron_expression") @db.VarChar(100)
  enabled         Boolean   @default(true) @db.TinyInt
  lastCollectedAt DateTime? @map("last_collected_at")
  userId          Int?      @map("user_id")
  createdAt       DateTime  @default(now()) @map("created_at")
  updatedAt       DateTime  @updatedAt @map("updated_at")

  articles       Article[]
  topicSources   TopicSource[]
  collectionLogs CollectionLog[]

  @@index([userId, enabled], map: "idx_user_enabled")
  @@index([type], map: "idx_type")
  @@map("sources")
}

// 推送渠道表
model Channel {
  id        Int      @id @default(autoincrement())
  name      String   @db.VarChar(100)
  type      String   @db.VarChar(50) // email/dingtalk/wechat/slack
  config    Json
  enabled   Boolean  @default(true) @db.TinyInt
  userId    Int?     @map("user_id")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  topicChannels TopicChannel[]
  pushLogs      PushLog[]

  @@index([userId, enabled], map: "idx_user_enabled")
  @@index([type], map: "idx_type")
  @@map("channels")
}

// 主题表
model Topic {
  id             Int      @id @default(autoincrement())
  name           String   @db.VarChar(100)
  description    String?  @db.Text
  processMode    String   @map("process_mode") @db.VarChar(50) // aggregate/summary/deep_analysis
  llmConfigId    Int?     @map("llm_config_id")
  scheduleConfig Json     @map("schedule_config")
  enabled        Boolean  @default(true) @db.TinyInt
  userId         Int?     @map("user_id")
  createdAt      DateTime @default(now()) @map("created_at")
  updatedAt      DateTime @updatedAt @map("updated_at")

  llmConfig      LlmConfig?      @relation(fields: [llmConfigId], references: [id])
  topicSources   TopicSource[]
  topicChannels  TopicChannel[]
  reports        Report[]
  conversations  Conversation[]

  @@index([userId, enabled], map: "idx_user_enabled")
  @@map("topics")
}

// 主题-数据源关联表
model TopicSource {
  id        Int      @id @default(autoincrement())
  topicId   Int      @map("topic_id")
  sourceId  Int      @map("source_id")
  createdAt DateTime @default(now()) @map("created_at")

  topic  Topic  @relation(fields: [topicId], references: [id], onDelete: Cascade)
  source Source @relation(fields: [sourceId], references: [id], onDelete: Cascade)

  @@unique([topicId, sourceId], map: "uk_topic_source")
  @@index([topicId], map: "idx_topic")
  @@index([sourceId], map: "idx_source")
  @@map("topic_sources")
}

// 主题-推送渠道关联表
model TopicChannel {
  id        Int      @id @default(autoincrement())
  topicId   Int      @map("topic_id")
  channelId Int      @map("channel_id")
  createdAt DateTime @default(now()) @map("created_at")

  topic   Topic   @relation(fields: [topicId], references: [id], onDelete: Cascade)
  channel Channel @relation(fields: [channelId], references: [id], onDelete: Cascade)

  @@unique([topicId, channelId], map: "uk_topic_channel")
  @@index([topicId], map: "idx_topic")
  @@index([channelId], map: "idx_channel")
  @@map("topic_channels")
}

// 资讯表
model Article {
  id          Int       @id @default(autoincrement())
  sourceId    Int       @map("source_id")
  title       String    @db.VarChar(500)
  content     String?   @db.Text
  summary     String?   @db.Text
  url         String?   @db.VarChar(1000)
  publishedAt DateTime? @map("published_at")
  collectedAt DateTime  @map("collected_at")
  rawData     Json?     @map("raw_data")
  createdAt   DateTime  @default(now()) @map("created_at")

  source        Source         @relation(fields: [sourceId], references: [id])
  conversations Conversation[]

  @@index([sourceId], map: "idx_source")
  @@index([publishedAt], map: "idx_published")
  @@index([collectedAt], map: "idx_collected")
  @@index([url(length: 255)], map: "idx_url")
  @@map("articles")
}

// 报告表
model Report {
  id           Int      @id @default(autoincrement())
  topicId      Int      @map("topic_id")
  title        String   @db.VarChar(500)
  content      String   @db.LongText
  periodStart  DateTime @map("period_start")
  periodEnd    DateTime @map("period_end")
  status       String   @db.VarChar(50) // pending/generating/completed/failed
  errorMessage String?  @map("error_message") @db.Text
  articleCount Int      @default(0) @map("article_count")
  userId       Int?     @map("user_id")
  createdAt    DateTime @default(now()) @map("created_at")
  updatedAt    DateTime @updatedAt @map("updated_at")

  topic         Topic          @relation(fields: [topicId], references: [id])
  pushLogs      PushLog[]
  conversations Conversation[]

  @@index([topicId], map: "idx_topic")
  @@index([status], map: "idx_status")
  @@index([periodStart, periodEnd], map: "idx_period")
  @@index([userId, createdAt], map: "idx_user_created")
  @@map("reports")
}

// 采集日志表
model CollectionLog {
  id            Int       @id @default(autoincrement())
  sourceId      Int       @map("source_id")
  status        String    @db.VarChar(50) // success/failed
  errorMessage  String?   @map("error_message") @db.Text
  articlesCount Int       @default(0) @map("articles_count")
  startedAt     DateTime  @map("started_at")
  finishedAt    DateTime? @map("finished_at")
  durationMs    Int?      @map("duration_ms")
  createdAt     DateTime  @default(now()) @map("created_at")

  source Source @relation(fields: [sourceId], references: [id])

  @@index([sourceId], map: "idx_source")
  @@index([status], map: "idx_status")
  @@index([startedAt], map: "idx_started")
  @@map("collection_logs")
}

// 推送日志表
model PushLog {
  id           Int      @id @default(autoincrement())
  reportId     Int      @map("report_id")
  channelId    Int      @map("channel_id")
  status       String   @db.VarChar(50) // success/failed
  errorMessage String?  @map("error_message") @db.Text
  createdAt    DateTime @default(now()) @map("created_at")

  report  Report  @relation(fields: [reportId], references: [id])
  channel Channel @relation(fields: [channelId], references: [id])

  @@index([reportId], map: "idx_report")
  @@index([channelId], map: "idx_channel")
  @@index([status], map: "idx_status")
  @@map("push_logs")
}

// AI对话记录表
model Conversation {
  id        Int      @id @default(autoincrement())
  reportId  Int?     @map("report_id")
  articleId Int?     @map("article_id")
  topicId   Int      @map("topic_id")
  messages  Json
  userId    Int?     @map("user_id")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  report  Report?  @relation(fields: [reportId], references: [id])
  article Article? @relation(fields: [articleId], references: [id])
  topic   Topic    @relation(fields: [topicId], references: [id])

  @@index([reportId], map: "idx_report")
  @@index([articleId], map: "idx_article")
  @@index([topicId], map: "idx_topic")
  @@index([userId], map: "idx_user")
  @@map("conversations")
}

2. 执行数据库迁移

cd backend

# 创建迁移文件并执行
npx prisma migrate dev --name init

# 生成 Prisma Client
npx prisma generate

3. 创建种子数据脚本

创建 backend/prisma/seed.ts:

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  console.log('开始创建种子数据...')

  // 创建默认 LLM 配置
  const llmConfig = await prisma.llmConfig.create({
    data: {
      name: '默认 OpenAI',
      baseUrl: 'https://api.openai.com/v1',
      model: 'gpt-4o-mini',
      apiKey: 'your-api-key-here',
      enabled: false, // 默认禁用,需要用户配置后启用
    },
  })
  console.log('✓ 创建默认 LLM 配置')

  // 创建示例数据源
  const source = await prisma.source.create({
    data: {
      name: 'Hacker News',
      type: 'api',
      config: {
        url: 'https://hacker-news.firebaseio.com/v0/topstories.json',
        method: 'GET',
        dataPath: '',
        mapping: {
          title: 'title',
          url: 'url',
          publishedAt: 'time',
        },
      },
      cronExpression: '0 */6 * * *', // 每6小时
      enabled: false, // 默认禁用
    },
  })
  console.log('✓ 创建示例数据源')

  // 创建示例推送渠道
  const channel = await prisma.channel.create({
    data: {
      name: '邮件通知',
      type: 'email',
      config: {
        smtp: {
          host: 'smtp.example.com',
          port: 465,
          secure: true,
          auth: {
            user: 'user@example.com',
            pass: 'password',
          },
        },
        from: 'News Aggregator <noreply@example.com>',
        to: ['user@example.com'],
      },
      enabled: false, // 默认禁用
    },
  })
  console.log('✓ 创建示例推送渠道')

  // 创建示例主题
  const topic = await prisma.topic.create({
    data: {
      name: '科技资讯',
      description: '关注最新的科技动态和产品发布',
      processMode: 'summary',
      llmConfigId: llmConfig.id,
      scheduleConfig: {
        cron: '0 9 * * *',
        timezone: 'Asia/Shanghai',
        period: 'daily',
        lookback: 24,
      },
      enabled: false, // 默认禁用
    },
  })
  console.log('✓ 创建示例主题')

  // 关联主题和数据源
  await prisma.topicSource.create({
    data: {
      topicId: topic.id,
      sourceId: source.id,
    },
  })
  console.log('✓ 关联主题和数据源')

  // 关联主题和推送渠道
  await prisma.topicChannel.create({
    data: {
      topicId: topic.id,
      channelId: channel.id,
    },
  })
  console.log('✓ 关联主题和推送渠道')

  console.log('种子数据创建完成!')
}

main()
  .catch((e) => {
    console.error('种子数据创建失败:', e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })

4. 配置种子数据脚本

更新 backend/package.json,添加 seed 脚本:

{
  "prisma": {
    "seed": "tsx prisma/seed.ts"
  },
  "scripts": {
    "prisma:seed": "tsx prisma/seed.ts"
  }
}

5. 执行种子数据

npm run prisma:seed

6. 创建数据库工具类

创建 backend/src/utils/prisma.ts:

import { PrismaClient } from '@prisma/client'

// 创建 Prisma Client 单例
const prismaClientSingleton = () => {
  return new PrismaClient({
    log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
  })
}

declare global {
  var prisma: undefined | ReturnType<typeof prismaClientSingleton>
}

const prisma = globalThis.prisma ?? prismaClientSingleton()

if (process.env.NODE_ENV !== 'production') {
  globalThis.prisma = prisma
}

export default prisma

验证步骤

1. 验证数据库连接

cd backend
npx prisma studio

应该能打开 Prisma Studio 并看到所有表。

2. 验证表结构

在 Prisma Studio 中检查:

  • 所有表都已创建
  • 索引都已创建
  • 外键关系正确

3. 验证种子数据

在 Prisma Studio 中检查:

  • llm_configs 表有 1 条记录
  • sources 表有 1 条记录
  • channels 表有 1 条记录
  • topics 表有 1 条记录
  • topic_sources 表有 1 条记录
  • topic_channels 表有 1 条记录

4. 验证 Prisma Client

创建测试文件 backend/src/test-db.ts:

import prisma from './utils/prisma'

async function test() {
  const topics = await prisma.topic.findMany({
    include: {
      llmConfig: true,
      topicSources: {
        include: {
          source: true,
        },
      },
      topicChannels: {
        include: {
          channel: true,
        },
      },
    },
  })

  console.log('主题列表:', JSON.stringify(topics, null, 2))
}

test()
  .catch(console.error)
  .finally(() => prisma.$disconnect())

运行测试:

npx tsx src/test-db.ts

应该能看到完整的主题数据,包括关联的 LLM 配置、数据源、推送渠道。

预期产物

  • ✅ Prisma Schema 创建完成
  • ✅ 数据库迁移执行成功
  • ✅ 所有表创建完成
  • ✅ Prisma Client 生成成功
  • ✅ 种子数据创建成功
  • ✅ 数据库工具类创建完成

常见问题

问题 1:数据库连接失败

解决方案:检查 .env 文件中的 DATABASE_URL 是否正确,确保 MySQL 服务已启动。

问题 2:迁移失败

解决方案:删除数据库重新创建,或使用 npx prisma migrate reset 重置数据库。

问题 3:Prisma Client 类型错误

解决方案:重新生成 Prisma Client:npx prisma generate

下一步

完成本任务后,继续 任务 03:后端核心框架。