Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.
Python aiburrchatbot-frameworkdagsgenerative-aigraphshacktoberfestllmopsllmsmlopspersistent-data-structurestate-machinestate-managementvisibility
Add general methods to sync and async SQLite persisters.
jernejfrankf30adf464b10
diff --git a/burr/core/persistence.py b/burr/core/persistence.pyindex 3b302ff1..24449a51 100644--- a/burr/core/persistence.py+++ b/burr/core/persistence.py@@ -288,6 +288,40 @@ class AsyncDevNullPersister(AsyncBaseStatePersister):class SQLitePersister(BaseStatePersister, BaseCopyable):"""Class for SQLite persistence of state. This is a simple implementation."""+ @classmethod+ def from_config(cls, config: dict) -> "SQLitePersister":+ """Creates a new instance of the SQLitePersister from a configuration dictionary.++ The config key:value pair needed are:+ db_path: str,+ table_name: str,+ serde_kwargs: dict,+ connect_kwargs: dict,+ """+ return cls.from_values(**config)++ @classmethod+ def from_values(+ cls,+ db_path: str,+ table_name: str = "burr_state",+ serde_kwargs: dict = None,+ connect_kwargs: dict = None,+ ) -> "SQLitePersister":+ """Creates a new instance of the SQLitePersister from passed in values.++ :param db_path: the path the DB will be stored.+ :param table_name: the table name to store things under.+ :param serde_kwargs: kwargs for state serialization/deserialization.+ :param connect_kwargs: kwargs to pass to the aiosqlite.connect method.+ :return: async sqlite persister instance with an open connection. You are responsible+ for closing the connection yourself.+ """+ connection = sqlite3.connect(+ db_path, **connect_kwargs if connect_kwargs is not None else {}+ )+ return cls(db_path, table_name, serde_kwargs, connection=connection)+def copy(self) -> "Self":return SQLitePersister(db_path=self.db_path,@@ -304,6 +338,7 @@ class SQLitePersister(BaseStatePersister, BaseCopyable):table_name: str = "burr_state",serde_kwargs: dict = None,connect_kwargs: dict = None,+ connection: sqlite3.Connection = None,):"""Constructor@@ -312,16 +347,37 @@ class SQLitePersister(BaseStatePersister, BaseCopyable)::param serde_kwargs: kwargs for state serialization/deserialization.:param connect_kwargs: kwargs to pass to the sqlite3.connect method.Use check_same_thread=False to enable use ina multithreaded context+ :param connection: ability to instantiate a db outside of the persister and pass+ in the connection to be used."""self.db_path = db_pathself.table_name = table_name- self.connection = sqlite3.connect(- db_path, **connect_kwargs if connect_kwargs is not None else {}- )++ # Here for backwards compatibility, the original idea was to create the connection+ # but later we realized it also makes sense to pass the connection to the class and+ # handle cleanup manually.+ if connection is None:+ self.connection = sqlite3.connect(+ db_path, **connect_kwargs if connect_kwargs is not None else {}+ )+ else:+ self.connection = connection+self.serde_kwargs = serde_kwargs or {}self._initialized = Falseself._connect_kwargs = connect_kwargs+ def __enter__(self):+ return self++ def __exit__(self, exc_type, exc_value, traceback):+ self.connection.close()+ return False++ def set_serde_kwargs(self, serde_kwargs: dict):+ """Sets the serde_kwargs for the persister."""+ self.serde_kwargs = serde_kwargs+def create_table_if_not_exists(self, table_name: str):"""Helper function to create the table where things are stored if it doesn't exist."""cursor = self.connection.cursor()@@ -485,7 +541,15 @@ class SQLitePersister(BaseStatePersister, BaseCopyable):)self.connection.commit()+ def cleanup(self):+ """Closes the connection to the database."""+ self.connection.close()+def __del__(self):+ # This should be deprecated -- using __del__ is unreliable for closing connections to db's;+ # the preferred way should be for the user to use a context manager or use the `.cleanup()`+ # method within a REST API framework.+# closes connection at end when things are being shutdown.self.connection.close()diff --git a/burr/integrations/persisters/b_aiosqlite.py b/burr/integrations/persisters/b_aiosqlite.pyindex 26508e6b..bb00b1af 100644--- a/burr/integrations/persisters/b_aiosqlite.py+++ b/burr/integrations/persisters/b_aiosqlite.py@@ -19,12 +19,20 @@ except ImportError:class AsyncSQLitePersister(AsyncBaseStatePersister, BaseCopyable):"""Class for asynchronous SQLite persistence of state. This is a simple implementation.- SQLite is specifically single-threaded and `aiosqlite <https://aiosqlite.omnilib.dev/en/latest/index.html>`_- creates async support through multi-threading. This persister is mainly here for quick prototyping and testing;- we suggest to consider a different database with native async support for production.+ .. warning::+ The synchronous persister closes the connection on deletion of the class using the ``__del__`` method.+ In an async context that is not reliable (the event loop may already be closed by the time ``__del__``+ gets invoked). Therefore, you are responsible for closing the connection yourself (i.e. manual cleanup).+ We suggest to use the persister either as a context manager through the ``async with`` clause or+ using the method ``.cleanup()``.- Note the third-party library `aiosqlite <https://aiosqlite.omnilib.dev/en/latest/index.html>`_,- is maintained and considered stable considered stable: https://github.com/omnilib/aiosqlite/issues/309.+ .. note::+ SQLite is specifically single-threaded and `aiosqlite <https://aiosqlite.omnilib.dev/en/latest/index.html>`_+ creates async support through multi-threading. This persister is mainly here for quick prototyping and testing;+ we suggest to consider a different database with native async support for production.++ Note the third-party library `aiosqlite <https://aiosqlite.omnilib.dev/en/latest/index.html>`_,+ is maintained and considered stable considered stable: https://github.com/omnilib/aiosqlite/issues/309."""def copy(self) -> "Self":@@ -34,6 +42,18 @@ class AsyncSQLitePersister(AsyncBaseStatePersister, BaseCopyable):PARTITION_KEY_DEFAULT = ""+ @classmethod+ async def from_config(cls, config: dict) -> "AsyncSQLitePersister":+ """Creates a new instance of the AsyncSQLitePersister from a configuration dictionary.++ The config key:value pair needed are:+ db_path: str,+ table_name: str,+ serde_kwargs: dict,+ connect_kwargs: dict,+ """+ return await cls.from_values(**config)+@classmethodasync def from_values(cls,@@ -76,6 +96,17 @@ class AsyncSQLitePersister(AsyncBaseStatePersister, BaseCopyable):self.serde_kwargs = serde_kwargs or {}self._initialized = False+ def set_serde_kwargs(self, serde_kwargs: dict):+ """Sets the serde_kwargs for the persister."""+ self.serde_kwargs = serde_kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc_value, traceback):+ await self.connection.close()+ return False+async def create_table_if_not_exists(self, table_name: str):"""Helper function to create the table where things are stored if it doesn't exist."""cursor = await self.connection.cursor()@@ -246,5 +277,11 @@ class AsyncSQLitePersister(AsyncBaseStatePersister, BaseCopyable):)await self.connection.commit()+ async def cleanup(self):+ """Closes the connection to the database."""+ await self.connection.close()+async def close(self):+ """This is deprecated, please use .cleanup()"""+ logger.warning("The .close() method will be deprecated, please use .cleanup() instead.")await self.connection.close()diff --git a/tests/core/test_persistence.py b/tests/core/test_persistence.pyindex f8370fba..a1adb799 100644--- a/tests/core/test_persistence.py+++ b/tests/core/test_persistence.py@@ -13,15 +13,19 @@ from burr.core.persistence import InMemoryPersister, SQLLitePersisterdef persistence(request):which = request.param["which"]if which == "sqlite":- return SQLLitePersister(db_path=":memory:", table_name="test_table")+ persister = SQLLitePersister(db_path=":memory:", table_name="test_table")+ yield persister+ persister.cleanup()elif which == "memory":- return InMemoryPersister()+ yield InMemoryPersister()# return SQLLitePersister(db_path=":memory:", table_name="test_table")@pytest.fixture()def initializing_persistence():- return SQLLitePersister(db_path=":memory:", table_name="test_table")+ persister = SQLLitePersister(db_path=":memory:", table_name="test_table")+ yield persister+ persister.cleanup()def test_persistence_initialization_creates_table(initializing_persistence):@@ -69,6 +73,8 @@ def test_sqlite_persistence_is_initialized_true_new_connection(tmp_path):assert p.is_initialized()p2 = SQLLitePersister(db_path=db_path, table_name="test_table")assert p2.is_initialized()+ p.cleanup()+ p2.cleanup()@pytest.mark.parametrize(diff --git a/tests/integrations/persisters/test_b_aiosqlite.py b/tests/integrations/persisters/test_b_aiosqlite.pyindex 889d54ef..8e5bfe50 100644--- a/tests/integrations/persisters/test_b_aiosqlite.py+++ b/tests/integrations/persisters/test_b_aiosqlite.py@@ -16,7 +16,7 @@ class AsyncSQLiteContextManager:return self.clientasync def __aexit__(self, exc_type, exc, tb):- await self.client.close()+ await self.client.cleanup()async def test_copy_persister(async_persistence: AsyncSQLitePersister):