Convert Figma logo to code with AI

encode logodatabases

Async database support for Python. 🗄

3,798
260
3,798
131

Top Related Projects

29,856

CockroachDB — the cloud native, distributed SQL database designed for high availability, effortless scale, and control over data placement.

36,869

TiDB is an open-source, cloud-native, distributed, MySQL-Compatible database for elastic scale and real-time analytics. Try AI-powered Chat2Query free at : https://www.pingcap.com/tidb-serverless/

18,397

Vitess is a database clustering system for horizontal scaling of MySQL.

YugabyteDB - the cloud native distributed SQL database for mission-critical applications.

4,762

Apache Ignite

Quick Overview

encode/databases is a high-level, asynchronous database toolkit for Python. It provides a simple, expressive interface for making queries to various database backends, including PostgreSQL, MySQL, and SQLite. The library is designed to work seamlessly with async frameworks like FastAPI and Starlette.

Pros

  • Supports multiple database backends with a unified API
  • Fully asynchronous, allowing for efficient I/O operations
  • Integrates well with popular async web frameworks
  • Type-safe query building and result handling

Cons

  • Learning curve for developers new to async programming
  • Limited support for advanced database-specific features
  • Relatively young project compared to some alternatives
  • May have performance overhead for simple use cases

Code Examples

  1. Connecting to a database:
from databases import Database

database = Database("postgresql://user:pass@localhost/dbname")

await database.connect()
  1. Executing a simple query:
query = "SELECT * FROM users WHERE age > :age"
results = await database.fetch_all(query=query, values={"age": 18})
  1. Using the query builder:
from databases import Database
from sqlalchemy import select, users

database = Database("sqlite:///example.db")
query = select([users.c.id, users.c.name]).where(users.c.age > 18)
results = await database.fetch_all(query)

Getting Started

To get started with encode/databases:

  1. Install the library:

    pip install databases
    
  2. Import and create a Database instance:

    from databases import Database
    
    database = Database("sqlite:///example.db")
    
  3. Connect to the database in your application startup:

    await database.connect()
    
  4. Use the database for queries in your application code:

    results = await database.fetch_all("SELECT * FROM users")
    
  5. Disconnect from the database on application shutdown:

    await database.disconnect()
    

Competitor Comparisons

29,856

CockroachDB — the cloud native, distributed SQL database designed for high availability, effortless scale, and control over data placement.

Pros of CockroachDB

  • Distributed SQL database with strong consistency and high availability
  • Designed for horizontal scalability and geographic distribution
  • Built-in support for multi-region deployments and survivability

Cons of CockroachDB

  • Higher complexity and resource requirements for small-scale applications
  • Steeper learning curve compared to simpler database solutions
  • Limited support for certain advanced SQL features found in traditional RDBMSs

Code Comparison

CockroachDB (SQL):

CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name STRING,
    created_at TIMESTAMP DEFAULT current_timestamp()
);

Databases (Python with SQLAlchemy):

from sqlalchemy import Column, String, DateTime
from sqlalchemy.dialects.postgresql import UUID
import datetime

class User(Base):
    __tablename__ = "users"
    id = Column(UUID(as_uuid=True), primary_key=True)
    name = Column(String)
    created_at = Column(DateTime, default=datetime.datetime.utcnow)

Key Differences

  • CockroachDB is a full-fledged distributed database system, while Databases is a Python library for database access
  • Databases supports multiple database backends, whereas CockroachDB is a specific database implementation
  • CockroachDB focuses on distributed SQL capabilities, while Databases emphasizes ORM functionality and database abstraction
36,869

TiDB is an open-source, cloud-native, distributed, MySQL-Compatible database for elastic scale and real-time analytics. Try AI-powered Chat2Query free at : https://www.pingcap.com/tidb-serverless/

Pros of TiDB

  • Distributed SQL database with horizontal scalability
  • HTAP (Hybrid Transactional/Analytical Processing) capabilities
  • Strong consistency and high availability

Cons of TiDB

  • More complex setup and maintenance
  • Steeper learning curve for newcomers
  • Higher resource requirements

Code Comparison

TiDB (SQL-based):

CREATE TABLE users (
  id INT PRIMARY KEY,
  name VARCHAR(255),
  created_at TIMESTAMP
);

Databases (Python-based):

from databases import Database

database = Database("sqlite:///example.db")

await database.execute("""
    CREATE TABLE users (
        id INTEGER PRIMARY KEY,
        name VARCHAR(255),
        created_at TIMESTAMP
    )
""")

Key Differences

  • TiDB is a full-fledged distributed database system, while Databases is a Python library for async database operations
  • TiDB uses SQL syntax directly, whereas Databases wraps SQL operations in Python code
  • TiDB offers advanced features like distributed transactions and HTAP, while Databases focuses on simplifying database access in Python applications

Use Cases

  • TiDB: Large-scale, distributed applications requiring high scalability and consistency
  • Databases: Python projects needing async database access, particularly for web applications
18,397

Vitess is a database clustering system for horizontal scaling of MySQL.

Pros of Vitess

  • Designed for horizontal scaling and sharding of MySQL databases
  • Provides advanced features like query routing and connection pooling
  • Supports high availability and disaster recovery for large-scale deployments

Cons of Vitess

  • Steeper learning curve and more complex setup compared to Databases
  • Primarily focused on MySQL, while Databases supports multiple database backends
  • Requires additional infrastructure and management overhead

