|
| 1 | +# SQLModel Repository - Python Repository Pattern Implementation for SQLModel |
| 2 | + |
| 3 | +[](https://github.com/code-specialist/python-repository/actions/workflows/github-code-scanning/codeql) [](https://github.com/code-specialist/python-repository/actions/workflows/test.yaml) |
| 4 | + |
| 5 | +SQLModel Repository implements the repository pattern and provides simple, robust and reliable CRUD operations for [SQLModels](https://sqlmodel.tiangolo.com/). 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. |
| 6 | + |
| 7 | +Any contributions are welcome. But we do not accept any pull requests that do not come with tests. |
| 8 | + |
| 9 | +## Installation |
| 10 | + |
| 11 | +```bash |
| 12 | +pip install sqlmodel-repository |
| 13 | +``` |
| 14 | + |
| 15 | +## Usage |
| 16 | + |
| 17 | +### 1. Create a Repository |
| 18 | + |
| 19 | +To create a repository you need to inherit from the `Repository` class and pass the entity type as a generic type argument. |
| 20 | + |
| 21 | +```python |
| 22 | +from typing import TypeVar |
| 23 | +from sqlalchemy.orm import Session |
| 24 | +from sqlmodel_repository import SQLModelEntity, Repository |
| 25 | + |
| 26 | +ExampleEntity = TypeVar("ExampleEntity", bound=SQLModelEntity) |
| 27 | + |
| 28 | + |
| 29 | +class AbstractRepository(Repository[ExampleEntity]): |
| 30 | + """Example base class for all repositories""" |
| 31 | + |
| 32 | + def get_session(self) -> Session: |
| 33 | + """Provides a session to work with""" |
| 34 | + # TODO: Implement a method to provide a session here |
| 35 | +``` |
| 36 | + |
| 37 | +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. |
| 38 | + |
| 39 | +### 2. Create Entities and Relationships |
| 40 | + |
| 41 | +```python |
| 42 | +from enum import Enum |
| 43 | +from sqlmodel import Relationship, Field |
| 44 | +from sqlmodel_repository import SQLModelEntity |
| 45 | + |
| 46 | + |
| 47 | +class PetType(Enum): |
| 48 | + """Enum that describes the type of pet""" |
| 49 | + |
| 50 | + DOG = "dog" |
| 51 | + CAT = "cat" |
| 52 | + FISH = "fish" |
| 53 | + |
| 54 | + |
| 55 | +class Pet(SQLModelEntity, table=True): |
| 56 | + """Pet model""" |
| 57 | + |
| 58 | + id: int = Field(index=True, default=None, primary_key=True) |
| 59 | + |
| 60 | + name: str |
| 61 | + age: int |
| 62 | + type: PetType |
| 63 | + shelter_id: int = Field(foreign_key="shelter.id") |
| 64 | + shelter: "Shelter" = Relationship(back_populates="pets") |
| 65 | + |
| 66 | +class Shelter(SQLModelEntity, table=True): |
| 67 | + """Shelter model""" |
| 68 | + |
| 69 | + id: int = Field(index=True, default=None, primary_key=True) |
| 70 | + |
| 71 | + name: str |
| 72 | + pets: list[Pet] = Relationship(back_populates="shelter", sa_relationship_kwargs={"cascade": "all, delete-orphan"}) |
| 73 | +``` |
| 74 | + |
| 75 | +### 3. Inherit from the Repository |
| 76 | + |
| 77 | +Now you can inherit from your `AbstractRepository` and tell it to manage the a specific entity. e.g. `Pet` and `Shelter`: |
| 78 | + |
| 79 | +```python |
| 80 | +class PetRepository(AbstractRepository[Pet]): |
| 81 | + """Repository to manage pets""" |
| 82 | + |
| 83 | +class ShelterRepository(AbstractRepository[Shelter]): |
| 84 | + """Repository to manage shelters""" |
| 85 | +``` |
| 86 | + |
| 87 | +Done 🚀 You can now use the repository to perform the operations on your entities. e.g.: |
| 88 | + |
| 89 | +```python |
| 90 | +from sqlmodel import col |
| 91 | + |
| 92 | +# Create a new shelter |
| 93 | +shelter = ShelterRepository().create(Shelter(name="Shelter 1")) |
| 94 | + |
| 95 | +# Create some pets |
| 96 | +fido = PetRepository().create(Pet(name="Fido", age=3, type=PetType.DOG, shelter_id=1)) |
| 97 | +fifi = PetRepository().create(Pet(name="Fifi", age=2, type=PetType.CAT, shelter_id=1)) |
| 98 | + |
| 99 | +# Find all pets that belong to the shelter |
| 100 | +PetRepository().find(shelter=shelter) |
| 101 | +``` |
| 102 | + |
| 103 | +No more session passing, no more boilerplate code. Just use the repository to perform the operations on your entities 🎉 |
| 104 | + |
| 105 | +## Methods |
| 106 | + |
| 107 | +### Repository |
| 108 | + |
| 109 | +Each `Repository` comes with a set of **typed methods** to perform common CRUD operations on your entities: |
| 110 | + |
| 111 | +- `create`: Create a new record of an entity |
| 112 | +- `create_batch`: Create a batch of records of an entity |
| 113 | + |
| 114 | +______________________________________________________________________ |
| 115 | + |
| 116 | +- `find`: Find all records of an entity that match the given filters |
| 117 | + |
| 118 | +______________________________________________________________________ |
| 119 | + |
| 120 | +- `get_by_id`: Get a single record by its ID |
| 121 | +- `get_batch`: Get all records of an entity that match the given filters |
| 122 | +- `get_batch_by_ids`: Get a batch of records by their IDs |
| 123 | +- `get_all`: Get all records of an entity |
| 124 | + |
| 125 | +______________________________________________________________________ |
| 126 | + |
| 127 | +- `update`: Update an entity instance |
| 128 | +- `update_by_id`: Update an entity by its ID |
| 129 | +- `update_batch`: Update a batch of entity instances with the same values |
| 130 | +- `update_batch_by_ids`: Update a batch of entities by their IDs |
| 131 | + |
| 132 | +______________________________________________________________________ |
| 133 | + |
| 134 | +- `delete`: Delete an entity instance |
| 135 | +- `delete_by_id`: Delete an entity by its ID |
| 136 | +- `delete_batch`: Delete a batch of entity instances |
| 137 | +- `delete_batch_by_ids`: Delete a batch of entities by their IDs |
| 138 | + |
| 139 | +### BaseRepository |
| 140 | + |
| 141 | +If you require more flexibility, you may also use the `BaseRepository` which provides more granular operations. The `BaseRepository` provides the following methods: |
| 142 | + |
| 143 | +- `_create`: Create a new record of an entity |
| 144 | +- `_create_batch`: Create a batch of records of an entity |
| 145 | +- `_update`: Update an entity instance |
| 146 | +- `_update_batch`: Update a batch of entity instances with the same values |
| 147 | +- `_get`: Get a single record by its ID |
| 148 | +- `_get_batch`: Get all records of an entity that match the given filters |
| 149 | +- `_delete`: Delete an entity instance |
| 150 | +- `_delete_batch`: Delete a batch of entity instances |
| 151 | + |
| 152 | +## Examples |
| 153 | + |
| 154 | +For a more detailed example, check out our [tests/integration/scenarios](tests/integration/scenarios) directory. We do not currently offer a full example application. |
0 commit comments