AIO-Databases
The package gives you async support for a range of databases (SQLite,
PostgreSQL, MySQL).
Features
Requirements
Installation
aio-databases should be installed using pip:
$ pip install aio-databases
You have to choose and install the required database drivers with:
# To support SQLite
$ pip install aio-databases[aiosqlite]
# To support MySQL
$ pip install aio-databases[aiomysql]
$ pip install aio-databases[trio_mysql]
# To support PostgreSQL (choose one)
$ pip install aio-databases[aiopg]
$ pip install aio-databases[asyncpg]
$ pip install aio-databases[triopg]
# To support ODBC (alpha state)
$ pip install aio-databases[aioodbc]
Usage
Init a database
from aio_databases import Database
db = Database('sqlite:///:memory:')
db = Database('asyncpg+pool://test:test@localhost:5432/tests', maxsize=10)
Supported schemas
aiomyql
aiomyql+pool
aiopg
aiopg+pool
asyncpg
asyncpg+pool
aioodbc
aioodbc+pool
aiosqlite
trio-mysql
triopg
Setup a pool of connections (optional)
Setup a pool of connections
async def my_app_starts():
await db.connect()
async def my_app_ends():
await db.disconnect()
async with db:
await my_main_coroutine()
Get a connection
async with db.connection():
await my_code()
async with db.connection(False):
await my_code()
If a pool is setup it will be used
Run SQL queries
await db.execute('select $1', '1')
await db.executemany('select $1', '1', '2', '3')
records = await db.fetchall('select (2 * $1) res', 2)
assert records == [(4,)]
record = await db.fetchone('select (2 * $1) res', 2)
assert record == (4,)
assert record['res'] == 4
result = await db.fetchval('select 2 * $1', 2)
assert result == 4
- Iterate through rows one by one
async for rec in db.iterate('select name from users'):
print(rec)
Manage connections
By default the database opens and closes a connection for a query.
await db.fetchone('select %s', 42)
await db.fetchone('select %s', 77)
Manually open and close a connection
async with db.connection():
await db.fetchone('select %s', 42)
await db.fetchone('select %s', 77)
async with db.connection(False):
If there any connection already db.method
would be using the current one
async with db.connection():
await db.fetchone('select %s', 42)
await db.fetchone('select %s', 77)
Manage transactions
async with db.transaction() as trans1:
async with db.transaction() as trans2:
await trans2.rollback()
await trans1.commit()
async with db.tranction(True) as trans:
Bug tracker
If you have any suggestions, bug reports or annoyances please report them to
the issue tracker at https://github.com/klen/aio-databases/issues
Contributing
Development of the project happens at: https://github.com/klen/aio-databases
License
Licensed under a MIT License