Skip to content

An async wrapper for the sqlite3 module compatible with both asyncio and trio.

License

Notifications You must be signed in to change notification settings

merlinz01/anysqlite3

Repository files navigation

anysqlite3

anysqlite3 is a wrapper around sqlite3 that allows you to interact with SQLite databases from async code. It is built on top of the built-in sqlite3 module and is compatible with both asyncio and trio code.

Installation

pip install anysqlite3

Usage

anysqlite3 provides essentially the same API as the built-in sqlite3 module, but with async versions of most methods.

import anyio # or asyncio or trio
import anysqlite3

async def main():
    async with await anysqlite3.connect(":memory:") as db:
        await db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
        await db.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
        await db.execute("INSERT INTO users (name) VALUES (?)", ("Bob",))

        async for row in db.execute("SELECT * FROM users"):
            print(row)

anyio.run(main())

Transactions

anysqlite3 provides a context manager for transactions. Use this instead of the database's commit and rollback methods. Transactions hold a lock on the database, so you should always use them in a with block.

async with db.transaction() as t:
    await db.execute("INSERT INTO users (name) VALUES (?)", ("Charlie",))
    await t.rollback()
    await db.execute("INSERT INTO users (name) VALUES (?)", ("David",))
    await t.commit() # Optional, as the transaction will commit automatically the with block exits without an exception

License

This project is licensed under the MIT License - see LICENSE.txt for details.

About

An async wrapper for the sqlite3 module compatible with both asyncio and trio.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages