Skip to main content

SQLModel Repository - Python Repository Pattern Implementation for SQLModel

CodeQL Tests

SQLModel Repository implements the repository pattern and provides simple, robust and reliable CRUD operations for SQLModels. The repository pattern is a great way to encapsulate the logic of your application and to separate the business logic from the data access layer.

Any contributions are welcome. But we do not accept any pull requests that do not come with tests.

Installation

pip install sqlmodel-repository

Usage

1. Create a Repository

To create a repository you need to inherit from the Repository class and pass the entity type as a generic type argument.

from typing import TypeVar
from sqlalchemy.orm import Session
from sqlmodel_repository import SQLModelEntity, Repository

ExampleEntity = TypeVar("ExampleEntity", bound=SQLModelEntity)


class AbstractRepository(Repository[ExampleEntity]):
    """Example base class for all repositories"""

    def get_session(self) -> Session:
        """Provides a session to work with"""
        # TODO: Implement a method to provide a session here

In this example we use a TypeVar to pass the generic type downwards. You have to implement the get_session method to provide a session to the repository.

2. Create Entities and Relationships

from enum import Enum
from sqlmodel import Relationship, Field
from sqlmodel_repository import SQLModelEntity


class PetType(Enum):
    """Enum that describes the type of pet"""

    DOG = "dog"
    CAT = "cat"
    FISH = "fish"


class Pet(SQLModelEntity, table=True):
    """Pet model"""

    id: int = Field(index=True, default=None, primary_key=True)

    name: str
    age: int
    type: PetType
    shelter_id: int = Field(foreign_key="shelter.id")
    shelter: "Shelter" = Relationship(back_populates="pets")

class Shelter(SQLModelEntity, table=True):
    """Shelter model"""

    id: int = Field(index=True, default=None, primary_key=True)

    name: str
    pets: list[Pet] = Relationship(back_populates="shelter", sa_relationship_kwargs={"cascade": "all, delete-orphan"})

3. Inherit from the Repository

Now you can inherit from your AbstractRepository and tell it to manage the a specific entity. e.g. Pet and Shelter:

class PetRepository(AbstractRepository[Pet]):
    """Repository to manage pets"""

class ShelterRepository(AbstractRepository[Shelter]):
    """Repository to manage shelters"""

Optionally, you may pass a logger keyword argument to the repository to log the operations. The logger should be a structlog logger with enabled JSONRenderer. If no logger is provided the repository will use its default logger (SQLModelRepositoryLogger).

Done 🚀 You can now use the repository to perform the operations on your entities. e.g.:

from sqlmodel import col

# Create a new shelter
shelter = ShelterRepository().create(Shelter(name="Shelter 1"))

# Create some pets
fido = PetRepository().create(Pet(name="Fido", age=3, type=PetType.DOG, shelter_id=1))
fifi = PetRepository().create(Pet(name="Fifi", age=2, type=PetType.CAT, shelter_id=1))

# Find all pets that belong to the shelter
PetRepository().find(shelter=shelter)

No more session passing, no more boilerplate code. Just use the repository to perform the operations on your entities 🎉

Methods

Repository

Each Repository comes with a set of typed methods to perform common CRUD operations on your entities:

  • create: Create a new record of an entity
  • create_batch: Create a batch of records of an entity

  • get: Get a single record by its ID
  • get_batch: Get all records of an entity that match the given filters
  • get_batch_by_ids: Get a batch of records by their IDs
  • get_all: Get all records of an entity

  • update: Update an entity instance
  • update_by_id: Update an entity by its ID
  • update_batch: Update a batch of entity instances with the same values
  • update_batch_by_ids: Update a batch of entities by their IDs

  • delete: Delete an entity instance
  • delete_by_id: Delete an entity by its ID
  • delete_batch: Delete a batch of entity instances
  • delete_batch_by_ids: Delete a batch of entities by their IDs

BaseRepository

If you require more flexibility, you may also use the BaseRepository which provides more granular operations. The BaseRepository provides the following methods:

  • create: Create a new record of an entity
  • create_batch: Create a batch of records of an entity
  • update: Update an entity instance
  • update_batch: Update a batch of entity instances with the same values
  • get: Get a single record by its ID
  • get_batch: Get all records of an entity that match the given filters
  • find: Find all records of an entity that match the given filters
  • delete: Delete an entity instance
  • delete_batch: Delete a batch of entity instances

Examples

For a more detailed example, check out our tests/integration/scenarios directory. We do not currently offer a full example application.

Metadata

Release files for sqlmodel-repository 2.0.1

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

Source distribution (sdist)

Source distribution for sqlmodel-repository 2.0.1
File Size Uploaded
sqlmodel_repository-2.0.1.tar.gz 20.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for sqlmodel-repository 2.0.1
File Interpreter ABI Platform
sqlmodel_repository-2.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 41.7 kB

Release files / sqlmodel_repository-2.0.1.tar.gz

Download URL sqlmodel_repository-2.0.1.tar.gz
Size 20.7 kB
Tags Source
SHA-256 checksum
How to use checksums
aad24efb5f96877a0f0129a6f6bf41070682988aa97c06999b7f30ed17dabe78
BLAKE2b-256 checksum
How to use checksums
0c8731f98b0d87d47133c66b022cc133f9446b1c53cced19a174127e926d8ef1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.4.2 CPython/3.10.6 Linux/5.15.0-1035-azure

Release files / sqlmodel_repository-2.0.1-py3-none-any.whl

Download URL sqlmodel_repository-2.0.1-py3-none-any.whl
Size 21.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f94b0906e6efc82d204717117e13c9aaf17ae168280b7faf7355dd0067321d1e
BLAKE2b-256 checksum
How to use checksums
eacead90a7672616fac0b8420ac8b0a15ae5e647df897dc091dfcd9f7d72fc45
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.4.2 CPython/3.10.6 Linux/5.15.0-1035-azure

Release history Release notifications | RSS feed

This release

2.0.1 This release

2 release files

2.0.0

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

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