DEV Community

Cover image for Write A Simple Toy Database in Python within Minutes!
Palash Bauri 👻
Palash Bauri 👻

Posted on • Edited on • Originally published at dev.palashbauri.in

Write A Simple Toy Database in Python within Minutes!

MySQL, PostgreSQL, Oracle, Redis... and many more you just name it... Databases are really an important piece of technology in the progress of human civilization. Today we can see how valuable Data is and so as keeping them safe and stable, this is where the database comes!

We can see how important databases are. For a quite some time I was thinking of creating My Own Toy Database just to understand, play and experiment with it as Richard Feynman said

What I cannot create, I do not understand

So Without any further talking let's jump into the fun part... Coding...

For this Toy Database, We'll use Python (My Favourite ❤️), I named this database FooBarDB (I couldn't find any name ;)), but you can call it whatever you want!

So first let's import some necessary python libraries which are already available in Python Standard Library

import json
import os
Enter fullscreen mode Exit fullscreen mode

Yes, We only need this two libs! json as our database will be based on json and os for some path related stuff!

Now Let's define the main class FoobarDB with some pretty basic function which I'll explain them below.

class FoobarDB(object):
    def __init__(self , location):
        self.location = os.path.expanduser(location)
        self.load(self.location)

    def load(self , location):
        if os.path.exists(location):
            self._load()
        else:
            self.db = {}
        return True

    def _load(self):
        self.db = json.load(open(self.location , "r"))

    def dumpdb(self):
        try:
            json.dump(self.db , open(self.location, "w+"))
            return True
        except:
            return False

Enter fullscreen mode Exit fullscreen mode

Here we defined our main class with a __init__ function, whenever creating a Foobar Database we only need to pass the location of the database.
In the first __init__ function we take the location parameter and replace ~ or ~user with users home directory to make it work intended way, and finally put it in self.location variable to access it later on the same class functions. At the end, we are calling the load function passing self.location as an argument.

. . . .
    def load(self , location):
        if os.path.exists(location):
            self._load()
        else:
            self.db = {}
        return True
. . . .

Enter fullscreen mode Exit fullscreen mode

In the next load function we take the location of the database as param, then check if the database exists or not, if it exists, we simply load it with _load() function (explained below) otherwise we create an empty in-memory JSON object. And Finally, return true on success.

. . . . 

    def _load(self):
        self.db = json.load(open(self.location , "r"))
. . . . 

Enter fullscreen mode Exit fullscreen mode

In _load function we just simply open the database file from the location stored in self.location then transform it into JSON object and loads it into self.db variable.

. . . .
    def dumpdb(self):
        try:
            json.dump(self.db , open(self.location, "w+"))
            return True
        except:
            return False

. . . .
Enter fullscreen mode Exit fullscreen mode

And Finally the dumpdb function, its name says what it does, it basically just take the in-memory database (actually a JSON object) from self.db variable and saves it in the database file! It returns True if saved successfully otherwise returns False

But, Wait a Minute! 😐 A Database is useless if it can't store and retrieve data, isn't it? 😉 Let's Go and add them also...😎

. . . .
    def set(self , key , value):
        try:
            self.db[str(key)] = value
            self.dumpdb()
            return True
        except Exception as e:
            print("[X] Error Saving Values to Database : " + str(e))
            return False

    def get(self , key):
        try:
            return self.db[key]
        except KeyError:
            print("No Value Can Be Found for " + str(key))  
            return False

    def delete(self , key):
        if not key in self.db:
            return False
        del self.db[key]
        self.dumpdb()
        return True
. . . . 

Enter fullscreen mode Exit fullscreen mode

The set function is to add data to the database, as our database is a simple key-value based database we'll only take a key and value as an argument. First, we'll try to add the key and value to the database them save the database, if everything goes right it will return True other it will print an error message and return False (We don't want it to crash and erase our data everytime an error occurs 😎).

. . . .
    def get(self, key):
        try:
            return self.db[key]
        except KeyError:
            return False
. . . .
Enter fullscreen mode Exit fullscreen mode

get is a simple function, we take key as an argument and try to return the value linked to the key from database other False is returned with a message.

. . . .
    def delete(self , key):
        if not key in self.db:
            return False
        del self.db[key]
        self.dumpdb()
        return True

. . . .
Enter fullscreen mode Exit fullscreen mode

delete function is to delete a key as well its value from the database. First we make sure the key is present in the database, if not we return False, Otherwise, we delete the key with the built-in del which automatically deletes the value of the key. Next, we save the database and returns false.

Now you might think what if I've created a large database and wants to reset it? In theory, we can use delete but it's not practical and also very time-consuming! ⏳⏳
So we can create a function to do this task...

. . . . 

    def resetdb(self):
        self.db={}
        self.dumpdb()
        return True
. . . .
Enter fullscreen mode Exit fullscreen mode

Here's the function to reset the database, resetdb! It's so simple, First we do is re-assign our in-memory database with an empty JSON object and just saves it! And that's it! Our Database is now again clean shaved!

Full Source is Here 👉 bauripalash/foobardb


That's it friends! We have created our own Toy Database !! 🎉🎉
Actually FoobarDB is just a simple demo of a database, it's like a cheap DIY toy, you can improve it any way you want! You can also add many other functions according to your needs!

I hope, You Enjoyed! Let Me Know Your Suggestions, Ideas or Mistakes I've made in the comments below! 👇

Follow/Ping Me On Socials 👉 Facebook , Twitter , Instagram

Thank You! See You Soon!


If You Like My Work (My Articles, Stories, Softwares, Researches and many more) Consider Buying Me A Coffee ☕ 🤗

Top comments (3)

Collapse
 
abdurrahmaanj profile image
Abdur-Rahmaan Janhangeer

actually not so much a toy as anti-malware tools use json storage, Avast for exmample.

Collapse
 
hchenni profile image
Hchenni

thank you that s usefull to me

Collapse
 
bauripalash profile image
Palash Bauri 👻

My pleasure