# Change: Migrate SQLite to MySQL with Table Prefix ## Why 目前專案使用 SQLite 作為開發資料庫,需要遷移到雲端 MySQL 資料庫以支援生產環境部署。由於 MySQL 資料庫 `db_A060` 會與其他專案共用,需要為所有資料表加上 `tr_` 前綴以避免命名衝突。 **遷移目標:** - 完全移除 SQLite 支援,統一使用 MySQL - 所有資料表加上 `tr_` 前綴(例如 `users` → `tr_users`) - 使用 Alembic 進行資料庫版本控制和遷移管理 - 確保遷移腳本只影響 `tr_` 前綴的資料表 ## What Changes ### 1. Database Configuration - 更新 `DATABASE_URL` 環境變數格式支援 MySQL - 移除 `app/core/database.py` 中的 SQLite 特殊處理 - 新增 MySQL 驅動相依套件 (`pymysql` 或 `mysqlclient`) ### 2. Model Table Prefix (**BREAKING**) 所有 10 個資料表將重新命名: | 原名稱 | 新名稱 | |--------|--------| | `users` | `tr_users` | | `user_sessions` | `tr_user_sessions` | | `incident_rooms` | `tr_incident_rooms` | | `room_members` | `tr_room_members` | | `room_templates` | `tr_room_templates` | | `messages` | `tr_messages` | | `message_reactions` | `tr_message_reactions` | | `message_edit_history` | `tr_message_edit_history` | | `generated_reports` | `tr_generated_reports` | | `room_files` | `tr_room_files` | ### 3. Alembic Integration - 初始化 Alembic 遷移框架 - 建立初始遷移腳本(建立所有 `tr_` 前綴資料表) - 移除 `app/main.py` 中的 `Base.metadata.create_all()` 自動建表 ### 4. Index and Constraint Naming - 更新所有索引名稱加上 `tr_` 前綴以避免衝突 - 更新唯一約束名稱 ### 5. MySQL Compatibility - 確保 JSON 欄位在 MySQL 中正確運作 - 確保 Enum 類型在 MySQL 中正確運作 - 處理 MySQL 的字串長度限制(VARCHAR vs TEXT) ## Impact - **Affected specs**: 新增 `database` spec - **Affected code**: - `app/core/database.py` - 移除 SQLite 支援 - `app/core/config.py` - 可能新增資料表前綴設定 - `app/modules/*/models.py` - 所有 5 個 models.py 檔案更新 `__tablename__` - `app/main.py` - 移除自動建表,改用 Alembic - `requirements.txt` - 新增 `alembic`, `pymysql` - `.env`, `.env.example` - 更新 DATABASE_URL 格式 - **Breaking changes**: - 所有資料表重新命名(需要重新建立資料庫或執行遷移) - SQLite 不再支援 - 現有 SQLite 資料不會自動遷移(需手動處理) - **New files**: - `alembic.ini` - Alembic 設定檔 - `alembic/` - 遷移腳本目錄