omnilib / aiosqlite

asyncio bridge to the standard sqlite3 module
https://aiosqlite.omnilib.dev
MIT License
1.22k stars 94 forks source link

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

Open ArtemIsmagilov opened 6 months ago

ArtemIsmagilov commented 6 months ago
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 commented 6 months ago

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.