Transactions play an integral role in ensuring consistent and atomic operations in any datastore system. But what do we mean by consistent and atomic? Let's take a detour into the world of finance to understand better.
Here, consistency means that a transaction brings your system from one valid state to another, maintaining the 'rules' of your system. For instance, in a banking app, consistency ensures that the total amount of money in the system remains the same before and after any transaction, despite money shifting between accounts. Atomicity, on the other hand, ensures that if a transaction is a series of operations, either all of them are performed, or none are—much like an atomic bomb: all or nothing.
In the case of our custom datastore, a transaction might involve the create
, update
, and delete
operations we implemented earlier. To ensure atomicity, we need to ensure that if an error occurs during a transaction (like attempting to update a nonexistent entry), the datastore reverts any changes made during the transaction, or in other words, 'rolls back' to its state at the start of the transaction. To achieve this, we keep track of all changes made during the transaction, in case a rollback is needed.
Now, let's write a python script simulating a simple transactional operation in a finance application, where multiple operations must be executed atomically and consistently. This will give us a basic understanding of how these principles can be implemented in real-world apps.
xxxxxxxxxx
print(f'A1 balance: {a1.balance}, A2 balance: {a2.balance}')
class Account:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
return True
return False
def withdraw(self, amount):
if amount > 0 and self.balance >= amount:
self.balance -= amount
return True
return False
if __name__ == '__main__':
# Create accounts
a1 = Account('A1', 500)
a2 = Account('A2', 300)
# Start Transaction
if a1.withdraw(200) and a2.deposit(200):
print('Transaction Successful')
else:
print('Transaction Failed - Rolling back')
# Code to roll back the changes