from django.apps import apps
from django.db import connection
from django.db.backends.utils import strip_quotes, truncate_name


rename_table_sql = "ALTER TABLE %s RENAME TO %s;"
rename_column_sql = "ALTER TABLE %s RENAME COLUMN %s to %s;"
max_name_length = connection.ops.max_name_length()


def old_quote_name(name):
    if not name.startswith('"') and not name.endswith('"'):
        name = '"%s"' % truncate_name(name.upper(), max_name_length)
    name = name.replace("%", "%%")
    return name.upper()


table_renames = []
column_renames = []

with connection.cursor() as cursor:
    table_list = connection.introspection.get_table_list(cursor)

    for _model in apps.get_models(include_auto_created=True):
        # Table names.
        db_table = _model._meta.db_table
        new_quoted_name = connection.ops.quote_name(db_table)
        old_quoted_name = new_quoted_name
        if len(db_table) > max_name_length:
            if new_quoted_name.lower() not in table_list:
                old_quoted_name = old_quote_name(_model._meta.db_table)
                table_renames.append(
                    rename_table_sql % (old_quoted_name, new_quoted_name)
                )

        # Column names:
        column_list = connection.introspection.get_table_description(
            cursor, strip_quotes(old_quoted_name)
        )
        for field in _model._meta.local_fields:
            if len(field.column) > max_name_length:
                field_quoted_name = connection.ops.quote_name(field.column)
                if field_quoted_name.lower() not in column_list:
                    column_renames.append(
                        rename_column_sql
                        % (
                            new_quoted_name,
                            old_quote_name(field.column),
                            field_quoted_name,
                        )
                    )

print("-- RENAME tables")
for sql in table_renames:
    print(sql)

print("-- RENAME columns")
for sql in column_renames:
    print(sql)
