Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.
This repository was archived by the owner on Aug 19, 2025. It is now read-only.

Errors with multiple tasks and transactions in postgresql and sqlite #134

Description

@reclosedev

Minimal reproduce script with comments

import asyncio

import databases
import sqlalchemy as sa

# import logging
# logging.basicConfig(level=logging.DEBUG)


DB_URL = "sqlite:////tmp/test.db"

metadata = sa.MetaData()
table = sa.Table(
    "t1", metadata,
    sa.Column("id", sa.Integer()),
    sa.Column("data", sa.String()),
)
database = databases.Database(DB_URL)


async def init_db():
    engine = sa.create_engine(DB_URL)
    metadata.create_all(engine)
    await database.connect()


async def work(start: int, n=5, data="a"):
    async with database.transaction():
        query = table.insert()
        for i in range(start, n):
            await database.execute(query, {"id": i, "data": data})
    print(f"Ok {start}")


async def main_async():
    await init_db()
    futures = []
    some_query = table.select()
    # Error is raised if there is query executed before creating futures
    # Doesn't matter if transaction is explicit or not
    async with database.transaction():
        # !!! If I remove this query (from parent task), it works fine
        await database.fetch_all(some_query)
    step = 5
    for i in range(0, 4 * step, step):
        fut = asyncio.ensure_future(work(i, i + step))
        futures.append(fut)
    await asyncio.wait(futures)
    print("Done")


loop = asyncio.get_event_loop()
loop.run_until_complete(main_async())

Error with sqlite database:

databases/core.py", line 305, in commit
assert self._connection._transaction_stack[-1] is self

Error with postgresql database:

  File "asyncpg/protocol/protocol.pyx", line 301, in query
  File "asyncpg/protocol/protocol.pyx", line 659, in asyncpg.protocol.protocol.BaseProtocol._check_state
asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions