Registry / database / databases

databases

JSON →
library0.9.0pypypi✓ verified 28d ago

The `databases` library provides asynchronous database support for Python, designed to work with `asyncio` and `await`. It supports PostgreSQL, MySQL, and SQLite, and integrates well with SQLAlchemy Core expression language. The current version is 0.9.0, and it has an active development cadence with regular updates.

pip install databases
INSTALL
IMPORT
SIG · DATABASES
D
databases
databasepythonv0.9.0
Install
3.4s avg
Import
676ms
Disk
52MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v0.9.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.717s · 51.3MB
glibc
py 3.10–3.920 runs
installs and imports cleanly · install 3.4s · import 0.635s · 52MB
52MB installed
● package 52MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Database
✓ from databases import Database
Record
✓ from databases import Record
Represents a single row from a database query result.

This quickstart demonstrates connecting to a database, executing a DDL statement to create a table, inserting a record, and fetching all records. It uses an in-memory SQLite database by default but can be configured with an environment variable for other databases. Remember to install the appropriate database driver (e.g., `pip install databases[sqlite]`).

import asyncio import os from databases import Database async def main(): # Use an in-memory SQLite database for a simple example. # For a real application, use a proper URL like DATABASE_URL = 'postgresql://user:pass@host/db' database = Database(os.environ.get('DATABASE_URL', 'sqlite:///./test.db')) try: await database.connect() print("Database connected.") # Create a table query = """ CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name VARCHAR(100) ); """ await database.execute(query=query) print("Table 'users' created or already exists.") # Insert data query = "INSERT INTO users(name) VALUES (:name)" await database.execute(query=query, values={"name": "Alice"}) print("Inserted 'Alice'.") # Select data query = "SELECT id, name FROM users" rows = await database.fetch_all(query=query) for row in rows: print(f"User: {row['id']}, {row['name']}") except Exception as e: print(f"An error occurred: {e}") finally: await database.disconnect() print("Database disconnected.") if __name__ == "__main__": asyncio.run(main())
Debug
Known issues
breakingVersion 0.9.0 dropped support for Python 3.7 and earlier versions. Additionally, it now officially supports SQLAlchemy 2.x, which might introduce compatibility issues if you are still using older SQLAlchemy 1.x versions.
fix
Ensure your project runs on Python 3.8 or higher. If using SQLAlchemy, consider upgrading to SQLAlchemy 2.x. If you must use older SQLAlchemy 1.x, consult `databases` documentation for specific version compatibility.
affects: >=0.9.0
breakingIn version 0.8.0, connection and transaction isolation was significantly improved. Database connections are now task-local and not inherited by child tasks. The `@db.transaction` decorator uses the calling task's connection, and new tasks use new connections unless explicitly provided.
fix
Carefully review concurrent database operations in your application. Ensure that connections and transactions are explicitly managed or passed between tasks where shared behavior is intended, rather than relying on implicit inheritance.
affects: >=0.8.0
gotchaYou must install the specific database driver package for your chosen database alongside `databases`. For example, `pip install databases asyncpg` for PostgreSQL, `pip install databases aiomysql` for MySQL, or `pip install databases aiosqlite` for SQLite. Installing just `databases` is not sufficient for database connectivity.
fix
Always install `databases` with the appropriate extras, e.g., `pip install databases[postgresql]`, or install the driver manually.
affects: all
gotchaCompatibility with SQLAlchemy 1.4.x has been a recurring issue across several `databases` versions, with specific pins and fixes (e.g., `0.6.2` pinned `<=1.4.41`, `0.7.0` supported `>=1.4.42,<1.5`). While `0.9.0` adds SQLAlchemy 2.x support, transitioning from older SQLAlchemy 1.x with `databases` can be complex.
fix
Always check the specific release notes for `databases` regarding SQLAlchemy compatibility. For `>=0.9.0`, it's highly recommended to use SQLAlchemy 2.x. If sticking with SQLAlchemy 1.x, careful version pinning of both `databases` and `SQLAlchemy` is required.
affects: 0.6.0 - 0.9.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'databases'
The `databases` library is not installed in the Python environment, or is not available in the active environment.
fix
Install the library using pip: `pip install databases`. If a specific database backend is used, ensure its corresponding async driver is also installed, e.g., `pip install databases[postgresql]` (which installs `asyncpg`) or `pip install databases[mysql]` (which installs `aiomysql`) or `pip install databases[sqlite]` (which installs `aiosqlite`).
RuntimeError: Database must be connected before use.
A database operation (e.g., `execute`, `fetch_one`) was attempted on a `databases.Database` instance before an active connection was established using `await database.connect()`.
fix
Ensure `await database.connect()` is called and awaited before any database interactions. For robust connection management, use an `async with` block: `async with database: await database.fetch_one(...)`.
asyncpg.exceptions.CannotConnectNowError: connection refused
The underlying PostgreSQL database server is not running, is not accessible at the specified host/port, or network/firewall rules are blocking the connection. Similar errors can occur with other database types (e.g., `OperationalError` for MySQL or SQLite).
fix
Verify that the database server is running, the connection URL (host, port, database name, user, password) is absolutely correct, and network configurations (like firewalls) permit the connection.
ValueError: No driver for postgresql+asyncpg available.
The `databases` library was initialized with a database URL specifying a backend driver (e.g., `postgresql+asyncpg`) but the corresponding asynchronous driver (`asyncpg` in this example) is not installed in the Python environment.
fix
Install the required driver. For PostgreSQL, use `pip install asyncpg`. For MySQL, `pip install aiomysql`. For SQLite, `pip install aiosqlite`. Using `pip install databases[backend_name]` is the recommended way to ensure correct driver installation.
Upgrade
Version history
0.9.0latest on PyPI · released Mar 1, 2024
Audit
Dependencies
sqlalchemyrequiredUsed for SQL expression language support, though raw SQL is also possible.
asyncpgoptionalPostgreSQL database driver.
aiomysqloptionalMySQL database driver. Alternatively, asyncmy can be used.
aiosqliteoptionalSQLite database driver.
Agent activity
18 hits · last 30 days
node
16
OpenAI (training)
1
Resources
databases — pip install databases · libregistry