Skip to content

Commit

Permalink
fix: remove null=True from UserOrigin.origin_id
Browse files Browse the repository at this point in the history
Possibly a race condition in authentication created duplicate
UserOrigin instances for a user with the same data source.
Since origin_id was null by default, it didn't hit the
data_source & origin_id uniqueness constraint. Null
is not handled the same way as an empty string in postgres.

With an empty string as the default the duplicate issue, which
required manual work to fix, shouldn't happen anymore.

Refs: HAUKI-656
  • Loading branch information
charn committed Jul 26, 2024
1 parent d239a20 commit 60fe755
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 1 deletion.
21 changes: 21 additions & 0 deletions users/migrations/0004_alter_userorigin_origin_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Generated by Django 4.2.13 on 2024-07-25 09:41

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("users", "0003_userorigin"),
]

operations = [
migrations.AlterField(
model_name="userorigin",
name="origin_id",
field=models.CharField(
blank=True, default="", max_length=100, verbose_name="Origin ID"
),
preserve_default=False,
),
]
2 changes: 1 addition & 1 deletion users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class UserOrigin(models.Model):
user = models.ForeignKey(User, related_name="origins", on_delete=models.CASCADE)
data_source = models.ForeignKey("hours.DataSource", on_delete=models.CASCADE)
origin_id = models.CharField(
verbose_name=_("Origin ID"), max_length=100, null=True, blank=True
verbose_name=_("Origin ID"), max_length=100, blank=True
)

class Meta:
Expand Down
6 changes: 6 additions & 0 deletions users/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from pytest_factoryboy import register

from hours.tests.conftest import DataSourceFactory, UserFactory

register(UserFactory)
register(DataSourceFactory)
14 changes: 14 additions & 0 deletions users/tests/test_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import pytest
from django.db import IntegrityError

from users.models import UserOrigin


@pytest.mark.django_db
def test_user_origin_shouldnt_allow_duplicate_empty_origin_id(user, data_source):
"""Duplicate UserOrigin instances shouldn't get created when data source is
the same but origin_id is empty.
"""
UserOrigin.objects.create(user=user, data_source=data_source)
with pytest.raises(IntegrityError):
UserOrigin.objects.create(user=user, data_source=data_source)

0 comments on commit 60fe755

Please sign in to comment.