Sqlite Integrated / The Idea

Sqlite Integrated - The Idea

I have this past month been developing my first python package! Its called sqlite-integrated in the pypi. Its purpose is to simplify editing sqlite3 databases. Originally is was my intention to represent a database entry simply as a python dictionary. Like this:

entry = {"id": 3, "Name": "Tom", "Age": 23}

This is nice because it makes it possible to use familiar python dictionary syntax to change the entry. We could for example alter the name like this:

entry["Name"] = "Tim"

The problem with this otherwise simple solution appears when we want to override the entry in the database with this new data. The entry variable only contains the data for the entry, and does not know what table it is a part of. Therefore, this implementation requires that we specify the table we are updating, when we update an entry.

# db is a Database object
db.add_entry(entry, "table_name")

On the surface, this may not seem too bad, but the problem is that the entry and the table are not independent. The entry fields are actually defined by the table, as you can not add an entry to a table, if their fields do not match. This means that the one entry will have the same corresponding table in almost all cases. Because of this, the entry should probably keep track of where it came from by itself, to relieve the programmer. It is because of this sqlite-integrated uses the DatabaseEntry class for storing table entries.

Notice that this class is an extension of the built in dict type. This makes sure that we can still edit the entry like a python dictionary.

class DatabaseEntry(dict):
    def __init__(self, entry_dict: dict, table: str):
        self.table = table
        self.update(entry_dict)

The class includes a second constructor and a __repr__, but apart from that, this is it. This simple change made it a lot nicer to edit an entry.

Now we can simply do this:

# Get the 4th person in the table "people". This returns a DatabaseEntry.
entry = db.get_entry_by_id("people", 4)

# Edit the data
entry['Name'] = "Newname"
entry['Age'] += 1

# Updating the database
db.update_entry(entry)

Isn’t that nice!