Code Comparison

Vitess (VTGate query):

SELECT * FROM users WHERE id = :id

Databases (SQLAlchemy query):

query = users.select().where(users.c.id == id)
result = await database.fetch_all(query)

Key Differences

  • Vitess is a comprehensive database clustering system, while Databases is a lightweight async database library
  • Vitess focuses on scalability and high availability for MySQL, whereas Databases provides a unified interface for various databases
  • Vitess requires a more complex infrastructure setup, while Databases can be easily integrated into existing Python applications

Use Cases

  • Choose Vitess for large-scale MySQL deployments requiring horizontal scaling and advanced features
  • Opt for Databases when building Python applications that need a simple, async interface to multiple database backends

YugabyteDB - the cloud native distributed SQL database for mission-critical applications.

Pros of YugabyteDB

  • Distributed SQL database with high scalability and fault tolerance
  • Supports both ACID transactions and high performance NoSQL-style operations
  • Compatible with PostgreSQL ecosystem and tools

Cons of YugabyteDB

  • More complex setup and maintenance compared to lightweight databases
  • Steeper learning curve for developers new to distributed systems
  • Higher resource requirements for optimal performance

Code Comparison

YugabyteDB (SQL query):

SELECT * FROM users WHERE age > 18 ORDER BY name LIMIT 10;

Databases (using SQLAlchemy with asyncio):

async with database.transaction():
    query = users.select().where(users.c.age > 18).order_by(users.c.name).limit(10)
    results = await database.fetch_all(query)

Key Differences

  • YugabyteDB is a full-fledged distributed database system, while Databases is a Python library for database connections
  • YugabyteDB offers native SQL support, whereas Databases provides an abstraction layer for various database backends
  • YugabyteDB focuses on scalability and distributed operations, while Databases emphasizes ease of use and async support in Python applications

Use Cases

  • Choose YugabyteDB for large-scale, distributed applications requiring high availability and strong consistency
  • Opt for Databases when building Python applications that need a simple, async-compatible database interface supporting multiple backends
4,762

Apache Ignite

Pros of Ignite

  • Distributed in-memory computing platform with advanced data processing capabilities
  • Supports SQL, key-value, and compute APIs for versatile data management
  • Offers built-in machine learning and deep learning capabilities

Cons of Ignite

  • Steeper learning curve due to its complex architecture and features
  • Requires more system resources and configuration compared to lightweight alternatives
  • May be overkill for simple database needs or smaller applications

Code Comparison

Ignite (Java):

Ignite ignite = Ignition.start();
IgniteCache<Integer, String> cache = ignite.getOrCreateCache("myCache");
cache.put(1, "Hello");
String val = cache.get(1);

Databases (Python):

from databases import Database

database = Database("sqlite:///example.db")
await database.connect()
query = "SELECT * FROM users WHERE id = :id"
result = await database.fetch_one(query=query, values={"id": 1})

Key Differences

  • Ignite is a comprehensive distributed computing platform, while Databases is a lightweight async database library
  • Ignite offers more advanced features like distributed computing and machine learning, whereas Databases focuses on simple database operations
  • Ignite primarily uses Java, while Databases is a Python library
  • Databases is more suitable for smaller projects or microservices, while Ignite is better for large-scale distributed applications

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Databases

Test Suite Package version

Databases gives you simple asyncio support for a range of databases.

It allows you to make queries using the powerful SQLAlchemy Core expression language, and provides support for PostgreSQL, MySQL, and SQLite.

Databases is suitable for integrating against any async Web framework, such as Starlette, Sanic, Responder, Quart, aiohttp, Tornado, or FastAPI.

Documentation: https://www.encode.io/databases/

Requirements: Python 3.8+


Installation

$ pip install databases

Database drivers supported are:

You can install the required database drivers with:

$ pip install databases[asyncpg]
$ pip install databases[aiopg]
$ pip install databases[aiomysql]
$ pip install databases[asyncmy]
$ pip install databases[aiosqlite]

Note that if you are using any synchronous SQLAlchemy functions such as engine.create_all() or alembic migrations then you still have to install a synchronous DB driver: psycopg2 for PostgreSQL and pymysql for MySQL.


Quickstart

For this example we'll create a very simple SQLite database to run some queries against.

$ pip install databases[aiosqlite]
$ pip install ipython

We can now run a simple example from the console.

Note that we want to use ipython here, because it supports using await expressions directly from the console.

# Create a database instance, and connect to it.
from databases import Database
database = Database('sqlite+aiosqlite:///example.db')
await database.connect()

# Create a table.
query = """CREATE TABLE HighScores (id INTEGER PRIMARY KEY, name VARCHAR(100), score INTEGER)"""
await database.execute(query=query)

# Insert some data.
query = "INSERT INTO HighScores(name, score) VALUES (:name, :score)"
values = [
    {"name": "Daisy", "score": 92},
    {"name": "Neil", "score": 87},
    {"name": "Carol", "score": 43},
]
await database.execute_many(query=query, values=values)

# Run a database query.
query = "SELECT * FROM HighScores"
rows = await database.fetch_all(query=query)
print('High Scores:', rows)

Check out the documentation on making database queries for examples of how to start using databases together with SQLAlchemy core expressions.

— ⭐️ —

Databases is BSD licensed code. Designed & built in Brighton, England.