Skip to content

Commit b3c0c5e

Browse files
authored
Merge pull request #1 from ByteStorage/api-dev
add db api
2 parents 3ca8c8d + c6e091b commit b3c0c5e

File tree

2 files changed

+218
-26
lines changed

2 files changed

+218
-26
lines changed

FlyDB/db.py

+185-24
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from pprint import pprint
12
from typing import Union
23
import grpc
34
from FlyDB.client_grpc import db_pb2_grpc
@@ -25,7 +26,6 @@ def __init__(self):
2526
# The stub provides methods to call the gRPC service methods defined in db.proto.
2627
self.stub = db_pb2_grpc.GStringServiceStub(self.channel)
2728

28-
2929
def _validate_input(self, value, value_type, param_name):
3030
if not isinstance(value, value_type):
3131
raise TypeError(f"{param_name} must be of type {value_type}")
@@ -35,7 +35,7 @@ def connect_option(self, dir_path: str, data_file_size: int, sync_write: bool):
3535
Connects to the gRPC server with provided options.
3636
3737
Parameters:
38-
dir_path (str): The directory path for the FlyDB2.
38+
dir_path (str): The directory path for the FlyDB.
3939
data_file_size (int): The size of data files.
4040
sync_write (bool): Indicates whether to use synchronous writes.
4141
@@ -60,13 +60,13 @@ def connect_option(self, dir_path: str, data_file_size: int, sync_write: bool):
6060

