init
This commit is contained in:
16
new-planet-backend/app/db/__init__.py
Normal file
16
new-planet-backend/app/db/__init__.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from app.db.base import Base, BaseModel
|
||||
from app.db.session import get_db, AsyncSessionLocal
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine
|
||||
from app.db.session import engine as _engine
|
||||
|
||||
# Для обратной совместимости
|
||||
engine: AsyncEngine = _engine
|
||||
|
||||
__all__ = [
|
||||
"Base",
|
||||
"BaseModel",
|
||||
"get_db",
|
||||
"AsyncSessionLocal",
|
||||
"engine",
|
||||
]
|
||||
|
||||
30
new-planet-backend/app/db/base.py
Normal file
30
new-planet-backend/app/db/base.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy import Column, DateTime, func
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
import uuid
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class BaseModel(Base):
|
||||
"""Базовая модель с общими полями"""
|
||||
__abstract__ = True
|
||||
|
||||
id = Column(
|
||||
UUID(as_uuid=False),
|
||||
primary_key=True,
|
||||
default=lambda: str(uuid.uuid4()),
|
||||
nullable=False
|
||||
)
|
||||
created_at = Column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
nullable=False
|
||||
)
|
||||
updated_at = Column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
onupdate=func.now(),
|
||||
nullable=False
|
||||
)
|
||||
|
||||
10
new-planet-backend/app/db/init_db.py
Normal file
10
new-planet-backend/app/db/init_db.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from app.db.base import Base
|
||||
from app.db.session import engine
|
||||
from app.models import user, schedule, task, reward, ai_conversation
|
||||
|
||||
|
||||
async def init_db():
|
||||
"""Инициализация БД - создание таблиц"""
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
26
new-planet-backend/app/db/session.py
Normal file
26
new-planet-backend/app/db/session.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_async_engine(
|
||||
settings.database_url,
|
||||
echo=settings.DEBUG,
|
||||
future=True
|
||||
)
|
||||
|
||||
AsyncSessionLocal = async_sessionmaker(
|
||||
engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
autocommit=False,
|
||||
autoflush=False
|
||||
)
|
||||
|
||||
|
||||
async def get_db() -> AsyncSession:
|
||||
"""Dependency для получения сессии БД"""
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
Reference in New Issue
Block a user