commit 115312bd5e66f29f99dd81a3ca8b982e71597860 Author: chakcy <947105045@qq.com> Date: Wed Jul 22 15:21:06 2026 +0800 add first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c8f0442 --- /dev/null +++ b/.gitignore @@ -0,0 +1,72 @@ +/target + +# Byte-compiled / optimized / DLL files +__pycache__/ +.pytest_cache/ +*.py[cod] + +# C extensions +*.so + +# Distribution / packaging +.Python +.venv/ +env/ +bin/ +build/ +develop-eggs/ +dist/ +eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +include/ +man/ +venv/ +*.egg-info/ +.installed.cfg +*.egg + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt +pip-selfcheck.json + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.cache +nosetests.xml +coverage.xml + +# Translations +*.mo + +# Mr Developer +.mr.developer.cfg +.project +.pydevproject + +# Rope +.ropeproject + +# Django stuff: +*.log +*.pot + +.DS_Store + +# Sphinx documentation +docs/_build/ + +# PyCharm +.idea/ + +# VSCode +.vscode/ + +# Pyenv +.python-version diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..50296d8 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,17 @@ +[build-system] +build-backend = "hatchling.build" +requires = ["hatchling"] + +[project] +name = "database" +version = "0.1.0" +description = "Add your description here" +readme = "README.md" +requires-python = ">=3.12" +dependencies = [ + "aiosqlite>=0.22.1", + "sqlmodel>=0.0.39", +] + +[tool.hatch.build.targets.wheel] +packages = ["src/chongming_database"] diff --git a/src/chongming_database/__init__.py b/src/chongming_database/__init__.py new file mode 100644 index 0000000..e18c02b --- /dev/null +++ b/src/chongming_database/__init__.py @@ -0,0 +1,39 @@ +from pathlib import Path +from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine, AsyncSession +from sqlalchemy.orm import sessionmaker +from sqlmodel import SQLModel + +class Database: + def __init__(self, db_path: Path): + self._engine: AsyncEngine | None = None + self._session_maker: sessionmaker | None = None + self._db_path = db_path + self._db_path.parent.mkdir(parents=True, exist_ok=True) + + async def initialize(self): + """异步初始化,创建引擎并建立表""" + self._engine = create_async_engine( + f"sqlite+aiosqlite:///{self._db_path}", + echo=False, + future=True, + ) + async with self._engine.begin() as conn: + await conn.run_sync(SQLModel.metadata.create_all) + self._session_maker = sessionmaker( + self._engine, # type: ignore + class_=AsyncSession, + expire_on_commit=False + ) # type: ignore + + def get_session(self): + """返回一个异步上下文管理器,用于获取会话""" + if self._session_maker is None: + raise RuntimeError("Database not initialized") + return self._session_maker() + + async def dispose(self): + """关闭引擎,释放资源""" + if self._engine: + await self._engine.dispose() + self._engine = None + self._session_maker = None \ No newline at end of file