6161
def set(self, key: str, value: Union[str, int, float, bool, bytes], expire: int):
6262
"""
63-
Sets the key-value pair in the FlyDB2.
63+
Sets the key-value pair in the FlyDB.
6464
6565
Parameters:
6666
key (str): The key to be set.
6767
value (Union[str, int, float, bool, bytes]): The value to be set.
68-
expire (int): The expiration time for the key-value pair in nanoseconds.
69-
When expire is 0, it never expires. Expire is in milliseconds.
68+
expire (int): The expiration time for the key-value pair in milliseconds.
69+
When expire is 0, it never expires.
7070
7171
Returns:
7272
None
@@ -94,9 +94,23 @@ def set(self, key: str, value: Union[str, int, float, bool, bytes], expire: int)
9494
if response.ok:
9595
print("Put data success!")
9696

97+
def _return_type_response(self, response):
98+
if response.HasField("StringValue"):
99+
return response.StringValue
100+
elif response.HasField("Int64Value"):
101+
return response.Int64Value
102+
elif response.HasField("Float64Value"):
103+
return response.Float64Value
104+
elif response.HasField("BoolValue"):
105+
return response.BoolValue
106+
elif response.HasField("BytesValue"):
107+
return response.BytesValue
108+
else:
109+
raise ValueError("Unsupported value type")
110+
97111
def get(self, key):
98112
"""
99-
Retrieves the value associated with the given key from the FlyDB2.
113+
Retrieves the value associated with the given key from the FlyDB.
100114
101115
Parameters:
102116
key (str): The key for which the value needs to be retrieved.
@@ -105,37 +119,26 @@ def get(self, key):
105119
Union[str, int, float, bool, bytes]: The value associated with the given key.
106120
107121
Raises:
108-
KeyError: If the key is not found in the FlyDB2.
109-
TimeoutError: If the key has expired in the FlyDB2.
122+
KeyError: If the key is not found in the FlyDB.
123+
TimeoutError: If the key has expired in the FlyDB.
110124
"""
111125
request = db_pb2.GetRequest()
112126
request.key = key
113127
try:
114128
response = self.stub.Get(request)
115129
# Determine the type of value and return accordingly
116-
if response.HasField("StringValue"):
117-
return response.StringValue
118-
elif response.HasField("Int64Value"):
119-
return response.Int64Value
120-
elif response.HasField("Float64Value"):
121-
return response.Float64Value
122-
elif response.HasField("BoolValue"):
123-
return response.BoolValue
124-
elif response.HasField("BytesValue"):
125-
return response.BytesValue
126-
else:
127-
raise ValueError("Unsupported value type")
130+
return self._return_type_response(response)
128131
except grpc._channel._InactiveRpcError as e:
129132
if "KeyNotFoundError" in str(e):
130-
raise KeyError("key is not found in the FlyDB2")
133+
raise KeyError("key is not found in the FlyDB")
131134
elif "Wrong value" in str(e):
132135
raise TimeoutError("key expired")
133136
else:
134137
raise
135138

136139
def delete(self, key):
137140
"""
138-
Deletes the key-value pair from the FlyDB2.
141+
Deletes the key-value pair from the FlyDB.
139142
140143
Parameters:
141144
key (str): The key to be deleted.
@@ -144,7 +147,7 @@ def delete(self, key):
144147
None
145148
146149
Raises:
147-
KeyError: If the key is not found in the FlyDB2.
150+
KeyError: If the key is not found in the FlyDB.
148151
"""
149152
request = db_pb2.DelRequest()
150153
request.key = key
@@ -154,8 +157,166 @@ def delete(self, key):
154157
print("Delete data success!")
155158
except grpc._channel._InactiveRpcError as e:
156159
if "KeyNotFoundError" in str(e):
157-
raise KeyError("key is not found in the FlyDB2")
160+
raise KeyError("key is not found in the FlyDB")
161+
else:
162+
raise
163+
164+
def type(self, key):
165+
"""
166+
Returns the type of the value associated with the given key.
167+
168+
Parameters:
169+
key (str): The key for which the value type needs to be retrieved.
170+
171+
Returns:
172+
str: The type of the value associated with the given key.
173+
174+
Raises:
175+
KeyError: If the key is not found in the FlyDB.
176+
"""
177+
request = db_pb2.TypeRequest()
178+
request.key = key
179+
try:
180+
response = self.stub.Type(request)
181+
return response.type
182+
except grpc._channel._InactiveRpcError as e:
183+
if "KeyNotFoundError" in str(e):
184+
raise KeyError("key is not found in the FlyDB")
158185
else:
159186
raise
160187

188+
def len(self, key):
189+
"""
190+
Returns the length of the string value associated with the given key.
161191
192+
Parameters:
193+
key (str): The key for which the string length needs to be retrieved.
194+
195+
Returns:
196+
int: The length of the string value associated with the given key.
197+
198+
Raises:
199+
KeyError: If the key is not found in the FlyDB.
200+
TypeError: If the value associated with the given key is not of type string.
201+
"""
202+
request = db_pb2.StrLenRequest()
203+
request.key = key
204+
try:
205+
response = self.stub.StrLen(request)
206+
return response.length
207+
except grpc._channel._InactiveRpcError as e:
208+
if "KeyNotFoundError" in str(e):
209+
raise KeyError("key is not found in the FlyDB")
210+
elif "Wrong value" in str(e):
211+
raise TypeError("value is not of type string")
212+
else:
213+
raise
214+
215+
def get_set(self, key, value, expire):
216+
"""
217+
Sets the value associated with the given key and returns the old value.
218+
219+
Parameters:
220+
key (str): The key for which the value needs to be set.
221+
value (Union[str, int, float, bool, bytes]): The value to be set.
222+
expire (int): The expiration time for the key-value pair in milliseconds.
223+
When expire is 0, it never expires.
224+
225+
Returns:
226+
Union[str, int, float, bool, bytes]: The old value associated with the given key.
227+
228+
Raises:
229+
TypeError: If the value associated with the given key is not of type string.
230+
"""
231+
request = db_pb2.GetSetRequest()
232+
request.key = key
233+
234+
if isinstance(value, str):
235+
request.StringValue = value
236+
elif isinstance(value, int):
237+
request.Int64Value = value
238+
elif isinstance(value, float):
239+
request.Float64Value = value
240+
elif isinstance(value, bool):
241+
request.BoolValue = value
242+
elif isinstance(value, bytes):
243+
request.BytesValue = value
244+
else:
245+
raise TypeError("Unsupported type")
246+
247+
request.expire = expire * 1000000
248+
try:
249+
response = self.stub.GetSet(request)
250+
return self._return_type_response(response)
251+
except grpc._channel._InactiveRpcError as e:
252+
if "Wrong value" in str(e):
253+
raise TypeError("value is not of type string")
254+
else:
255+
raise
256+
257+
def exist(self, key):
258+
"""
259+
Checks if the given key exists in the FlyDB.
260+
261+
Parameters:
262+
key (str): The key to be checked.
263+
264+
Returns:
265+
bool: True if the key exists in the FlyDB, False otherwise.
266+
"""
267+
request = db_pb2.ExistsRequest()
268+
request.key = key
269+
response = self.stub.Exists(request)
270+
return response.exists
271+
272+
def persist(self, key):
273+
"""
274+
Removes the expiration associated with the given key.
275+
276+
Parameters:
277+
key (str): The key for which the expiration needs to be removed.
278+
279+
Returns:
280+
None
281+
282+
Raises:
283+
KeyError: If the key is not found in the FlyDB.
284+
"""
285+
request = db_pb2.PersistRequest()
286+
request.key = key
287+
try:
288+
response = self.stub.Persist(request)
289+
if response.ok:
290+
print("Persist success!")
291+
except grpc._channel._InactiveRpcError as e:
292+
if "KeyNotFoundError" in str(e):
293+
raise KeyError("key is not found in the FlyDB")
294+
else:
295+
raise
296+
297+
def mget(self, keys):
298+
"""
299+
Retrieves the values associated with the given keys from the FlyDB.
300+
301+
Parameters:
302+
keys (list): The list of keys for which the values need to be retrieved.
303+
304+
Returns:
305+
list: The list of values associated with the given keys.
306+
307+
Raises:
308+
KeyError: If any of the keys is not found in the FlyDB.
309+
"""
310+
request = db_pb2.MGetRequest()
311+
request.keys.extend(keys)
312+
try:
313+
response = self.stub.MGet(request)
314+
values = []
315+
for value in response.values:
316+
values.append(value)
317+
return values
318+
except grpc._channel._InactiveRpcError as e:
319+
if "KeyNotFoundError" in str(e):
320+
raise KeyError("key is not found in the FlyDB")
321+
else:
322+
raise

FlyDB/example/simple.py

+33-2
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,50 @@
1+
import time
12
from pathlib import Path
23
from FlyDB import db
34

45
# Create a FlyDB2 client
56
db_client = db.FlyDB()
67

7-
# Connect to the FlyDB2
8+
# Connect to the FlyDB
89
path = Path.cwd().joinpath("data")
910
db_client.connect_option(str(path), 256*1024*1024, True)
1011

1112
# Set a key-value pair
12-
db_client.set("key", "value", 0)
13+
db_client.set("key", "value",0)
1314

1415
# Get the value of a key
1516
value = db_client.get("key")
1617
print(value)
1718

19+
# Get the type of a key
20+
types = db_client.type("key")
21+
print(types)
22+
23+
# Get the length of a value
24+
length = db_client.len("key")
25+
print(length)
26+
27+
# Set the value and return the old value
28+
new_value = db_client.get_set("key", "value22222", 0)
29+
print(new_value)
30+
value = db_client.get("key")
31+
print(value)
32+
33+
# Exist a key
34+
ok = db_client.exist("key")
35+
print(ok)
36+
37+
# Persist expire time
38+
db_client.set("key1", "value1", 2)
39+
db_client.persist("key")
40+
time.sleep(3)
41+
value = db_client.get("key")
42+
print(value)
43+
44+
# mgset
45+
db_client.set("key2", "value2", 0)
46+
v = db_client.mget(["key", "key2"])
47+
print(v)
48+
1849
# Delete a key-value pair
1950
db_client.delete("key")

0 commit comments

Comments
 (0)