""" Alembic environment configuration Автор: Сергей Антропов Сайт: https://devops.org.ru """ from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from alembic import context import os import sys # Добавляем путь к приложению app_dir = os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0, app_dir) # Также добавляем родительскую директорию для правильных импортов parent_dir = os.path.dirname(app_dir) if parent_dir not in sys.path: sys.path.insert(0, parent_dir) # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. if config.config_file_name is not None: fileConfig(config.config_file_name) # Устанавливаем URL базы данных из переменных окружения или настроек db_url = os.getenv("DATABASE_URL", "postgresql://devopslab:devopslab123@postgres:5432/devopslab") if db_url.startswith("postgresql+asyncpg://"): db_url = db_url.replace("postgresql+asyncpg://", "postgresql://") config.set_main_option("sqlalchemy.url", db_url) # Импортируем модели для autogenerate try: from app.models.user import Base as UserBase from app.models.database import Base as DatabaseBase # Объединяем метаданные target_metadata = UserBase.metadata # Добавляем таблицы из database.py for table_name, table in DatabaseBase.metadata.tables.items(): if table_name not in target_metadata.tables: target_metadata._add_table(table_name, table.schema, table) except ImportError: # Если не удалось импортировать, используем только UserBase try: from app.models.user import Base target_metadata = Base.metadata except ImportError: # Если и это не работает, создаем пустые метаданные from sqlalchemy import MetaData target_metadata = MetaData() def run_migrations_offline() -> None: """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ url = config.get_main_option("sqlalchemy.url") context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, ) with context.begin_transaction(): context.run_migrations() def run_migrations_online() -> None: """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = engine_from_config( config.get_section(config.config_ini_section, {}), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()