|
| 1 | +import logging |
| 2 | + |
| 3 | +import psycopg |
| 4 | +from psycopg import sql |
| 5 | +from django.db import migrations |
| 6 | + |
| 7 | +from maxkb.const import CONFIG |
| 8 | + |
| 9 | + |
| 10 | +def get_connect(db_name): |
| 11 | + return psycopg.connect( |
| 12 | + dbname=db_name, |
| 13 | + user=CONFIG.get('DB_USER'), |
| 14 | + password=CONFIG.get('DB_PASSWORD'), |
| 15 | + host=CONFIG.get('DB_HOST'), |
| 16 | + port=CONFIG.get('DB_PORT'), |
| 17 | + autocommit=True, |
| 18 | + ) |
| 19 | + |
| 20 | + |
| 21 | +def has_collation_version_mismatch(conn): |
| 22 | + with conn.cursor() as cursor: |
| 23 | + cursor.execute( |
| 24 | + """ |
| 25 | + SELECT datcollversion IS DISTINCT FROM pg_database_collation_actual_version(oid) |
| 26 | + FROM pg_database |
| 27 | + WHERE datname = current_database() |
| 28 | + """ |
| 29 | + ) |
| 30 | + result = cursor.fetchone() |
| 31 | + return result is not None and result[0] |
| 32 | + |
| 33 | + |
| 34 | +def refresh_database_collation(db_name): |
| 35 | + with get_connect(db_name) as conn: |
| 36 | + if not has_collation_version_mismatch(conn): |
| 37 | + return |
| 38 | + with conn.cursor() as cursor: |
| 39 | + database_identifier = sql.Identifier(db_name) |
| 40 | + cursor.execute(sql.SQL("REINDEX DATABASE {}").format(database_identifier)) |
| 41 | + cursor.execute(sql.SQL("ALTER DATABASE {} REFRESH COLLATION VERSION").format(database_identifier)) |
| 42 | + |
| 43 | + |
| 44 | +def refresh_collation(apps, schema_editor): |
| 45 | + app_db_name = CONFIG.get('DB_NAME') |
| 46 | + refresh_database_collation(app_db_name) |
| 47 | + if app_db_name == 'root': |
| 48 | + return |
| 49 | + try: |
| 50 | + refresh_database_collation('root') |
| 51 | + except Exception: |
| 52 | + logging.exception('Failed to refresh collation version for database root') |
| 53 | + |
| 54 | + |
| 55 | +class Migration(migrations.Migration): |
| 56 | + dependencies = [ |
| 57 | + ('system_manage', '0005_resourcemapping'), |
| 58 | + ] |
| 59 | + |
| 60 | + operations = [ |
| 61 | + migrations.RunPython(refresh_collation, reverse_code=migrations.RunPython.noop, atomic=False), |
| 62 | + ] |
0 commit comments