db.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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, Set
  14. from abc import ABC, abstractmethod
  15. import aiosqlite
  16. # Schema version for migrations
  17. SCHEMA_VERSION = 1
  18. # Define all columns that should exist in the accounts table
  19. # Format: (column_name, column_type_sqlite, column_type_postgres, column_type_mysql, default_value)
  20. ACCOUNTS_COLUMNS = [
  21. ("id", "TEXT PRIMARY KEY", "TEXT PRIMARY KEY", "VARCHAR(255) PRIMARY KEY", None),
  22. ("label", "TEXT", "TEXT", "TEXT", None),
  23. ("clientId", "TEXT", "TEXT", "TEXT", None),
  24. ("clientSecret", "TEXT", "TEXT", "TEXT", None),
  25. ("refreshToken", "TEXT", "TEXT", "TEXT", None),
  26. ("accessToken", "TEXT", "TEXT", "TEXT", None),
  27. ("other", "TEXT", "TEXT", "TEXT", None),
  28. ("last_refresh_time", "TEXT", "TEXT", "TEXT", None),
  29. ("last_refresh_status", "TEXT", "TEXT", "TEXT", None),
  30. ("created_at", "TEXT", "TEXT", "TEXT", None),
  31. ("updated_at", "TEXT", "TEXT", "TEXT", None),
  32. ("enabled", "INTEGER DEFAULT 1", "INTEGER DEFAULT 1", "INT DEFAULT 1", "1"),
  33. ("error_count", "INTEGER DEFAULT 0", "INTEGER DEFAULT 0", "INT DEFAULT 0", "0"),
  34. ("success_count", "INTEGER DEFAULT 0", "INTEGER DEFAULT 0", "INT DEFAULT 0", "0"),
  35. ("expires_at", "TEXT", "TEXT", "TEXT", None),
  36. ]
  37. # Optional imports for other backends
  38. try:
  39. import asyncpg
  40. HAS_ASYNCPG = True
  41. except ImportError:
  42. HAS_ASYNCPG = False
  43. try:
  44. import aiomysql
  45. HAS_AIOMYSQL = True
  46. except ImportError:
  47. HAS_AIOMYSQL = False
  48. class DatabaseBackend(ABC):
  49. """Abstract base class for database backends."""
  50. @abstractmethod
  51. async def initialize(self) -> None:
  52. """Initialize connection and ensure schema exists."""
  53. pass
  54. @abstractmethod
  55. async def close(self) -> None:
  56. """Close database connections."""
  57. pass
  58. @abstractmethod
  59. async def execute(self, query: str, params: tuple = ()) -> int:
  60. """Execute a query and return affected row count."""
  61. pass
  62. @abstractmethod
  63. async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
  64. """Fetch a single row as dict."""
  65. pass
  66. @abstractmethod
  67. async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
  68. """Fetch all rows as list of dicts."""
  69. pass
  70. class SQLiteBackend(DatabaseBackend):
  71. """SQLite database backend using aiosqlite."""
  72. def __init__(self, db_path: Path):
  73. self._db_path = db_path
  74. self._initialized = False
  75. self._conn: Optional[aiosqlite.Connection] = None
  76. async def _get_existing_columns(self) -> Set[str]:
  77. """Get existing column names from accounts table."""
  78. try:
  79. async with self._conn.execute("PRAGMA table_info(accounts)") as cursor:
  80. rows = await cursor.fetchall()
  81. return {row[1] for row in rows}
  82. except Exception:
  83. return set()
  84. async def _migrate_schema(self) -> None:
  85. """Add missing columns to accounts table."""
  86. existing_cols = await self._get_existing_columns()
  87. if not existing_cols:
  88. return # Table doesn't exist yet, will be created fresh
  89. for col_name, col_type, _, _, _ in ACCOUNTS_COLUMNS:
  90. if col_name not in existing_cols and "PRIMARY KEY" not in col_type:
  91. # Extract just the type without DEFAULT clause for ALTER TABLE
  92. base_type = col_type.split(" DEFAULT")[0].strip()
  93. try:
  94. await self._conn.execute(f"ALTER TABLE accounts ADD COLUMN {col_name} {base_type}")
  95. print(f"[DB Migration] Added column: {col_name}")
  96. except Exception as e:
  97. print(f"[DB Migration] Failed to add column {col_name}: {e}")
  98. async def initialize(self) -> None:
  99. if self._initialized:
  100. return
  101. self._db_path.parent.mkdir(parents=True, exist_ok=True)
  102. self._conn = await aiosqlite.connect(self._db_path)
  103. # Performance tuning PRAGMAs
  104. await self._conn.execute("PRAGMA journal_mode=WAL;")
  105. await self._conn.execute("PRAGMA synchronous = NORMAL;")
  106. await self._conn.execute("PRAGMA cache_size = -65536; -- 64MB")
  107. await self._conn.execute("PRAGMA temp_store = MEMORY;")
  108. # Build CREATE TABLE statement from schema definition
  109. columns_sql = ", ".join([f"{col[0]} {col[1]}" for col in ACCOUNTS_COLUMNS])
  110. await self._conn.execute(f"""
  111. CREATE TABLE IF NOT EXISTS accounts ({columns_sql})
  112. """)
  113. # Run migrations for existing tables
  114. await self._migrate_schema()
  115. # Create indexes for performance
  116. await self._conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_enabled ON accounts (enabled);")
  117. await self._conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_created_at ON accounts (created_at);")
  118. await self._conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_success_count ON accounts (success_count);")
  119. await self._conn.commit()
  120. self._initialized = True
  121. async def close(self) -> None:
  122. if self._conn:
  123. await self._conn.close()
  124. self._conn = None
  125. self._initialized = False
  126. async def execute(self, query: str, params: tuple = ()) -> int:
  127. cursor = await self._conn.execute(query, params)
  128. await self._conn.commit()
  129. return cursor.rowcount
  130. async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
  131. self._conn.row_factory = aiosqlite.Row
  132. async with self._conn.execute(query, params) as cursor:
  133. row = await cursor.fetchone()
  134. return dict(row) if row else None
  135. async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
  136. self._conn.row_factory = aiosqlite.Row
  137. async with self._conn.execute(query, params) as cursor:
  138. rows = await cursor.fetchall()
  139. return [dict(row) for row in rows]
  140. class PostgresBackend(DatabaseBackend):
  141. """PostgreSQL database backend using asyncpg."""
  142. def __init__(self, dsn: str):
  143. self._dsn = dsn
  144. self._pool: "Optional[asyncpg.pool.Pool]" = None
  145. self._initialized = False
  146. async def _get_existing_columns(self, conn) -> Set[str]:
  147. """Get existing column names from accounts table."""
  148. try:
  149. rows = await conn.fetch("""
  150. SELECT column_name FROM information_schema.columns
  151. WHERE table_name = 'accounts'
  152. """)
  153. return {row['column_name'] for row in rows}
  154. except Exception:
  155. return set()
  156. async def _migrate_schema(self, conn) -> None:
  157. """Add missing columns to accounts table."""
  158. existing_cols = await self._get_existing_columns(conn)
  159. if not existing_cols:
  160. return # Table doesn't exist yet
  161. for col_name, _, col_type, _, _ in ACCOUNTS_COLUMNS:
  162. if col_name not in existing_cols and "PRIMARY KEY" not in col_type:
  163. base_type = col_type.split(" DEFAULT")[0].strip()
  164. try:
  165. await conn.execute(f"ALTER TABLE accounts ADD COLUMN IF NOT EXISTS {col_name} {base_type}")
  166. print(f"[DB Migration] Added column: {col_name}")
  167. except Exception as e:
  168. print(f"[DB Migration] Failed to add column {col_name}: {e}")
  169. async def initialize(self) -> None:
  170. if not HAS_ASYNCPG:
  171. raise ImportError("asyncpg is required for PostgreSQL support. Install with: pip install asyncpg")
  172. self._pool = await asyncpg.create_pool(dsn=self._dsn, min_size=1, max_size=20)
  173. async with self._pool.acquire() as conn:
  174. # Build CREATE TABLE statement from schema definition
  175. columns_sql = ", ".join([f"{col[0]} {col[2]}" for col in ACCOUNTS_COLUMNS])
  176. await conn.execute(f"""
  177. CREATE TABLE IF NOT EXISTS accounts ({columns_sql})
  178. """)
  179. # Run migrations
  180. await self._migrate_schema(conn)
  181. self._initialized = True
  182. async def close(self) -> None:
  183. if self._pool:
  184. await self._pool.close()
  185. self._pool = None
  186. self._initialized = False
  187. def _convert_placeholders(self, query: str) -> str:
  188. """Convert ? placeholders to $1, $2, etc."""
  189. result = []
  190. param_num = 0
  191. i = 0
  192. while i < len(query):
  193. if query[i] == '?':
  194. param_num += 1
  195. result.append(f'${param_num}')
  196. else:
  197. result.append(query[i])
  198. i += 1
  199. return ''.join(result)
  200. async def execute(self, query: str, params: tuple = ()) -> int:
  201. pg_query = self._convert_placeholders(query)
  202. async with self._pool.acquire() as conn:
  203. result = await conn.execute(pg_query, *params)
  204. # asyncpg returns string like "UPDATE 1"
  205. try:
  206. return int(result.split()[-1])
  207. except (ValueError, IndexError):
  208. return 0
  209. async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
  210. pg_query = self._convert_placeholders(query)
  211. async with self._pool.acquire() as conn:
  212. row = await conn.fetchrow(pg_query, *params)
  213. return dict(row) if row else None
  214. async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
  215. pg_query = self._convert_placeholders(query)
  216. async with self._pool.acquire() as conn:
  217. rows = await conn.fetch(pg_query, *params)
  218. return [dict(row) for row in rows]
  219. class MySQLBackend(DatabaseBackend):
  220. """MySQL database backend using aiomysql."""
  221. def __init__(self, dsn: str):
  222. self._dsn = dsn
  223. self._pool = None
  224. self._initialized = False
  225. self._config = self._parse_dsn(dsn)
  226. def _parse_dsn(self, dsn: str) -> Dict[str, Any]:
  227. """Parse MySQL DSN into connection parameters."""
  228. # mysql://user:password@host:port/database
  229. from urllib.parse import urlparse, parse_qs
  230. parsed = urlparse(dsn)
  231. config = {
  232. 'host': parsed.hostname or 'localhost',
  233. 'port': parsed.port or 3306,
  234. 'user': parsed.username or 'root',
  235. 'password': parsed.password or '',
  236. 'db': parsed.path.lstrip('/') if parsed.path else 'test',
  237. }
  238. # Handle SSL
  239. query = parse_qs(parsed.query)
  240. if 'ssl' in query or 'sslmode' in query or 'ssl-mode' in query:
  241. config['ssl'] = True
  242. return config
  243. async def _get_existing_columns(self, cur) -> Set[str]:
  244. """Get existing column names from accounts table."""
  245. try:
  246. await cur.execute(f"DESCRIBE accounts")
  247. rows = await cur.fetchall()
  248. return {row[0] if isinstance(row, tuple) else row['Field'] for row in rows}
  249. except Exception:
  250. return set()
  251. async def _migrate_schema(self, cur) -> None:
  252. """Add missing columns to accounts table."""
  253. existing_cols = await self._get_existing_columns(cur)
  254. if not existing_cols:
  255. return # Table doesn't exist yet
  256. for col_name, _, _, col_type, _ in ACCOUNTS_COLUMNS:
  257. if col_name not in existing_cols and "PRIMARY KEY" not in col_type:
  258. base_type = col_type.split(" DEFAULT")[0].strip()
  259. try:
  260. await cur.execute(f"ALTER TABLE accounts ADD COLUMN {col_name} {base_type}")
  261. print(f"[DB Migration] Added column: {col_name}")
  262. except Exception as e:
  263. # Column might already exist
  264. if "Duplicate column" not in str(e):
  265. print(f"[DB Migration] Failed to add column {col_name}: {e}")
  266. async def initialize(self) -> None:
  267. if not HAS_AIOMYSQL:
  268. raise ImportError("aiomysql is required for MySQL support. Install with: pip install aiomysql")
  269. self._pool = await aiomysql.create_pool(
  270. host=self._config['host'],
  271. port=self._config['port'],
  272. user=self._config['user'],
  273. password=self._config['password'],
  274. db=self._config['db'],
  275. minsize=1,
  276. maxsize=20,
  277. autocommit=True
  278. )
  279. async with self._pool.acquire() as conn:
  280. async with conn.cursor() as cur:
  281. # Build CREATE TABLE statement from schema definition
  282. columns_sql = ", ".join([f"{col[0]} {col[3]}" for col in ACCOUNTS_COLUMNS])
  283. await cur.execute(f"""
  284. CREATE TABLE IF NOT EXISTS accounts ({columns_sql})
  285. """)
  286. # Run migrations
  287. await self._migrate_schema(cur)
  288. self._initialized = True
  289. async def close(self) -> None:
  290. if self._pool:
  291. self._pool.close()
  292. await self._pool.wait_closed()
  293. self._pool = None
  294. self._initialized = False
  295. def _convert_placeholders(self, query: str) -> str:
  296. """Convert ? placeholders to %s for MySQL."""
  297. return query.replace('?', '%s')
  298. async def execute(self, query: str, params: tuple = ()) -> int:
  299. mysql_query = self._convert_placeholders(query)
  300. async with self._pool.acquire() as conn:
  301. async with conn.cursor() as cur:
  302. await cur.execute(mysql_query, params)
  303. return cur.rowcount
  304. async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
  305. mysql_query = self._convert_placeholders(query)
  306. async with self._pool.acquire() as conn:
  307. async with conn.cursor(aiomysql.DictCursor) as cur:
  308. await cur.execute(mysql_query, params)
  309. return await cur.fetchone()
  310. async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
  311. mysql_query = self._convert_placeholders(query)
  312. async with self._pool.acquire() as conn:
  313. async with conn.cursor(aiomysql.DictCursor) as cur:
  314. await cur.execute(mysql_query, params)
  315. return await cur.fetchall()
  316. # Global database instance
  317. _db: Optional[DatabaseBackend] = None
  318. def get_database_backend() -> DatabaseBackend:
  319. """Get the configured database backend based on DATABASE_URL."""
  320. global _db
  321. if _db is not None:
  322. return _db
  323. database_url = os.getenv('DATABASE_URL', '').strip()
  324. if database_url.startswith(('postgres://', 'postgresql://')):
  325. # Fix common postgres:// to postgresql:// for asyncpg
  326. dsn = database_url.replace('postgres://', 'postgresql://', 1) if database_url.startswith('postgres://') else database_url
  327. _db = PostgresBackend(dsn)
  328. print(f"[DB] Using PostgreSQL backend")
  329. elif database_url.startswith('mysql://'):
  330. _db = MySQLBackend(database_url)
  331. print(f"[DB] Using MySQL backend")
  332. else:
  333. # Default to SQLite
  334. base_dir = Path(__file__).resolve().parent
  335. db_path = base_dir / "data.sqlite3"
  336. _db = SQLiteBackend(db_path)
  337. print(f"[DB] Using SQLite backend: {db_path}")
  338. return _db
  339. async def init_db() -> DatabaseBackend:
  340. """Initialize and return the database backend."""
  341. db = get_database_backend()
  342. await db.initialize()
  343. return db
  344. async def close_db() -> None:
  345. """Close the database backend."""
  346. global _db
  347. if _db:
  348. await _db.close()
  349. _db = None
  350. # Helper functions for common operations
  351. def row_to_dict(row: Dict[str, Any]) -> Optional[Dict[str, Any]]:
  352. """Convert a database row to dict with JSON parsing for 'other' field."""
  353. if row is None:
  354. return None
  355. d = dict(row)
  356. if d.get("other"):
  357. try:
  358. d["other"] = json.loads(d["other"])
  359. except Exception:
  360. pass
  361. # normalize enabled to bool
  362. if "enabled" in d and d["enabled"] is not None:
  363. try:
  364. d["enabled"] = bool(int(d["enabled"]))
  365. except Exception:
  366. d["enabled"] = bool(d["enabled"])
  367. return d