beaver-db 0.6.0__py3-none-any.whl → 0.7.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.

Potentially problematic release.


This version of beaver-db might be problematic. Click here for more details.

@@ -4,7 +4,7 @@ import time
4
4
  from typing import Any, Iterator
5
5
 
6
6
 
7
- class SubWrapper(Iterator):
7
+ class ChannelManager(Iterator):
8
8
  """
9
9
  A synchronous, blocking iterator that polls a channel for new messages.
10
10
  """
@@ -25,7 +25,7 @@ class SubWrapper(Iterator):
25
25
  self._poll_interval = poll_interval
26
26
  self._last_seen_timestamp = time.time()
27
27
 
28
- def __iter__(self) -> "SubWrapper":
28
+ def __iter__(self) -> "ChannelManager":
29
29
  """Returns the iterator object itself."""
30
30
  return self
31
31
 
beaver/collections.py CHANGED
@@ -45,7 +45,7 @@ class Document:
45
45
  return f"Document(id='{self.id}', {metadata_str})"
46
46
 
47
47
 
48
- class CollectionWrapper:
48
+ class CollectionManager:
49
49
  """
50
50
  A wrapper for multi-modal collection operations with an in-memory ANN index,
51
51
  FTS, and graph capabilities.
beaver/core.py CHANGED
@@ -3,10 +3,10 @@ import sqlite3
3
3
  import time
4
4
  from typing import Any
5
5
 
6
- from .dicts import DictWrapper
7
- from .lists import ListWrapper
8
- from .subscribers import SubWrapper
9
- from .collections import CollectionWrapper
6
+ from .dicts import DictManager
7
+ from .lists import ListManager
8
+ from .channels import ChannelManager
9
+ from .collections import CollectionManager
10
10
 
11
11
 
12
12
  class BeaverDB:
@@ -48,6 +48,7 @@ class BeaverDB:
48
48
  dict_name TEXT NOT NULL,
49
49
  key TEXT NOT NULL,
50
50
  value TEXT NOT NULL,
51
+ expires_at REAL,
51
52
  PRIMARY KEY (dict_name, key)
52
53
  )
53
54
  """
@@ -151,21 +152,21 @@ class BeaverDB:
151
152
 
152
153
  # --- Factory and Passthrough Methods ---
153
154
 
154
- def dict(self, name: str) -> DictWrapper:
155
+ def dict(self, name: str) -> DictManager:
155
156
  """Returns a wrapper object for interacting with a named dictionary."""
156
157
  if not isinstance(name, str) or not name:
157
158
  raise TypeError("Dictionary name must be a non-empty string.")
158
- return DictWrapper(name, self._conn)
159
+ return DictManager(name, self._conn)
159
160
 
160
- def list(self, name: str) -> ListWrapper:
161
+ def list(self, name: str) -> ListManager:
161
162
  """Returns a wrapper object for interacting with a named list."""
162
163
  if not isinstance(name, str) or not name:
163
164
  raise TypeError("List name must be a non-empty string.")
164
- return ListWrapper(name, self._conn)
165
+ return ListManager(name, self._conn)
165
166
 
166
- def collection(self, name: str) -> CollectionWrapper:
167
+ def collection(self, name: str) -> CollectionManager:
167
168
  """Returns a wrapper for interacting with a document collection."""
168
- return CollectionWrapper(name, self._conn)
169
+ return CollectionManager(name, self._conn)
169
170
 
170
171
  def publish(self, channel_name: str, payload: Any):
171
172
  """Publishes a JSON-serializable message to a channel. This is synchronous."""
@@ -182,6 +183,6 @@ class BeaverDB:
182
183
  (time.time(), channel_name, json_payload),
183
184
  )
184
185
 
185
- def subscribe(self, channel_name: str) -> SubWrapper:
186
+ def subscribe(self, channel_name: str) -> ChannelManager:
186
187
  """Subscribes to a channel, returning a synchronous iterator."""
187
- return SubWrapper(self._conn, channel_name)
188
+ return ChannelManager(self._conn, channel_name)
beaver/dicts.py CHANGED
@@ -1,46 +1,64 @@
1
1
  import json
2
2
  import sqlite3
3
+ import time # Add this import
3
4
  from typing import Any, Iterator, Tuple
4
5
 
5
-
6
- class DictWrapper:
6
+ class DictManager:
7
7
  """A wrapper providing a Pythonic interface to a dictionary in the database."""
8
8
 
9
9
  def __init__(self, name: str, conn: sqlite3.Connection):
10
10
  self._name = name
11
11
  self._conn = conn
12
12
 
