Files
core/storage/schema.py
Untone 7325cdc5f5
All checks were successful
Deploy on push / deploy (push) Successful in 5m42s
[0.9.15] - 2025-08-30
### 🔧 Fixed
- **🧾 Database Table Creation**: Унифицирован подход к созданию таблиц БД между продакшеном и тестами
  - Исправлена ошибка "no such table: author" в тестах
  - Обновлена функция `create_all_tables()` в `storage/schema.py` для использования стандартного SQLAlchemy подхода
  - Улучшены фикстуры тестов с принудительным импортом всех ORM моделей
  - Добавлена детальная диагностика создания таблиц в тестах
  - Добавлены fallback механизмы для создания таблиц в проблемных окружениях

### 🧪 Testing
- Все RBAC тесты теперь проходят успешно
- Исправлены фикстуры `test_engine`, `db_session` и `test_session_factory`
- Добавлены функции `ensure_all_tables_exist()` и `ensure_all_models_imported()` для диагностики

### 📝 Technical Details
- Заменен подход `create_table_if_not_exists()` на стандартный `Base.metadata.create_all()`
- Улучшена обработка ошибок при создании таблиц
- Добавлена проверка регистрации всех критических таблиц в metadata
2025-08-30 22:20:58 +03:00

98 lines
3.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from asyncio.log import logger
from enum import Enum
from ariadne import (
MutationType,
ObjectType,
QueryType,
SchemaBindable,
load_schema_from_path,
)
from storage.db import engine
# Создаем основные типы
query = QueryType()
mutation = MutationType()
type_draft = ObjectType("Draft")
type_community = ObjectType("Community")
type_collection = ObjectType("Collection")
type_author = ObjectType("Author")
# Загружаем определения типов из файлов схемы
type_defs = load_schema_from_path("schema/")
# Список всех типов для схемы
resolvers: SchemaBindable | type[Enum] | list[SchemaBindable | type[Enum]] = [
query,
mutation,
type_draft,
type_community,
type_collection,
type_author,
]
def create_all_tables() -> None:
"""Create all database tables using SQLAlchemy's standard approach."""
try:
# Импортируем все модели чтобы они были зарегистрированы в Base.metadata
# Получаем Base с зарегистрированными моделями
from orm.base import BaseModel as Base
# Проверяем что все критические таблицы зарегистрированы
required_tables = [
"author",
"community",
"community_author",
"community_follower",
"draft",
"draft_author",
"draft_topic",
"shout",
"shout_author",
"shout_topic",
"shout_reactions_followers",
"topic",
"topic_followers",
"reaction",
"invite",
"notification",
"collection",
"author_follower",
"author_rating",
"author_bookmark",
]
registered_tables = list(Base.metadata.tables.keys())
missing_tables = [table for table in required_tables if table not in registered_tables]
if missing_tables:
logger.warning(f"Missing tables in Base.metadata: {missing_tables}")
logger.info(f"Available tables: {registered_tables}")
# Создаем все таблицы стандартным способом SQLAlchemy
logger.info("Creating all database tables...")
Base.metadata.create_all(bind=engine)
# Проверяем результат
from sqlalchemy import inspect
inspector = inspect(engine)
created_tables = inspector.get_table_names()
logger.info(f"✅ Created tables: {created_tables}")
# Проверяем критически важные таблицы
missing_created = [table for table in required_tables if table not in created_tables]
if missing_created:
error_msg = f"Failed to create critical tables: {missing_created}"
logger.error(f"❌ Missing critical tables: {missing_created}")
raise RuntimeError(error_msg)
logger.info("✅ All critical tables created successfully")
except Exception as e:
logger.error(f"❌ Error creating database tables: {e}")
raise