1- from django .db import migrations
2-
3-
4- def refresh_collation_and_reindex (apps , schema_editor ):
5- # 获取当前数据库名
6- db_name = schema_editor .connection .settings_dict ["NAME" ]
7- with schema_editor .connection .cursor () as cursor :
8- cursor .execute (f'ALTER DATABASE "{ db_name } " REFRESH COLLATION VERSION;' )
9- cursor .execute (f'REINDEX DATABASE "{ db_name } ";' )
1+ import logging
102
3+ import psycopg
4+ from django .db import migrations
115
12- def noop (apps , schema_editor ):
13- # 不可逆操作,留空
14- pass
6+ from smartdoc .const import CONFIG
7+
8+
9+ def get_connect (db_name ):
10+ conn_params = {
11+ "dbname" : db_name ,
12+ "user" : CONFIG .get ('DB_USER' ),
13+ "password" : CONFIG .get ('DB_PASSWORD' ),
14+ "host" : CONFIG .get ('DB_HOST' ),
15+ "port" : CONFIG .get ('DB_PORT' )
16+ }
17+ # 建立连接
18+ connect = psycopg .connect (** conn_params )
19+ return connect
20+
21+
22+ def sql_execute (conn , reindex_sql : str , alter_database_sql : str ):
23+ """
24+ 执行一条sql
25+ @param reindex_sql:
26+ @param conn:
27+ @param alter_database_sql:
28+ """
29+ conn .autocommit = True
30+ with conn .cursor () as cursor :
31+ cursor .execute (reindex_sql , [])
32+ cursor .execute (alter_database_sql , [])
33+ cursor .close ()
34+
35+ def re_index (apps , schema_editor ):
36+ app_db_name = CONFIG .get ('DB_NAME' )
37+ try :
38+ re_index_database (app_db_name )
39+ except Exception as e :
40+ logging .error (f'reindex database { app_db_name } 发送错误:{ str (e )} ' )
41+ try :
42+ re_index_database ('root' )
43+ except Exception as e :
44+ logging .error (f'reindex database root 发送错误:{ str (e )} ' )
45+
46+
47+ def re_index_database (db_name ):
48+ db_conn = get_connect (db_name )
49+ sql_execute (db_conn , f'REINDEX DATABASE "{ db_name } ";' , f'ALTER DATABASE "{ db_name } " REFRESH COLLATION VERSION;' )
50+ db_conn .close ()
1551
1652
1753class Migration (migrations .Migration ):
18- atomic = False # ALTER DATABASE/REINDEX 需在事务外执行
1954
2055 dependencies = [
2156 ('setting' , '0010_log' ),
2257 ]
2358
2459 operations = [
25- migrations .RunPython (refresh_collation_and_reindex , reverse_code = noop ),
26- ]
60+ migrations .RunPython (re_index , atomic = False )
61+ ]
0 commit comments