def between(self, start, end): """Query records in a start and end range :param start: `int` or `datetime` object :param end: `int` or `datetime` object :raise: :QueryTypeError: if start or end arguments is of an invalid type :return: self """ if hasattr(start, 'strftime') and hasattr(end, 'strftime'): dt_between = ( 'javascript:gs.dateGenerate("%(start)s")' "@" 'javascript:gs.dateGenerate("%(end)s")' ) % { 'start': start.strftime('%Y-%m-%d %H:%M:%S'), 'end': end.strftime('%Y-%m-%d %H:%M:%S') } elif isinstance(start, int) and isinstance(end, int): dt_between = '%d@%d' % (start, end) else: raise QueryTypeError("Expected `start` and `end` of type `int` " "or instance of `datetime`, not %s and %s" % (type(start), type(end))) return self._add_condition('BETWEEN', dt_between, types=[str])
def _add_condition(self, operator, value, types): """ Appends condition to self._query after performing validation :param operator: operator (str) :param value: value / operand :param types: allowed types :raise: :QueryMissingField: if a field hasn't been set :QueryMultipleExpressions: if a condition already has been set :QueryTypeError: if the value is of an unexpected type :return: self """ if not self.current_field: raise QueryMissingField("Expressions requires a field()") elif not type(value) in types: caller = inspect.currentframe().f_back.f_code.co_name raise QueryTypeError("Invalid type passed to %s() , expected: %s" % (caller, types)) elif self.c_oper: raise QueryMultipleExpressions("Expected logical operator after expression") self.c_oper = inspect.currentframe().f_back.f_code.co_name self._query.append("%(current_field)s%(operator)s%(value)s" % { 'current_field': self.current_field, 'operator': operator, 'value': value}) return self
def less_than(self, value): """Query records with the given field less than the value specified""" if hasattr(value, 'strftime'): value = value.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(value, str): raise QueryTypeError('Expected value of type `int` or instance of `datetime`, not %s' % type(value)) return self._add_condition('<', value, types=[int, str])
def not_equals(self, value): """ Query records with the given field not equalling: - the value specified - any of the values specified (list) """ if isinstance(value, str): return self._add_condition('!=', value, types=[int, str]) elif isinstance(value, list): return self._add_condition('NOT IN', ",".join(value), types=[str]) raise QueryTypeError('Expected value of type `str` or `list`, not %s' % type(value))
def equals(self, data): """ Query records with the given field equalling either: - the value passed (str) - any of the values passed (list) """ if isinstance(data, str): return self._add_condition('=', data, types=[int, str]) elif isinstance(data, list): return self._add_condition('IN', ",".join(map(str, data)), types=[str]) raise QueryTypeError('Expected value of type `str` or `list`, not %s' % type(data))