0002_refresh_collation_reindex.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import logging
  2. import psycopg
  3. from django.db import migrations
  4. from maxkb.const import CONFIG
  5. def get_connect(db_name):
  6. conn_params = {
  7. "dbname": db_name,
  8. "user": CONFIG.get('DB_USER'),
  9. "password": CONFIG.get('DB_PASSWORD'),
  10. "host": CONFIG.get('DB_HOST'),
  11. "port": CONFIG.get('DB_PORT')
  12. }
  13. # 建立连接
  14. connect = psycopg.connect(**conn_params)
  15. return connect
  16. def sql_execute(conn, reindex_sql: str, alter_database_sql: str):
  17. """
  18. 执行一条sql
  19. @param reindex_sql:
  20. @param conn:
  21. @param alter_database_sql:
  22. """
  23. conn.autocommit = True
  24. with conn.cursor() as cursor:
  25. cursor.execute(reindex_sql, [])
  26. cursor.execute(alter_database_sql, [])
  27. cursor.close()
  28. def re_index(apps, schema_editor):
  29. app_db_name = CONFIG.get('DB_NAME')
  30. try:
  31. re_index_database(app_db_name)
  32. except Exception as e:
  33. logging.error(f'reindex database {app_db_name}发送错误:{str(e)}')
  34. try:
  35. re_index_database('root')
  36. except Exception as e:
  37. logging.error(f'reindex database root 发送错误:{str(e)}')
  38. def re_index_database(db_name):
  39. db_conn = get_connect(db_name)
  40. sql_execute(db_conn, f'REINDEX DATABASE "{db_name}";', f'ALTER DATABASE "{db_name}" REFRESH COLLATION VERSION;')
  41. db_conn.close()
  42. class Migration(migrations.Migration):
  43. dependencies = [
  44. ("system_manage", "0001_initial"),
  45. ]
  46. operations = [
  47. migrations.RunPython(re_index, atomic=False)
  48. ]