db.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. """
  2. Database abstraction layer supporting SQLite, PostgreSQL, and MySQL.
  3. Backend selection is based on DATABASE_URL environment variable:
  4. - postgres://... or postgresql://... -> PostgreSQL
  5. - mysql://... -> MySQL
  6. - Not set -> SQLite (default)
  7. """
  8. import os
  9. import json
  10. import time
  11. import asyncio
  12. from pathlib import Path
  13. from typing import Dict, List, Any, Optional, Tuple
  14. from abc import ABC, abstractmethod
  15. import aiosqlite
  16. # Optional imports for other backends
  17. try:
  18. import asyncpg
  19. HAS_ASYNCPG = True
  20. except ImportError:
  21. HAS_ASYNCPG = False
  22. try:
  23. import aiomysql
  24. HAS_AIOMYSQL = True
  25. except ImportError:
  26. HAS_AIOMYSQL = False
  27. class DatabaseBackend(ABC):
  28. """Abstract base class for database backends."""
  29. @abstractmethod
  30. async def initialize(self) -> None:
  31. """Initialize connection and ensure schema exists."""
  32. pass
  33. @abstractmethod
  34. async def close(self) -> None:
  35. """Close database connections."""
  36. pass
  37. @abstractmethod
  38. async def execute(self, query: str, params: tuple = ()) -> int:
  39. """Execute a query and return affected row count."""
  40. pass
  41. @abstractmethod
  42. async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
  43. """Fetch a single row as dict."""
  44. pass
  45. @abstractmethod
  46. async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
  47. """Fetch all rows as list of dicts."""
  48. pass
  49. class SQLiteBackend(DatabaseBackend):
  50. """SQLite database backend using aiosqlite."""
  51. def __init__(self, db_path: Path):
  52. self._db_path = db_path
  53. self._initialized = False
  54. self._conn: Optional[aiosqlite.Connection] = None
  55. async def initialize(self) -> None:
  56. if self._initialized:
  57. return
  58. self._db_path.parent.mkdir(parents=True, exist_ok=True)
  59. self._conn = await aiosqlite.connect(self._db_path)
  60. # Performance tuning PRAGMAs
  61. await self._conn.execute("PRAGMA journal_mode=WAL;")
  62. await self._conn.execute("PRAGMA synchronous = NORMAL;")
  63. await self._conn.execute("PRAGMA cache_size = -65536; -- 64MB")
  64. await self._conn.execute("PRAGMA temp_store = MEMORY;")
  65. await self._conn.execute("""
  66. CREATE TABLE IF NOT EXISTS accounts (
  67. id TEXT PRIMARY KEY,
  68. label TEXT,
  69. clientId TEXT,
  70. clientSecret TEXT,
  71. refreshToken TEXT,
  72. accessToken TEXT,
  73. other TEXT,
  74. last_refresh_time TEXT,
  75. last_refresh_status TEXT,
  76. created_at TEXT,
  77. updated_at TEXT,
  78. enabled INTEGER DEFAULT 1,
  79. error_count INTEGER DEFAULT 0,
  80. success_count INTEGER DEFAULT 0
  81. )
  82. """)
  83. # Create indexes for performance
  84. await self._conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_enabled ON accounts (enabled);")
  85. await self._conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_created_at ON accounts (created_at);")
  86. await self._conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_success_count ON accounts (success_count);")
  87. await self._conn.commit()
  88. self._initialized = True
  89. async def close(self) -> None:
  90. if self._conn:
  91. await self._conn.close()
  92. self._conn = None
  93. self._initialized = False
  94. async def execute(self, query: str, params: tuple = ()) -> int:
  95. cursor = await self._conn.execute(query, params)
  96. await self._conn.commit()
  97. return cursor.rowcount
  98. async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
  99. self._conn.row_factory = aiosqlite.Row
  100. async with self._conn.execute(query, params) as cursor:
  101. row = await cursor.fetchone()
  102. return dict(row) if row else None
  103. async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
  104. self._conn.row_factory = aiosqlite.Row
  105. async with self._conn.execute(query, params) as cursor:
  106. rows = await cursor.fetchall()
  107. return [dict(row) for row in rows]
  108. class PostgresBackend(DatabaseBackend):
  109. """PostgreSQL database backend using asyncpg."""
  110. def __init__(self, dsn: str):
  111. self._dsn = dsn
  112. self._pool: "Optional[asyncpg.pool.Pool]" = None
  113. self._initialized = False
  114. async def initialize(self) -> None:
  115. if not HAS_ASYNCPG:
  116. raise ImportError("asyncpg is required for PostgreSQL support. Install with: pip install asyncpg")
  117. self._pool = await asyncpg.create_pool(dsn=self._dsn, min_size=1, max_size=20)
  118. async with self._pool.acquire() as conn:
  119. await conn.execute("""
  120. CREATE TABLE IF NOT EXISTS accounts (
  121. id TEXT PRIMARY KEY,
  122. label TEXT,
  123. clientId TEXT,
  124. clientSecret TEXT,
  125. refreshToken TEXT,
  126. accessToken TEXT,
  127. other TEXT,
  128. last_refresh_time TEXT,
  129. last_refresh_status TEXT,
  130. created_at TEXT,
  131. updated_at TEXT,
  132. enabled INTEGER DEFAULT 1,
  133. error_count INTEGER DEFAULT 0,
  134. success_count INTEGER DEFAULT 0
  135. )
  136. """)
  137. self._initialized = True
  138. async def close(self) -> None:
  139. if self._pool:
  140. await self._pool.close()
  141. self._pool = None
  142. self._initialized = False
  143. def _convert_placeholders(self, query: str) -> str:
  144. """Convert ? placeholders to $1, $2, etc."""
  145. result = []
  146. param_num = 0
  147. i = 0
  148. while i < len(query):
  149. if query[i] == '?':
  150. param_num += 1
  151. result.append(f'${param_num}')
  152. else:
  153. result.append(query[i])
  154. i += 1
  155. return ''.join(result)
  156. async def execute(self, query: str, params: tuple = ()) -> int:
  157. pg_query = self._convert_placeholders(query)
  158. async with self._pool.acquire() as conn:
  159. result = await conn.execute(pg_query, *params)
  160. # asyncpg returns string like "UPDATE 1"
  161. try:
  162. return int(result.split()[-1])
  163. except (ValueError, IndexError):
  164. return 0
  165. async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
  166. pg_query = self._convert_placeholders(query)
  167. async with self._pool.acquire() as conn:
  168. row = await conn.fetchrow(pg_query, *params)
  169. return dict(row) if row else None
  170. async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
  171. pg_query = self._convert_placeholders(query)
  172. async with self._pool.acquire() as conn:
  173. rows = await conn.fetch(pg_query, *params)
  174. return [dict(row) for row in rows]
  175. class MySQLBackend(DatabaseBackend):
  176. """MySQL database backend using aiomysql."""
  177. def __init__(self, dsn: str):
  178. self._dsn = dsn
  179. self._pool = None
  180. self._initialized = False
  181. self._config = self._parse_dsn(dsn)
  182. def _parse_dsn(self, dsn: str) -> Dict[str, Any]:
  183. """Parse MySQL DSN into connection parameters."""
  184. # mysql://user:password@host:port/database
  185. from urllib.parse import urlparse, parse_qs
  186. parsed = urlparse(dsn)
  187. config = {
  188. 'host': parsed.hostname or 'localhost',
  189. 'port': parsed.port or 3306,
  190. 'user': parsed.username or 'root',
  191. 'password': parsed.password or '',
  192. 'db': parsed.path.lstrip('/') if parsed.path else 'test',
  193. }
  194. # Handle SSL
  195. query = parse_qs(parsed.query)
  196. if 'ssl' in query or 'sslmode' in query or 'ssl-mode' in query:
  197. config['ssl'] = True
  198. return config
  199. async def initialize(self) -> None:
  200. if not HAS_AIOMYSQL:
  201. raise ImportError("aiomysql is required for MySQL support. Install with: pip install aiomysql")
  202. self._pool = await aiomysql.create_pool(
  203. host=self._config['host'],
  204. port=self._config['port'],
  205. user=self._config['user'],
  206. password=self._config['password'],
  207. db=self._config['db'],
  208. minsize=1,
  209. maxsize=20,
  210. autocommit=True
  211. )
  212. async with self._pool.acquire() as conn:
  213. async with conn.cursor() as cur:
  214. await cur.execute("""
  215. CREATE TABLE IF NOT EXISTS accounts (
  216. id VARCHAR(255) PRIMARY KEY,
  217. label TEXT,
  218. clientId TEXT,
  219. clientSecret TEXT,
  220. refreshToken TEXT,
  221. accessToken TEXT,
  222. other TEXT,
  223. last_refresh_time TEXT,
  224. last_refresh_status TEXT,
  225. created_at TEXT,
  226. updated_at TEXT,
  227. enabled INT DEFAULT 1,
  228. error_count INT DEFAULT 0,
  229. success_count INT DEFAULT 0
  230. )
  231. """)
  232. self._initialized = True
  233. async def close(self) -> None:
  234. if self._pool:
  235. self._pool.close()
  236. await self._pool.wait_closed()
  237. self._pool = None
  238. self._initialized = False
  239. def _convert_placeholders(self, query: str) -> str:
  240. """Convert ? placeholders to %s for MySQL."""
  241. return query.replace('?', '%s')
  242. async def execute(self, query: str, params: tuple = ()) -> int:
  243. mysql_query = self._convert_placeholders(query)
  244. async with self._pool.acquire() as conn:
  245. async with conn.cursor() as cur:
  246. await cur.execute(mysql_query, params)
  247. return cur.rowcount
  248. async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
  249. mysql_query = self._convert_placeholders(query)
  250. async with self._pool.acquire() as conn:
  251. async with conn.cursor(aiomysql.DictCursor) as cur:
  252. await cur.execute(mysql_query, params)
  253. return await cur.fetchone()
  254. async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
  255. mysql_query = self._convert_placeholders(query)
  256. async with self._pool.acquire() as conn:
  257. async with conn.cursor(aiomysql.DictCursor) as cur:
  258. await cur.execute(mysql_query, params)
  259. return await cur.fetchall()
  260. # Global database instance
  261. _db: Optional[DatabaseBackend] = None
  262. def get_database_backend() -> DatabaseBackend:
  263. """Get the configured database backend based on DATABASE_URL."""
  264. global _db
  265. if _db is not None:
  266. return _db
  267. database_url = os.getenv('DATABASE_URL', '').strip()
  268. if database_url.startswith(('postgres://', 'postgresql://')):
  269. # Fix common postgres:// to postgresql:// for asyncpg
  270. dsn = database_url.replace('postgres://', 'postgresql://', 1) if database_url.startswith('postgres://') else database_url
  271. _db = PostgresBackend(dsn)
  272. print(f"[DB] Using PostgreSQL backend")
  273. elif database_url.startswith('mysql://'):
  274. _db = MySQLBackend(database_url)
  275. print(f"[DB] Using MySQL backend")
  276. else:
  277. # Default to SQLite
  278. base_dir = Path(__file__).resolve().parent
  279. db_path = base_dir / "data.sqlite3"
  280. _db = SQLiteBackend(db_path)
  281. print(f"[DB] Using SQLite backend: {db_path}")
  282. return _db
  283. async def init_db() -> DatabaseBackend:
  284. """Initialize and return the database backend."""
  285. db = get_database_backend()
  286. await db.initialize()
  287. return db
  288. async def close_db() -> None:
  289. """Close the database backend."""
  290. global _db
  291. if _db:
  292. await _db.close()
  293. _db = None
  294. # Helper functions for common operations
  295. def row_to_dict(row: Dict[str, Any]) -> Optional[Dict[str, Any]]:
  296. """Convert a database row to dict with JSON parsing for 'other' field."""
  297. if row is None:
  298. return None
  299. d = dict(row)
  300. if d.get("other"):
  301. try:
  302. d["other"] = json.loads(d["other"])
  303. except Exception:
  304. pass
  305. # normalize enabled to bool
  306. if "enabled" in d and d["enabled"] is not None:
  307. try:
  308. d["enabled"] = bool(int(d["enabled"]))
  309. except Exception:
  310. d["enabled"] = bool(d["enabled"])
  311. return d