ZCore LogoZCore
Api reference

BaseRepository

Comprehensive API reference for the BaseRepository class, composite primary keys, query scoping, bulk operations, soft-delete lifecycles, and restoration methods.

BaseRepository provides standard asynchronous database access, combining Read, Write, Bulk Mutation, Soft-Delete Restoration, Keyset Pagination, and Search capabilities. It decouples business logic from SQLAlchemy 2.0 sessions, enforces context security through model-level query scoping, and natively supports composite primary keys with database partition pruning.

Class Definition

from typing import Generic, TypeVar
from sqlalchemy.ext.asyncio import AsyncSession
from zcore import BaseRepository
from zcore.db.setup import Base

ModelType = TypeVar("ModelType", bound=Base)

class BaseRepository(
    Generic[ModelType],
    ReadRepositoryMixin[ModelType],
    WriteRepositoryMixin[ModelType],
    SearchRepositoryMixin[ModelType]
):
    def __init__(self, model: type[ModelType], db: AsyncSession):
        ...

Properties

Prop

Type


Composite Primary Keys & Partition Pruning

BaseRepository inspects all primary key columns defined on the model mapper without hardcoding single-column lookups:

  • Single Target Lookup (_build_pk_condition): Resolves an equality clause whether target is a model instance, a dictionary mapping ({"id": 1, "date": "..."}), a tuple/list ((1, "...")), or a scalar value.
  • Batch Multi-Key Operations (_build_ids_condition): When executing batch methods (get_by_ids, delete_multi, restore_multi), composite entities compile into standard SQL row-value constructor clauses:
    (col1, col2) IN ((val1_a, val2_a), (val1_b, val2_b), ...)
    This allows database engines (such as PostgreSQL) to execute Partition Pruning on partitioned tables (e.g., Range or List partitioning) rather than scanning all physical table partitions.

Query Scoping & Soft Delete (_get_base_query)

BaseRepository constructs its initial SELECT statements via _get_base_query().

If your SQLAlchemy model declares a classmethod named scope_query (or inherits from SoftDeleteMixin), _get_base_query() automatically passes the query through this hook before applying any route-level filters:

# Internal mechanics in BaseRepository
def _get_base_query(self) -> Select:
    query = select(self.model)
    scoper = getattr(self.model, "scope_query", None)
    if scoper:
        return scoper(query)
    return query

def _supports_soft_delete(self) -> bool:
    """Determine whether the underlying model implements SoftDeleteMixin."""
    return hasattr(self.model, "deleted_at") and hasattr(self.model, "soft_delete")

Model Scoping Hooks:

# Inheriting SoftDeleteMixin automatically filters out deleted records
class Task(Base, SoftDeleteMixin):
    __tablename__ = "tasks"
    ...

All read, listing, count, search, and existence queries automatically apply row-level scoping and soft-deletion filters.


Read Methods

get

Fetches a single model instance matching dynamic criteria or primary key conditions.

async def get(
    self, 
    *criterion: Any, 
    fields: list[Any] | None = None, 
    options: list[ExecutableOption] | None = None,
    **filters: Any
) -> ModelType | None: ...

Prop

Type

get_by_ids

Fetches a sequence of records matching a list of primary keys in a single query. Supports scalar keys, composite key tuples, dictionary mappings, or model instances.

async def get_by_ids(
    self, 
    ids: Sequence[Any], 
    fields: list[Any] | None = None, 
    options: list[ExecutableOption] | None = None
) -> Sequence[ModelType]: ...

Prop

Type

get_list

Fetches a paginated or complete listing of records. Automatically derives runtime cursor_field and order parameters if using CursorParams.

async def get_list(
    self, 
    *criterion: Any,
    pagination: Any = None, 
    fields: list[Any] | None = None, 
    options: list[ExecutableOption] | None = None,
    **filters: Any
) -> Sequence[ModelType] | PaginatedResult[ModelType]: ...

Prop

Type

exist

Checks if records matching the filters exist in the database (automatically applies scope_query and checks all composite columns).

async def exist(self, *criterion: Any, **filters: Any) -> bool: ...

Prop

Type

count

Counts records matching dynamic criteria.

async def count(self, *criterion: Any, **filters: Any) -> int: ...

Prop

Type


Write, Bulk Mutation & Restoration Methods

create

Creates and persists a single record from a Pydantic schema.

async def create(self, schema: BaseModel, **extra_data: Any) -> ModelType: ...

Prop

Type

create_multi

Creates multiple database records with dialect-aware fallback for returning support.

async def create_multi(
    self, 
    schemas: list[BaseModel], 
    refresh: bool = False
) -> Sequence[ModelType]: ...

Prop

Type

update

Updates an existing database record from a model instance, scalar primary key, composite tuple, or composite mapping.

async def update(
    self, 
    target: ModelType | Any, 
    schema: BaseModel, 
    partial: bool = False, 
    **extra_data: Any
) -> ModelType | None: ...

Prop

Type

update_multi

Bulk updates multiple database records using DBAPI executemany. Validates complete key payloads for both single and composite key entities.

async def update_multi(
    self, 
    data: dict[ModelType | Any, BaseModel], 
    partial: bool = False, 
    refresh: bool = False
) -> Sequence[ModelType]: ...

Prop

Type

delete

Deletes a single record by its model instance, scalar primary key, composite tuple, or composite mapping. Automatically applies soft-deletion if supported unless force=True.

async def delete(self, target: ModelType | Any, force: bool = False) -> ModelType | None: ...

Prop

Type

delete_multi

Deletes multiple records matching the provided sequence of primary keys. Automatically executes an atomic soft-delete update (deleted_at = now()) unless force=True. Supports single and composite entities with partition pruning.

async def delete_multi(self, ids: Sequence[Any], force: bool = False) -> Sequence[ModelType]: ...

Prop

Type

restore

Restores a previously soft-deleted record by primary key, composite tuple/mapping, or model instance.

async def restore(self, target: ModelType | Any) -> ModelType | None: ...

Prop

Type

restore_multi

Restores multiple soft-deleted records using an atomic batch UPDATE ... WHERE deleted_at IS NOT NULL statement with dialect-aware RETURNING optimization and partition pruning.

async def restore_multi(self, ids: Sequence[Any]) -> Sequence[ModelType]: ...

Prop

Type


Search Methods

Dynamically parses and executes a structured SearchRequest with automatic security checks, inverted operators, logical negation, column projection, relation eager-loading, and keyset cursor synchronization.

async def search(
    self, 
    search_in: SearchRequest, 
    pagination: Any = None,
    fields: list[Any] | None = None,
    options: list[ExecutableOption] | None = None,
) -> Sequence[ModelType] | PaginatedResult[ModelType]: ...

Prop

Type

On this page