fix: 修复索引添加脚本的MySQL语法兼容性

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Jowe
2026-03-13 21:18:45 +08:00
parent ecfb0db1fa
commit e3d1551058

View File

@@ -5,42 +5,40 @@ from app import create_app, db
app = create_app() app = create_app()
def add_index_safe(index_name, table_name, column_name):
"""安全添加索引,如果已存在则跳过"""
try:
# 先检查索引是否存在
result = db.session.execute(db.text(f"""
SELECT COUNT(*) as cnt FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = '{table_name}'
AND index_name = '{index_name}'
""")).fetchone()
if result[0] > 0:
print(f"{index_name} 索引已存在,跳过")
return
# 创建索引
db.session.execute(db.text(f"""
CREATE INDEX {index_name} ON {table_name}({column_name});
"""))
db.session.commit()
print(f"✓ 已添加 {index_name} 索引")
except Exception as e:
db.session.rollback()
print(f"✗ 添加 {index_name} 失败: {e}")
with app.app_context(): with app.app_context():
print("开始添加索引...") print("开始添加索引...\n")
# 为 site_tags 表添加索引 # 为 site_tags 表添加索引
try: add_index_safe('idx_site_tags_site_id', 'site_tags', 'site_id')
db.session.execute(db.text(""" add_index_safe('idx_site_tags_tag_id', 'site_tags', 'tag_id')
CREATE INDEX IF NOT EXISTS idx_site_tags_site_id ON site_tags(site_id);
"""))
print("✓ 已添加 idx_site_tags_site_id 索引")
except Exception as e:
print(f"✗ 添加 idx_site_tags_site_id 失败: {e}")
try:
db.session.execute(db.text("""
CREATE INDEX IF NOT EXISTS idx_site_tags_tag_id ON site_tags(tag_id);
"""))
print("✓ 已添加 idx_site_tags_tag_id 索引")
except Exception as e:
print(f"✗ 添加 idx_site_tags_tag_id 失败: {e}")
# 为 sites 表添加常用查询字段索引 # 为 sites 表添加常用查询字段索引
try: add_index_safe('idx_sites_is_active', 'sites', 'is_active')
db.session.execute(db.text(""" add_index_safe('idx_sites_view_count', 'sites', 'view_count')
CREATE INDEX IF NOT EXISTS idx_sites_is_active ON sites(is_active);
"""))
print("✓ 已添加 idx_sites_is_active 索引")
except Exception as e:
print(f"✗ 添加 idx_sites_is_active 失败: {e}")
try:
db.session.execute(db.text("""
CREATE INDEX IF NOT EXISTS idx_sites_view_count ON sites(view_count);
"""))
print("✓ 已添加 idx_sites_view_count 索引")
except Exception as e:
print(f"✗ 添加 idx_sites_view_count 失败: {e}")
db.session.commit()
print("\n索引添加完成!") print("\n索引添加完成!")