aiosqlite icon indicating copy to clipboard operation
aiosqlite copied to clipboard

fix error for cursor.connection(return not async connection)

Open ArtemIsmagilov opened this issue 1 year ago • 1 comments
trafficstars

await cur.connection.commit()
          ^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 126329731884608 and this is thread id 126329755602944.

Description

method connection for cursor return not async connection

Fixes: # replace on async connection self._conn

ArtemIsmagilov avatar May 02 '24 00:05 ArtemIsmagilov

my usecase, where was error.

from contextlib import asynccontextmanager

import aiosqlite
from aiosqlite import Cursor

from settings import conf


@asynccontextmanager
async def get_db() -> Cursor:
    async with aiosqlite.connect(conf.DATABASE_URL) as conn:
        conn.row_factory = aiosqlite.Row
        if conf.SQLITE3_ECHO:
            await conn.set_trace_callback(print)
        async with conn.cursor() as cur:
            yield cur
import asyncio
from sql_app.database import get_db


async def main():

    async with get_db() as cur:
        with open("sql_app/sql_files/create_table_cities.sql") as f:
            data = f.read()
        await cur.executescript(data)
        await cur.connection.commit()


if __name__ == "__main__":
    asyncio.run(main())

result:

await cur.connection.commit()

          ^^^^^^^^^^^^^^^^^^^^^^^

sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 126329731884608 and this is thread id 126329755602944.

ArtemIsmagilov avatar May 02 '24 00:05 ArtemIsmagilov

This is unfortunately a breaking change of functionality that should have a greater think about how to transition functionality. As a workaround, await cursor._conn.commit() should work.

amyreese avatar Feb 03 '25 07:02 amyreese