13
- def set(self, key: str, value: Any):
14
- """Sets a value for a key in the dictionary."""
15
- self.__setitem__(key, value)
13
+ def set(self, key: str, value: Any, ttl_seconds: int | None = None):
14
+ """Sets a value for a key, with an optional TTL."""
15
+ self.__setitem__(key, value, ttl_seconds=ttl_seconds)
16
16
 
17
- def __setitem__(self, key: str, value: Any):
17
+ def __setitem__(self, key: str, value: Any, ttl_seconds: int | None = None):
18
18
  """Sets a value for a key (e.g., `my_dict[key] = value`)."""
19
+ expires_at = None
20
+ if ttl_seconds is not None:
21
+ if not isinstance(ttl_seconds, int) or ttl_seconds <= 0:
22
+ raise ValueError("ttl_seconds must be a positive integer.")
23
+ expires_at = time.time() + ttl_seconds
24
+
19
25
  with self._conn:
20
26
  self._conn.execute(
21
- "INSERT OR REPLACE INTO beaver_dicts (dict_name, key, value) VALUES (?, ?, ?)",
22
- (self._name, key, json.dumps(value)),
27
+ "INSERT OR REPLACE INTO beaver_dicts (dict_name, key, value, expires_at) VALUES (?, ?, ?, ?)",
28
+ (self._name, key, json.dumps(value), expires_at),
23
29
  )
24
30
 
25
31
  def get(self, key: str, default: Any = None) -> Any:
26
- """Gets a value for a key, with a default if it doesn't exist."""
32
+ """Gets a value for a key, with a default if it doesn't exist or is expired."""
27
33
  try:
28
34
  return self[key]
29
35
  except KeyError:
30
36
  return default
31
37
 
32
38
  def __getitem__(self, key: str) -> Any:
33
- """Retrieves a value for a given key (e.g., `my_dict[key]`)."""
39
+ """Retrieves a value for a given key, raising KeyError if expired."""
34
40
  cursor = self._conn.cursor()
35
41
  cursor.execute(
36
- "SELECT value FROM beaver_dicts WHERE dict_name = ? AND key = ?",
42
+ "SELECT value, expires_at FROM beaver_dicts WHERE dict_name = ? AND key = ?",
37
43
  (self._name, key),
38
44
  )
39
45
  result = cursor.fetchone()
40
- cursor.close()
46
+
41
47
  if result is None:
48
+ cursor.close()
42
49
  raise KeyError(f"Key '{key}' not found in dictionary '{self._name}'")
43
- return json.loads(result["value"])
50
+
51
+ value, expires_at = result["value"], result["expires_at"]
52
+
53
+ if expires_at is not None and time.time() > expires_at:
54
+ # Expired: delete the key and raise KeyError
55
+ cursor.execute("DELETE FROM beaver_dicts WHERE dict_name = ? AND key = ?", (self._name, key))
56
+ self._conn.commit()
57
+ cursor.close()
58
+ raise KeyError(f"Key '{key}' not found in dictionary '{self._name}' (expired)")
59
+
60
+ cursor.close()
61
+ return json.loads(value)
44
62
 
45
63
  def __delitem__(self, key: str):
46
64
  """Deletes a key-value pair (e.g., `del my_dict[key]`)."""
beaver/lists.py CHANGED
@@ -1,10 +1,9 @@
1
1
  import json
2
2
  import sqlite3
3
- from typing import Any, Union
3
+ from typing import Any, Union, Iterator
4
4
 
5
-
6
- class ListWrapper:
7
- """A wrapper providing a Pythonic interface to a list in the database."""
5
+ class ListManager:
6
+ """A wrapper providing a Pythonic, full-featured interface to a list in the database."""
8
7
 
9
8
  def __init__(self, name: str, conn: sqlite3.Connection):
10
9
  self._name = name
@@ -61,6 +60,87 @@ class ListWrapper:
61
60
  else:
62
61
  raise TypeError("List indices must be integers or slices.")
63
62
 
