Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add data migration to purge deleted submissions #744

Merged
merged 1 commit into from
Jun 30, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions onadata/apps/logger/migrations/0019_purge_deleted_instances.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Generated by Django 2.2.14 on 2021-06-30 19:00
from django.conf import settings
from django.db import migrations


def purge_deleted_instances(apps, schema_editor):
"""
Remove all submissions that have been already marked as deleted from both
PostgreSQL and MongoDB. If this is too slow, revert to a previous release
and run the code in
https://github.com/kobotoolbox/kobocat/issues/696#issuecomment-809622367
using `manage.py shell_plus`.
"""
Instance = apps.get_model('logger', 'Instance')
to_purge = Instance.objects.exclude(deleted_at=None).only('pk')
if not to_purge.exists():
return
print(
f'Purging {to_purge.count()} deleted instances...', end='', flush=True
)
Comment on lines +18 to +20
Copy link
Contributor

@noliveleger noliveleger Jun 30, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI: I cannot see the output of these print .
In other migrations, we used sys.stdout.write and sys.stderr.write

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, I'm only now seeing this! I'm surprised you couldn't see it the output if count was greater than zero on your database, but print() certainly doesn't seem ideal to use here (although neither does sys.stdout.write 😉). I guess migrations are part of a management command and theoretically ought to have access somehow to self.stdout provided somewhere by the BaseCommand class.

Be more insistent that I acknowledge your feedback next time 😛

for instance in to_purge.iterator():
# Manually delete from MongoDB because signals are not called in
# migrations (that would require freezing all application code, not
# just the models!)
settings.MONGO_DB.instances.delete_one({'_id': instance.pk})
instance.delete()
print('Done!', flush=True)


def do_nothing(apps, schema_editor):
pass


class Migration(migrations.Migration):
dependencies = [
('logger', '0018_add_submission_counter'),
]
operations = [
migrations.RunPython(
purge_deleted_instances, reverse_code=do_nothing
),
]