Ticket #33789: generate_rename_table_colums_new_trunc.py

File generate_rename_table_colums_new_trunc.py, 2.0 KB (added by Mariusz Felisiak, 2 years ago)
Line 
1from django.apps import apps
2from django.db import connection
3from django.db.backends.utils import strip_quotes, truncate_name
4
5
6rename_table_sql = "ALTER TABLE %s RENAME TO %s;"
7rename_column_sql = "ALTER TABLE %s RENAME COLUMN %s to %s;"
8max_name_length = connection.ops.max_name_length()
9
10
11def 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
18table_renames = []
19column_renames = []
20
21with 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
53print("-- RENAME tables")
54for sql in table_renames:
55 print(sql)
56
57print("-- RENAME columns")
58for sql in column_renames:
59 print(sql)
Back to Top