authentic/src/authentic2/apps.py

64 lines
2.3 KiB
Python

import re
from django.apps import AppConfig
from django.views import debug
from django.db import connection
from django.db.models.signals import post_migrate
from . import plugins, compat
class Authentic2Config(AppConfig):
name = 'authentic2'
verbose_name = 'Authentic2'
def post_migrate_update_json_column(self, sender, **kwargs):
# adapted from https://github.com/kbussell/django-jsonfield-compat/blob/4f6ac4bfaea2224559b174b6d16d846b93d125c6/jsonfield_compat/convert.py
# MIT License, kbussel
if connection.vendor != 'postgresql':
return
if compat.has_postgresql_support():
expected_type = 'JSONB'
else:
expected_type = 'TEXT'
def convert_column_to_json(model, column_name):
table_name = model._meta.db_table
with connection.cursor() as cursor:
cursor.execute(
"select data_type from information_schema.columns "
"where table_name = %s and column_name = %s;",
[table_name, column_name])
current_type = cursor.fetchone()[0].upper()
if current_type != expected_type:
print("{app}: Converting {col} to use native {type} field".format(
app=model._meta.app_label, col=column_name, type=expected_type))
cursor.execute(
"ALTER TABLE {table} ALTER COLUMN {col} "
"TYPE {type} USING {col}::{type};".format(
table=table_name, col=column_name, type=expected_type
)
)
def convert_model_json_fields(model):
json_fields = [f for f in model._meta.fields if f.__class__ == compat.JSONField]
for field in json_fields:
_, column_name = field.get_attname_column()
convert_column_to_json(model, column_name)
for model in list(sender.get_models()):
convert_model_json_fields(model)
def ready(self):
plugins.init()
debug.HIDDEN_SETTINGS = re.compile(
'API|TOKEN|KEY|SECRET|PASS|PROFANITIES_LIST|SIGNATURE|LDAP')
post_migrate.connect(self.post_migrate_update_json_column)