From 57385506c1eb0c40e48756f4dbe0a357fe8d1291 Mon Sep 17 00:00:00 2001 From: Yiorgis Gozadinos Date: Thu, 23 Apr 2026 15:29:10 +0300 Subject: [PATCH] Fix is_new_db detection when create=True is passed on an existing DB --- haiku_rag_slim/haiku/rag/store/engine.py | 16 +++++++--------- tests/store/test_migrations.py | 11 +++++++++++ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/haiku_rag_slim/haiku/rag/store/engine.py b/haiku_rag_slim/haiku/rag/store/engine.py index 0c3c3907..08f3279a 100644 --- a/haiku_rag_slim/haiku/rag/store/engine.py +++ b/haiku_rag_slim/haiku/rag/store/engine.py @@ -188,6 +188,7 @@ class Store: self._skip_validation = skip_validation self._skip_migration_check = skip_migration_check self._vacuum_lock = asyncio.Lock() + self._is_new_db = False # Check if database exists (for local filesystem only) if self._connection_mode == ConnectionMode.LOCAL: @@ -197,6 +198,7 @@ class Store: f"Database does not exist at {self.db_path.absolute()}. " "Use 'haiku-rag init' to create a new database." ) + self._is_new_db = True # Ensure parent directories exist for new databases if not db_path.parent.exists(): Path.mkdir(db_path.parent, parents=True) @@ -211,15 +213,11 @@ class Store: self._config, self.db_path ) - # Detect new vs existing database - is_new_db = False - if self._connection_mode == ConnectionMode.LOCAL: - is_new_db = not self.db_path.exists() or self._create - # Re-check after connect: if path didn't exist before, it's new - existing_tables = (await self.db.list_tables()).tables - if not existing_tables: - is_new_db = True - else: + # For remote stores (and as a safety net for local paths that exist but + # have no tables — e.g. a previously failed init), detect new DB by + # checking whether any tables exist. + is_new_db = self._is_new_db + if not is_new_db: existing_tables = (await self.db.list_tables()).tables if not existing_tables: is_new_db = True diff --git a/tests/store/test_migrations.py b/tests/store/test_migrations.py index 85c7104b..ff8f0f94 100644 --- a/tests/store/test_migrations.py +++ b/tests/store/test_migrations.py @@ -67,6 +67,17 @@ class TestMigrationCheck: pass assert "migrate" in str(exc_info.value).lower() + @pytest.mark.asyncio + async def test_pending_migrations_raises_error_with_create_flag(self, temp_db_path): + """Opening an existing DB with create=True must still check migrations.""" + async with Store(temp_db_path, create=True) as store: + await store.set_haiku_version("0.19.0") + + # create=True is idempotent — must not mark an existing populated DB as new + with pytest.raises(MigrationRequiredError): + async with Store(temp_db_path, create=True) as store: + pass + @pytest.mark.asyncio async def test_pending_migrations_read_only_raises_error(self, temp_db_path): """Read-only mode with pending migrations should still raise."""