Skip to main content

Abstraction from DBMS, queries without explicit use of SQL, and convenient work with high-level object-containers.

Project description

dbrequest

dbrequest is a library for easy database handling. The library is primarily designed for simple projects where complex SQL queries are not needed and SQLite can be used as the DBMS (although the library supports other DBMS as well).

The library provides an abstraction from the DBMS and allows working with storing, loading, modifying, and deleting object-containers without explicit use of SQL.

Contents

Installation

Installation from a GitHub repository (requires pip version 20 and above).

$ pip install git+https://github.com/korandr/dbrequest.git

Library import:

import dbrequest

Disclaimer

The library is primarily developed for the developer's personal projects and does not prioritize suitability for any projects.

Some restrictions are used in the library (for example, all objects to be saved must have an id of type int), which are convenient for the developer's projects but may not necessarily be suitable for other projects.

Nevertheless, the developer is not against integrating this library into other projects if it solves the necessary tasks.

The library does not adhere to the PEP code style and is unlikely to do so. Objects, methods, and properties are always named using camelCase here. However, an important task is to adhere to the SOLID principles.

Quick Start

For example, let's create a table users. Describe it in the file create_table.sql.

create table IF NOT EXISTS users (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  username TEXT NOT NULL UNIQUE,
  last_message TEXT DEFAULT NULL
);

First of all, let's initialize the library.

import dbrequest

dbrequest.init(executor='SQLite', database_filename='database.db')

Now let's create a table users in the database.

from dbrequest import UniversalExecutor
from dbrequest.sql_requests import SQLFile

request = SQLFile()
request.setArgs(filename='create_table.sql')

executor = UniversalExecutor()
executor.start(request)

Next, in the file user.py, let's create a class User. Inheriting from Savable will automatically add the _id field and the id property to the class, which is the implementation of the dbrequest.ISavable interface.

from dbrequest import Savable

class User(Savable):
    def __init__(self) -> None:
        super().__init__()
        self._username: str = None
        self._last_message: str = None

    @property
    def username(self) -> str:
        return self._username
    
    @property
    def lastMessage(self) -> str:
        return self._last_message

    @username.setter
    def username(self, value:str) -> None:
        if not isinstance(value, str):
            raise TypeError(type(value))
        if value == '':
            raise ValueError(value)
        self._username = value
    
    @lastMessage.setter
    def lastMessage(self, value:str) -> None:
        if not isinstance(value, str) and not value is None:
            raise TypeError(type(value))
        self._last_message = value

Now let's create the file user_fields.py and implement classes in it that will be used by the library to load and save fields of the User class in the database.

from dbrequest import AbstractField

from user import User


class UserUsernameField(AbstractField):
    def getValueFromObject(self, object:User) -> None:
        self._value = object.username 

    def setValueToObject(self, object:User) -> None:
        object.username = self._value

class UserLastMessageField(AbstractField):
    def getValueFromObject(self, object:User) -> None:
        self._value = object.lastMessage 

    def setValueToObject(self, object:User) -> None:
        object.lastMessage = self._value

If needed, these classes can contain additional logic for data processing when exchanging data between the container class and the database. For example, converting non-standard data types to data types supported by the database.

The last step is to create a class for database requests related to the user. Let's create the file user_request.py.

from dbrequest import AbstarctDBRequest
from dbrequest import IdField

from user_fields import *

class UserDBRequest(AbstarctDBRequest):
    def __init__(self) -> None:
        super().__init__()
        self._TABLE_NAME = 'users'
        self._FIELDS = (
            IdField(),
            UserUsernameField('username', str),
            UserLastMessageField('last_message', str, allowed_none=True)
        )

In self._TABLE_NAME, specify the name of the corresponding table.

Through the property self._FIELDS, the connection with columns in the database is established. The method takes a tuple of implementations of AbstractField. The fields should be arranged in the same order as the columns in the database. In the constructor of each field class, specify the column name and its type. If the column can accept a NULL value, then allowednone=True must be defined.

The abstraction is created. Now it is convenient to perform operations with the User class and the database.

from typing import Tuple

from user import User
from user_request import UserDBRequest


user = User()
user.username = 'simple_user'

request = UserDBRequest()
request.save(user)

user: User = request.loadAll(User(), limit=1)[0]
print(user.id)

sameUser = User()
sameUser.id = user.id
request.load(sameUser)
print(sameUser.username)

user.lastMessage = 'Hello world!'
request.update(user)

admin = User()
admin.username = 'admin'
admin.lastMessage = 'Do you want to be banned?'

request.save(admin)

users: Tuple[User] = request.loadAll(User())
for user in users:
    print(f'The user who said "{user.lastMessage}" has been deleted')
    request.delete(user)

Documentation

The documentation for the library is only available in Russian. If you are genuinely interested in the documentation, I suggest using Google Translate as a browser extension, as it works really well.

Feedback

Developer: Andrey Korovyanskiy | korandrmail@ya.ru

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

dbrequest-0.1.0.tar.gz (14.0 kB view details)

Uploaded Source

Built Distribution

dbrequest-0.1.0-py3-none-any.whl (15.8 kB view details)

Uploaded Python 3

File details

Details for the file dbrequest-0.1.0.tar.gz.

File metadata

  • Download URL: dbrequest-0.1.0.tar.gz
  • Upload date:
  • Size: 14.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.11.5

File hashes

Hashes for dbrequest-0.1.0.tar.gz
Algorithm Hash digest
SHA256 2baf88932402227de18bb8316e8bf36c7d290ac5c5a3969f95ad40cc4d21211d
MD5 4d3d3b37a3548f0ef595cfbac39c4abd
BLAKE2b-256 1b83785da48c8cbf4b8131ba76d04eda88346cc20befeb271870c2c0d737cb09

See more details on using hashes here.

File details

Details for the file dbrequest-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: dbrequest-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 15.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.11.5

File hashes

Hashes for dbrequest-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 73269d9436c89c99dfde354da08111b8a08139a39bd3da578cc9075b21d7c2f8
MD5 05631c3ab3b345aaf18c2663eda4bdff
BLAKE2b-256 7307cd9e1a7f7ec5d974986fafcfdf40b7703b905066b2f108f2ed8d513cc4fa

See more details on using hashes here.

Supported by

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