Repository: WeblateOrg/weblate

Issue:
IntegrityError at /projects/X insert or update on table "trans_translation" violates foreign key constraint
### Describe the issue

Found the following weblate exception, I'm not sure if this is actionable without more information, but I still wanted to report it.

```
IntegrityError at /projects/keyoxide/
insert or update on table "trans_translation" violates foreign key constraint "trans_translation_component_id_c4b70a26_fk_trans_component_id"
DETAIL:  Key (component_id)=(258) is not present in table "trans_component".
```

### I already tried

- [X] I've read and searched [the documentation](https://docs.weblate.org/).
- [X] I've searched for similar issues in this repository.

### Steps to reproduce the behavior

Currently unknown.

### Expected behavior

_No response_

### Screenshots

_No response_

### Exception traceback

```pytb
Traceback (most recent call last):
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 880, in _resolve_lookup
    current = current[bit]

During handling of the above exception ('ProjectLanguageStats' object is not subscriptable), another exception occurred:
  File "/usr/local/lib/python3.11/site-packages/weblate/trans/models/component.py", line 990, in source_translation
    return self.translation_set.get(language_id=self.source_language_id)
  File "/usr/local/lib/python3.11/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.11/site-packages/django/db/models/query.py", line 650, in get
    raise self.model.DoesNotExist(

During handling of the above exception (Translation matching query does not exist.), another exception occurred:
  File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)

The above exception (insert or update on table "trans_translation" violates foreign key constraint "trans_translation_component_id_c4b70a26_fk_trans_component_id"
DETAIL:  Key (component_id)=(258) is not present in table "trans_component".
) was the direct cause of the following exception:
  File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 56, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.11/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.11/site-packages/weblate/trans/views/basic.py", line 164, in show_project
    return render(
  File "/usr/local/lib/python3.11/site-packages/weblate/trans/util.py", line 222, in render
    return django_render(request, template, context, status=status)
  File "/usr/local/lib/python3.11/site-packages/django/shortcuts.py", line 24, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/usr/local/lib/python3.11/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/usr/local/lib/python3.11/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 175, in render
    return self._render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/loader_tags.py", line 157, in render
    return compiled_parent._render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/loader_tags.py", line 63, in render
    result = block.nodelist.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/loader_tags.py", line 208, in render
    return template.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 177, in render
    return self._render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/defaulttags.py", line 321, in render
    return nodelist.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/defaulttags.py", line 238, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/defaulttags.py", line 321, in render
    return nodelist.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/defaulttags.py", line 321, in render
    return nodelist.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/defaulttags.py", line 314, in render
    match = condition.eval(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/defaulttags.py", line 877, in eval
    return self.value.resolve(context, ignore_failures=True)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 715, in resolve
    obj = self.var.resolve(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 847, in resolve
    value = self._resolve_lookup(context)
  File "/usr/local/lib/python3.11/site-packages/django/template/base.py", line 890, in _resolve_lookup
    current = getattr(current, bit)
  File "/usr/local/lib/python3.11/site-packages/weblate/utils/stats.py", line 189, in __getattr__
    self.prefetch_basic()
  File "/usr/local/lib/python3.11/site-packages/weblate/utils/stats.py", line 250, in prefetch_basic
    self._prefetch_basic()
  File "/usr/local/lib/python3.11/site-packages/weblate/utils/stats.py", line 856, in _prefetch_basic
    super()._prefetch_basic()
  File "/usr/local/lib/python3.11/site-packages/weblate/utils/stats.py", line 636, in _prefetch_basic
    self.prefetch_source()
  File "/usr/local/lib/python3.11/site-packages/weblate/utils/stats.py", line 847, in prefetch_source
    stats_obj = component.source_translation.stats
  File "/usr/local/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python3.11/site-packages/weblate/trans/models/component.py", line 993, in source_translation
    return self.translation_set.create(
  File "/usr/local/lib/python3.11/site-packages/django/db/models/fields/related_descriptors.py", line 766, in create
    return super(RelatedManager, self.db_manager(db)).create(**kwargs)
  File "/usr/local/lib/python3.11/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.11/site-packages/django/db/models/query.py", line 671, in create
    obj.save(force_insert=True, using=self.db)
  File "/usr/local/lib/python3.11/site-packages/django/db/models/base.py", line 812, in save
    self.save_base(
  File "/usr/local/lib/python3.11/site-packages/django/db/models/base.py", line 863, in save_base
    updated = self._save_table(
  File "/usr/local/lib/python3.11/site-packages/django/db/models/base.py", line 1006, in _save_table
    results = self._do_insert(
  File "/usr/local/lib/python3.11/site-packages/django/db/models/base.py", line 1047, in _do_insert
    return manager._insert(
  File "/usr/local/lib/python3.11/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.11/site-packages/django/db/models/query.py", line 1791, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/usr/local/lib/python3.11/site-packages/django/db/models/sql/compiler.py", line 1660, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(
  File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 84, in _execute
    with self.db.wrap_database_errors:
  File "/usr/local/lib/python3.11/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)

Exception Type: IntegrityError at /projects/keyoxide/
Exception Value: insert or update on table "trans_translation" violates foreign key constraint "trans_translation_component_id_c4b70a26_fk_trans_component_id"
DETAIL:  Key (component_id)=(258) is not present in table "trans_component".

Raised during: weblate.trans.views.basic.show_project
```
```


### How do you run Weblate?

Docker container

### Weblate versions

4.16.2

### Weblate deploy checks

_No response_

### Additional context

Codeberg tracking issue: https://codeberg.org/Codeberg/Community/issues/962


Discussion:

Resolving patch:
diff --git a/weblate/trans/models/component.py b/weblate/trans/models/component.py
--- a/weblate/trans/models/component.py
+++ b/weblate/trans/models/component.py
@@ -20,7 +20,7 @@
 from django.core.cache import cache
 from django.core.exceptions import ObjectDoesNotExist, ValidationError
 from django.core.validators import MaxValueValidator
-from django.db import models, transaction
+from django.db import IntegrityError, models, transaction
 from django.db.models import Count, F, Q
 from django.urls import reverse
 from django.utils.functional import cached_property
@@ -987,17 +987,29 @@ def get_source_translation(self):
 
     @cached_property
     def source_translation(self):
+        # This is basically copy of get_or_create, but avoids additional
+        # SQL query to get source_langauge in case the source translation
+        # already exists. The source_language is only fetched in the slow
+        # path when creating the translation.
         try:
             return self.translation_set.get(language_id=self.source_language_id)
-        except ObjectDoesNotExist:
+        except self.translation_set.model.DoesNotExist:
             language = self.source_language
-            return self.translation_set.create(
-                language=language,
-                check_flags="read-only",
-                filename=self.template,
-                plural=self.file_format_cls.get_plural(language),
-                language_code=language.code,
-            )
+            try:
+                with transaction.atomic():
+                    return self.translation_set.create(
+                        language=language,
+                        check_flags="read-only",
+                        filename=self.template,
+                        plural=self.file_format_cls.get_plural(language),
+                        language_code=language.code,
+                    )
+            except IntegrityError:
+                try:
+                    return self.translation_set.get(language_id=self.source_language_id)
+                except self.translation_set.model.DoesNotExist:
+                    pass
+                raise
 
     def preload_sources(self, sources=None):
         """Preload source objects to improve performance on load."""


Test patch: