Skip to content

Commit

Permalink
[fix] Added data migration to deal with DeviceConnection.unique_toget…
Browse files Browse the repository at this point in the history
…her #846

In PR #806,
a unique_together constraint was added to the DeviceConnection model
to ensure that adding more than one row with the same
device_id and credentials_id in the database is not allowed.

However, applying the migration may fail if the database already contains
objects that contradict this unique constraint.

To address this, we have added a data migration step to remove the
conflicting objects from the database before applying the migration.

Unfortunately this change may not be fully backward compatible
for those who are using the development version, if you incur
in any issue while running the migrations, you can fix this with:

./manage.py migrate --fake connection 0009
./manage.py migrate

Fixes #846

Co-authored-by: Federico Capoano <[email protected]>
  • Loading branch information
Dhanus3133 and nemesifier committed May 21, 2024
1 parent f0bdf03 commit c4a1683
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from django.db import migrations, models


def remove_conflicting_deviceconnections(apps, schema_editor):
DeviceConnection = apps.get_model('connection', 'DeviceConnection')
duplicates = (
DeviceConnection.objects.values('device_id', 'credentials_id')
.annotate(count=models.Count('id'))
.filter(count__gt=1)
)
for duplicate in duplicates:
# Get all instances of this duplicate and order them by oldest to newest
instances = DeviceConnection.objects.filter(
device_id=duplicate['device_id'], credentials_id=duplicate['credentials_id']
).order_by('created')
# Keep the old instance and delete the rest
for instance in instances[1:]:
instance.delete()


class Migration(migrations.Migration):

dependencies = [
('connection', '0007_command'),
]

operations = [
migrations.RunPython(
remove_conflicting_deviceconnections, reverse_code=migrations.RunPython.noop
),
]
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.CONFIG_DEVICE_MODEL),
('connection', '0007_command'),
('connection', '0008_remove_conflicting_deviceconnections'),
]

operations = [
Expand Down

0 comments on commit c4a1683

Please sign in to comment.