Skip to main content

Spakky Data

Spakky Framework를 위한 데이터 접근 레이어 추상화입니다. Repository와 transaction boundary를 application layer에서 backend-neutral하게 선언하도록 돕습니다.

설치

pip install spakky-data

주요 기능

  • Repository 패턴: Aggregate 영속화를 위한 generic repository 인터페이스
  • 트랜잭션 관리: autocommit을 지원하는 추상 transaction 클래스
  • External Proxy: 데이터베이스가 아닌 외부 service/storage 데이터 접근용 proxy 패턴

spakky-data는 core 추상화 패키지입니다. SQLAlchemy engine/session/table mapping 구현체가 필요하면 spakky-sqlalchemy를 함께 설치하세요.

공통 실행 모드 설정

spakky.data.config.DataConfig가 SPAKKY_DATA__SUPPORT_ASYNC_MODE를 읽습니다. 기본값은 true이며, false이면 Data는 동기 TransactionalAspect만 등록합니다. SQLAlchemy 등 영속성 구현 플러그인도 같은 설정으로 비동기 Pod 등록을 제어합니다. 따라서 동기 전용 드라이버를 사용하는 앱은 비동기 transaction provider 없이 시작할 수 있습니다. 비동기 트랜잭션을 사용하는 앱은 이 값을 true로 두고 비동기 provider를 제공해야 합니다.

이전 SPAKKY_SQLALCHEMY__SUPPORT_ASYNC_MODE는 제거됐습니다. 기존 설정은 SPAKKY_DATA__SUPPORT_ASYNC_MODE로 변경하세요. 두 변수의 우선순위나 호환 별칭은 없습니다.

설계 원칙

Repository는 영속화 전용

Repository는 domain aggregate에 대한 CRUD operation만 처리합니다. find_by_xxx, search_xxx 같은 query method를 repository에 추가하지 마세요.

복잡한 query는 ORM/SQL을 사용해 QueryUseCase에서 직접 구현해야 합니다. Query 관심사를 도메인 레이어 밖에 두어 도메인 오염을 방지합니다.

# ❌ 잘못된 예: repository에 query 관심사 포함
class IUserRepository:
    def find_by_email(self, email: str) -> User | None: ...

# ✅ 올바른 예: QueryUseCase에서 직접 구현
@UseCase()
class FindUserByEmailUseCase(IAsyncQueryUseCase[FindUserByEmailQuery, UserDTO]):
    async def run(self, query: FindUserByEmailQuery) -> UserDTO:
        # ORM/SQL 직접 사용
        ...

외부 연동 Proxy와 Repository

관점 Repository External Proxy
목적 Domain aggregate persistence 외부 service data access
대상 Database(ORM 경유) REST API, gRPC, legacy system
연산 CRUD(save, delete, get) Read-only(get, range)
도메인 내부 bounded context 외부 service

빠른 시작

SQLAlchemy와 함께 쓰는 기본 흐름

사용자 애플리케이션에서 가장 흔한 구성은 spakky-data의 Repository/Transaction 계약을 spakky-sqlalchemy 구현체로 채우는 방식입니다.

pip install spakky-data spakky-sqlalchemy
export SPAKKY_SQLALCHEMY__CONNECTION_STRING="postgresql+psycopg://user:pass@localhost/app"
export SPAKKY_DATA__SUPPORT_ASYNC_MODE="true"

흐름은 다음 순서로 구성합니다.

  1. AbstractAggregateRoot 기반 domain aggregate를 정의합니다.
  2. spakky.plugins.sqlalchemy.orm.table.AbstractMappableTable과 @Table(Domain)으로 ORM table을 매핑합니다.
  3. spakky.plugins.sqlalchemy.persistency.repository.AbstractAsyncGenericRepository를 상속한 @Repository() 구현체를 등록합니다.
  4. @UseCase() 메서드에 @Transactional()을 붙이고 Repository를 호출합니다.
  5. 복잡한 조회는 Repository에 query method를 추가하지 않고 QueryUseCase에서 AsyncSessionManager 또는 SessionManager로 직접 SQLAlchemy query를 실행합니다.

전체 예제는 데이터베이스 가이드를 참고하세요.

