0
# Key-Value Storage
1
2
Core database operations for storing, retrieving, and managing key-value pairs in UnQLite. Provides both explicit method calls and Python dictionary-style interface for natural data access patterns.
3
4
## Capabilities
5
6
### Basic Storage Operations
7
8
Store, retrieve, and delete key-value pairs with automatic type handling.
9
10
```python { .api }
11
def store(self, key, value):
12
"""Store key-value pair in database."""
13
...
14
15
def fetch(self, key):
16
"""Retrieve value at given key. Raises KeyError if key not found."""
17
...
18
19
def delete(self, key):
20
"""Delete the value stored at the given key."""
21
...
22
23
def append(self, key, value):
24
"""Append to the value stored in the given key."""
25
...
26
```
27
28
**Usage Example:**
29
30
```python
31
db = UnQLite(':mem:')
32
33
# Store data
34
db.store('user:1', '{"name": "Alice", "age": 30}')
35
db.store('counter', '0')
36
37
# Retrieve data
38
user_data = db.fetch('user:1')
39
print(user_data) # '{"name": "Alice", "age": 30}'
40
41
# Append to existing value
42
db.append('counter', '1')
43
counter_value = db.fetch('counter')
44
print(counter_value) # '01'
45
46
# Delete data
47
db.delete('user:1')
48
```
49
50
### Dictionary-Style Interface
51
52
Python dictionary-like operations for natural data access.
53
54
```python { .api }
55
def __setitem__(self, key, value):
56
"""Store key-value pair using db[key] = value syntax."""
57
...
58
59
def __getitem__(self, key):
60
"""Retrieve value using db[key] syntax. Raises KeyError if not found."""
61
...
62
63
def __delitem__(self, key):
64
"""Delete key using del db[key] syntax."""
65
...
66
67
def __contains__(self, key):
68
"""Check if key exists using 'key in db' syntax."""
69
...
70
```
71
72
**Usage Example:**
73
74
```python
75
db = UnQLite(':mem:')
76
77
# Dictionary-style operations
78
db['name'] = 'UnQLite Database'
79
db['version'] = '1.1.9'
80
db['features'] = ['key-value', 'json', 'transactions']
81
82
# Check existence
83
if 'name' in db:
84
print(f"Database name: {db['name']}")
85
86
# Iterate over all items
87
for key in db:
88
print(f"{key}: {db[key]}")
89
90
# Delete items
91
del db['version']
92
```
93
94
### Existence Checking
95
96
Check if keys exist in the database without retrieving values.
97
98
```python { .api }
99
def exists(self, key):
100
"""Check if key exists in database. Returns boolean."""
101
...
102
```
103
104
**Usage Example:**
105
106
```python
107
db = UnQLite(':mem:')
108
db['test_key'] = 'test_value'
109
110
# Explicit existence check
111
if db.exists('test_key'):
112
print("Key exists")
113
114
# Using 'in' operator (equivalent)
115
if 'test_key' in db:
116
print("Key exists")
117
```
118
119
### Bulk Operations
120
121
Update multiple key-value pairs efficiently.
122
123
```python { .api }
124
def update(self, dict values):
125
"""Update database with multiple key-value pairs from dictionary."""
126
...
127
```
128
129
### Iteration Methods
130
131
Efficiently iterate through database keys, values, or key-value pairs.
132
133
```python { .api }
134
def keys(self):
135
"""Efficiently iterate through the database's keys."""
136
...
137
138
def values(self):
139
"""Efficiently iterate through the database's values."""
140
...
141
142
def items(self):
143
"""Efficiently iterate through the database's key/value pairs."""
144
...
145
146
def range(self, start_key, end_key, include_end_key=True):
147
"""Iterate through a range of keys."""
148
...
149
150
def __len__(self):
151
"""Return the total number of records in the database."""
152
...
153
154
def __iter__(self):
155
"""Return iterator over database keys."""
156
...
157
```
158
159
**Usage Example:**
160
161
```python
162
db = UnQLite(':mem:')
163
164
# Add test data
165
for i in range(5):
166
db[f'key{i:02d}'] = f'value{i}'
167
168
# Iterate over keys
169
print("Keys:")
170
for key in db.keys():
171
print(f" {key}")
172
173
# Iterate over values
174
print("Values:")
175
for value in db.values():
176
print(f" {value}")
177
178
# Iterate over key-value pairs
179
print("Items:")
180
for key, value in db.items():
181
print(f" {key}: {value}")
182
183
# Range iteration
184
print("Range key01 to key03:")
185
for key, value in db.range('key01', 'key03'):
186
print(f" {key}: {value}")
187
188
# Get total count
189
print(f"Total records: {len(db)}")
190
191
# Use iterator protocol
192
print("Using iterator:")
193
for key in db:
194
print(f" {key}: {db[key]}")
195
```
196
197
## Data Encoding
198
199
UnQLite automatically handles encoding between Python strings and bytes. String data is encoded as UTF-8 for storage and decoded back to strings when retrieved. Binary data can be stored as bytes objects.
200
201
```python
202
db = UnQLite(':mem:')
203
204
# Bulk update
205
user_data = {
206
'user:1': '{"name": "Alice", "email": "alice@example.com"}',
207
'user:2': '{"name": "Bob", "email": "bob@example.com"}',
208
'settings': '{"theme": "dark", "notifications": true}'
209
}
210
211
db.update(user_data)
212
213
# Verify data was stored
214
for key in user_data:
215
print(f"{key}: {db[key]}")
216
```
217
218
## Data Encoding
219
220
UnQLite automatically handles encoding between Python strings and bytes. String data is encoded as UTF-8 for storage and decoded back to strings when retrieved. Binary data can be stored as bytes objects.
221
222
```python
223
db = UnQLite(':mem:')
224
225
# String data (automatically encoded/decoded)
226
db['text'] = 'Hello, 世界!'
227
text = db['text'] # Returns string
228
229
# Binary data
230
db['binary'] = b'\x00\x01\x02\x03'
231
binary = db['binary'] # Returns bytes
232
233
# JSON data (stored as strings)
234
import json
235
db['json_data'] = json.dumps({'key': 'value'})
236
data = json.loads(db['json_data'])
237
```
238
239
## Error Handling
240
241
Key-value operations raise standard Python exceptions:
242
243
- `KeyError`: Raised when trying to fetch or delete non-existent keys
244
- `UnQLiteError`: Raised for database-level errors
245
- `MemoryError`: Raised when out of memory
246
- `NotImplementedError`: Raised for unsupported operations
247
248
```python
249
db = UnQLite(':mem:')
250
251
try:
252
value = db['nonexistent_key']
253
except KeyError:
254
print("Key not found")
255
256
try:
257
db.store('key', 'value')
258
except UnQLiteError as e:
259
print(f"Database error: {e}")
260
```