63
+ def __setitem__(self, key: int, value: Any):
64
+ """Sets the value of an item at a specific index (e.g., `my_list[0] = 'new'`)."""
65
+ if not isinstance(key, int):
66
+ raise TypeError("List indices must be integers.")
67
+
68
+ list_len = len(self)
69
+ if key < -list_len or key >= list_len:
70
+ raise IndexError("List index out of range.")
71
+
72
+ offset = key if key >= 0 else list_len + key
73
+
74
+ with self._conn:
75
+ cursor = self._conn.cursor()
76
+ # Find the rowid of the item to update
77
+ cursor.execute(
78
+ "SELECT rowid FROM beaver_lists WHERE list_name = ? ORDER BY item_order ASC LIMIT 1 OFFSET ?",
79
+ (self._name, offset)
80
+ )
81
+ result = cursor.fetchone()
82
+ if not result:
83
+ raise IndexError("List index out of range during update.")
84
+
85
+ rowid_to_update = result['rowid']
86
+ # Update the value for that specific row
87
+ cursor.execute(
88
+ "UPDATE beaver_lists SET item_value = ? WHERE rowid = ?",
89
+ (json.dumps(value), rowid_to_update)
90
+ )
91
+
92
+ def __delitem__(self, key: int):
93
+ """Deletes an item at a specific index (e.g., `del my_list[0]`)."""
94
+ if not isinstance(key, int):
95
+ raise TypeError("List indices must be integers.")
96
+
97
+ list_len = len(self)
98
+ if key < -list_len or key >= list_len:
99
+ raise IndexError("List index out of range.")
100
+
101
+ offset = key if key >= 0 else list_len + key
102
+
103
+ with self._conn:
104
+ cursor = self._conn.cursor()
105
+ # Find the rowid of the item to delete
106
+ cursor.execute(
107
+ "SELECT rowid FROM beaver_lists WHERE list_name = ? ORDER BY item_order ASC LIMIT 1 OFFSET ?",
108
+ (self._name, offset)
109
+ )
110
+ result = cursor.fetchone()
111
+ if not result:
112
+ raise IndexError("List index out of range during delete.")
113
+
114
+ rowid_to_delete = result['rowid']
115
+ # Delete that specific row
116
+ cursor.execute("DELETE FROM beaver_lists WHERE rowid = ?", (rowid_to_delete,))
117
+
118
+ def __iter__(self) -> Iterator[Any]:
119
+ """Returns an iterator for the list."""
120
+ cursor = self._conn.cursor()
121
+ cursor.execute(
122
+ "SELECT item_value FROM beaver_lists WHERE list_name = ? ORDER BY item_order ASC",
123
+ (self._name,)
124
+ )
125
+ for row in cursor:
126
+ yield json.loads(row['item_value'])
127
+ cursor.close()
128
+
129
+ def __contains__(self, value: Any) -> bool:
130
+ """Checks for the existence of an item in the list (e.g., `'item' in my_list`)."""
131
+ cursor = self._conn.cursor()
132
+ cursor.execute(
133
+ "SELECT 1 FROM beaver_lists WHERE list_name = ? AND item_value = ? LIMIT 1",
134
+ (self._name, json.dumps(value))
135
+ )
136
+ result = cursor.fetchone()
137
+ cursor.close()
138
+ return result is not None
139
+
140
+ def __repr__(self) -> str:
141
+ """Returns a developer-friendly representation of the object."""
142
+ return f"ListWrapper(name='{self._name}')"
143
+
64
144
  def _get_order_at_index(self, index: int) -> float:
65
145
  """Helper to get the float `item_order` at a specific index."""
66
146
  cursor = self._conn.cursor()
@@ -163,4 +243,4 @@ class ListWrapper:
163
243
  cursor.execute(
164
244
  "DELETE FROM beaver_lists WHERE rowid = ?", (rowid_to_delete,)
165
245
  )
166
- return json.loads(value_to_return)
246
+ return json.loads(value_to_return)
@@ -1,14 +1,20 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: beaver-db
3
- Version: 0.6.0
3
+ Version: 0.7.0
4
4
  Summary: Fast, embedded, and multi-modal DB based on SQLite for AI-powered applications.
5
5
  Requires-Python: >=3.13
6
6
  Description-Content-Type: text/markdown
7
+ License-File: LICENSE
7
8
  Requires-Dist: numpy>=2.3.3
8
9
  Requires-Dist: scipy>=1.16.2
10
+ Dynamic: license-file
9
11
 
10
12
  # beaver 🦫
11
13
 
