Debian Codegraph @

django/db/backends/ddl_references.py

raw
1 """
2 Helpers to manipulate deferred DDL statements that might need to be adjusted or
3 discarded within when executing a migration.
4 """
5
6 from copy import deepcopy
7
8
9 class Reference:
10 """Base class that defines the reference interface."""
11
12 def references_table(self, table):
13 """
14 Return whether or not this instance references the specified table.
15 """
16 return False
17
18 def references_column(self, table, column):
19 """
20 Return whether or not this instance references the specified column.
21 """
22 return False
23
24 def references_index(self, table, index):
25 """
26 Return whether or not this instance references the specified index.
27 """
28 return False
29
30 def rename_table_references(self, old_table, new_table):
31 """
32 Rename all references to the old_name to the new_table.
33 """
34 pass
35
36 def rename_column_references(self, table, old_column, new_column):
37 """
38 Rename all references to the old_column to the new_column.
39 """
40 pass
41
42 def __repr__(self):
43 return "<%s %r>" % (self.__class__.__name__, str(self))
44
45 def __str__(self):
46 raise NotImplementedError(
47 "Subclasses must define how they should be converted to string."
48 )
49
50
51 class Table(Reference):
52 """Hold a reference to a table."""
53
54 def __init__(self, table, quote_name):
55 self.table = table
56 self.quote_name = quote_name
57
58 def references_table(self, table):
59 return self.table == table
60
61 def references_index(self, table, index):
62 return self.references_table(table) and str(self) == index
63
64 def rename_table_references(self, old_table, new_table):
65 if self.table == old_table:
66 self.table = new_table
67
68 def __str__(self):
69 return self.quote_name(self.table)
70
71
72 class TableColumns(Table):
73 """Base class for references to multiple columns of a table."""
74
75 def __init__(self, table, columns):
76 self.table = table
77 self.columns = columns
78
79 def references_column(self, table, column):
80 return self.table == table and column in self.columns
81
82 def rename_column_references(self, table, old_column, new_column):
83 if self.table == table:
84 for index, column in enumerate(self.columns):
85 if column == old_column:
86 self.columns[index] = new_column
87
88
89 class Columns(TableColumns):
90 """Hold a reference to one or many columns."""
91
92 def __init__(self, table, columns, quote_name, col_suffixes=()):
93 self.quote_name = quote_name
94 self.col_suffixes = col_suffixes
95 super().__init__(table, columns)
96
97 def __str__(self):
98 def col_str(column, idx):
99 col = self.quote_name(column)
100 try:
101 suffix = self.col_suffixes[idx]
102 if suffix:
103 col = "{} {}".format(col, suffix)
104 except IndexError:
105 pass
106 return col
107
108 return ", ".join(
109 col_str(column, idx) for idx, column in enumerate(self.columns)
110 )
111
112
113 class IndexName(TableColumns):
114 """Hold a reference to an index name."""
115
116 def __init__(self, table, columns, suffix, create_index_name):
117 self.suffix = suffix
118 self.create_index_name = create_index_name
119 super().__init__(table, columns)
120
121 def __str__(self):
122 return self.create_index_name(self.table, self.columns, self.suffix)
123
124
125 class IndexColumns(Columns):
126 def __init__(self, table, columns, quote_name, col_suffixes=(), opclasses=()):
127 self.opclasses = opclasses
128 super().__init__(table, columns, quote_name, col_suffixes)
129
130 def __str__(self):
131 def col_str(column, idx):
132 # Index.__init__() guarantees that self.opclasses is the same
133 # length as self.columns.
134 col = "{} {}".format(self.quote_name(column), self.opclasses[idx])
135 try:
136 suffix = self.col_suffixes[idx]
137 if suffix:
138 col = "{} {}".format(col, suffix)
139 except IndexError:
140 pass
141 return col
142
143 return ", ".join(
144 col_str(column, idx) for idx, column in enumerate(self.columns)
145 )
146
147
148 class ForeignKeyName(TableColumns):
149 """Hold a reference to a foreign key name."""
150
151 def __init__(
152 self,
153 from_table,
154 from_columns,
155 to_table,
156 to_columns,
157 suffix_template,
158 create_fk_name,
159 ):
160 self.to_reference = TableColumns(to_table, to_columns)
161 self.suffix_template = suffix_template
162 self.create_fk_name = create_fk_name
163 super().__init__(
164 from_table,
165 from_columns,
166 )
167
168 def references_table(self, table):
169 return super().references_table(table) or self.to_reference.references_table(
170 table
171 )
172
173 def references_column(self, table, column):
174 return super().references_column(
175 table, column
176 ) or self.to_reference.references_column(table, column)
177
178 def rename_table_references(self, old_table, new_table):
179 super().rename_table_references(old_table, new_table)
180 self.to_reference.rename_table_references(old_table, new_table)
181
182 def rename_column_references(self, table, old_column, new_column):
183 super().rename_column_references(table, old_column, new_column)
184 self.to_reference.rename_column_references(table, old_column, new_column)
185
186 def __str__(self):
187 suffix = self.suffix_template % {
188 "to_table": self.to_reference.table,
189 "to_column": self.to_reference.columns[0],
190 }
191 return self.create_fk_name(self.table, self.columns, suffix)
192
193
194 class Statement(Reference):
195 """
196 Statement template and formatting parameters container.
197
198 Allows keeping a reference to a statement without interpolating identifiers
199 that might have to be adjusted if they're referencing a table or column
200 that is removed
201 """
202
203 def __init__(self, template, **parts):
204 self.template = template
205 self.parts = parts
206
207 def references_table(self, table):
208 return any(
209 hasattr(part, "references_table") and part.references_table(table)
210 for part in self.parts.values()
211 )
212
213 def references_column(self, table, column):
214 return any(
215 hasattr(part, "references_column") and part.references_column(table, column)
216 for part in self.parts.values()
217 )
218
219 def references_index(self, table, index):
220 return any(
221 hasattr(part, "references_index") and part.references_index(table, index)
222 for part in self.parts.values()
223 )
224
225 def rename_table_references(self, old_table, new_table):
226 for part in self.parts.values():
227 if hasattr(part, "rename_table_references"):
228 part.rename_table_references(old_table, new_table)
229
230 def rename_column_references(self, table, old_column, new_column):
231 for part in self.parts.values():
232 if hasattr(part, "rename_column_references"):
233 part.rename_column_references(table, old_column, new_column)
234
235 def __str__(self):
236 return self.template % self.parts
237
238
239 class Expressions(TableColumns):
240 def __init__(self, table, expressions, compiler, quote_value):
241 self.compiler = compiler
242 self.expressions = expressions
243 self.quote_value = quote_value
244 columns = [
245 col.target.column
246 for col in self.compiler.query._gen_cols([self.expressions])
247 ]
248 super().__init__(table, columns)
249
250 def rename_table_references(self, old_table, new_table):
251 if self.table != old_table:
252 return
253 self.expressions = self.expressions.relabeled_clone({old_table: new_table})
254 super().rename_table_references(old_table, new_table)
255
256 def rename_column_references(self, table, old_column, new_column):
257 if self.table != table:
258 return
259 expressions = deepcopy(self.expressions)
260 self.columns = []
261 for col in self.compiler.query._gen_cols([expressions]):
262 if col.target.column == old_column:
263 col.target.column = new_column
264 self.columns.append(col.target.column)
265 self.expressions = expressions
266
267 def __str__(self):
268 sql, params = self.compiler.compile(self.expressions)
269 params = map(self.quote_value, params)
270 return sql % tuple(params)