Skip to content

IntegrityError in corpus deletion due to elements having types from other corpora

Sentry Issue: ARKINDEX-BACKEND-6H

ForeignKeyViolation: update or delete on table "documents_elementtype" violates foreign key constraint "documents_element_type_id_bc9a4d56_fk_documents_elementtype_id" on table "documents_element"
DETAIL:  Key (id)=(053a6653-e445-46f2-bf99-a7cf8d94616d) is still referenced from table "documents_element".

  File "django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)

IntegrityError: update or delete on table "documents_elementtype" violates foreign key constraint "documents_element_type_id_bc9a4d56_fk_documents_elementtype_id" on table "documents_element"
DETAIL:  Key (id)=(053a6653-e445-46f2-bf99-a7cf8d94616d) is still referenced from table "documents_element".

(6 additional frame(s) were not displayed)
...
  File "django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)

Assuming you have the following two corpora:

  • Corpus A with types folder and file
  • Corpus B with types book and page

Create an element on corpus A with type 'folder', then open the admin page and change the element's corpus to Corpus B. You get an element on Corpus B with a type from corpus A. Trying to delete corpus A will then cause an IntegrityError because this element refers to a type from corpus A.

We can:

  • Make the corpus ID field read only in the admin
  • Update the types on 1 affected element in preprod and 3 affected elements in prod
  • Add code to try to fix this in corpus_delete (Remove elements from other corpora too? Try to change their types?) or in arkindex cleanup

It is likely that some of those elements came from before we made changes in the admin to prevent setting an element's type to a type from another corpus.