Skip to main content

CRUD tools for working with database via SQLAlchemy.

Project description

DB-First

CRUD tools for working with database via SQLAlchemy.

Features

  • CreateMixin, ReadMixin, UpdateMixin, DeleteMixin for CRUD operation for database.
  • Bulk methods for CreateMixin, ReadMixin, UpdateMixin, DeleteMixin.
  • ReadMixin support paginated data from database.
  • StatementMaker class for create query 'per-one-model'.
  • Decorators Validation for validation and serialize/deserialize arguments, parameters and return data for function and methods.
  • Marshmallow (https://github.com/marshmallow-code/marshmallow) schemas for serialization input data.
  • Marshmallow schemas for deserialization SQLAlchemy result object to dict.

Installation

Recommended using the latest version of Python. DB-First supports Python 3.9 and newer.

Install and update using pip:

$ pip install -U db_first

Examples

Full example

from db_first import BaseCRUD
from db_first.base_model import ModelMixin
from db_first.decorators import Validation
from db_first.mixins import CreateMixin
from db_first.mixins import DeleteMixin
from db_first.mixins import ReadMixin
from db_first.mixins import UpdateMixin
from marshmallow import fields
from marshmallow import Schema
from sqlalchemy import create_engine
from sqlalchemy import Result
from sqlalchemy.exc import NoResultFound
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import Session

engine = create_engine('sqlite://', echo=True, future=True)
session = Session(engine)
Base = declarative_base()


class Items(ModelMixin, Base):
    __tablename__ = 'items'
    data: Mapped[str] = mapped_column(comment='Data of item.')


Base.metadata.create_all(engine)


class IdSchema(Schema):
    id = fields.UUID()


class SchemaOfCreate(Schema):
    data = fields.String()


class SchemaOfUpdate(IdSchema, SchemaOfCreate):
    """Update item schema."""


class OutputSchema(SchemaOfUpdate):
    created_at = fields.DateTime()


class ItemController(CreateMixin, ReadMixin, UpdateMixin, DeleteMixin, BaseCRUD):
    class Meta:
        session = session
        model = Items
        sortable = ['created_at']

    @Validation.input(SchemaOfCreate)
    @Validation.output(OutputSchema, serialize=True)
    def create(self, **data) -> Result:
        return super().create_object(**data)

    @Validation.input(IdSchema, keys=['id'])
    @Validation.output(OutputSchema, serialize=True)
    def read(self, **data) -> Result:
        return super().read_object(data['id'])

    @Validation.input(SchemaOfUpdate)
    @Validation.output(OutputSchema, serialize=True)
    def update(self, **data) -> Result:
        return super().update_object(**data)

    @Validation.input(IdSchema, keys=['id'])
    def delete(self, **data) -> None:
        super().delete_object(**data)


if __name__ == '__main__':
    item_controller = ItemController()

    new_item = item_controller.create(data='first')
    print('Item as dict:', new_item)

    item = item_controller.read(id=new_item['id'])
    print('Item as dict:', item)

    updated_item = item_controller.update(id=new_item['id'], data='updated_first')
    print('Item as dict:', updated_item)

    item_controller.delete(id=new_item['id'])
    try:
        item = item_controller.read(id=new_item['id'])
    except NoResultFound:
        print('Item deleted:', item)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

db_first-4.2.0.tar.gz (14.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

db_first-4.2.0-py3-none-any.whl (11.2 kB view details)

Uploaded Python 3

File details

Details for the file db_first-4.2.0.tar.gz.

File metadata

  • Download URL: db_first-4.2.0.tar.gz
  • Upload date:
  • Size: 14.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for db_first-4.2.0.tar.gz
Algorithm Hash digest
SHA256 43716ac8bbbe997d9d7b6d5ef2dffa5b21de1b8946988e42d4308a54c466f943
MD5 60f71f6681c4d632cd777a05c7ab35fc
BLAKE2b-256 dc255073722e19541c314d28d3218dcfb839b7e3b2c9c2307d4a6c37526d5e18

See more details on using hashes here.

File details

Details for the file db_first-4.2.0-py3-none-any.whl.

File metadata

  • Download URL: db_first-4.2.0-py3-none-any.whl
  • Upload date:
  • Size: 11.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for db_first-4.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f146fa4d71ddce1f3ce590d46e25e09f5b3640a888955b7b6b7402e3ea2b7e23
MD5 afef3f29adf0196800fc917944351347
BLAKE2b-256 334a10c456ea5f8fec45751d118967218e2778bfe102f3b5a1b6c6f58c751ccf

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page