Skip to content

Commit

Permalink
Use previous migration date for lower bound range
Browse files Browse the repository at this point in the history
  • Loading branch information
noliveleger committed Oct 6, 2023
1 parent 8be441d commit f90d0e0
Showing 1 changed file with 13 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.db import migrations
from django.db.migrations.recorder import MigrationRecorder
from django.db.models import Sum
from django.db.models import Value, F, DateField
from django.db.models.functions import Cast, Concat
Expand All @@ -11,25 +12,29 @@ def populate_missing_monthly_counters(apps, schema_editor):
DailyXFormSubmissionCounter = apps.get_model('logger', 'DailyXFormSubmissionCounter') # noqa
MonthlyXFormSubmissionCounter = apps.get_model('logger', 'MonthlyXFormSubmissionCounter') # noqa

first_daily_counter = DailyXFormSubmissionCounter.objects.order_by(
'date'
).first()

if not first_daily_counter:
if not DailyXFormSubmissionCounter.objects.all().exists():
return

previous_migration = MigrationRecorder.Migration.objects.filter(
app='logger', name='0029_populate_daily_xform_counters_for_year'
).first()

# Delete monthly counters in the range if any (to avoid conflicts in bulk_create below)
MonthlyXFormSubmissionCounter.objects.annotate(
date=Cast(
Concat(
F('year'), Value('-'), F('month'), Value('-'), 1
),
DateField(),
)
).filter(date__gte=first_daily_counter.date.replace(day=1)).delete()
).filter(date__gte=previous_migration.applied.date().replace(day=1)).delete()

records = (
DailyXFormSubmissionCounter.objects.filter(
date__range=[first_daily_counter.date.replace(day=1), now().date()]
date__range=[
previous_migration.applied.date().replace(day=1),
now().date()
]
)
.annotate(year=ExtractYear('date'), month=ExtractMonth('date'))
.values('month', 'year')
Expand All @@ -39,7 +44,7 @@ def populate_missing_monthly_counters(apps, schema_editor):

# Do not use `ignore_conflicts=True` to ensure all counters are successfully
# create.
# TODO use `update_conflicts` with Django 4.2
# TODO use `update_conflicts` with Django 4.2 and avoid `.delete()` above
MonthlyXFormSubmissionCounter.objects.bulk_create(
[
MonthlyXFormSubmissionCounter(
Expand Down

0 comments on commit f90d0e0

Please sign in to comment.