From 2ef199e4c5e7bd98d82a51179802b85293c74d20 Mon Sep 17 00:00:00 2001 From: bonamin Date: Fri, 17 Apr 2026 16:01:50 +0300 Subject: [PATCH] fix: login issue --- backend/database/pg_mqtt.py | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/backend/database/pg_mqtt.py b/backend/database/pg_mqtt.py index 5534c4a..0e35f64 100644 --- a/backend/database/pg_mqtt.py +++ b/backend/database/pg_mqtt.py @@ -14,25 +14,13 @@ import json import logging from datetime import date, datetime, timedelta, timezone -from dateutil.relativedelta import relativedelta from sqlalchemy import text -from sqlalchemy.ext.asyncio import AsyncSession - from config import settings from database.postgres import AsyncSessionLocal logger = logging.getLogger("database.pg_mqtt") -# --------------------------------------------------------------------------- -# Internal session helper — used by fire-and-forget insert paths that are -# called from the MQTT ingestion thread (not inside a FastAPI request). -# --------------------------------------------------------------------------- - -async def _session() -> AsyncSession: - return AsyncSessionLocal() - - # --------------------------------------------------------------------------- # Insert operations # --------------------------------------------------------------------------- @@ -302,14 +290,21 @@ async def get_alerts(device_serial: str) -> list: # Partition management # --------------------------------------------------------------------------- +def _add_months(d: date, months: int) -> date: + month = d.month - 1 + months + year = d.year + month // 12 + month = month % 12 + 1 + return d.replace(year=year, month=month, day=1) + + async def ensure_current_partitions(): """Create device_logs partitions for the current and next month if missing.""" async with AsyncSessionLocal() as session: for month_offset in (0, 1): - d = date.today().replace(day=1) + relativedelta(months=month_offset) + d = _add_months(date.today().replace(day=1), month_offset) partition_name = f"device_logs_{d.strftime('%Y_%m')}" start = d.isoformat() - end = (d + relativedelta(months=1)).isoformat() + end = _add_months(d, 1).isoformat() await session.execute(text(f""" CREATE TABLE IF NOT EXISTS {partition_name} PARTITION OF device_logs @@ -321,7 +316,7 @@ async def ensure_current_partitions(): async def drop_old_partitions(keep_months: int = 6): """Drop device_logs partitions older than keep_months.""" - cutoff = date.today().replace(day=1) - relativedelta(months=keep_months) + cutoff = _add_months(date.today().replace(day=1), -keep_months) async with AsyncSessionLocal() as session: result = await session.execute(text(""" SELECT tablename FROM pg_tables