Files
2025-12-26 13:42:22 +08:00

99 lines
2.1 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.
# 数据库模块说明
本目录包含数据库相关的所有代码。
## 文件说明
- `app/models/` - 数据库模型定义(9个表)
- `app/db/session.py` - 数据库连接和配置
- `app/db/init_db.py` - 数据库初始化脚本
## 安装依赖
```bash
pip install -r ../requirements.txt
```
## 初始化数据库
### 首次创建数据库
运行以下命令创建数据库表:
```bash
cd backend
python -m app.db.init_db
```
或者从项目根目录运行:
```bash
python -m backend.app.db.init_db
```
执行后会在项目根目录生成 `blogweb.db` SQLite 数据库文件。
### 模型更新后更新数据库
⚠️ **重要提示**`create_all()` 只会创建**不存在的表**,**不会修改已存在表的结构**。
如果 models 有更新(添加字段、修改字段类型等),有两种方式:
#### 方式1:重置数据库(开发环境推荐)
⚠️ **会删除所有数据**,适合开发环境:
```bash
python -m app.db.init_db --reset
```
#### 方式2:使用数据库迁移工具(生产环境推荐)
对于生产环境,建议使用 **Alembic** 进行数据库迁移:
```bash
# 安装 Alembic
pip install alembic
# 初始化迁移环境
alembic init alembic
# 生成迁移脚本
alembic revision --autogenerate -m "描述变更"
# 执行迁移
alembic upgrade head
```
## 数据库表结构
根据 `数据库设计说明.md` 创建了以下9个表:
1. **users** - 用户账户信息
2. **todos** - 待办事项列表
3. **posts** - 博客文章
4. **transactions** - 个人记账记录
5. **media** - 书影音收藏条目
6. **tags** - 媒体标签
7. **media_tags** - 媒体与标签的多对多关联表
8. **chat_messages** - 聊天室消息记录
9. **uploads** - 用户上传的文件元数据
## 使用示例
在 FastAPI 应用中使用数据库:
```python
from app.db.session import get_db
from app.models import User, Todo
from sqlmodel import Session, select
# 在路由中使用
@app.get("/users")
def get_users(session: Session = Depends(get_db)):
statement = select(User)
users = session.exec(statement).all()
return users
```