fix: refactor database collation refresh and reindex logic with improved error handling
This commit is contained in:
parent
b9fcd68418
commit
7fc1d89659
@ -1,26 +1,61 @@
|
|||||||
|
import logging
|
||||||
|
|
||||||
|
import psycopg
|
||||||
from django.db import migrations
|
from django.db import migrations
|
||||||
|
|
||||||
|
from maxkb.const import CONFIG
|
||||||
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}";')
|
|
||||||
|
|
||||||
|
|
||||||
def noop(apps, schema_editor):
|
def get_connect(db_name):
|
||||||
# 不可逆操作,留空
|
conn_params = {
|
||||||
pass
|
"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):
|
class Migration(migrations.Migration):
|
||||||
atomic = False # ALTER DATABASE/REINDEX 需在事务外执行
|
|
||||||
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
("system_manage", "0001_initial"),
|
("system_manage", "0001_initial"),
|
||||||
]
|
]
|
||||||
|
|
||||||
operations = [
|
operations = [
|
||||||
migrations.RunPython(refresh_collation_and_reindex, reverse_code=noop),
|
migrations.RunPython(re_index, atomic=False)
|
||||||
]
|
]
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user