Spaces:
Runtime error

File size: 1,515 Bytes
f82e38a
 
 
aa6d2f2
f82e38a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import logging
from sqlmodel import create_engine, Session, SQLModel
from models import User, Task
import os

# Set up logging
logger = logging.getLogger(__name__)

# Get database URL from environment
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./todo_app.db")

from tenacity import retry, stop_after_attempt, wait_exponential


@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
def create_engine_with_retry():
    """Create database engine with retry logic"""
    try:
        engine = create_engine(
            DATABASE_URL,
            echo=False,
            pool_size=20,  # Number of connections to maintain in the pool
            max_overflow=30,  # Number of connections to allow in addition to pool_size
            pool_pre_ping=True,  # Verify connections before using them
            pool_recycle=3600,  # Recycle connections after 1 hour
            pool_timeout=30  # Time to wait for a connection from the pool
        )
        # Test the connection
        with engine.connect() as conn:
            pass
        return engine
    except Exception as e:
        logger.error(f"Database connection failed: {str(e)}")
        raise


# Create engine with connection pool configuration and retry logic
engine = create_engine_with_retry()


def create_db_and_tables():
    """Create database tables"""
    SQLModel.metadata.create_all(engine)


def get_session():
    """Get database session"""
    with Session(engine) as session:
        yield session