Paijo commited on
Commit
ad09154
·
verified ·
1 Parent(s): befd390

update app/database.py

Browse files
Files changed (1) hide show
  1. app/database.py +57 -0
app/database.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
2
+ from sqlalchemy.orm import DeclarativeBase
3
+ from sqlalchemy import create_engine
4
+ import os
5
+
6
+ DATABASE_URL = os.getenv("DATABASE_URL", "sqlite+aiosqlite:///./data/1proxy.db")
7
+
8
+ # Auto-create data directory for SQLite if it doesn't exist
9
+ if "sqlite" in DATABASE_URL and "./data/" in DATABASE_URL:
10
+ os.makedirs("./data", exist_ok=True)
11
+
12
+ # Configure connection pooling for production performance
13
+ engine_kwargs = {
14
+ "echo": False,
15
+ "future": True,
16
+ }
17
+
18
+ # SQLite doesn't support connection pooling, only add pool settings for PostgreSQL
19
+ if DATABASE_URL.startswith("postgresql"):
20
+ engine_kwargs.update(
21
+ {
22
+ "pool_size": 20, # Number of permanent connections
23
+ "max_overflow": 30, # Additional connections beyond pool_size
24
+ "pool_pre_ping": True, # Verify connections before using
25
+ "pool_recycle": 3600, # Recycle connections after 1 hour
26
+ "pool_timeout": 30, # Wait max 30s for connection from pool
27
+ }
28
+ )
29
+
30
+ engine = create_async_engine(DATABASE_URL, **engine_kwargs)
31
+
32
+ AsyncSessionLocal = async_sessionmaker(
33
+ engine,
34
+ class_=AsyncSession,
35
+ expire_on_commit=False,
36
+ )
37
+
38
+
39
+ class Base(DeclarativeBase):
40
+ pass
41
+
42
+
43
+ async def get_db():
44
+ async with AsyncSessionLocal() as session:
45
+ try:
46
+ yield session
47
+ await session.commit()
48
+ except Exception:
49
+ await session.rollback()
50
+ raise
51
+ finally:
52
+ await session.close()
53
+
54
+
55
+ async def init_db():
56
+ async with engine.begin() as conn:
57
+ await conn.run_sync(Base.metadata.create_all)