Building a very simple ORM

Posted by Jonas Sandström on Mon 05 September 2022

I've stumbled across two great resources for building simple ORMs in Python. With simple I mean "As simple as it can get" and therefore far from something you would like to put into production in a business critical system... But as always great for learning and understanding how ORMs (like sqlalchemy or the Django ORM) works, and most importantly it's fun to write!

The resources

"Let's Build an ORM" - Greg Backc Youtube
Second part of a paid course on testdriven.io by Jahongir Rahmonov.

What is an ORM anyway?

The short answer is: an object oriented programming model that helps to bridge the gap between your classes and your database. Longer and more precise answers can be found all over the internet ;)

Instead of me writing about how to do this I just recommend you to watch the video. If that sparked your interest (as it did for me!) you can take a look at my implementation of a simple Postgres ORM on my github.

Here is my example file

from psql_orm import Database, Column, Table, ForeignKey

db = Database(
    database="test_database",
    user="postgres",
    password="1234",
    host="localhost",
    port="5432",
)

#  Create tables
class School(Table):
    country = Column(str)
    name = Column(str)


class Student(Table):
    name = Column(str)
    school = ForeignKey(School)


db.create(School)
db.create(Student)

# Save school
school = School(name="Hogwarts", country="England")
db.save(school)

# Save students
harry = Student(name="Harry Potter", school=school)
ron = Student(name="Ron Weasley", school=school)
db.save([harry, ron])

# Make queries
all_students = db.all(Student)
harrys_school = db.query(Student, name="Harry Potter")[0].school
hogwarts = db.query(School, country="Eng%")[0]  # use % for wildcard search.
print(harrys_school.country, hogwarts.country)
assert harrys_school.country == hogwarts.country