1 | from django.apps import apps
|
---|
2 | from django.db import connection
|
---|
3 | from django.db.backends.utils import strip_quotes, truncate_name
|
---|
4 |
|
---|
5 |
|
---|
6 | rename_table_sql = "ALTER TABLE %s RENAME TO %s;"
|
---|
7 | rename_column_sql = "ALTER TABLE %s RENAME COLUMN %s to %s;"
|
---|
8 | max_name_length = connection.ops.max_name_length()
|
---|
9 |
|
---|
10 |
|
---|
11 | def old_quote_name(name):
|
---|
12 | if not name.startswith('"') and not name.endswith('"'):
|
---|
13 | name = '"%s"' % truncate_name(name.upper(), max_name_length)
|
---|
14 | name = name.replace("%", "%%")
|
---|
15 | return name.upper()
|
---|
16 |
|
---|
17 |
|
---|
18 | table_renames = []
|
---|
19 | column_renames = []
|
---|
20 |
|
---|
21 | with connection.cursor() as cursor:
|
---|
22 | table_list = connection.introspection.get_table_list(cursor)
|
---|
23 |
|
---|
24 | for _model in apps.get_models(include_auto_created=True):
|
---|
25 | # Table names.
|
---|
26 | db_table = _model._meta.db_table
|
---|
27 | new_quoted_name = connection.ops.quote_name(db_table)
|
---|
28 | old_quoted_name = new_quoted_name
|
---|
29 | if len(db_table) > max_name_length:
|
---|
30 | if new_quoted_name.lower() not in table_list:
|
---|
31 | old_quoted_name = old_quote_name(_model._meta.db_table)
|
---|
32 | table_renames.append(
|
---|
33 | rename_table_sql % (old_quoted_name, new_quoted_name)
|
---|
34 | )
|
---|
35 |
|
---|
36 | # Column names:
|
---|
37 | column_list = connection.introspection.get_table_description(
|
---|
38 | cursor, strip_quotes(old_quoted_name)
|
---|
39 | )
|
---|
40 | for field in _model._meta.local_fields:
|
---|
41 | if len(field.column) > max_name_length:
|
---|
42 | field_quoted_name = connection.ops.quote_name(field.column)
|
---|
43 | if field_quoted_name.lower() not in column_list:
|
---|
44 | column_renames.append(
|
---|
45 | rename_column_sql
|
---|
46 | % (
|
---|
47 | new_quoted_name,
|
---|
48 | old_quote_name(field.column),
|
---|
49 | field_quoted_name,
|
---|
50 | )
|
---|
51 | )
|
---|
52 |
|
---|
53 | print("-- RENAME tables")
|
---|
54 | for sql in table_renames:
|
---|
55 | print(sql)
|
---|
56 |
|
---|
57 | print("-- RENAME columns")
|
---|
58 | for sql in column_renames:
|
---|
59 | print(sql)
|
---|