Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 157 additions & 0 deletions alembic/versions/1045577547bf_baseline.py
Original file line number Diff line number Diff line change
@@ -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 ###
4 changes: 2 additions & 2 deletions core/socket_manager.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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"}
Expand Down
29 changes: 15 additions & 14 deletions db/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,35 @@

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"))
print(f"Conectado a PostgreSQL: {result.fetchone()}")
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)
Expand Down
4 changes: 2 additions & 2 deletions tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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,
Expand Down
Loading