14
+ ![PyPI - Downloads](https://img.shields.io/pypi/dm/beaver-db)
15
+ ![PyPI](https://img.shields.io/pypi/v/beaver-db)
16
+ ![License](https://img.shields.io/github/license/apiad/beaver)
17
+
12
18
  A fast, single-file, multi-modal database for Python, built with the standard `sqlite3` library.
13
19
 
14
20
  `beaver` is the **B**ackend for **E**mbedded, **A**ll-in-one **V**ector, **E**ntity, and **R**elationship storage. It's a simple, local, and embedded database designed to manage complex, modern data types without requiring a database server, built on top of SQLite.
@@ -26,8 +32,8 @@ A fast, single-file, multi-modal database for Python, built with the standard `s
26
32
  ## Core Features
27
33
 
28
34
  - **Synchronous Pub/Sub**: A simple, thread-safe, Redis-like publish-subscribe system for real-time messaging.
29
- - **Namespaced Key-Value Dictionaries**: A Pythonic, dictionary-like interface for storing any JSON-serializable object within separate namespaces.
30
- - **Pythonic List Management**: A fluent, Redis-like interface for managing persistent, ordered lists.
35
+ - **Namespaced Key-Value Dictionaries**: A Pythonic, dictionary-like interface for storing any JSON-serializable object within separate namespaces with optional TTL for cache implementations.
36
+ - **Pythonic List Management**: A fluent, Redis-like interface for managing persistent, ordered lists, with all operations in constant time.
31
37
  - **Efficient Vector Storage & Search**: Store vector embeddings and perform fast approximate nearest neighbor searches using an in-memory k-d tree.
32
38
  - **Full-Text Search**: Automatically index and search through document metadata using SQLite's powerful FTS5 engine.
33
39
  - **Graph Traversal**: Create relationships between documents and traverse the graph to find neighbors or perform multi-hop walks.
@@ -174,6 +180,18 @@ listener_thread.join()
174
180
  publisher_thread.join()
175
181
  ```
176
182
 
183
+ ## Roadmap
184
+
185
+ These are some of the features and improvements planned for future releases:
186
+
187
+ - **Fuzzy search**: Implement fuzzy matching capabilities for text search.
188
+ - **Faster ANN**: Explore integrating more advanced ANN libraries like `faiss` for improved vector search performance.
189
+ - **Priority Queues**: Introduce a priority queue data structure for task management.
190
+ - **Improved Pub/Sub**: Fan-out implementation with a more Pythonic API.
191
+ - **Async API**: Comprehensive async support with on-demand wrappers for all collections.
192
+
193
+ Check out the [roadmap](roadmap.md) for a detailed list of upcoming features and design ideas.
194
+
177
195
  ## License
178
196
 
179
197
  This project is licensed under the MIT License.
@@ -0,0 +1,11 @@
1
+ beaver/__init__.py,sha256=-z5Gj6YKMOswpJOOn5Gej8z5i6k3c0Xs00DIYLA-bMI,75
2
+ beaver/channels.py,sha256=2lem2_yEFMc7cjdSx4FbFZQOaeT-HtbSvon3WYYRYzY,1952
3
+ beaver/collections.py,sha256=htlOnjQl8YwjNKkDsK74c805PQQO9Zq2kIhnKxekLds,15064
4
+ beaver/core.py,sha256=K_abD1RiAMT1jYv6T11fpckNljjqcotu3lkLkCz0bHg,6670
5
+ beaver/dicts.py,sha256=y4z632XKWU29ekP_vdFSOP-MAG9Z8b79kBEHA88gO7E,4463
6
+ beaver/lists.py,sha256=jFlDWwyaYycG0ZFVm58rMChefUaVZhaP1UeQ-hVo3Sg,9082
7
+ beaver_db-0.7.0.dist-info/licenses/LICENSE,sha256=1xrIY5JnMk_QDQzsqmVzPIIyCgZAkWCC8kF2Ddo1UT0,1071
8
+ beaver_db-0.7.0.dist-info/METADATA,sha256=MmlUva8ILoEMDdXyoujG1N-iGwMSScFuEx3qqF_vGyU,7196
9
+ beaver_db-0.7.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
+ beaver_db-0.7.0.dist-info/top_level.txt,sha256=FxA4XnX5Qm5VudEXCduFriqi4dQmDWpQ64d7g69VQKI,7
11
+ beaver_db-0.7.0.dist-info/RECORD,,
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Alejandro Piad
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.
@@ -1,10 +0,0 @@
1
- beaver/__init__.py,sha256=-z5Gj6YKMOswpJOOn5Gej8z5i6k3c0Xs00DIYLA-bMI,75
2
- beaver/collections.py,sha256=II26aeXelbtfs0zkcHImvPDtoyDhPCCP8bsosEqoKvw,15064
3
- beaver/core.py,sha256=CDAnIF1InFLb_JxMiO_bWo8coXIemhB68_WBkSTTKzU,6624
4
- beaver/dicts.py,sha256=XgkflJegQAY0YnkxnwWw_LGAeRtGFHzGtuaLAK2GfZg,3558
5
- beaver/lists.py,sha256=JG1JOkaYCUldADUzPJhaNi93w-k3S8mUzcCw574uht4,5915
6
- beaver/subscribers.py,sha256=tCty2iDbeE9IXcPicbxj2CB5gqfLufMB9-nLQwqNBUU,1944
7
- beaver_db-0.6.0.dist-info/METADATA,sha256=TwpfIsOef1GXpRdCpVEaQLVWtK1Ql11M9L7QLpSkphk,6265
8
- beaver_db-0.6.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
- beaver_db-0.6.0.dist-info/top_level.txt,sha256=FxA4XnX5Qm5VudEXCduFriqi4dQmDWpQ64d7g69VQKI,7
10
- beaver_db-0.6.0.dist-info/RECORD,,