Files
server-core/scripts/fix_index_names.py
T
Pine 0ab2c84813 fix(compute): 图标中心 URL 统一 resolve 补全 + 生产库运维脚本
- icon_to_dict/options/create/update 用 resolve_url 补全相对路径
- 新增生产库结构对比/索引修复/建表脚本
2026-09-13 12:23:24 +08:00

83 lines
3.1 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""修复生产数据库索引名称,使其与开发数据库一致。"""
import sys
PROD_HOST = "124.221.143.140"
PORT = 8091
USER = "opc"
PASSWORD = "jjjsgysyujkwjwgb"
DB_NAME = "opc"
PROD_URL = f"mysql+pymysql://{USER}:{PASSWORD}@{PROD_HOST}:{PORT}/{DB_NAME}?charset=utf8mb4"
from sqlalchemy import create_engine, text, inspect
print(f"连接生产数据库: {PROD_HOST}:{PORT}/{DB_NAME}")
print()
engine = create_engine(PROD_URL, pool_pre_ping=True, connect_args={'connect_timeout': 10})
try:
# 需要重命名的索引:旧名称 -> 新名称
index_renames = [
('compute_series', 'idx_compute_series_name', 'ix_compute_series_name'),
('compute_icons', 'idx_compute_icons_name', 'ix_compute_icons_name'),
('compute_icons', 'idx_compute_icons_category', 'ix_compute_icons_category'),
]
inspector = inspect(engine)
for table, old_name, new_name in index_renames:
print(f"处理表 [{table}] 索引: {old_name} -> {new_name}")
# 检查旧索引是否存在
existing_indexes = [idx['name'] for idx in inspector.get_indexes(table)]
if old_name in existing_indexes and new_name not in existing_indexes:
# MySQL 不支持直接重命名索引,需要先删除再创建
# 获取索引的列信息
old_index = next((idx for idx in inspector.get_indexes(table) if idx['name'] == old_name), None)
if old_index:
columns = ', '.join(old_index['column_names'])
with engine.begin() as conn:
# 删除旧索引
conn.execute(text(f"ALTER TABLE {table} DROP INDEX {old_name}"))
# 创建新索引
conn.execute(text(f"CREATE INDEX {new_name} ON {table} ({columns})"))
print(f" ✓ 索引已重命名")
else:
print(f" ⚠️ 找不到旧索引 {old_name} 的详细信息")
elif new_name in existing_indexes:
print(f" ✓ 新索引 {new_name} 已存在,跳过")
# 如果旧索引也存在,删除旧索引
if old_name in existing_indexes:
with engine.begin() as conn:
conn.execute(text(f"ALTER TABLE {table} DROP INDEX {old_name}"))
print(f" ✓ 已删除重复的旧索引 {old_name}")
else:
print(f" ⚠️ 旧索引 {old_name} 不存在,跳过")
# 验证结果
print()
print("验证索引名称...")
inspector = inspect(engine)
for table in ['compute_series', 'compute_icons']:
indexes = inspector.get_indexes(table)
print(f" [{table}] 索引:")
for idx in indexes:
print(f" - {idx['name']}: {idx['column_names']} (unique={idx.get('unique', False)})")
print()
print("=" * 60)
print("✅ 索引名称修复完成!")
print("=" * 60)
except Exception as e:
print(f"❌ 错误: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
finally:
engine.dispose()