Skip to main content

No project description provided

Project description

Activealchemy Documentation

Activealchemy is a Python library that simplifies database interactions by providing an Active Record pattern and automatic session management. It supports both synchronous and asynchronous operations, making it flexible for various application needs.

Installation

pip install activealchemy

Configuration

Activealchemy uses a configuration schema to manage database connection details. Here's an example using the PostgreSQLConfigSchema:

from activealchemy.config import PostgreSQLConfigSchema

config = PostgreSQLConfigSchema(
    db="mydatabase",
    user="myuser",
    password="mypassword",
    host="localhost",
    port=5432,
)

See mise.local.toml and other examples for different configuration options.

Setting up the Engine

The ActiveEngine class manages database connections. You can set it up for synchronous or asynchronous operations:

Synchronous:

from activealchemy import ActiveEngine

engine = ActiveEngine(config)

Asynchronous:

from activealchemy.aio import ActiveEngine

engine = ActiveEngine(config)

Set the engine for your models:

from activealchemy import ActiveRecord
from myapp.models import MyModel # Assuming 'MyModel' inherits from ActiveRecord

MyModel.set_engine(engine)

Basic CRUD Operations

Creating and Saving Records

from myapp.models import User

# Method 1: Create and save.
user = User(name="Alice", email="alice@example.com")
user.save()

# Method 2: Using add.
user = User(name="Bob")
User.add(user, commit=True) # commit=True commits the change immediately.

Querying

# Retrieve all users
users = User.all()

# Find a user by primary key.
user_pk = uuid.UUID("some uuid here")
user = User.find(user_pk) # using PKMixin which adds find().


# Find a user by email
user = User.find_by(email="alice@example.com")

# Find users with a specific name
users = User.where(User.name == "Alice").all()


# Find the first user in the database.
first_user = User.first() # Orders by the primary key.


# Find the last user in the database, ordered by a column.
last_user = User.last(User.name) # Orders by User.name DESC.


# Use a custom query with advanced selects
query = User.select().where(User.created_at < some_date)
users = User.all(query=query) # Can combine custom queries with other operations

# Find the first created user
first_created_user = User.first_created()

# Find the last created user
last_created_user = User.last_created()

# Count users
user_count = User.count()

Updating Records

user = User.find_by(name="Alice")
if user:
    user.name = "Alicia"
    user.save()

Deleting Records

user = User.find_by(name="Bob")
if user:
    User.delete(user)

Asynchronous Operations

Activealchemy supports asynchronous operations using asyncio and async/await. Use activealchemy.aio.ActiveRecord, activealchemy.aio.ActiveEngine, and activealchemy.aio.Schema:

import asyncio
from activealchemy.aio import ActiveRecord, Schema

# ... (setup engine as described above, using the async ActiveEngine) ...

async def create_user():
    user = User(name="Dave")
    await user.save()
    print(f"Created user: {user}")

asyncio.run(create_user())

# Use async methods for querying and operations
users = await User.all()

# Convert model instances to dictionaries and vice-versa
user_data = user.dump_model()
restored_user = User.load(**user_data)

schema = User.Schema() # Convert schemas to model instances and back
user_instance = schema.to_model(User)
user_schema = User.Schema.model_validate(user_instance)

See activealchemy/demo/amodels.py for a detailed example.

Explicit sessions

session = User.new_session()
try:
    user = User(name='Bob')
    session.add(user)
    session.commit()
finally:
    session.close()

# async
async def async_example():
    async_session = await User.new_session()
    try:
        user = User(name='Bob')
        async_session.add(user)
        await async_session.commit()
    finally:
        await async_session.close()

async def context_session():
    async with User.new_session() as session:    
        user = User(name='Bob')        
        async_session.add(user)
        await async_session.commit(session)
        # or 
        user2 = User(name='Alice')
        user2 = await Use.add(user2, commit=True, session=session)

Transactions

Transactions are automatically handled for add(), delete(), and save().

For fine-grained control use a context manager with begin() and begin_nested():

with User.new_session() as session
    try:
        # Operations here
        # Rollback will happen automatically
        session.add(user1)
        session.add(user2)
        1 / 0 # Will rollback to here
    except Exception as e:
        print(f"Error: {e}") # Will rollback to here
    session.commit()
    
## Session is closed on context exit

See activealchemy/utils/retry.py for how the Q context manager implements retries and transactions.

Custom Schemas

Create custom schemas by inheriting from activealchemy.Schema or activealchemy.aio.Schema and using Pydantic's features.

Examples

For more comprehensive examples, refer to the following:

  • activealchemy/demo for sample models and usage.
  • models.py and amodels.py for synchronous and asynchronous model definitions.

This documentation provides a starting point for using Activealchemy. Explore the code examples and docstrings for more in-depth information.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aiochemy-0.2.0.tar.gz (23.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aiochemy-0.2.0-py3-none-any.whl (25.0 kB view details)

Uploaded Python 3

File details

Details for the file aiochemy-0.2.0.tar.gz.

File metadata

  • Download URL: aiochemy-0.2.0.tar.gz
  • Upload date:
  • Size: 23.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.2 CPython/3.12.8 Linux/5.15.167.4-microsoft-standard-WSL2

File hashes

Hashes for aiochemy-0.2.0.tar.gz
Algorithm Hash digest
SHA256 4181a9075dba4434536cd1db1856af3bb3bb0de61a43419aa48ae989f3715a83
MD5 f07b1d14d853740f75a277556016fe3a
BLAKE2b-256 b64714475de0667f7224c7428ea45d5be7264928f5ac3c366a9a542e75844e7b

See more details on using hashes here.

File details

Details for the file aiochemy-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: aiochemy-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 25.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.2 CPython/3.12.8 Linux/5.15.167.4-microsoft-standard-WSL2

File hashes

Hashes for aiochemy-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 db9ffc80ce8ce7b97701beee29afbe15b9ffe582071193e5022ebf7b080a92ba
MD5 f63c68b41d4285a5da657af92b93d7c4
BLAKE2b-256 03b5694862e562610d45685703f4bffd279cb19e0e82683f9a5aba75ce081e6e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page