Usage
=====

Installation
------------

Default installation option is to use pip+git

.. code-block:: console

    (venv) $ pip install git+https://gitea.parrrate.ru/PTV/ptvp35.git

Basic functionality
-------------------

:class:`~ptvp35.DbFactory` class provides context management for database connections (:class:`~ptvp35.DbConnection`) via :code:`async with` statement.
The connection isn't just a "connection", it's also the MMDB itself, so **using two connections to one database is an undefined behaviour**.
Also, that means that each connection start/shutdown is quite time expensive.
These two facts together tell that, if you intend on using the connection, you should probably wrap the main program in an :code:`async with` block.

.. code-block:: python3

    import pathlib
    from ptvp35 import DbFactory, KVJson

    async def main():
        async with DbFactory(pathlib.Path('example.db'), kvfactory=KVJson()) as connection:
            await _main(connection)

Different ways to get/set a value:

.. code-block:: python3

    from ptvp35 import DbConnection

    async def _main(connection: DbConnection):
        value0 = connection.get('increment-0', 0)
        await connection.set('increment-0', value0 + 1)

        value1 = connection.get('increment-1', 0)
        connection.set_nowait('increment-1', value1 + 1)
        await connection.commit()

        async with connection.transaction() as transaction:
            value2 = transaction.get('increment-2', 0)
            transaction.set_nowait('increment-2', value2 + 1)

        async with connection.transaction() as transaction:
            value3 = transaction.get('increment-3', 0)
            transaction.set_nowait('increment-3', value3 + 1)
            await transaction.commit()

        with connection.transaction() as transaction:
            value4 = transaction.get('increment-4', 0)
            transaction.set_nowait('increment-4', value4 + 1)
            await transaction.commit()

        with connection.transaction() as transaction:
            value5 = transaction.get('increment-5', 0)
            transaction.set_nowait('increment-5', value5 + 1)
        await connection.commit()

For common methods see: :class:`~ptvp35.AbstractDbConnection`