65 lines
2.0 KiB
Python
65 lines
2.0 KiB
Python
from logging.config import fileConfig
|
|
from sqlalchemy import engine_from_config
|
|
from sqlalchemy import pool
|
|
from alembic import context
|
|
import os
|
|
from dotenv import load_dotenv
|
|
import sys
|
|
import os
|
|
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
|
import asyncio
|
|
|
|
# Cargar variables de entorno desde .env
|
|
load_dotenv()
|
|
|
|
# Agregar el directorio 'backend' al PYTHONPATH
|
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
|
|
# Configuración de Alembic
|
|
config = context.config
|
|
|
|
# Configurar logging
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
# Agregar la URL de la base de datos desde las variables de entorno
|
|
config.set_main_option(
|
|
"sqlalchemy.url",
|
|
os.getenv("DATABASE_URL", "postgresql+asyncpg://user:password@localhost/dbname")
|
|
)
|
|
|
|
# Importar modelos para las migraciones
|
|
from app.models import * # Importa todos los modelos aquí
|
|
from app.core.database import Base
|
|
|
|
target_metadata = Base.metadata # Reemplaza con tu metadata
|
|
|
|
# Cambiar el motor a asíncrono para Alembic
|
|
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
|
|
|
# Crear el motor asíncrono
|
|
connectable = create_async_engine(
|
|
os.getenv("DATABASE_URL", "postgresql+asyncpg://user:password@localhost/dbname"),
|
|
echo=True, # Habilitar logs para depuración
|
|
)
|
|
|
|
async def run_migrations():
|
|
async with connectable.connect() as connection:
|
|
await connection.run_sync(do_run_migrations)
|
|
|
|
def do_run_migrations(connection):
|
|
context.configure(connection=connection, target_metadata=target_metadata)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
# Configurar migraciones en modo offline
|
|
def run_migrations_offline():
|
|
context.configure(url=os.getenv("DATABASE_URL"), target_metadata=target_metadata, literal_binds=True)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
asyncio.run(run_migrations()) |