HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Simple in-memory database

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
databasesimplememory

Problem

How can I improve this code (elegance, best practices, etc)?

```
""" Simple in-memory database as a response to the Thumbtack coding challenge. """

class SimpleDb(object):

""" Simple in-memory database as a response to the Thumbtack coding challenge. """

def __init__(self):
""" Initialize SimpleDb instance. """
self.__db = {}
self.__num_equal_to_cache = {}
self.__transactions = [] # Stores previous values to allow rollback

def assign(self, name, value):
""" Sets value of name to value. Inserts name into database if it doesn't already exist. """
current_value = self.get(name)
if current_value == value:
return
self.__update_num_equal_to(current_value, value)
self.__update_current_transaction(name, current_value)
self.__db[name] = value

def get(self, name):
""" Returns value of name if it exists in the database, otherwise returns None. """
return self.__db[name] if name in self.__db else None

def get_num_equal_to(self, value):
""" Returns number of entries in the database that have the specified value. """
return self.__num_equal_to_cache[value] if value in self.__num_equal_to_cache else 0

def unset(self, name):
""" Removes name from database if it's present. """
current_value = self.__db.pop(name, None)
if current_value is None:
return
self.__update_num_equal_to(current_value)
self.__update_current_transaction(name, current_value)

def begin(self):
""" Opens transaction block. """
self.__transactions += [{}]

def rollback(self):
"""
Reverts database to its state before most current transaction.
Returns True on success, returns False if there aren't any open transactions.
"""
if not self.__transactions:
return False
for name, value in self.__transactions.pop().iteritems():

Solution

I find your treatment of transactions odd. I would expect that when a transaction is in progress, data modifications commands get buffered; queries would consult the state stored in the current transaction for any relevant data, then any stacked transactions, then finally consulting the "real" database. Instead, you immediately "auto-commit" each command, and add an entry to the undo list; a commit simply discards the undo list. That's not a realistic model of a database: one would expect that a commit either succeeds atomically or has no effect at all on the database.

Context

StackExchange Code Review Q#41930, answer score: 6

Revisions (0)

No revisions yet.