Search for all documents matching a 'where' cond. :param cond: the condition to check against :returns: list of matching documents
(self, cond: QueryLike)
| 237 | return list(iter(self)) |
| 238 | |
| 239 | def search(self, cond: QueryLike) -> List[Document]: |
| 240 | """ |
| 241 | Search for all documents matching a 'where' cond. |
| 242 | |
| 243 | :param cond: the condition to check against |
| 244 | :returns: list of matching documents |
| 245 | """ |
| 246 | |
| 247 | # First, we check the query cache to see if it has results for this |
| 248 | # query |
| 249 | cached_results = self._query_cache.get(cond) |
| 250 | if cached_results is not None: |
| 251 | return cached_results[:] |
| 252 | |
| 253 | # Perform the search by applying the query to all documents. |
| 254 | # Then, only if the document matches the query, convert it |
| 255 | # to the document class and document ID class. |
| 256 | docs = [ |
| 257 | self.document_class(doc, self.document_id_class(doc_id)) |
| 258 | for doc_id, doc in self._read_table().items() |
| 259 | if cond(doc) |
| 260 | ] |
| 261 | |
| 262 | # Only cache cacheable queries. |
| 263 | # |
| 264 | # This weird `getattr` dance is needed to make MyPy happy as |
| 265 | # it doesn't know that a query might have a `is_cacheable` method |
| 266 | # that is not declared in the `QueryLike` protocol due to it being |
| 267 | # optional. |
| 268 | # See: https://github.com/python/mypy/issues/1424 |
| 269 | # |
| 270 | # Note also that by default we expect custom query objects to be |
| 271 | # cacheable (which means they need to have a stable hash value). |
| 272 | # This is to keep consistency with TinyDB's behavior before |
| 273 | # `is_cacheable` was introduced which assumed that all queries |
| 274 | # are cacheable. |
| 275 | is_cacheable: Callable[[], bool] = getattr(cond, 'is_cacheable', |
| 276 | lambda: True) |
| 277 | if is_cacheable(): |
| 278 | # Update the query cache |
| 279 | self._query_cache[cond] = docs[:] |
| 280 | |
| 281 | return docs |
| 282 | |
| 283 | def get( |
| 284 | self, |