-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathdb.py
More file actions
438 lines (367 loc) · 16.2 KB
/
db.py
File metadata and controls
438 lines (367 loc) · 16.2 KB
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
"""
Database abstraction layer supporting SQLite, PostgreSQL, and MySQL.
Backend selection is based on DATABASE_URL environment variable:
- postgres://... or postgresql://... -> PostgreSQL
- mysql://... -> MySQL
- Not set -> SQLite (default)
"""
import os
import json
import time
import asyncio
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple, Set
from abc import ABC, abstractmethod
import aiosqlite
# Schema version for migrations
SCHEMA_VERSION = 1
# Define all columns that should exist in the accounts table
# Format: (column_name, column_type_sqlite, column_type_postgres, column_type_mysql, default_value)
ACCOUNTS_COLUMNS = [
("id", "TEXT PRIMARY KEY", "TEXT PRIMARY KEY", "VARCHAR(255) PRIMARY KEY", None),
("label", "TEXT", "TEXT", "TEXT", None),
("clientId", "TEXT", "TEXT", "TEXT", None),
("clientSecret", "TEXT", "TEXT", "TEXT", None),
("refreshToken", "TEXT", "TEXT", "TEXT", None),
("accessToken", "TEXT", "TEXT", "TEXT", None),
("other", "TEXT", "TEXT", "TEXT", None),
("last_refresh_time", "TEXT", "TEXT", "TEXT", None),
("last_refresh_status", "TEXT", "TEXT", "TEXT", None),
("created_at", "TEXT", "TEXT", "TEXT", None),
("updated_at", "TEXT", "TEXT", "TEXT", None),
("enabled", "INTEGER DEFAULT 1", "INTEGER DEFAULT 1", "INT DEFAULT 1", "1"),
("error_count", "INTEGER DEFAULT 0", "INTEGER DEFAULT 0", "INT DEFAULT 0", "0"),
("success_count", "INTEGER DEFAULT 0", "INTEGER DEFAULT 0", "INT DEFAULT 0", "0"),
("expires_at", "TEXT", "TEXT", "TEXT", None),
]
# Optional imports for other backends
try:
import asyncpg
HAS_ASYNCPG = True
except ImportError:
HAS_ASYNCPG = False
try:
import aiomysql
HAS_AIOMYSQL = True
except ImportError:
HAS_AIOMYSQL = False
class DatabaseBackend(ABC):
"""Abstract base class for database backends."""
@abstractmethod
async def initialize(self) -> None:
"""Initialize connection and ensure schema exists."""
pass
@abstractmethod
async def close(self) -> None:
"""Close database connections."""
pass
@abstractmethod
async def execute(self, query: str, params: tuple = ()) -> int:
"""Execute a query and return affected row count."""
pass
@abstractmethod
async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
"""Fetch a single row as dict."""
pass
@abstractmethod
async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
"""Fetch all rows as list of dicts."""
pass
class SQLiteBackend(DatabaseBackend):
"""SQLite database backend using aiosqlite."""
def __init__(self, db_path: Path):
self._db_path = db_path
self._initialized = False
self._conn: Optional[aiosqlite.Connection] = None
async def _get_existing_columns(self) -> Set[str]:
"""Get existing column names from accounts table."""
try:
async with self._conn.execute("PRAGMA table_info(accounts)") as cursor:
rows = await cursor.fetchall()
return {row[1] for row in rows}
except Exception:
return set()
async def _migrate_schema(self) -> None:
"""Add missing columns to accounts table."""
existing_cols = await self._get_existing_columns()
if not existing_cols:
return # Table doesn't exist yet, will be created fresh
for col_name, col_type, _, _, _ in ACCOUNTS_COLUMNS:
if col_name not in existing_cols and "PRIMARY KEY" not in col_type:
# Extract just the type without DEFAULT clause for ALTER TABLE
base_type = col_type.split(" DEFAULT")[0].strip()
try:
await self._conn.execute(f"ALTER TABLE accounts ADD COLUMN {col_name} {base_type}")
print(f"[DB Migration] Added column: {col_name}")
except Exception as e:
print(f"[DB Migration] Failed to add column {col_name}: {e}")
async def initialize(self) -> None:
if self._initialized:
return
self._db_path.parent.mkdir(parents=True, exist_ok=True)
self._conn = await aiosqlite.connect(self._db_path)
# Performance tuning PRAGMAs
await self._conn.execute("PRAGMA journal_mode=WAL;")
await self._conn.execute("PRAGMA synchronous = NORMAL;")
await self._conn.execute("PRAGMA cache_size = -65536; -- 64MB")
await self._conn.execute("PRAGMA temp_store = MEMORY;")
# Build CREATE TABLE statement from schema definition
columns_sql = ", ".join([f"{col[0]} {col[1]}" for col in ACCOUNTS_COLUMNS])
await self._conn.execute(f"""
CREATE TABLE IF NOT EXISTS accounts ({columns_sql})
""")
# Run migrations for existing tables
await self._migrate_schema()
# Create indexes for performance
await self._conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_enabled ON accounts (enabled);")
await self._conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_created_at ON accounts (created_at);")
await self._conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_success_count ON accounts (success_count);")
await self._conn.commit()
self._initialized = True
async def close(self) -> None:
if self._conn:
await self._conn.close()
self._conn = None
self._initialized = False
async def execute(self, query: str, params: tuple = ()) -> int:
cursor = await self._conn.execute(query, params)
await self._conn.commit()
return cursor.rowcount
async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
self._conn.row_factory = aiosqlite.Row
async with self._conn.execute(query, params) as cursor:
row = await cursor.fetchone()
return dict(row) if row else None
async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
self._conn.row_factory = aiosqlite.Row
async with self._conn.execute(query, params) as cursor:
rows = await cursor.fetchall()
return [dict(row) for row in rows]
class PostgresBackend(DatabaseBackend):
"""PostgreSQL database backend using asyncpg."""
def __init__(self, dsn: str):
self._dsn = dsn
self._pool: "Optional[asyncpg.pool.Pool]" = None
self._initialized = False
async def _get_existing_columns(self, conn) -> Set[str]:
"""Get existing column names from accounts table."""
try:
rows = await conn.fetch("""
SELECT column_name FROM information_schema.columns
WHERE table_name = 'accounts'
""")
return {row['column_name'] for row in rows}
except Exception:
return set()
async def _migrate_schema(self, conn) -> None:
"""Add missing columns to accounts table."""
existing_cols = await self._get_existing_columns(conn)
if not existing_cols:
return # Table doesn't exist yet
for col_name, _, col_type, _, _ in ACCOUNTS_COLUMNS:
if col_name not in existing_cols and "PRIMARY KEY" not in col_type:
base_type = col_type.split(" DEFAULT")[0].strip()
try:
await conn.execute(f"ALTER TABLE accounts ADD COLUMN IF NOT EXISTS {col_name} {base_type}")
print(f"[DB Migration] Added column: {col_name}")
except Exception as e:
print(f"[DB Migration] Failed to add column {col_name}: {e}")
async def initialize(self) -> None:
if not HAS_ASYNCPG:
raise ImportError("asyncpg is required for PostgreSQL support. Install with: pip install asyncpg")
self._pool = await asyncpg.create_pool(dsn=self._dsn, min_size=1, max_size=20)
async with self._pool.acquire() as conn:
# Build CREATE TABLE statement from schema definition
columns_sql = ", ".join([f"{col[0]} {col[2]}" for col in ACCOUNTS_COLUMNS])
await conn.execute(f"""
CREATE TABLE IF NOT EXISTS accounts ({columns_sql})
""")
# Run migrations
await self._migrate_schema(conn)
self._initialized = True
async def close(self) -> None:
if self._pool:
await self._pool.close()
self._pool = None
self._initialized = False
def _convert_placeholders(self, query: str) -> str:
"""Convert ? placeholders to $1, $2, etc."""
result = []
param_num = 0
i = 0
while i < len(query):
if query[i] == '?':
param_num += 1
result.append(f'${param_num}')
else:
result.append(query[i])
i += 1
return ''.join(result)
async def execute(self, query: str, params: tuple = ()) -> int:
pg_query = self._convert_placeholders(query)
async with self._pool.acquire() as conn:
result = await conn.execute(pg_query, *params)
# asyncpg returns string like "UPDATE 1"
try:
return int(result.split()[-1])
except (ValueError, IndexError):
return 0
async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
pg_query = self._convert_placeholders(query)
async with self._pool.acquire() as conn:
row = await conn.fetchrow(pg_query, *params)
return dict(row) if row else None
async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
pg_query = self._convert_placeholders(query)
async with self._pool.acquire() as conn:
rows = await conn.fetch(pg_query, *params)
return [dict(row) for row in rows]
class MySQLBackend(DatabaseBackend):
"""MySQL database backend using aiomysql."""
def __init__(self, dsn: str):
self._dsn = dsn
self._pool = None
self._initialized = False
self._config = self._parse_dsn(dsn)
def _parse_dsn(self, dsn: str) -> Dict[str, Any]:
"""Parse MySQL DSN into connection parameters."""
# mysql://user:password@host:port/database
from urllib.parse import urlparse, parse_qs
parsed = urlparse(dsn)
config = {
'host': parsed.hostname or 'localhost',
'port': parsed.port or 3306,
'user': parsed.username or 'root',
'password': parsed.password or '',
'db': parsed.path.lstrip('/') if parsed.path else 'test',
}
# Handle SSL
query = parse_qs(parsed.query)
if 'ssl' in query or 'sslmode' in query or 'ssl-mode' in query:
config['ssl'] = True
return config
async def _get_existing_columns(self, cur) -> Set[str]:
"""Get existing column names from accounts table."""
try:
await cur.execute(f"DESCRIBE accounts")
rows = await cur.fetchall()
return {row[0] if isinstance(row, tuple) else row['Field'] for row in rows}
except Exception:
return set()
async def _migrate_schema(self, cur) -> None:
"""Add missing columns to accounts table."""
existing_cols = await self._get_existing_columns(cur)
if not existing_cols:
return # Table doesn't exist yet
for col_name, _, _, col_type, _ in ACCOUNTS_COLUMNS:
if col_name not in existing_cols and "PRIMARY KEY" not in col_type:
base_type = col_type.split(" DEFAULT")[0].strip()
try:
await cur.execute(f"ALTER TABLE accounts ADD COLUMN {col_name} {base_type}")
print(f"[DB Migration] Added column: {col_name}")
except Exception as e:
# Column might already exist
if "Duplicate column" not in str(e):
print(f"[DB Migration] Failed to add column {col_name}: {e}")
async def initialize(self) -> None:
if not HAS_AIOMYSQL:
raise ImportError("aiomysql is required for MySQL support. Install with: pip install aiomysql")
self._pool = await aiomysql.create_pool(
host=self._config['host'],
port=self._config['port'],
user=self._config['user'],
password=self._config['password'],
db=self._config['db'],
minsize=1,
maxsize=20,
autocommit=True
)
async with self._pool.acquire() as conn:
async with conn.cursor() as cur:
# Build CREATE TABLE statement from schema definition
columns_sql = ", ".join([f"{col[0]} {col[3]}" for col in ACCOUNTS_COLUMNS])
await cur.execute(f"""
CREATE TABLE IF NOT EXISTS accounts ({columns_sql})
""")
# Run migrations
await self._migrate_schema(cur)
self._initialized = True
async def close(self) -> None:
if self._pool:
self._pool.close()
await self._pool.wait_closed()
self._pool = None
self._initialized = False
def _convert_placeholders(self, query: str) -> str:
"""Convert ? placeholders to %s for MySQL."""
return query.replace('?', '%s')
async def execute(self, query: str, params: tuple = ()) -> int:
mysql_query = self._convert_placeholders(query)
async with self._pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(mysql_query, params)
return cur.rowcount
async def fetchone(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
mysql_query = self._convert_placeholders(query)
async with self._pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cur:
await cur.execute(mysql_query, params)
return await cur.fetchone()
async def fetchall(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
mysql_query = self._convert_placeholders(query)
async with self._pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cur:
await cur.execute(mysql_query, params)
return await cur.fetchall()
# Global database instance
_db: Optional[DatabaseBackend] = None
def get_database_backend() -> DatabaseBackend:
"""Get the configured database backend based on DATABASE_URL."""
global _db
if _db is not None:
return _db
database_url = os.getenv('DATABASE_URL', '').strip()
if database_url.startswith(('postgres://', 'postgresql://')):
# Fix common postgres:// to postgresql:// for asyncpg
dsn = database_url.replace('postgres://', 'postgresql://', 1) if database_url.startswith('postgres://') else database_url
_db = PostgresBackend(dsn)
print(f"[DB] Using PostgreSQL backend")
elif database_url.startswith('mysql://'):
_db = MySQLBackend(database_url)
print(f"[DB] Using MySQL backend")
else:
# Default to SQLite
base_dir = Path(__file__).resolve().parent
db_path = base_dir / "data.sqlite3"
_db = SQLiteBackend(db_path)
print(f"[DB] Using SQLite backend: {db_path}")
return _db
async def init_db() -> DatabaseBackend:
"""Initialize and return the database backend."""
db = get_database_backend()
await db.initialize()
return db
async def close_db() -> None:
"""Close the database backend."""
global _db
if _db:
await _db.close()
_db = None
# Helper functions for common operations
def row_to_dict(row: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Convert a database row to dict with JSON parsing for 'other' field."""
if row is None:
return None
d = dict(row)
if d.get("other"):
try:
d["other"] = json.loads(d["other"])
except Exception:
pass
# normalize enabled to bool
if "enabled" in d and d["enabled"] is not None:
try:
d["enabled"] = bool(int(d["enabled"]))
except Exception:
d["enabled"] = bool(d["enabled"])
return d