feat: migrate configuration to .env environment variables

This commit implements a complete migration from JSON-based configuration
to .env environment variables, providing better security and flexibility.

Key Changes:
- Add python-dotenv dependency for environment variable support
- Create config/env_loader.py with type conversion utilities
- Add from_env() class methods to all config dataclasses
- Update ConfigLoader to prioritize environment variables
- Add save_to_env() method for .env file management
- Implement database connection factory pattern
- Add base DAO and connection classes for better abstraction
- Support both SQL Server and MySQL with unified interface
- Create migration script (scripts/migrate_to_env.py)
- Update GUI to read/write .env files
- Add comprehensive migration documentation

New Files:
- config/env_loader.py - Environment variable loader
- db/base_connection.py - Base database connection interface
- db/base_dao.py - Base DAO with common utilities
- db/connection_factory.py - Factory for creating connections
- db/mysql_connection.py - MySQL-specific connection
- db/sqlserver_connection.py - SQL Server-specific connection
- db/table_name_converter.py - SQL dialect converter
- scripts/migrate_to_env.py - Configuration migration tool
- docs/ENV_MIGRATION.md - Complete migration guide
- .env.example - Environment variable template

Testing:
- Verified MySQL connection (8.0.44)
- Tested all DAO operations
- Confirmed 150 tables accessible
- Validated configuration loading

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Misaka
2026-02-09 22:39:14 +08:00
parent 04b99292ad
commit aaa46ef282
22 changed files with 2545 additions and 563 deletions

View File

@@ -4,6 +4,7 @@
配置管理器
负责加载、保存和管理用户配置。
支持从环境变量和 .env 文件加载配置。
"""
import os
from typing import TYPE_CHECKING
@@ -19,15 +20,17 @@ if TYPE_CHECKING:
class ConfigManager:
"""配置管理器"""
def __init__(self, config_file: str = "config/user_settings.json"):
def __init__(self, config_file: str = "config/user_settings.json", use_env: bool = True):
"""
初始化配置管理器
Args:
config_file: 配置文件路径
config_file: 配置文件路径(向后兼容)
use_env: 是否使用环境变量,默认为 True
"""
self.config_file = config_file
self.config: AppConfig = ConfigLoader.load(config_file)
self.use_env = use_env
self.config: AppConfig = ConfigLoader.load(config_file, use_env=use_env)
# 验证配置
errors = self.config.validate()
@@ -40,10 +43,16 @@ class ConfigManager:
"""
保存配置到文件
如果使用环境变量,则保存到 .env 文件
否则保存到 JSON 文件(向后兼容)
Returns:
保存是否成功
"""
return ConfigLoader.save(self.config, self.config_file)
if self.use_env:
return ConfigLoader.save_to_env(self.config, ".env")
else:
return ConfigLoader.save(self.config, self.config_file)
def get(self, key: str, default=None):
"""
@@ -90,7 +99,7 @@ class ConfigManager:
def reset_to_defaults(self) -> None:
"""重置为默认配置"""
self.config = ConfigLoader.load("default") # 重新加载默认配置
self.config = AppConfig.from_env() # 重新从环境变量加载默认配置
self.save()
@property