diff --git a/src/core/db.py b/src/core/db.py new file mode 100644 index 0000000..728f35d --- /dev/null +++ b/src/core/db.py @@ -0,0 +1,25 @@ +"""ChromaDB 数据库层.""" +import chromadb +from chromadb.api.models.Collection import Collection + + +class VectorDB: + """向量数据库封装.""" + + def __init__(self, persist_dir: str = "./data"): + self.client = chromadb.PersistentClient(path=persist_dir) + + def get_or_create_collection(self, name: str) -> Collection: + """获取或创建 collection.""" + return self.client.get_or_create_collection(name=name) + + def delete_collection(self, name: str) -> None: + """删除 collection.""" + try: + self.client.delete_collection(name=name) + except ValueError: + pass # collection 不存在则忽略 + + def close(self) -> None: + """释放数据库连接.""" + self.client.close() diff --git a/tests/test_db.py b/tests/test_db.py new file mode 100644 index 0000000..f217e95 --- /dev/null +++ b/tests/test_db.py @@ -0,0 +1,48 @@ +"""数据库层测试.""" +import gc +import tempfile +from pathlib import Path + +import pytest + +from src.core.db import VectorDB + + +class TestVectorDB: + """VectorDB 测试.""" + + @pytest.fixture + def temp_dir(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as d: + yield d + + def test_init_creates_persist_directory(self, temp_dir): + """初始化时自动创建持久化目录.""" + db = VectorDB(persist_dir=temp_dir + "/subdir") + assert Path(temp_dir + "/subdir").exists() + assert db.client is not None + + def test_get_or_create_collection(self, temp_dir): + """创建或获取 collection.""" + db = VectorDB(persist_dir=temp_dir) + col = db.get_or_create_collection("test_col") + assert col.name == "test_col" + + # 再次获取应返回同一个 + col2 = db.get_or_create_collection("test_col") + assert col2.name == "test_col" + + def test_count_returns_zero_for_empty_collection(self, temp_dir): + """空 collection 文档数为 0.""" + db = VectorDB(persist_dir=temp_dir) + col = db.get_or_create_collection("test_col") + assert col.count() == 0 + + def test_delete_collection(self, temp_dir): + """删除 collection.""" + db = VectorDB(persist_dir=temp_dir) + db.get_or_create_collection("tmp_col") + db.delete_collection("tmp_col") + # 再次获取会创建新的 + col = db.get_or_create_collection("tmp_col") + assert col.count() == 0