In continuing to expand our basic datastore functionality and achieve feature parity with more complex systems, it's time to implement CRUD operations—which stands for Create, Retrieve, Update, and Delete. A simple Python datastore class, BasicDataStore
, maintains these internal states using a dictionary.
create
: This operation takes a unique key and a value. It adds the key-value pair to the store if the key does not exist already.retrieve
: It accepts a key and returns the corresponding value from the store. If the key does not exist, it returns None.update
: This method takes a key and a new value. If the key exists in the store, it updates the value. If the key does not exist, it returns False.delete
: This operation removes a key-value pair from the store given a key. If the key does not exist, it returns False.
We are using IBM's stock price as an example to illustrate these operations. We create a record for IBM with a price, retrieve it, update it, delete the record, and try to retrieve it again which returns None now.
This is a basic implementation of CRUD operations for our datastore. It resembles how more sophisticated datastores handle these functionalities internally mapping them to complex data manipulations.
xxxxxxxxxx
class BasicDataStore:
def __init__(self):
self.store = {}
def create(self, key, value):
if key not in self.store:
self.store[key] = value
return True
return False
def retrieve(self, key):
return self.store.get(key, None)
def update(self, key, value):
if key in self.store:
self.store[key] = value
return True
return False
def delete(self, key):
if key in self.store:
del self.store[key]
return True
return False
​
if __name__ == '__main__':
datastore = BasicDataStore()
print(datastore.create('IBM', 140.63)) # True
print(datastore.retrieve('IBM')) # 140.63
print(datastore.update('IBM', 141.14)) # True
print(datastore.delete('IBM')) # True
print(datastore.retrieve('IBM')) # None