scruby-dict 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ # Copyright (c) 2026 Gennady Kostyunin
2
+ # SPDX-License-Identifier: MIT
3
+ """Scruby-Dict - In search methods, returns result as dictionaries."""
4
+
5
+ from __future__ import annotations
6
+
7
+ __all__ = ("ReturnDict",)
8
+
9
+ from scruby_dict.plugin import ReturnDict
scruby_dict/plugin.py ADDED
@@ -0,0 +1,166 @@
1
+ # Scruby-Dict - In search methods, returns result as dictionaries.
2
+ # Copyright (c) 2026 Gennady Kostyunin
3
+ # SPDX-License-Identifier: MIT
4
+ """Scruby-Dict Plugin."""
5
+
6
+ from __future__ import annotations
7
+
8
+ __all__ = ("ReturnDict",)
9
+
10
+
11
+ import concurrent.futures
12
+ from collections.abc import Callable
13
+ from typing import Any, final
14
+
15
+ import orjson
16
+ from anyio import Path
17
+ from scruby import Scruby
18
+ from scruby_plugin import ScrubyPlugin
19
+
20
+
21
+ class ReturnDict(ScrubyPlugin):
22
+ """Scruby-Dict Plugin.
23
+
24
+ In search methods, returns result as dictionaries.
25
+ """
26
+
27
+ def __init__(self, scruby_self: Scruby) -> None: # noqa: D107
28
+ ScrubyPlugin.__init__(self, scruby_self)
29
+
30
+ @final
31
+ @staticmethod
32
+ async def _task_find(
33
+ branch_number: int,
34
+ filter_fn: Callable,
35
+ hash_reduce_left: int,
36
+ db_root: str,
37
+ class_model: Any,
38
+ ) -> list[dict[str, Any]] | None:
39
+ """Task for find documents.
40
+
41
+ This method is for internal use.
42
+
43
+ Returns:
44
+ List of documents as dictionaries or None.
45
+ """
46
+ branch_number_as_hash: str = f"{branch_number:08x}"[hash_reduce_left:]
47
+ separated_hash: str = "/".join(list(branch_number_as_hash))
48
+ leaf_path = Path(
49
+ *(
50
+ db_root,
51
+ class_model.__name__,
52
+ separated_hash,
53
+ "leaf.json",
54
+ ),
55
+ )
56
+ docs: list[dict[str, Any]] = []
57
+ if await leaf_path.exists():
58
+ data_json: bytes = await leaf_path.read_bytes()
59
+ data: dict[str, str] = orjson.loads(data_json) or {}
60
+ for _, val in data.items():
61
+ doc = class_model.model_validate_json(val)
62
+ if filter_fn(doc):
63
+ docs.append(doc.model_dump())
64
+ return docs or None
65
+
66
+ @final
67
+ async def find_one(
68
+ self,
69
+ filter_fn: Callable,
70
+ ) -> dict[str, Any] | None:
71
+ """Asynchronous method for find one document matching the filter.
72
+
73
+ Attention:
74
+ - The search is based on the effect of a quantum loop.
75
+ - The search effectiveness depends on the number of processor threads.
76
+
77
+ Args:
78
+ filter_fn (Callable): A function that execute the conditions of filtering.
79
+
80
+ Returns:
81
+ One document as dictionary or None.
82
+ """
83
+ # Get Scruby instance
84
+ scruby_self = self.scruby_self()
85
+ # Variable initialization
86
+ search_task_fn: Callable = self._task_find
87
+ branch_numbers: range = range(scruby_self._max_number_branch)
88
+ hash_reduce_left: int = scruby_self._hash_reduce_left
89
+ db_root: str = scruby_self._db_root
90
+ class_model: Any = scruby_self._class_model
91
+ # Run quantum loop
92
+ with concurrent.futures.ThreadPoolExecutor(scruby_self._max_workers) as executor:
93
+ for branch_number in branch_numbers:
94
+ future = executor.submit(
95
+ search_task_fn,
96
+ branch_number,
97
+ filter_fn,
98
+ hash_reduce_left,
99
+ db_root,
100
+ class_model,
101
+ )
102
+ docs = await future.result()
103
+ if docs is not None:
104
+ return docs[0]
105
+ return None
106
+
107
+ @final
108
+ async def find_many(
109
+ self,
110
+ filter_fn: Callable = lambda _: True,
111
+ limit_docs: int = 100,
112
+ page_number: int = 1,
113
+ ) -> list[dict[str, Any]] | None:
114
+ """Asynchronous method for find many documents matching the filter.
115
+
116
+ Attention:
117
+ - The search is based on the effect of a quantum loop.
118
+ - The search effectiveness depends on the number of processor threads.
119
+
120
+ Args:
121
+ filter_fn (Callable): A function that execute the conditions of filtering.
122
+ By default it searches for all documents.
123
+ limit_docs (int): Limiting the number of documents. By default = 100.
124
+ page_number (int): For pagination. By default = 1.
125
+ Number of documents per page = limit_docs.
126
+
127
+ Returns:
128
+ List of documents as dictionaries or None.
129
+ """
130
+ # The `page_number` parameter must not be less than one
131
+ assert page_number > 0, "`find_many` => The `page_number` parameter must not be less than one."
132
+ # Get Scruby instance
133
+ scruby_self = self.scruby_self()
134
+ # Variable initialization
135
+ search_task_fn: Callable = self._task_find
136
+ branch_numbers: range = range(scruby_self._max_number_branch)
137
+ hash_reduce_left: int = scruby_self._hash_reduce_left
138
+ db_root: str = scruby_self._db_root
139
+ class_model: Any = scruby_self._class_model
140
+ counter: int = 0
141
+ number_docs_skippe: int = limit_docs * (page_number - 1) if page_number > 1 else 0
142
+ result: list[dict[str, Any]] = []
143
+ # Run quantum loop
144
+ with concurrent.futures.ThreadPoolExecutor(scruby_self._max_workers) as executor:
145
+ for branch_number in branch_numbers:
146
+ if number_docs_skippe == 0 and counter >= limit_docs:
147
+ return result[:limit_docs]
148
+ future = executor.submit(
149
+ search_task_fn,
150
+ branch_number,
151
+ filter_fn,
152
+ hash_reduce_left,
153
+ db_root,
154
+ class_model,
155
+ )
156
+ docs = await future.result()
157
+ if docs is not None:
158
+ for doc in docs:
159
+ if number_docs_skippe == 0:
160
+ if counter >= limit_docs:
161
+ return result[:limit_docs]
162
+ result.append(doc)
163
+ counter += 1
164
+ else:
165
+ number_docs_skippe -= 1
166
+ return result or None
scruby_dict/py.typed ADDED
File without changes
@@ -0,0 +1,159 @@
1
+ Metadata-Version: 2.4
2
+ Name: scruby-dict
3
+ Version: 0.3.0
4
+ Summary: Plugin for Scruby - In search methods, returns results in the form of dictionaries.
5
+ Project-URL: Bug Tracker, https://github.com/kebasyaty/scruby-dict/issues
6
+ Project-URL: Changelog, https://github.com/kebasyaty/scruby-dict/blob/v0/CHANGELOG.md
7
+ Project-URL: Homepage, https://kebasyaty.github.io/scruby-dict/
8
+ Project-URL: Repository, https://github.com/kebasyaty/scruby-dict
9
+ Project-URL: Source, https://github.com/kebasyaty/scruby-dict
10
+ Author-email: kebasyaty <kebasyaty@gmail.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: database,dictionary,plugin,scruby
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: MacOS :: MacOS X
17
+ Classifier: Operating System :: Microsoft :: Windows
18
+ Classifier: Operating System :: POSIX
19
+ Classifier: Operating System :: POSIX :: Linux
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Programming Language :: Python :: Implementation :: CPython
26
+ Classifier: Topic :: Database
27
+ Classifier: Topic :: Software Development :: Libraries
28
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
+ Classifier: Typing :: Typed
30
+ Requires-Python: <4.0,>=3.12
31
+ Requires-Dist: anyio>=4.12.1
32
+ Requires-Dist: scruby-plugin>=0.3.6
33
+ Description-Content-Type: text/markdown
34
+
35
+ <div align="center">
36
+ <p align="center">
37
+ <a href="https://github.com/kebasyaty/scruby-dict">
38
+ <img
39
+ height="80"
40
+ alt="Logo"
41
+ src="https://raw.githubusercontent.com/kebasyaty/scruby-dict/main/assets/logo.svg">
42
+ </a>
43
+ </p>
44
+ <p>
45
+ <h1>scruby-dict</h1>
46
+ <h3>Plugin for Scruby - In search methods, returns result as dictionaries.</h3>
47
+ <p align="center">
48
+ <a href="https://github.com/kebasyaty/scruby-dict/actions/workflows/test.yml" alt="Build Status"><img src="https://github.com/kebasyaty/scruby-dict/actions/workflows/test.yml/badge.svg" alt="Build Status"></a>
49
+ <a href="https://kebasyaty.github.io/scruby-dict/" alt="Docs"><img src="https://img.shields.io/badge/docs-available-brightgreen.svg" alt="Docs"></a>
50
+ <a href="https://pypi.python.org/pypi/scruby-dict/" alt="PyPI pyversions"><img src="https://img.shields.io/pypi/pyversions/scruby-dict.svg" alt="PyPI pyversions"></a>
51
+ <a href="https://pypi.python.org/pypi/scruby-dict/" alt="PyPI status"><img src="https://img.shields.io/pypi/status/scruby-dict.svg" alt="PyPI status"></a>
52
+ <a href="https://pypi.python.org/pypi/scruby-dict/" alt="PyPI version fury.io"><img src="https://badge.fury.io/py/scruby-dict.svg" alt="PyPI version fury.io"></a>
53
+ <br>
54
+ <a href="https://pyrefly.org/" alt="Types: Pyrefly"><img src="https://img.shields.io/badge/types-Pyrefly-FFB74D.svg" alt="Types: Pyrefly"></a>
55
+ <a href="https://docs.astral.sh/ruff/" alt="Code style: Ruff"><img src="https://img.shields.io/badge/code%20style-Ruff-FDD835.svg" alt="Code style: Ruff"></a>
56
+ <a href="https://pypi.org/project/scruby-dict"><img src="https://img.shields.io/pypi/format/scruby-dict" alt="Format"></a>
57
+ <a href="https://pepy.tech/projects/scruby-dict"><img src="https://static.pepy.tech/badge/scruby-dict" alt="PyPI Downloads"></a>
58
+ <a href="https://github.com/kebasyaty/scruby-dict/blob/main/LICENSE" alt="GitHub license"><img src="https://img.shields.io/github/license/kebasyaty/scruby-dict" alt="GitHub license"></a>
59
+ </p>
60
+ <p align="center">
61
+ Scruby-Dict is a plugin for the <a href="https://pypi.org/project/scruby/" alt="Scruby">Scruby</a> project.
62
+ </p>
63
+ </p>
64
+ </div>
65
+
66
+ ##
67
+
68
+ <br>
69
+
70
+ [![Documentation](https://raw.githubusercontent.com/kebasyaty/scruby-dict/v0/assets/links/documentation.svg "Documentation")](https://kebasyaty.github.io/scruby-dict/ "Documentation")
71
+
72
+ [![Requirements](https://raw.githubusercontent.com/kebasyaty/scruby-dict/v0/assets/links/requirements.svg "Requirements")](https://github.com/kebasyaty/scruby-dict/blob/v0/REQUIREMENTS.md "Requirements")
73
+
74
+ ## Installation
75
+
76
+ ```shell
77
+ uv add scruby-dict
78
+ ```
79
+
80
+ ## Usage
81
+
82
+ [![Examples](https://raw.githubusercontent.com/kebasyaty/scruby-dict/v0/assets/links/examples.svg "Examples")](https://kebasyaty.github.io/scruby-dict/latest/pages/usage/ "Examples")
83
+
84
+ ```python
85
+ import anyio
86
+ from typing import Any
87
+ from pydantic import Field
88
+ from scruby import Scruby, ScrubyModel, ScrubySettings
89
+ from scruby_dict import ReturnDict
90
+ from pprint import pprint as pp
91
+
92
+ # Plugins connection.
93
+ ScrubySettings.plugins = [
94
+ ReturnDict,
95
+ ]
96
+
97
+
98
+ class Car(ScrubyModel):
99
+ """Car model."""
100
+ brand: str = Field(strict=True, frozen=True)
101
+ model: str = Field(strict=True, frozen=True)
102
+ year: int = Field(strict=True, frozen=True)
103
+ power_reserve: int = Field(strict=True, frozen=True)
104
+ description: str = Field(strict=True)
105
+ # key is always at bottom
106
+ key: str = Field(
107
+ strict=True,
108
+ frozen=True,
109
+ default_factory=lambda data: f"{data['brand']}:{data['model']}",
110
+ )
111
+
112
+
113
+ async def main() -> None:
114
+ """Example."""
115
+ # Get collection `Car`
116
+ car_coll = await Scruby.collection(Car)
117
+ # Create cars.
118
+ for num in range(1, 10):
119
+ car = Car(
120
+ brand="Mazda",
121
+ model=f"EZ-6 {num}",
122
+ year=2025,
123
+ power_reserve=600,
124
+ description="Electric cars are the future of the global automotive industry.",
125
+ )
126
+ await car_coll.add_doc(car)
127
+
128
+ # Find one car
129
+ car_dict: dict[str, Any] | None = await car_coll.plugins.returnDict.find_one(c
130
+ filter_fn=lambda doc: doc.brand == "Mazda" and doc.model == "EZ-6 9",
131
+ )
132
+ if car_dict is not None:
133
+ pp(car_dict)
134
+ else:
135
+ print("Not Found")
136
+
137
+ # Fand many cars
138
+ car_list: list[dict[str, Any]] | None = await car_coll.plugins.returnDict.find_many(
139
+ filter_fn=lambda doc: doc.brand == "Mazda",
140
+ )
141
+ if car_list is not None:
142
+ pp(car_list)
143
+ else:
144
+ print("Not Found")
145
+
146
+ # Full database deletion.
147
+ # Hint: The main purpose is tests.
148
+ Scruby.napalm()
149
+
150
+
151
+ if __name__ == "__main__":
152
+ anyio.run(main)
153
+ ```
154
+
155
+ <br>
156
+
157
+ [![Changelog](https://raw.githubusercontent.com/kebasyaty/scruby-dict/v0/assets/links/changelog.svg "Changelog")](https://github.com/kebasyaty/scruby-dict/blob/v0/CHANGELOG.md "Changelog")
158
+
159
+ [![GPL-3.0](https://raw.githubusercontent.com/kebasyaty/scruby-dict/v0/assets/links/mit.svg "MIT")](https://github.com/kebasyaty/scruby-dict/blob/main/LICENSE "MIT")
@@ -0,0 +1,7 @@
1
+ scruby_dict/__init__.py,sha256=-11wZwiS0eCInhbWWhFdHXM5-_BCpxr9fJDBT-XRHKU,247
2
+ scruby_dict/plugin.py,sha256=6RLmXaY8f473j2KKOn6MrlWpxOQt9SwgDiTaiNBVuuo,5957
3
+ scruby_dict/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ scruby_dict-0.3.0.dist-info/METADATA,sha256=PwWWZM9TbIH76hc9VNimTEJFQxXkHIc5GmumUzGh1rM,6616
5
+ scruby_dict-0.3.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
6
+ scruby_dict-0.3.0.dist-info/licenses/LICENSE,sha256=mvh5qv1YJGyuVCkRxonDDNOzxlwXszKvwxXfOeXKrqw,1074
7
+ scruby_dict-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gennady Kostyunin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.