From c043579d65f4c0e55c2acbccb55e93f9101cbe10 Mon Sep 17 00:00:00 2001 From: Mirko Stamm Date: Tue, 20 Oct 2026 10:09:32 +0100 Subject: [PATCH] fix(db): DATABASE_URL fallback and alembic baseline squash - Build engine URL from POSTGRES_* vars when DATABASE_URL is unset, with a clear RuntimeError when neither source is available - Replace shared sessionlocal instance with SessionLocal factory in tasks.py and socket_manager.py (per-call sessions, worker-safe) - Squash 17 broken migration chains (two disconnected roots, no base tables) into a single 0001-style baseline matching current models; legacy migrations moved to alembic/legacy/versions/ for reference --- ...26e_task_and_user_modified_to_have_one_.py | 0 .../{ => legacy}/versions/4033d9ff7961_.py | 0 .../412868709e85_task_with_due_date_null.py | 0 .../{ => legacy}/versions/4ea1d38c82ed_.py | 0 ...432a6f92_agregado_eliminacion_en_labels.py | 0 .../{ => legacy}/versions/5128ff2bed08_.py | 0 ...44786b0f93_register_notifications_table.py | 0 .../{ => legacy}/versions/6a0c4820346e_.py | 0 .../{ => legacy}/versions/7a739d51991b_.py | 0 .../{ => legacy}/versions/820a9cff9606_.py | 0 .../versions/8cac2b8b6ff2_temp_baseline.py | 0 .../{ => legacy}/versions/aaf7bb5ea051_.py | 0 .../{ => legacy}/versions/ad7bba107fd2_.py | 0 .../{ => legacy}/versions/d67c6981a1c5_.py | 0 .../{ => legacy}/versions/da1879cc255c_.py | 0 .../{ => legacy}/versions/ddbb9579a2d3_.py | 0 .../{ => legacy}/versions/e324270afb11_.py | 0 alembic/versions/1045577547bf_baseline.py | 157 ++++++++++++++++++ core/socket_manager.py | 4 +- db/database.py | 29 ++-- tasks.py | 4 +- 21 files changed, 176 insertions(+), 18 deletions(-) rename alembic/{ => legacy}/versions/0ca9a9a1726e_task_and_user_modified_to_have_one_.py (100%) rename alembic/{ => legacy}/versions/4033d9ff7961_.py (100%) rename alembic/{ => legacy}/versions/412868709e85_task_with_due_date_null.py (100%) rename alembic/{ => legacy}/versions/4ea1d38c82ed_.py (100%) rename alembic/{ => legacy}/versions/511f432a6f92_agregado_eliminacion_en_labels.py (100%) rename alembic/{ => legacy}/versions/5128ff2bed08_.py (100%) rename alembic/{ => legacy}/versions/5c44786b0f93_register_notifications_table.py (100%) rename alembic/{ => legacy}/versions/6a0c4820346e_.py (100%) rename alembic/{ => legacy}/versions/7a739d51991b_.py (100%) rename alembic/{ => legacy}/versions/820a9cff9606_.py (100%) rename alembic/{ => legacy}/versions/8cac2b8b6ff2_temp_baseline.py (100%) rename alembic/{ => legacy}/versions/aaf7bb5ea051_.py (100%) rename alembic/{ => legacy}/versions/ad7bba107fd2_.py (100%) rename alembic/{ => legacy}/versions/d67c6981a1c5_.py (100%) rename alembic/{ => legacy}/versions/da1879cc255c_.py (100%) rename alembic/{ => legacy}/versions/ddbb9579a2d3_.py (100%) rename alembic/{ => legacy}/versions/e324270afb11_.py (100%) create mode 100644 alembic/versions/1045577547bf_baseline.py diff --git a/alembic/versions/0ca9a9a1726e_task_and_user_modified_to_have_one_.py b/alembic/legacy/versions/0ca9a9a1726e_task_and_user_modified_to_have_one_.py similarity index 100% rename from alembic/versions/0ca9a9a1726e_task_and_user_modified_to_have_one_.py rename to alembic/legacy/versions/0ca9a9a1726e_task_and_user_modified_to_have_one_.py diff --git a/alembic/versions/4033d9ff7961_.py b/alembic/legacy/versions/4033d9ff7961_.py similarity index 100% rename from alembic/versions/4033d9ff7961_.py rename to alembic/legacy/versions/4033d9ff7961_.py diff --git a/alembic/versions/412868709e85_task_with_due_date_null.py b/alembic/legacy/versions/412868709e85_task_with_due_date_null.py similarity index 100% rename from alembic/versions/412868709e85_task_with_due_date_null.py rename to alembic/legacy/versions/412868709e85_task_with_due_date_null.py diff --git a/alembic/versions/4ea1d38c82ed_.py b/alembic/legacy/versions/4ea1d38c82ed_.py similarity index 100% rename from alembic/versions/4ea1d38c82ed_.py rename to alembic/legacy/versions/4ea1d38c82ed_.py diff --git a/alembic/versions/511f432a6f92_agregado_eliminacion_en_labels.py b/alembic/legacy/versions/511f432a6f92_agregado_eliminacion_en_labels.py similarity index 100% rename from alembic/versions/511f432a6f92_agregado_eliminacion_en_labels.py rename to alembic/legacy/versions/511f432a6f92_agregado_eliminacion_en_labels.py diff --git a/alembic/versions/5128ff2bed08_.py b/alembic/legacy/versions/5128ff2bed08_.py similarity index 100% rename from alembic/versions/5128ff2bed08_.py rename to alembic/legacy/versions/5128ff2bed08_.py diff --git a/alembic/versions/5c44786b0f93_register_notifications_table.py b/alembic/legacy/versions/5c44786b0f93_register_notifications_table.py similarity index 100% rename from alembic/versions/5c44786b0f93_register_notifications_table.py rename to alembic/legacy/versions/5c44786b0f93_register_notifications_table.py diff --git a/alembic/versions/6a0c4820346e_.py b/alembic/legacy/versions/6a0c4820346e_.py similarity index 100% rename from alembic/versions/6a0c4820346e_.py rename to alembic/legacy/versions/6a0c4820346e_.py diff --git a/alembic/versions/7a739d51991b_.py b/alembic/legacy/versions/7a739d51991b_.py similarity index 100% rename from alembic/versions/7a739d51991b_.py rename to alembic/legacy/versions/7a739d51991b_.py diff --git a/alembic/versions/820a9cff9606_.py b/alembic/legacy/versions/820a9cff9606_.py similarity index 100% rename from alembic/versions/820a9cff9606_.py rename to alembic/legacy/versions/820a9cff9606_.py diff --git a/alembic/versions/8cac2b8b6ff2_temp_baseline.py b/alembic/legacy/versions/8cac2b8b6ff2_temp_baseline.py similarity index 100% rename from alembic/versions/8cac2b8b6ff2_temp_baseline.py rename to alembic/legacy/versions/8cac2b8b6ff2_temp_baseline.py diff --git a/alembic/versions/aaf7bb5ea051_.py b/alembic/legacy/versions/aaf7bb5ea051_.py similarity index 100% rename from alembic/versions/aaf7bb5ea051_.py rename to alembic/legacy/versions/aaf7bb5ea051_.py diff --git a/alembic/versions/ad7bba107fd2_.py b/alembic/legacy/versions/ad7bba107fd2_.py similarity index 100% rename from alembic/versions/ad7bba107fd2_.py rename to alembic/legacy/versions/ad7bba107fd2_.py diff --git a/alembic/versions/d67c6981a1c5_.py b/alembic/legacy/versions/d67c6981a1c5_.py similarity index 100% rename from alembic/versions/d67c6981a1c5_.py rename to alembic/legacy/versions/d67c6981a1c5_.py diff --git a/alembic/versions/da1879cc255c_.py b/alembic/legacy/versions/da1879cc255c_.py similarity index 100% rename from alembic/versions/da1879cc255c_.py rename to alembic/legacy/versions/da1879cc255c_.py diff --git a/alembic/versions/ddbb9579a2d3_.py b/alembic/legacy/versions/ddbb9579a2d3_.py similarity index 100% rename from alembic/versions/ddbb9579a2d3_.py rename to alembic/legacy/versions/ddbb9579a2d3_.py diff --git a/alembic/versions/e324270afb11_.py b/alembic/legacy/versions/e324270afb11_.py similarity index 100% rename from alembic/versions/e324270afb11_.py rename to alembic/legacy/versions/e324270afb11_.py diff --git a/alembic/versions/1045577547bf_baseline.py b/alembic/versions/1045577547bf_baseline.py new file mode 100644 index 00000000..3b6c474e --- /dev/null +++ b/alembic/versions/1045577547bf_baseline.py @@ -0,0 +1,157 @@ +"""baseline + +Revision ID: 1045577547bf +Revises: +Create Date: 2026-10-20 08:41:48.561871 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel + + +# revision identifiers, used by Alembic. +revision: str = '1045577547bf' +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('group', + sa.Column('group_id', sa.Integer(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('date_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('group_id') + ) + op.create_table('session', + sa.Column('jti', sqlmodel.sql.sqltypes.AutoString(length=36), nullable=False), + sa.Column('sub', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('use_count', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('expires_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('jti') + ) + op.create_index(op.f('ix_session_sub'), 'session', ['sub'], unique=False) + op.create_table('user', + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('username', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('password', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('user_id') + ) + op.create_table('group_user', + sa.Column('group_id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('role', sa.Enum('ADMIN', 'EDITOR', 'MEMBER', name='group_role'), nullable=False), + sa.ForeignKeyConstraint(['group_id'], ['group.group_id'], ), + sa.ForeignKeyConstraint(['user_id'], ['user.user_id'], ), + sa.PrimaryKeyConstraint('group_id', 'user_id') + ) + op.create_table('notifications', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('type', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('payload', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status', sa.Enum('ENVIADO', 'SIN_ENVIAR', name='notify_state'), nullable=False), + sa.Column('timestamp', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['user.user_id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('project', + sa.Column('project_id', sa.Integer(), nullable=False), + sa.Column('group_id', sa.Integer(), nullable=False), + sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('date_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['group_id'], ['group.group_id'], ), + sa.PrimaryKeyConstraint('project_id') + ) + op.create_index(op.f('ix_project_group_id'), 'project', ['group_id'], unique=False) + op.create_table('project_user', + sa.Column('project_id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('permission', sa.Enum('ADMIN', 'WRITE', 'READ', name='project_permission'), nullable=False), + sa.ForeignKeyConstraint(['project_id'], ['project.project_id'], ), + sa.ForeignKeyConstraint(['user_id'], ['user.user_id'], ), + sa.PrimaryKeyConstraint('project_id', 'user_id') + ) + op.create_table('projectchat', + sa.Column('chat_id', sa.Integer(), nullable=False), + sa.Column('project_id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('message', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('timestamp', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['project_id'], ['project.project_id'], ), + sa.ForeignKeyConstraint(['user_id'], ['user.user_id'], ), + sa.PrimaryKeyConstraint('chat_id') + ) + op.create_index(op.f('ix_projectchat_project_id'), 'projectchat', ['project_id'], unique=False) + op.create_index(op.f('ix_projectchat_user_id'), 'projectchat', ['user_id'], unique=False) + op.create_table('task', + sa.Column('task_id', sa.Integer(), nullable=False), + sa.Column('project_id', sa.Integer(), nullable=False), + sa.Column('assigned_user_id', sa.Integer(), nullable=True), + sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('date_exp', sa.DateTime(), nullable=True), + sa.Column('state', sa.Enum('COMPLETADO', 'EN_PROCESO', 'CANCELADO', 'SIN_EMPEZAR', name='state'), nullable=False), + sa.ForeignKeyConstraint(['assigned_user_id'], ['user.user_id'], ), + sa.ForeignKeyConstraint(['project_id'], ['project.project_id'], ), + sa.PrimaryKeyConstraint('task_id') + ) + op.create_index(op.f('ix_task_assigned_user_id'), 'task', ['assigned_user_id'], unique=False) + op.create_index(op.f('ix_task_project_id'), 'task', ['project_id'], unique=False) + op.create_table('task_comments', + sa.Column('comment_id', sa.Integer(), nullable=False), + sa.Column('task_id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('content', sqlmodel.sql.sqltypes.AutoString(length=300), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('update_at', sa.DateTime(), nullable=True), + sa.Column('is_deleted', sa.Boolean(), nullable=False), + sa.ForeignKeyConstraint(['task_id'], ['task.task_id'], ), + sa.ForeignKeyConstraint(['user_id'], ['user.user_id'], ), + sa.PrimaryKeyConstraint('comment_id') + ) + op.create_index(op.f('ix_task_comments_task_id'), 'task_comments', ['task_id'], unique=False) + op.create_index(op.f('ix_task_comments_user_id'), 'task_comments', ['user_id'], unique=False) + op.create_table('tasklabellink', + sa.Column('task_id', sa.Integer(), nullable=False), + sa.Column('label', sa.Enum('BUG', 'FEATURE', 'REFACTOR', 'DOCS', 'TESTS', 'UI_UX', 'URGENT', 'HIGH_PRIORITY', 'MEDIUM_PRIORITY', 'LOW_PRIORITY', 'BLOCKER', 'FRONTEND', 'BACKEND', 'DATABASE', 'API', 'INFRASTRUCTURE', name='typeoflabel'), nullable=False), + sa.ForeignKeyConstraint(['task_id'], ['task.task_id'], ), + sa.PrimaryKeyConstraint('task_id', 'label') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('tasklabellink') + op.drop_index(op.f('ix_task_comments_user_id'), table_name='task_comments') + op.drop_index(op.f('ix_task_comments_task_id'), table_name='task_comments') + op.drop_table('task_comments') + op.drop_index(op.f('ix_task_project_id'), table_name='task') + op.drop_index(op.f('ix_task_assigned_user_id'), table_name='task') + op.drop_table('task') + op.drop_index(op.f('ix_projectchat_user_id'), table_name='projectchat') + op.drop_index(op.f('ix_projectchat_project_id'), table_name='projectchat') + op.drop_table('projectchat') + op.drop_table('project_user') + op.drop_index(op.f('ix_project_group_id'), table_name='project') + op.drop_table('project') + op.drop_table('notifications') + op.drop_table('group_user') + op.drop_table('user') + op.drop_index(op.f('ix_session_sub'), table_name='session') + op.drop_table('session') + op.drop_table('group') + # ### end Alembic commands ### diff --git a/core/socket_manager.py b/core/socket_manager.py index a34c3826..296a6c4c 100644 --- a/core/socket_manager.py +++ b/core/socket_manager.py @@ -1,7 +1,7 @@ from typing import Dict, List from fastapi import WebSocket from .logger import logger -from db.database import redis_client, sessionlocal +from db.database import redis_client, SessionLocal from redis.asyncio import Redis from tasks import save_notification_in_db, get_pending_notifications_for_user from core.event_ws import format_notification @@ -146,7 +146,7 @@ async def connect_to_user_projects(self, websocket, user_id: int, session): async def send_pending_notifications(user_id: int): - session = sessionlocal + session = SessionLocal() pending = get_pending_notifications_for_user(user_id) if not pending: return {"detail": "No habian notificaciones a enviar"} diff --git a/db/database.py b/db/database.py index 633a89e9..a5b991b6 100644 --- a/db/database.py +++ b/db/database.py @@ -10,23 +10,27 @@ load_dotenv() -user = os.environ.get("POSTGRES_USER") -db_name = os.environ.get("POSTGRES_DB") -password = os.environ.get("POSTGRES_PASSWORD") -db_host = os.environ.get("POSTGRES_HOST") -db_port = os.environ.get("POSTGRES_PORT") +DATABASE_URL = os.environ.get("DATABASE_URL") -# url = f'postgresql+psycopg2://{user}:{password}@localhost:5432/{db_name}' +if DATABASE_URL: + engine = create_engine(DATABASE_URL) # echo=True, pool_pre_ping=True +else: + missing = [k for k in ("POSTGRES_USER", "POSTGRES_PASSWORD", "POSTGRES_HOST", "POSTGRES_PORT", "POSTGRES_DB") + if not os.environ.get(k)] + if missing: + raise RuntimeError(f"DATABASE_URL no definida y faltan variables: {', '.join(missing)}") -DATABASE_URL = os.environ.get("DATABASE_URL") + user = os.environ.get("POSTGRES_USER") + db_name = os.environ.get("POSTGRES_DB") + password = os.environ.get("POSTGRES_PASSWORD") + db_host = os.environ.get("POSTGRES_HOST") + db_port = os.environ.get("POSTGRES_PORT") -engine = create_engine(DATABASE_URL) # echo=True, pool_pre_ping=True + url = f'postgresql+psycopg2://{user}:{password}@{db_host}:{db_port}/{db_name}' + engine = create_engine(url) # echo=True, pool_pre_ping=True def create_db_and_tables(): - ## Solo para entornos de testing/ local muy iniciales - # SQLModel.metadata.create_all(engine) - try: with engine.connect() as connection: result = connection.execute(text("SELECT 1")) @@ -34,10 +38,7 @@ def create_db_and_tables(): except Exception as e: raise Exception(f"Error al conectar a la base de datos: {e}, {e.args}") - SessionLocal = sessionmaker(autoflush=False, autocommit=False, bind=engine) -sessionlocal = Session(engine) - def get_session(): session = Session(engine) diff --git a/tasks.py b/tasks.py index 834ac45b..b18d5819 100644 --- a/tasks.py +++ b/tasks.py @@ -3,7 +3,7 @@ import os import json from dotenv import load_dotenv -from db.database import SessionLocal, sessionlocal, select, SQLAlchemyError +from db.database import SessionLocal, select, SQLAlchemyError from models import db_models, schemas from core.logger import logger @@ -21,7 +21,7 @@ @app.task(retry_backoff=5) def get_pending_notifications_for_user(user_id: int) -> List[db_models.Notifications]: - session = sessionlocal + session = SessionLocal() try: stmt = select(db_models.Notifications).where( db_models.Notifications.user_id == user_id,