|
1 | 1 | """Database management commands.""" |
2 | 2 |
|
3 | 3 | import asyncio |
| 4 | +from pathlib import Path |
4 | 5 |
|
5 | 6 | import typer |
6 | 7 | from loguru import logger |
| 8 | +from rich.console import Console |
| 9 | +from sqlalchemy.exc import OperationalError |
7 | 10 |
|
8 | 11 | from basic_memory import db |
9 | 12 | from basic_memory.cli.app import app |
10 | | -from basic_memory.config import ConfigManager, BasicMemoryConfig, save_basic_memory_config |
| 13 | +from basic_memory.config import ConfigManager |
| 14 | +from basic_memory.repository import ProjectRepository |
| 15 | +from basic_memory.services.initialization import reconcile_projects_with_config |
| 16 | +from basic_memory.sync.sync_service import get_sync_service |
| 17 | + |
| 18 | +console = Console() |
| 19 | + |
| 20 | + |
| 21 | +async def _reindex_projects(app_config): |
| 22 | + """Reindex all projects in a single async context. |
| 23 | +
|
| 24 | + This ensures all database operations use the same event loop, |
| 25 | + and proper cleanup happens when the function completes. |
| 26 | + """ |
| 27 | + try: |
| 28 | + await reconcile_projects_with_config(app_config) |
| 29 | + |
| 30 | + # Get database session (migrations already run if needed) |
| 31 | + _, session_maker = await db.get_or_create_db( |
| 32 | + db_path=app_config.database_path, |
| 33 | + db_type=db.DatabaseType.FILESYSTEM, |
| 34 | + ) |
| 35 | + project_repository = ProjectRepository(session_maker) |
| 36 | + projects = await project_repository.get_active_projects() |
| 37 | + |
| 38 | + for project in projects: |
| 39 | + console.print(f" Indexing [cyan]{project.name}[/cyan]...") |
| 40 | + logger.info(f"Starting sync for project: {project.name}") |
| 41 | + sync_service = await get_sync_service(project) |
| 42 | + sync_dir = Path(project.path) |
| 43 | + await sync_service.sync(sync_dir, project_name=project.name) |
| 44 | + logger.info(f"Sync completed for project: {project.name}") |
| 45 | + finally: |
| 46 | + # Clean up database connections before event loop closes |
| 47 | + await db.shutdown_db() |
11 | 48 |
|
12 | 49 |
|
13 | 50 | @app.command() |
14 | 51 | def reset( |
15 | 52 | reindex: bool = typer.Option(False, "--reindex", help="Rebuild db index from filesystem"), |
16 | 53 | ): # pragma: no cover |
17 | 54 | """Reset database (drop all tables and recreate).""" |
18 | | - if typer.confirm("This will delete all data in your db. Are you sure?"): |
| 55 | + console.print( |
| 56 | + "[yellow]Note:[/yellow] This only deletes the index database. " |
| 57 | + "Your markdown note files will not be affected.\n" |
| 58 | + "Use [green]bm reset --reindex[/green] to automatically rebuild the index afterward." |
| 59 | + ) |
| 60 | + if typer.confirm("Reset the database index?"): |
19 | 61 | logger.info("Resetting database...") |
20 | 62 | config_manager = ConfigManager() |
21 | 63 | app_config = config_manager.config |
22 | 64 | # Get database path |
23 | 65 | db_path = app_config.app_database_path |
24 | 66 |
|
25 | | - # Delete the database file if it exists |
26 | | - if db_path.exists(): |
27 | | - db_path.unlink() |
28 | | - logger.info(f"Database file deleted: {db_path}") |
| 67 | + # Delete the database file and WAL files if they exist |
| 68 | + for suffix in ["", "-shm", "-wal"]: |
| 69 | + path = db_path.parent / f"{db_path.name}{suffix}" |
| 70 | + if path.exists(): |
| 71 | + try: |
| 72 | + path.unlink() |
| 73 | + logger.info(f"Deleted: {path}") |
| 74 | + except OSError as e: |
| 75 | + console.print( |
| 76 | + f"[red]Error:[/red] Cannot delete {path.name}: {e}\n" |
| 77 | + "The database may be in use by another process (e.g., MCP server).\n" |
| 78 | + "Please close Claude Desktop or any other Basic Memory clients and try again." |
| 79 | + ) |
| 80 | + raise typer.Exit(1) |
29 | 81 |
|
30 | | - # Reset project configuration |
31 | | - config = BasicMemoryConfig() |
32 | | - save_basic_memory_config(config_manager.config_file, config) |
33 | | - logger.info("Project configuration reset to default") |
34 | | - |
35 | | - # Create a new empty database |
36 | | - asyncio.run(db.run_migrations(app_config)) |
37 | | - logger.info("Database reset complete") |
| 82 | + # Create a new empty database (preserves project configuration) |
| 83 | + try: |
| 84 | + asyncio.run(db.run_migrations(app_config)) |
| 85 | + except OperationalError as e: |
| 86 | + if "disk I/O error" in str(e) or "database is locked" in str(e): |
| 87 | + console.print( |
| 88 | + "[red]Error:[/red] Cannot access database. " |
| 89 | + "It may be in use by another process (e.g., MCP server).\n" |
| 90 | + "Please close Claude Desktop or any other Basic Memory clients and try again." |
| 91 | + ) |
| 92 | + raise typer.Exit(1) |
| 93 | + raise |
| 94 | + console.print("[green]Database reset complete[/green]") |
38 | 95 |
|
39 | 96 | if reindex: |
40 | | - # Run database sync directly |
41 | | - from basic_memory.cli.commands.command_utils import run_sync |
42 | | - |
43 | | - logger.info("Rebuilding search index from filesystem...") |
44 | | - asyncio.run(run_sync(project=None)) |
| 97 | + projects = list(app_config.projects) |
| 98 | + if not projects: |
| 99 | + console.print("[yellow]No projects configured. Skipping reindex.[/yellow]") |
| 100 | + else: |
| 101 | + console.print(f"Rebuilding search index for {len(projects)} project(s)...") |
| 102 | + asyncio.run(_reindex_projects(app_config)) |
| 103 | + console.print("[green]Reindex complete[/green]") |
0 commit comments