Check each table name in `table_names` for rows with invalid foreign key references. This method is intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to determine if rows with invalid references were entered w
(self, table_names=None)
| 314 | self.needs_rollback = needs_rollback |
| 315 | |
| 316 | def check_constraints(self, table_names=None): |
| 317 | """ |
| 318 | Check each table name in `table_names` for rows with invalid foreign |
| 319 | key references. This method is intended to be used in conjunction with |
| 320 | `disable_constraint_checking()` and `enable_constraint_checking()`, to |
| 321 | determine if rows with invalid references were entered while constraint |
| 322 | checks were off. |
| 323 | """ |
| 324 | with self.cursor() as cursor: |
| 325 | if table_names is None: |
| 326 | table_names = self.introspection.table_names(cursor) |
| 327 | for table_name in table_names: |
| 328 | primary_key_column_name = self.introspection.get_primary_key_column( |
| 329 | cursor, table_name |
| 330 | ) |
| 331 | if not primary_key_column_name: |
| 332 | continue |
| 333 | relations = self.introspection.get_relations(cursor, table_name) |
| 334 | for column_name, ( |
| 335 | referenced_column_name, |
| 336 | referenced_table_name, |
| 337 | _, |
| 338 | ) in relations.items(): |
| 339 | cursor.execute( |
| 340 | """ |
| 341 | SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING |
| 342 | LEFT JOIN `%s` as REFERRED |
| 343 | ON (REFERRING.`%s` = REFERRED.`%s`) |
| 344 | WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL |
| 345 | """ |
| 346 | % ( |
| 347 | primary_key_column_name, |
| 348 | column_name, |
| 349 | table_name, |
| 350 | referenced_table_name, |
| 351 | column_name, |
| 352 | referenced_column_name, |
| 353 | column_name, |
| 354 | referenced_column_name, |
| 355 | ) |
| 356 | ) |
| 357 | for bad_row in cursor.fetchall(): |
| 358 | raise IntegrityError( |
| 359 | "The row in table '%s' with primary key '%s' has an " |
| 360 | "invalid foreign key: %s.%s contains a value '%s' that " |
| 361 | "does not have a corresponding value in %s.%s." |
| 362 | % ( |
| 363 | table_name, |
| 364 | bad_row[0], |
| 365 | table_name, |
| 366 | column_name, |
| 367 | bad_row[1], |
| 368 | referenced_table_name, |
| 369 | referenced_column_name, |
| 370 | ) |
| 371 | ) |
| 372 | |
| 373 | def is_usable(self): |