Fix is_new_db detection when create=True is passed on an existing DB

This commit is contained in:
Yiorgis Gozadinos 2026-04-23 15:29:10 +03:00
parent ce2df2e0bd
commit 57385506c1
No known key found for this signature in database
2 changed files with 18 additions and 9 deletions

View file

@ -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

View file

@ -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."""