TinyDB Queries. Allows building queries for TinyDB databases. There are two main ways of using queries: 1) ORM-like usage: >>> User = Query() >>> db.search(User.name == 'John Doe') >>> db.search(User['logged-in'] == True) 2) Classical usage: >>> db.search(wh
| 128 | |
| 129 | |
| 130 | class Query(QueryInstance): |
| 131 | """ |
| 132 | TinyDB Queries. |
| 133 | |
| 134 | Allows building queries for TinyDB databases. There are two main ways of |
| 135 | using queries: |
| 136 | |
| 137 | 1) ORM-like usage: |
| 138 | |
| 139 | >>> User = Query() |
| 140 | >>> db.search(User.name == 'John Doe') |
| 141 | >>> db.search(User['logged-in'] == True) |
| 142 | |
| 143 | 2) Classical usage: |
| 144 | |
| 145 | >>> db.search(where('value') == True) |
| 146 | |
| 147 | Note that ``where(...)`` is a shorthand for ``Query(...)`` allowing for |
| 148 | a more fluent syntax. |
| 149 | |
| 150 | Besides the methods documented here you can combine queries using the |
| 151 | binary AND and OR operators: |
| 152 | |
| 153 | >>> # Binary AND: |
| 154 | >>> db.search((where('field1').exists()) & (where('field2') == 5)) |
| 155 | >>> # Binary OR: |
| 156 | >>> db.search((where('field1').exists()) | (where('field2') == 5)) |
| 157 | |
| 158 | Queries are executed by calling the resulting object. They expect to get |
| 159 | the document to test as the first argument and return ``True`` or |
| 160 | ``False`` depending on whether the documents match the query or not. |
| 161 | """ |
| 162 | |
| 163 | def __init__(self) -> None: |
| 164 | # The current path of fields to access when evaluating the object |
| 165 | self._path: Tuple[Union[str, Callable], ...] = () |
| 166 | |
| 167 | # Prevent empty queries to be evaluated |
| 168 | def notest(_): |
| 169 | raise RuntimeError('Empty query was evaluated') |
| 170 | |
| 171 | super().__init__( |
| 172 | test=notest, |
| 173 | hashval=(None,) |
| 174 | ) |
| 175 | |
| 176 | def __repr__(self): |
| 177 | return '{}()'.format(type(self).__name__) |
| 178 | |
| 179 | def __hash__(self): |
| 180 | return super().__hash__() |
| 181 | |
| 182 | def __getattr__(self, item: str): |
| 183 | # Generate a new query object with the new query path |
| 184 | # We use type(self) to get the class of the current query in case |
| 185 | # someone uses a subclass of ``Query`` |
| 186 | query = type(self)() |
| 187 |
no outgoing calls
searching dependent graphs…