Skip to main content

Data access layer for Spakky Framework (Repository implementations, ORM integration)

Project description

Spakky Data

Data access layer abstractions for Spakky Framework.

Installation

pip install spakky-data

Features

  • Repository Pattern: Generic repository interfaces for aggregate persistence
  • Transaction Management: Abstract transaction classes with autocommit support
  • External Proxy: Proxy pattern for external service/storage data access (NOT for database)

Design Principles

Repository is for Persistence Only

Repositories handle CRUD operations for domain aggregates only. Do NOT add query methods like find_by_xxx, search_xxx to repositories.

Complex queries should be implemented directly in QueryUseCase using ORM/SQL. This prevents domain pollution by keeping query concerns out of the domain layer.

# ❌ Wrong: Query concerns in repository
class IUserRepository:
    def find_by_email(self, email: str) -> User | None: ...

# ✅ Correct: Direct implementation in QueryUseCase
@QueryUseCase()
class FindUserByEmailUseCase(IAsyncQueryUseCase[FindUserByEmailQuery, UserDTO]):
    async def run(self, query: FindUserByEmailQuery) -> UserDTO:
        # Use ORM/SQL directly
        ...

External Proxy vs Repository

Aspect Repository External Proxy
Purpose Domain aggregate persistence External service data access
Target Database (via ORM) REST API, gRPC, legacy systems
Operations CRUD (save, delete, get) Read-only (get, range)
Domain Internal bounded context External services

Quick Start

Repository Pattern

Define repository interfaces for your domain aggregates:

from abc import abstractmethod
from uuid import UUID

from spakky.data.persistency.repository import IAsyncGenericRepository
from spakky.domain.models.aggregate_root import AbstractAggregateRoot


class User(AbstractAggregateRoot[UUID]):
    name: str
    email: str


# Repository interface - CRUD only, no query methods
class IUserRepository(IAsyncGenericRepository[User, UUID]):
    pass  # get, get_or_none, contains, range, save, save_all, delete, delete_all

Transaction Management

Use abstract transactions for database operations:

from spakky.data.persistency.transaction import AbstractAsyncTransaction


class SQLAlchemyTransaction(AbstractAsyncTransaction):
    def __init__(self, session_factory, autocommit: bool = True) -> None:
        super().__init__(autocommit)
        self.session_factory = session_factory
        self.session = None

    async def initialize(self) -> None:
        self.session = self.session_factory()

    async def dispose(self) -> None:
        await self.session.close()

    async def commit(self) -> None:
        await self.session.commit()

    async def rollback(self) -> None:
        await self.session.rollback()

Usage with context manager:

async with transaction:
    user = await repository.get(user_id)
    user.name = "New Name"
    await repository.save(user)
    # Automatically commits on success, rollbacks on exception

External Proxy Pattern

Access external services (NOT databases) with proxy interfaces. Use this for REST APIs, gRPC services, legacy systems, etc.

from spakky.data.external.proxy import ProxyModel, IAsyncGenericProxy


# Data model from external payment service
class PaymentInfo(ProxyModel[str]):
    transaction_id: str
    amount: int
    status: str


# Proxy interface for external payment service
class IPaymentProxy(IAsyncGenericProxy[PaymentInfo, str]):
    pass


# Implementation calls external API
class PaymentServiceProxy(IPaymentProxy):
    async def get(self, proxy_id: str) -> PaymentInfo:
        response = await self._http_client.get(f"/payments/{proxy_id}")
        return PaymentInfo(...)

API Reference

Persistency

Class Description
IGenericRepository Sync generic repository interface
IAsyncGenericRepository Async generic repository interface
AbstractTransaction Sync transaction with context manager
AbstractAsyncTransaction Async transaction with context manager
EntityNotFoundError Raised when entity not found

External

Class Description
ProxyModel Base class for external service data models
IGenericProxy Sync proxy interface
IAsyncGenericProxy Async proxy interface

Errors

Class Description
AbstractSpakkyPersistencyError Base error for persistency operations
AbstractSpakkyExternalError Base error for external service operations

Related Packages

Package Description
spakky-domain DDD building blocks (Entity, AggregateRoot, ValueObject)
spakky-event Event publisher/consumer interfaces

License

MIT License

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

spakky_data-6.1.2.tar.gz (6.7 kB view details)

Uploaded Source

Built Distribution

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

spakky_data-6.1.2-py3-none-any.whl (11.6 kB view details)

Uploaded Python 3

File details

Details for the file spakky_data-6.1.2.tar.gz.

File metadata

  • Download URL: spakky_data-6.1.2.tar.gz
  • Upload date:
  • Size: 6.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for spakky_data-6.1.2.tar.gz
Algorithm Hash digest
SHA256 7f061e2fa400df9a38319d652e811f2d1fa42d9013a28c089c342ae94448674c
MD5 088258e29758023fd2a90d0a703a257e
BLAKE2b-256 e799d3394d129ca7ce61a2c3c4fc06c697dfdcc621f12eb2fee0ee8590eb79c7

See more details on using hashes here.

Provenance

The following attestation bundles were made for spakky_data-6.1.2.tar.gz:

Publisher: release.yml on E5presso/spakky-framework

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file spakky_data-6.1.2-py3-none-any.whl.

File metadata

  • Download URL: spakky_data-6.1.2-py3-none-any.whl
  • Upload date:
  • Size: 11.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for spakky_data-6.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 6d7a5d127dce40e1fc49e1d8e34dd63e546c02cc952e9ec59a16edb1dab3cc56
MD5 e689f53ef51aafc08f7349d85e4e9529
BLAKE2b-256 e08c9f6bfd8b0a9f84f2c1094805d88aac1f6e009b1bebdc120434fe7fe34ca7

See more details on using hashes here.

Provenance

The following attestation bundles were made for spakky_data-6.1.2-py3-none-any.whl:

Publisher: release.yml on E5presso/spakky-framework

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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