Skip to content

Commit 90c8d95

Browse files
committed
WIP - long running migration for setting users to null in audit logs
1 parent 91cfeb8 commit 90c8d95

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from django.conf import settings
2+
from django.db.models.query import QuerySet
3+
4+
from kobo.apps.audit_log.models import AuditLog
5+
from kobo.apps.kobo_auth.shortcuts import User
6+
7+
8+
CHUNK_SIZE = 1000
9+
10+
11+
def process_user(user_id):
12+
AuditLog.objects.filter(user_id=user_id).update(user_id=None)
13+
14+
15+
def get_queryset(from_user_pk: int) -> QuerySet:
16+
users = (
17+
User.objects.order_by('pk')
18+
.filter(
19+
pk__gt=from_user_pk,
20+
# Filter users that have been removed
21+
is_active=False,
22+
extra_details__date_removed__isnull=False,
23+
)
24+
.values('id')[:CHUNK_SIZE]
25+
)
26+
27+
return users
28+
29+
30+
def run():
31+
"""
32+
Set to null user_id for removed users in audit logs
33+
"""
34+
35+
migrated_users = 0
36+
last_pk = 0
37+
adapter = get_adapter()
38+
while True:
39+
users = get_queryset(last_pk)
40+
if not users:
41+
break
42+
43+
users_count = len(users)
44+
last_pk = users[len(users) - 1]['id']
45+
print(f'Processing chunk of {users_count} users ...')
46+
# Let concurrent library automatically decide the number of workers
47+
for user in users
48+
process_user(user['id'])
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from django.db import migrations
2+
3+
4+
def add_long_running_migration(apps, schema_editor):
5+
LongRunningMigration = apps.get_model(
6+
'long_running_migrations', 'LongRunningMigration'
7+
)
8+
LongRunningMigration.objects.create(name='0014_set_null_for_removed_users')
9+
10+
11+
def noop(*args, **kwargs):
12+
pass
13+
14+
15+
class Migration(migrations.Migration):
16+
17+
dependencies = [
18+
('long_running_migrations', '0013_migrate_mfa_data'),
19+
]
20+
21+
operations = [
22+
migrations.RunPython(add_long_running_migration, noop),
23+
]

0 commit comments

Comments
 (0)