54 lines
1.6 KiB
Python
54 lines
1.6 KiB
Python
# ==============================================================================
|
|
# Gestor de Conexiones y Sesiones de Base de Datos SQL Server (videoman)
|
|
# Compatible con Windows 10/11, LXC (FreeTDS) y Docker
|
|
# ==============================================================================
|
|
from contextlib import contextmanager
|
|
from typing import Generator
|
|
import pymssql
|
|
from app.core.config import settings
|
|
|
|
|
|
def get_raw_connection() -> pymssql.Connection:
|
|
"""Crea y retorna una nueva conexión física a Microsoft SQL Server."""
|
|
return pymssql.connect(
|
|
server=settings.DB_SERVER,
|
|
port=settings.DB_PORT,
|
|
user=settings.DB_USER,
|
|
password=settings.DB_PASSWORD,
|
|
database=settings.DB_NAME,
|
|
charset=settings.DB_CHARSET,
|
|
login_timeout=settings.DB_TIMEOUT,
|
|
timeout=settings.DB_TIMEOUT,
|
|
autocommit=False, # Control transaccional explícito
|
|
)
|
|
|
|
|
|
@contextmanager
|
|
def db_session() -> Generator[pymssql.Connection, None, None]:
|
|
"""
|
|
Context manager seguro para consultas y transacciones con commit/rollback atómico.
|
|
|
|
Uso:
|
|
with db_session() as conn:
|
|
cursor = conn.cursor(as_dict=True)
|
|
cursor.execute(...)
|
|
"""
|
|
conn = None
|
|
try:
|
|
conn = get_raw_connection()
|
|
yield conn
|
|
conn.commit()
|
|
except Exception:
|
|
if conn:
|
|
try:
|
|
conn.rollback()
|
|
except Exception:
|
|
pass
|
|
raise
|
|
finally:
|
|
if conn:
|
|
try:
|
|
conn.close()
|
|
except Exception:
|
|
pass
|