Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for datetime.date objects for date-like query fields #7

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/tutorials/query_fields.rst
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ Field Definitions

**Time related**

For those fields you can either pass instance of datetime.date or date-like string.

.. glossary::

BEFORE('date-like')
Expand Down
23 changes: 11 additions & 12 deletions redbox/query/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .query import Flag, ValueField, KeyValueField, ALL, OR, NOT, BaseField
from .query import Flag, ValueField, DateField, KeyValueField, ALL, OR, NOT, BaseField

HEADER = KeyValueField("HEADER")

Expand All @@ -21,7 +21,6 @@
SEEN = Flag("SEEN")
UNSEEN = Flag("UNSEEN")


BCC = ValueField("BCC")
CC = ValueField("CC")

Expand All @@ -32,15 +31,13 @@
TO = ValueField("TO")
FROM = ValueField("FROM")

ON = ValueField("ON")


SENTON = ValueField("SENTON")
SENTBEFORE = ValueField("SENTBEFORE")
SENTSINCE = ValueField("SENTSINCE")
SENTBEFORE = DateField("SENTBEFORE")
SENTON = DateField("SENTON")
SENTSINCE = DateField("SENTSINCE")

BEFORE = ValueField("BEFORE")
SINCE = ValueField("SINCE")
BEFORE = DateField("BEFORE")
ON = DateField("ON")
SINCE = DateField("SINCE")

LARGER = ValueField("LARGER")
SMALLER = ValueField("SMALLER")
Expand All @@ -49,7 +46,8 @@
KEYWORD = ValueField("KEYWORD")
UNKEYWORD = ValueField("UNKEYWORD")

def _build(key:str, val):

def _build(key: str, val):
# Turning from_ --> "FROM", "to" --> "TO" etc.
key = key.upper().rstrip("_")
obj = BaseField._fields[key]
Expand All @@ -69,6 +67,7 @@ def _build(key:str, val):
else:
raise TypeError("Invalid field")


def build(**kwargs) -> str:
qry = None
for key, val in kwargs.items():
Expand All @@ -77,4 +76,4 @@ def build(**kwargs) -> str:
qry = cmp
else:
qry &= cmp
return str(qry)
return str(qry)
56 changes: 47 additions & 9 deletions redbox/query/query.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@

from copy import copy
from typing import Dict
from datetime import date

class BaseQuery:

class BaseQuery:
def __and__(self, other):
return ALL(self, other)

Expand All @@ -12,16 +13,18 @@ def __or__(self, other):
def __invert__(self):
return NOT(self)


class BaseField(BaseQuery):
_fields = {}

def __init__(self, name):
self._fields[name] = self
self._name = name


class Flag(BaseField):
def __str__(self):
return f'({self._name})'
return f"({self._name})"


class ValueField(BaseField):
Expand All @@ -33,6 +36,38 @@ def __call__(self, value):
def __str__(self):
raise ValueError(f"Field {self._name} needs a value")


class DateField(ValueField):
"Field that contains a date value"

def __call__(self, datelike: date):
if isinstance(datelike, date):
# see date-month token (section 9.0 Formal Syntax)
# https://www.rfc-editor.org/rfc/rfc3501
imap_months = [
"",
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
return ValueFilled(
self, f"{datelike.day:02}-{imap_months[datelike.month]}-{datelike.year}"
)
return ValueFilled(self, str(datelike))

def __str__(self):
raise ValueError(f"Field {self._name} needs a value")


class KeyValueField(BaseField):
"Field that contains a key and a value"

Expand All @@ -42,6 +77,7 @@ def __call__(self, key, value):
def __str__(self):
raise ValueError(f"Field {self._name} needs a value")


class CompareField(BaseField):
"Field that contains a statement"

Expand All @@ -53,6 +89,7 @@ def __str__(self):
return f"({self._name})"
raise ValueError(f"{self._name} requires statement")


class NotField(BaseField):
"NOT field"

Expand All @@ -64,18 +101,18 @@ def __str__(self):


class LogicalFilled(BaseField):

def __init__(self, field, values:tuple):
def __init__(self, field, values: tuple):
self._field = field
self._values = values

def __str__(self):
if isinstance(self._values, tuple):
a, b = self._values
return f'({self._field._name} {a} {b})'
return f"({self._field._name} {a} {b})"
else:
value = self._values
return f'({self._field._name} {value})'
return f"({self._field._name} {value})"


class ValueFilled(BaseQuery):
"Field that has already a value"
Expand All @@ -87,6 +124,7 @@ def __init__(self, field, value):
def __str__(self):
return f'({self._field._name} "{self._value}")'


class KeyValueFilled(BaseQuery):
"Field that has already a key and a value"

Expand All @@ -98,7 +136,7 @@ def __init__(self, field, key, value):
def __str__(self):
return f'({self._field._name} "{self._key}" "{self._value}")'


ALL = CompareField("ALL")
OR = CompareField("OR")
NOT = NotField("NOT")

10 changes: 6 additions & 4 deletions redbox/tests/test_query.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

import pytest
from redbox.query import ALL, NEW, OR, TO, UNSEEN, SINCE, RECENT, NOT, TEXT, HEADER, SUBJECT, SEEN, build
from datetime import datetime

# A282 SEARCH FLAGGED SINCE 1-Feb-1994 NOT FROM "Smith"

Expand All @@ -16,7 +16,8 @@
pytest.param(NOT(UNSEEN), '(NOT (UNSEEN))'),
pytest.param(~UNSEEN, '(NOT (UNSEEN))'),

pytest.param(SINCE("2022-01-01"), '(SINCE "2022-01-01")'),
pytest.param(SINCE("01-Jan-2022"), '(SINCE "01-Jan-2022")'),
pytest.param(SINCE(datetime(2022, 1, 1)), '(SINCE "01-Jan-2022")'),
pytest.param(HEADER("Mime-Version", "1.0"), '(HEADER "Mime-Version" "1.0")'),

pytest.param(NOT(NEW & TEXT("hello")), '(NOT (ALL (NEW) (TEXT "hello")))'),
Expand All @@ -36,9 +37,10 @@ def test_expression(qry, expected):
pytest.param(dict(unseen=False), '(NOT (UNSEEN))'),
pytest.param(dict(seen=True), '(SEEN)'),
pytest.param(dict(seen=False), '(NOT (SEEN))'),
pytest.param(dict(since="2022-01-01"), '(SINCE "2022-01-01")'),
pytest.param(dict(since="01-Jan-2022"), '(SINCE "01-Jan-2022")'),
pytest.param(dict(header=('Mime-Version', '1.0')), '(HEADER "Mime-Version" "1.0")'),
pytest.param(dict(since="2022-01-01", seen=True), '(ALL (SINCE "2022-01-01") (SEEN))'),
pytest.param(dict(since="01-Jan-2022", seen=True), '(ALL (SINCE "01-Jan-2022") (SEEN))'),
pytest.param(dict(since=datetime(2022, 1, 1), seen=True), '(ALL (SINCE "01-Jan-2022") (SEEN))'),

pytest.param(dict(from_="me@example.com"), '(FROM "me@example.com")'),

Expand Down