"""A file containing the implementation of the Query and Condition classes for filtering and querying data"""importoperatorfromtypingimportTYPE_CHECKING,Any,Dict,ListifTYPE_CHECKING:from.modelsimportMODEL,Field
[docs]classQuery:"""A class representing a database query"""def__init__(self,model:"MODEL")->None:"""Initialize a new query object Params: model (``Model``): The model class to query against """self.model=modelself.conditions:List[Condition]=[]def__str__(self)->str:returnself.__repr__()def__repr__(self)->str:returnf"Query(model={self.model.__name__}, conditions={[repr(condition)forconditioninself.conditions]})"
[docs]defwhere(self,*conditions:List["Condition"],**filters:Dict[str,Any])->"Query":"""Add a condition to the query Params: condition (``Condition``): The conditions to add to the query filters (``Dict[str, Any]``): Keyword arguments representing filter criteria for the model instances Returns: ``Query``: The updated query object """self.conditions.extend(conditions)forfield_name,valueinfilters.items():field=getattr(self.model,field_name)self.conditions.append(Condition(field,"==",value))returnself
[docs]defexecute(self)->List["MODEL"]:"""Execute the query and return the filtered results Returns: ```List[Model]```: The filtered results of the query """models=self.model.all()filtered_results=[modelformodelinmodelsifself.evaluate_conditions(model)]returnfiltered_results
[docs]defevaluate_conditions(self,model:"MODEL")->bool:"""Evaluate the conditions for a given model Params: model (``Model``): The model to evaluate the conditions against Returns: ``bool``: True if all conditions are met, False otherwise """returnall(condition.evaluate(model)forconditioninself.conditions)
[docs]classCondition:"""A class representing a condition in a database query"""def__init__(self,field:"Field",op:str,value:Any)->None:"""Initialize a new condition object Params: field (``Field``): The field to apply the condition to op (``str``): The operator for the condition (e.g., "==", "!=", "<", "<=", ">", ">=") value (``Any``): The value to compare against """self.field=fieldself.op=opself.value=valuedef__str__(self)->str:returnself.__repr__()def__repr__(self)->str:returnf"Condition(field={self.field}, operator='{self.op}', value={self.value})"
[docs]defevaluate(self,model:"MODEL")->bool:"""Evaluate the condition for a given model Params: model (``Model``): The model to evaluate the condition against Returns: ``bool``: True if the condition is met, False otherwise """operators_map={"==":operator.eq,"!=":operator.ne,"<":operator.lt,"<=":operator.le,">":operator.gt,">=":operator.ge}value=getattr(model,self.field.name)returnoperators_map[self.op](value,self.value)