Skip to main content

SQLModel BaseCRUD

codecov PyPI version PyPI - Python Version Downloads

Simple package that provides base CRUD operations for your models.


Documentation: https://woofz.github.io/sqlmodel-basecrud/latest

Sources: https://github.com/woofz/sqlmodel-basecrud


What is SQLModel BaseCRUD?

With SQLModel BaseCRUD, you can implement your CRUD operations easily in your project. It is simple as declaring a variable!
This package consists in two classes: BaseCRUD and BaseRepository.
BaseCRUD is the basic class that implements the basic CRUD operations, while BaseRepository is the repository used to execute those operations. You could also write your own repository class and use basic CRUD operation provided by BaseRepository class by extending it to your own repository class!

Installation

Using pip

pip install sqlmodel-basecrud

Using poetry

poetry add sqlmodel-basecrud

Operations

Usage

Basic setup

Consider these two models as example:

class Team(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(index=True)
    headquarters: str

    heroes: List["Hero"] = Relationship(back_populates="team")
    
    
class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(index=True)
    secret_name: str
    age: Optional[int] = Field(default=None, index=True)

    team_id: Optional[int] = Field(default=None, foreign_key="team.id")
    team: Optional[Team] = Relationship(back_populates="heroes")

We want to perform some operations on these models. First of all we instantiate a BaseRepository, specifying the database session and the model that we want to manipulate.

# other imports..
from sqlmodel_basecrud import BaseRepository

with Session(engine) as session:
    hero_repository = BaseRepository(db=session, model=Hero)
    team_repository = BaseRepository(db=session, model=Team)
CREATE operation

Persists an item into the database.

# CREATE operation
my_hero = Hero(name='Github Hero', secret_name='Gitty', age=31)
hero_repository.create(my_hero)
# now my_hero is persisting in the database!
BULK CREATE operation

Persists multiple items into the database. You have to pass them in a list.

# BULK CREATE operation
my_heros_list = [ Hero(name='Github Hero', secret_name='Gitty', age=31),
                 Hero(name='Hero 2', secret_name='Hero2', age=21),
                 Hero(name='Hero 3', secret_name='Hero3', age=29)
               ]
hero_repository.bulk_create(my_heros_list)
GET operation

GET operation simply gets a single record from the database.

result = hero_repository.get(id=1, name='Github Hero')

Note that you can also use a BinaryExpression. Here's an example:

result = hero_repository.get(Hero.id >= 3)

result variable will be an instance of Hero, if a result matches the criteria, or None type.

FILTER operation

Gets one or more instances from the database, filtering them by one or more column/s.

results = hero_repository.filter(age=31)

Like the GET operation, here you can use a BinaryExpression as well. Here's an example:

result = hero_repository.filter(Hero.age == 31)

results will be a List with zero or more elements.

GET ALL operation

Gets all instances of given module from the Database

results = hero_repository.get_all()

results will be a List with zero or more elements.

UPDATE operation

Updates a record into the database.

instance_to_update = hero_repository.get(id=1)
instance_to_update.name = 'Super New Name'
instance_to_update.age = 27

hero_repository.update(instance_to_update)

The hero will have his columns name and age with updated values.

DELETE operation

Removes an instance from the database

instance_to_remove = hero_repository.get(id=1)
hero_repository.delete(instance_to_remove)

The instance will be removed from the database.

Custom Repository

If you want to extend the BaseRepository class with some custom methods, you can write your own repository class. Just extend BaseRepository or BaseCRUD class and call the super class constructor, by passing it two essential parameters:

  • db: must be a Session instance;
  • model: must be a Type[SQLModel].
from sqlmodel_basecrud import BaseRepository


class MyCustomRepository(BaseRepository):

    def __init__(self, db: Session, model: Type[SQLModel]):
        super().__init__(model=model, db=db)

What's next

The first thing that comes to my mind is to extend the features of Async to BaseCRUD class. I will try to enhance the features of the project. Suggestions are appreciated 🤩

Inspired by

FastAPI: framework, high performance, easy to learn, fast to code, ready for production

SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness.

Metadata

Release files for sqlmodel-basecrud 0.1.9

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-basecrud 0.1.9
File Size Uploaded Provenance Actions
sqlmodel-basecrud-0.1.9.tar.gz 5.9 kB Without provenance Details for sqlmodel-basecrud-0.1.9.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sqlmodel-basecrud 0.1.9
File Interpreter ABI Platform Actions
sqlmodel_basecrud-0.1.9-py3-none-any.whl Python 3 none any Details for sqlmodel_basecrud-0.1.9-py3-none-any.whl

Total release size: 11.7 kB

Release files / sqlmodel-basecrud-0.1.9.tar.gz

Download URL sqlmodel-basecrud-0.1.9.tar.gz
Size 5.9 kB
Tags Source
SHA-256 checksum
How to use checksums
9c97a371684974c7ca987ab2c7849e7d3548523aa072c7c0f0cfba88f8deece8
BLAKE2b-256 checksum
How to use checksums
c01ca3c8b22b69dbb149d36a192057ab54b822bd5f5c2ee9c2f5a359d79998ea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.13 CPython/3.10.0 Windows/10

Release files / sqlmodel_basecrud-0.1.9-py3-none-any.whl

Download URL sqlmodel_basecrud-0.1.9-py3-none-any.whl
Size 5.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e44379d730e49955eedce787f1da7989429194c41d11d68544074d3867239824
BLAKE2b-256 checksum
How to use checksums
230869d4c7137d88530846670acfe9a29a7650cf81156899f1db16e51e190ec4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.13 CPython/3.10.0 Windows/10

Security for sqlmodel-basecrud 0.1.9

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

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