crypto.ai/cryptoai/utils/update_db_charset.py
2025-05-06 12:09:13 +08:00

65 lines
1.9 KiB
Python
Raw 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.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
更新数据库表字符集为utf8mb4以支持emoji和其他特殊字符
"""
import logging
from cryptoai.utils.db_manager import get_db_manager
from sqlalchemy import text
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('update_db_charset')
def update_table_charset():
"""更新数据库表字符集为utf8mb4"""
try:
# 获取数据库管理器
db_manager = get_db_manager()
if not db_manager.engine:
logger.error("数据库连接失败")
return False
# 创建会话
session = db_manager.Session()
try:
# 更新数据库字符集
session.execute(text("ALTER DATABASE CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"))
# 更新agent_feeds表字符集
session.execute(text("""
ALTER TABLE agent_feeds
CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
"""))
# 特别更新content列的字符集
session.execute(text("""
ALTER TABLE agent_feeds
MODIFY content TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
"""))
session.commit()
logger.info("成功更新数据库表字符集为utf8mb4")
return True
except Exception as e:
session.rollback()
logger.error(f"更新数据库表字符集失败: {e}")
return False
finally:
session.close()
except Exception as e:
logger.error(f"更新数据库表字符集失败: {e}")
return False
if __name__ == "__main__":
update_table_charset()