File size: 2,127 Bytes
9d8ff93
b4c1a74
 
450d1c9
b4c1a74
 
 
 
9d8ff93
 
b4c1a74
 
9d8ff93
b4c1a74
450d1c9
 
 
 
 
9d8ff93
 
 
e3dc289
450d1c9
 
 
 
 
 
 
 
 
 
9d8ff93
 
 
 
 
 
450d1c9
b4c1a74
9d8ff93
b4c1a74
 
 
 
9d8ff93
 
 
b4c1a74
 
9d8ff93
450d1c9
 
9d8ff93
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from .config import settings
import logging
import ssl

logger = logging.getLogger(__name__)

class Database:
    engine = None
    async_session = None

    @classmethod
    def connect(cls):
        try:
            # Create SSL context for Supabase connection
            ssl_context = ssl.create_default_context()
            ssl_context.check_hostname = False
            ssl_context.verify_mode = ssl.CERT_NONE
            
            cls.engine = create_async_engine(
                settings.POSTGRES_URL,
                echo=False,
                future=True,
                pool_size=5,
                max_overflow=10,
                pool_pre_ping=True,
                pool_recycle=300,
                connect_args={
                    "ssl": ssl_context,
                    "server_settings": {
                        "application_name": "yt-automation"
                    }
                }
            )
            cls.async_session = async_sessionmaker(
                cls.engine, 
                expire_on_commit=False, 
                class_=AsyncSession
            )
            logger.info(f"Successfully configured PostgreSQL connection")
        except Exception as e:
            logger.error(f"Could not configure PostgreSQL: {e}")
            raise

    @classmethod
    async def close(cls):
        if cls.engine:
            await cls.engine.dispose()
            logger.info("PostgreSQL connection closed")

    @classmethod
    def get_session(cls) -> AsyncSession:
        if cls.async_session is None:
            raise RuntimeError("Database not initialized. Call Database.connect() first.")
        return cls.async_session()

# Database initialization helper
async def init_db():
    from .models import Base
    Database.connect()
    async with Database.engine.begin() as conn:
        # This will create tables if they don't exist
        # In production, use Alembic for migrations
        await conn.run_sync(Base.metadata.create_all)
    logger.info("Database tables initialized")