Files
sakhteman/core/utils/sumery/__init__.py
T
2024-02-15 00:17:51 +03:30

90 lines
2.9 KiB
Python

"""
smart upon mini query
amazing mini query in any database
"""
from core.models.base import DELETED_AT_QUERY
from core.utils import smart_cast
from core.service.mongo_db import use_collection
from core.exceptions import ValidationException
class SumeryObject:
db: str
object_name: str
table_name: str
driver: str = 'mongo'
query_fn: callable
cols_search: list
key_col: str = '_id'
value_col: str
value_fn: callable
limit: 10
def __init__(self, db: str,
object_name: str,
cols_search: list,
key_col: str,
value_col: str,
driver: str = 'mongo',
table_name: str = None,
query_fn: callable = None,
limit: int = 10,
value_fn: callable = None,
):
self.db = db
self.table_name = table_name
self.object_name = object_name
self.driver = driver
self.query_fn = query_fn
self.cols_search = cols_search
self.key_col = key_col
self.value_col = value_col
self.value_fn = value_fn
self.limit = limit
__sumery_list: list[SumeryObject] = []
async def sumery_executor(object_name: str, query: str, extra_filter: dict = None):
__query = query.strip()
if len(__query) < 3:
raise ValidationException('length of query not valid')
_so = next((x for x in __sumery_list if x.object_name == object_name), None)
if not _so:
raise ValidationException('summery object not found')
_query = {'$and': [{'$or': [{x: {'$regex': __query}} for x in _so.cols_search]},
DELETED_AT_QUERY,
extra_filter if extra_filter else {}]}
_projection = {
'_id': False,
'key': f'${_so.key_col}',
'value': f'${_so.value_col}'
}
records = use_collection(_so.table_name or _so.object_name, _so.db).find(_query, _projection).limit(_so.limit)
return [x async for x in records]
async def sumery_default_getter(object_name: str, ids: list, extra_filter: dict = None):
if not len(ids):
raise ValidationException('length of ids not valid')
_so = next((x for x in __sumery_list if x.object_name == object_name), None)
if not _so:
raise ValidationException('summery object not found')
__cast_ids = [smart_cast(x) for x in ids]
_query = {'$and': [{_so.key_col: {'$in': __cast_ids}},
DELETED_AT_QUERY,
extra_filter if extra_filter else {}]}
_projection = {
'_id': False,
'key': f'${_so.key_col}',
'value': f'${_so.value_col}'
}
records = use_collection(_so.table_name or _so.object_name, _so.db).find(_query, _projection).limit(100)
return [x async for x in records]
def setup_sumery_object(so: SumeryObject):
__sumery_list.append(so)