From e6a027943b5b98eebc79eeba364b21a0e7f592a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikolai=20R=C3=B8ed=20Kristiansen?= Date: Mon, 4 Aug 2025 15:04:05 +0200 Subject: [PATCH] fix: Create partitions from the next time unit This fixes initial creation of partitions when there is existing data --- .../shared/shared/django_apps/utils/partitioning.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/libs/shared/shared/django_apps/utils/partitioning.py b/libs/shared/shared/django_apps/utils/partitioning.py index a1bb3010b8..91dbc4ac0b 100644 --- a/libs/shared/shared/django_apps/utils/partitioning.py +++ b/libs/shared/shared/django_apps/utils/partitioning.py @@ -1,3 +1,4 @@ +from datetime import datetime, timezone from dateutil.relativedelta import relativedelta from psqlextra.partitioning import ( PostgresCurrentTimePartitioningStrategy, @@ -10,6 +11,12 @@ from shared.django_apps.upload_breadcrumbs.models import UploadBreadcrumb from shared.django_apps.user_measurements.models import UserMeasurement +class PostgresTimeUnitNextPartitioningStrategy(PostgresCurrentTimePartitioningStrategy): + def get_start_datetime(self) -> datetime: + """ Add 1 of PostgresTimePartitionUnit""" + unit_plus_one = {self.size.unit: 1} + return datetime.now(timezone.utc) + relativedelta(**unit_plus_one) + # Overlapping partitions will cause errors - https://www.postgresql.org/docs/current/ddl-partitioning.html#DDL-PARTITIONING-DECLARATIVE -> "create partitions" # Note that the partitioning manager will not perform the actual creation and deletion of partitions automatically, we have a Celery task for that. manager = PostgresPartitioningManager( @@ -19,7 +26,7 @@ # Partitions will be named `[table_name]_[year]_[3-letter month name]` PostgresPartitioningConfig( model=UserMeasurement, - strategy=PostgresCurrentTimePartitioningStrategy( + strategy=PostgresTimeUnitNextPartitioningStrategy( size=PostgresTimePartitionSize(months=1), count=12, max_age=relativedelta(months=12), @@ -30,7 +37,7 @@ # Partitions will be named `[table_name]_[year]_[3-letter month name]` PostgresPartitioningConfig( model=DailyTestRollup, - strategy=PostgresCurrentTimePartitioningStrategy( + strategy=PostgresTimeUnitNextPartitioningStrategy( size=PostgresTimePartitionSize(months=1), count=3, max_age=relativedelta(months=3), @@ -41,7 +48,7 @@ # Partitions will be named `[table_name]_[year]_week_[week number]` PostgresPartitioningConfig( model=UploadBreadcrumb, - strategy=PostgresCurrentTimePartitioningStrategy( + strategy=PostgresTimeUnitNextPartitioningStrategy( size=PostgresTimePartitionSize(weeks=1), count=3, max_age=relativedelta(months=3),