File size: 4,902 Bytes
2985cd5 22947a0 0567988 2985cd5 22947a0 4047f1c 0567988 4047f1c 0567988 22947a0 4047f1c 22947a0 4047f1c 22947a0 4047f1c 22947a0 2985cd5 22947a0 2985cd5 22947a0 2985cd5 22947a0 2985cd5 | 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | from sqlmodel import create_engine, Session
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
import urllib.parse
import re
from ..config import settings
def is_sqlite_db(database_url: str) -> bool:
"""Check if the database URL is for SQLite."""
parsed = urllib.parse.urlparse(database_url)
return parsed.scheme.lower().startswith('sqlite')
def clean_database_url(database_url: str) -> str:
"""Remove unsupported parameters from database URL for compatibility."""
if is_sqlite_db(database_url):
return database_url
# Fix common typos in database URLs (like "ostgresql" or "ppostgresql" instead of "postgresql")
if "ostgresql" in database_url:
# Handle cases like "ppostgresql" -> "postgresql" or "ostgresql" -> "postgresql"
# Replace any occurrence of p*ostgresql (where p* means zero or more 'p's) with postgresql
database_url = re.sub(r'p*ostgresql', 'postgresql', database_url)
# Parse the URL to remove unsupported parameters
parsed = urllib.parse.urlparse(database_url)
query_params = urllib.parse.parse_qs(parsed.query)
# Remove unsupported parameters
unsupported_params = {'channel_binding', 'sslmode'}
for param in unsupported_params:
query_params.pop(param, None)
# Reconstruct the URL without unsupported parameters
new_query = urllib.parse.urlencode(query_params, doseq=True)
cleaned_url = urllib.parse.urlunparse((
parsed.scheme,
parsed.netloc,
parsed.path,
parsed.params,
new_query,
parsed.fragment
))
return cleaned_url
def get_sync_pg_url(database_url: str) -> str:
"""Ensures a PostgreSQL URL uses a synchronous driver (psycopg2 by default)."""
if database_url.startswith("postgresql+asyncpg://"):
return database_url.replace("postgresql+asyncpg://", "postgresql://", 1)
return database_url
# Determine if we're using SQLite
using_sqlite = is_sqlite_db(settings.database_url)
# Clean database URLs for compatibility
cleaned_database_url = clean_database_url(settings.database_url)
cleaned_async_database_url = clean_database_url(settings.async_database_url)
# Ensure sync engine uses a synchronous PG driver if applicable
sync_db_url_for_engine = get_sync_pg_url(cleaned_database_url)
# Synchronous engine for general use
if using_sqlite:
# SQLite doesn't support connection pooling options
sync_engine = create_engine(
sync_db_url_for_engine,
echo=settings.database_echo, # Set to True for SQL query logging
)
else:
# PostgreSQL supports connection pooling options
sync_engine = create_engine(
sync_db_url_for_engine,
echo=settings.database_echo, # Set to True for SQL query logging
pool_pre_ping=True, # Verify connections before use
pool_recycle=300, # Recycle connections every 5 minutes
pool_size=5, # Number of connections to maintain
max_overflow=10, # Additional connections beyond pool_size
pool_timeout=30, # Timeout for getting connection from pool
)
# Async engine for async operations
if is_sqlite_db(cleaned_async_database_url):
# SQLite doesn't support connection pooling options
async_engine = create_async_engine(
cleaned_async_database_url,
echo=settings.database_echo, # Set to True for SQL query logging
)
else:
# PostgreSQL supports connection pooling options
async_engine = create_async_engine(
cleaned_async_database_url,
echo=settings.database_echo, # Set to True for SQL query logging
pool_pre_ping=True, # Verify connections before use
pool_recycle=300, # Recycle connections every 5 minutes
pool_size=5, # Number of connections to maintain
max_overflow=10, # Additional connections beyond pool_size
pool_timeout=30, # Timeout for getting connection from pool,
connect_args={
"ssl": "require",
"server_settings": {
"application_name": "todo-backend",
}
}
)
# Session makers
AsyncSessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=async_engine,
class_=AsyncSession,
expire_on_commit=False
)
SyncSessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=sync_engine,
expire_on_commit=False
)
def get_sync_session():
"""Get a synchronous database session."""
session = SyncSessionLocal()
try:
yield session
finally:
session.close()
async def get_async_session():
"""Get an asynchronous database session."""
async with AsyncSessionLocal() as session:
yield session
await session.close() |