Repository 패턴

domain aggregate용 repository interface를 정의합니다.

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, query method 없음
class IUserRepository(IAsyncGenericRepository[User, UUID]):
    pass  # get, get_or_none, contains, range, save, save_all, delete, delete_all

Transaction 관리

database operation에는 추상 transaction을 사용합니다. 직접 구현해야 하는 경우도 있지만, SQLAlchemy를 쓴다면 spakky-sqlalchemy의 Transaction / AsyncTransaction이 이 계약을 이미 구현합니다.

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()

context manager로 사용할 수 있습니다.

async with transaction:
    user = await repository.get(user_id)
    user.name = "New Name"
    await repository.save(user)
    # 성공 시 자동 commit, exception 발생 시 rollback

외부 연동 Proxy 패턴

Proxy 인터페이스로 데이터베이스가 아닌 외부 서비스에 접근합니다. REST API, gRPC 서비스, legacy 시스템 등에 사용합니다.

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


# 외부 payment service의 data model
class PaymentInfo(ProxyModel[str]):
    transaction_id: str
    amount: int
    status: str


# 외부 payment service용 proxy interface
class IPaymentProxy(IAsyncGenericProxy[PaymentInfo, str]):
    pass


# 구현체는 외부 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 레퍼런스

영속성

클래스 설명
IGenericRepository 동기 generic repository interface
IAsyncGenericRepository 비동기 generic repository interface
AbstractTransaction context manager를 가진 동기 transaction
AbstractAsyncTransaction context manager를 가진 비동기 transaction
EntityNotFoundError entity를 찾지 못했을 때 발생

외부 연동

클래스 설명
ProxyModel 외부 service data model 기반 클래스
IGenericProxy 동기 proxy interface
IAsyncGenericProxy 비동기 proxy interface

에러

클래스 설명
AbstractSpakkyPersistencyError persistency operation 기반 error
AbstractSpakkyExternalError 외부 service operation 기반 error

관련 패키지

패키지 설명
spakky-domain DDD building block(Entity, AggregateRoot, ValueObject)
spakky-event Event publisher/consumer interface

개발 검증

패키지 단위 검증은 해당 패키지 디렉토리에서 실행합니다.

uv run ruff format .
uv run ruff check .
uv run pyrefly check
uv run pytest

pytest는 각 패키지 pyproject.toml의 coverage 설정을 사용합니다.

라이선스

MIT License

수집 목록의 실행 격리

AggregateCollector의 수집 목록은 Python 실행 컨텍스트별로 분리됩니다. Singleton Repository나 Aspect가 동일한 collector를 주입받아도 동시 비동기 요청의 목록은 섞이지 않습니다. 수집된 이벤트의 발행 및 종료 정리는 spakky-event의 트랜잭션 이벤트 Aspect가 담당합니다.

Metadata

Release files for spakky-data 8.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for spakky-data 8.3.0
File Size Uploaded Provenance Actions
spakky_data-8.3.0.tar.gz 10.1 kB With provenance Details for spakky_data-8.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for spakky-data 8.3.0
File Interpreter ABI Platform Actions
spakky_data-8.3.0-py3-none-any.whl Python 3 none any Details for spakky_data-8.3.0-py3-none-any.whl

Total release size: 23.9 kB

Release files / spakky_data-8.3.0.tar.gz

Download URL spakky_data-8.3.0.tar.gz
Size 10.1 kB
Tags Source
SHA-256 checksum
How to use checksums
f4367d7b12a9039b0ffe75c190c042707b933d9f5cf886dc22446bc138346cdc
BLAKE2b-256 checksum
How to use checksums
7256a1364dbe121c2915ea26acf3690390c841759bb2499357369c2ffd2613c9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Release files / spakky_data-8.3.0-py3-none-any.whl

Download URL spakky_data-8.3.0-py3-none-any.whl
Size 13.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b693e738a53a0a79a6ce8347997c38246fe04a9918a374efc2abeaaf531c4435
BLAKE2b-256 checksum
How to use checksums
063ccd1df4776ad3f9e063ca0a592753fe33dfee6bd7052a4bdbe202fb57215e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Security for spakky-data 8.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for spakky_data-8.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

8.3.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page