Debian Codegraph @

modeltranslation/management/commands/sync_translation_fields.py

raw symbols SCIP
1 """
2 Detect new translatable fields in all models and sync database structure.
3
4 You will need to execute this command in two cases:
5
6 1. When you add new languages to settings.LANGUAGES.
7 2. When you add new translatable fields to your models.
8
9 Credits: Heavily inspired by django-transmeta's sync_transmeta_db command.
10 """
11
12 from __future__ import annotations
13
14 from typing import Any, cast
15 from collections.abc import Iterator
16
17 from django.core.management.base import BaseCommand, CommandParser
18 from django.core.management.color import no_style
19 from django.db import connection
20 from django.db.models import Model, Field
21
22 from modeltranslation.settings import AVAILABLE_LANGUAGES
23 from modeltranslation.translator import translator
24 from modeltranslation.utils import build_localized_fieldname
25
26
27 def ask_for_confirmation(sql_sentences: list[str], model_full_name: str, interactive: bool) -> bool:
28 print('\nSQL to synchronize "%s" schema:' % model_full_name)
29 for sentence in sql_sentences:
30 print(" %s" % sentence)
31 while True:
32 prompt = "\nAre you sure that you want to execute the previous SQL: (y/n) [n]: "
33 if interactive:
34 answer = input(prompt).strip()
35 else:
36 answer = "y"
37 if answer == "":
38 return False
39 elif answer not in ("y", "n", "yes", "no"):
40 print("Please answer yes or no")
41 elif answer == "y" or answer == "yes":
42 return True
43 else:
44 return False
45
46
47 def print_missing_langs(missing_langs: list[str], field_name: str, model_name: str) -> None:
48 print(
49 'Missing languages in "%s" field from "%s" model: %s'
50 % (field_name, model_name, ", ".join(missing_langs))
51 )
52
53
54 class Command(BaseCommand):
55 help = (
56 "Detect new translatable fields or new available languages and"
57 " sync database structure. Does not remove columns of removed"
58 " languages or undeclared fields."
59 )
60
61 def add_arguments(self, parser: CommandParser) -> None:
62 (
63 parser.add_argument(
64 "--noinput",
65 action="store_false",
66 dest="interactive",
67 default=True,
68 help="Do NOT prompt the user for input of any kind.",
69 ),
70 )
71
72 def handle(self, *args: Any, **options: Any) -> None:
73 """
74 Command execution.
75 """
76 self.cursor = connection.cursor()
77 self.introspection = connection.introspection
78 self.interactive = options["interactive"]
79
80 found_missing_fields = False
81 models = translator.get_registered_models(abstract=False)
82 for model in models:
83 db_table = model._meta.db_table
84 model_name = model._meta.model_name
85 model_full_name = "{}.{}".format(model._meta.app_label, model_name)
86 opts = translator.get_options_for_model(model)
87 for field_name, fields in opts.local_fields.items():
88 # Take `db_column` attribute into account
89 try:
90 field = list(fields)[0]
91 except IndexError:
92 # Ignore IndexError for ProxyModel
93 # maybe there is better way to handle this
94 continue
95 column_name = field.db_column if field.db_column else field_name
96 missing_langs = list(self.get_missing_languages(column_name, db_table))
97 if missing_langs:
98 found_missing_fields = True
99 print_missing_langs(missing_langs, field_name, model_full_name)
100 sql_sentences = self.get_sync_sql(field_name, missing_langs, model)
101 execute_sql = ask_for_confirmation(
102 sql_sentences, model_full_name, self.interactive
103 )
104 if execute_sql:
105 print("Executing SQL...")
106 for sentence in sql_sentences:
107 self.cursor.execute(sentence)
108 print("Done")
109 else:
110 print("SQL not executed")
111
112 if not found_missing_fields:
113 print("No new translatable fields detected")
114
115 def get_table_fields(self, db_table: str) -> list[str]:
116 """
117 Gets table fields from schema.
118 """
119 db_table_desc = self.introspection.get_table_description(self.cursor, db_table)
120 return [t[0] for t in db_table_desc]
121
122 def get_missing_languages(self, field_name: str, db_table: str) -> Iterator[str]:
123 """
124 Gets only missing fields.
125 """
126 db_table_fields = self.get_table_fields(db_table)
127 for lang_code in AVAILABLE_LANGUAGES:
128 if build_localized_fieldname(field_name, lang_code) not in db_table_fields:
129 yield lang_code
130
131 def get_sync_sql(
132 self, field_name: str, missing_langs: list[str], model: type[Model]
133 ) -> list[str]:
134 """
135 Returns SQL needed for sync schema for a new translatable field.
136 """
137 qn = connection.ops.quote_name
138 style = no_style()
139 sql_output: list[str] = []
140 db_table = model._meta.db_table
141 for lang in missing_langs:
142 new_field = build_localized_fieldname(field_name, lang)
143 f = cast(Field, model._meta.get_field(new_field))
144 col_type = f.db_type(connection=connection)
145 field_sql = [style.SQL_FIELD(qn(f.column)), style.SQL_COLTYPE(col_type)] # type: ignore[arg-type]
146 # column creation
147 stmt = "ALTER TABLE {} ADD COLUMN {}".format(qn(db_table), " ".join(field_sql))
148 if not f.null:
149 stmt += " " + style.SQL_KEYWORD("NOT NULL")
150 sql_output.append(stmt + ";")
151 return sql_output