|
3 | 3 | from sqlalchemy import String, Text, ForeignKey, Boolean, Integer |
4 | 4 | from sqlalchemy.ext.asyncio import create_async_engine |
5 | 5 | from sqlalchemy.types import TypeDecorator |
| 6 | + from sqlalchemy.exc import OperationalError |
6 | 7 | except ImportError as e: |
7 | 8 | raise ImportError( |
8 | 9 | "This module requires 'sqlalchemy' and 'ulid-py'. " |
9 | 10 | "Install them with: pip install codetide[agents-ui]" |
10 | | - ) from e |
| 11 | + ) from e |
11 | 12 |
|
| 13 | +import asyncio |
12 | 14 | from datetime import datetime |
13 | | -from sqlalchemy import Select |
14 | 15 | from ulid import ulid |
15 | | -import asyncio |
16 | 16 | import json |
17 | 17 |
|
18 | 18 | # SQLite-compatible JSON and UUID types |
@@ -169,11 +169,27 @@ class Feedback(Base): |
169 | 169 | # chats = await db.list_chats() |
170 | 170 | # for c in chats: |
171 | 171 | # print(f"{c.id} — {c.name}") |
172 | | -async def init_db(path: str): |
173 | | - from sqlalchemy.ext.asyncio import async_sessionmaker, AsyncSession |
174 | | - engine = create_async_engine(f"sqlite+aiosqlite:///{path}") |
175 | | - async with engine.begin() as conn: |
176 | | - await conn.run_sync(Base.metadata.create_all) |
177 | | - |
178 | | -if __name__ == "__main__": |
179 | | - asyncio.run(init_db("database.db")) |
| 172 | + |
| 173 | +async def init_db(conn_str: str, max_retries: int = 5, retry_delay: int = 2): |
| 174 | + """ |
| 175 | + Initialize database with retry logic for connection issues. |
| 176 | + """ |
| 177 | + engine = create_async_engine(conn_str) |
| 178 | + |
| 179 | + for attempt in range(max_retries): |
| 180 | + try: |
| 181 | + async with engine.begin() as conn: |
| 182 | + await conn.run_sync(Base.metadata.create_all) |
| 183 | + print("Database initialized successfully!") |
| 184 | + return |
| 185 | + except OperationalError as e: |
| 186 | + if attempt == max_retries - 1: |
| 187 | + print(f"Failed to initialize database after {max_retries} attempts: {e}") |
| 188 | + raise |
| 189 | + else: |
| 190 | + print(f"Database connection failed (attempt {attempt + 1}/{max_retries}): {e}") |
| 191 | + print(f"Retrying in {retry_delay} seconds...") |
| 192 | + await asyncio.sleep(retry_delay) |
| 193 | + except Exception as e: |
| 194 | + print(f"Unexpected error initializing database: {e}") |
| 195 | + raise |
0 commit comments