fix: refactor database collation refresh and reindex logic with improved error handling

This commit is contained in:
CaptainB 2025-08-19 15:48:38 +08:00
parent b9fcd68418
commit 7fc1d89659

View File

@ -1,26 +1,61 @@
import logging
import psycopg
from django.db import migrations
def refresh_collation_and_reindex(apps, schema_editor):
# 获取当前数据库名
db_name = schema_editor.connection.settings_dict["NAME"]
with schema_editor.connection.cursor() as cursor:
cursor.execute(f'ALTER DATABASE "{db_name}" REFRESH COLLATION VERSION;')
cursor.execute(f'REINDEX DATABASE "{db_name}";')
from maxkb.const import CONFIG
def noop(apps, schema_editor):
# 不可逆操作,留空
pass
def get_connect(db_name):
conn_params = {
"dbname": db_name,
"user": CONFIG.get('DB_USER'),
"password": CONFIG.get('DB_PASSWORD'),
"host": CONFIG.get('DB_HOST'),
"port": CONFIG.get('DB_PORT')
}
# 建立连接
connect = psycopg.connect(**conn_params)
return connect
def sql_execute(conn, reindex_sql: str, alter_database_sql: str):
"""
执行一条sql
@param reindex_sql:
@param conn:
@param alter_database_sql:
"""
conn.autocommit = True
with conn.cursor() as cursor:
cursor.execute(reindex_sql, [])
cursor.execute(alter_database_sql, [])
cursor.close()
def re_index(apps, schema_editor):
app_db_name = CONFIG.get('DB_NAME')
try:
re_index_database(app_db_name)
except Exception as e:
logging.error(f'reindex database {app_db_name}发送错误:{str(e)}')
try:
re_index_database('root')
except Exception as e:
logging.error(f'reindex database root 发送错误:{str(e)}')
def re_index_database(db_name):
db_conn = get_connect(db_name)
sql_execute(db_conn, f'REINDEX DATABASE "{db_name}";', f'ALTER DATABASE "{db_name}" REFRESH COLLATION VERSION;')
db_conn.close()
class Migration(migrations.Migration):
atomic = False # ALTER DATABASE/REINDEX 需在事务外执行
dependencies = [
("system_manage", "0001_initial"),
]
operations = [
migrations.RunPython(refresh_collation_and_reindex, reverse_code=noop),
]
migrations.RunPython(re_index, atomic=False)
]