From e3d1551058b715cfc5f8131c2cfb78495e46b991 Mon Sep 17 00:00:00 2001 From: Jowe <123822645+Selei1983@users.noreply.github.com> Date: Fri, 13 Mar 2026 21:18:45 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E7=B4=A2=E5=BC=95?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=84=9A=E6=9C=AC=E7=9A=84MySQL=E8=AF=AD?= =?UTF-8?q?=E6=B3=95=E5=85=BC=E5=AE=B9=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 4.6 --- add_site_tags_indexes.py | 62 +++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/add_site_tags_indexes.py b/add_site_tags_indexes.py index 3a0e719..6b9245c 100644 --- a/add_site_tags_indexes.py +++ b/add_site_tags_indexes.py @@ -5,42 +5,40 @@ from app import create_app, db 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(): - print("开始添加索引...") + print("开始添加索引...\n") # 为 site_tags 表添加索引 - try: - db.session.execute(db.text(""" - 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}") + add_index_safe('idx_site_tags_site_id', 'site_tags', 'site_id') + add_index_safe('idx_site_tags_tag_id', 'site_tags', 'tag_id') # 为 sites 表添加常用查询字段索引 - try: - db.session.execute(db.text(""" - 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}") + add_index_safe('idx_sites_is_active', 'sites', 'is_active') + add_index_safe('idx_sites_view_count', 'sites', 'view_count') - 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索引添加完成!")