I'm about to do a few videos on some Go ORM packages and thought it wouldn't hurt to do a dedicated segment on just talking about what ORMs are and why you should or shouldn't use them.
What does ORM(Object relational mapping) stand for?
ORM stands for Object Relation Mapping. Typically, this means communicating with a system using a language other than the native language is expecting.
An example of this would be a SQL database. A SQL database is expecting, well, a SQL query to interact with it, but what if we wanted to interact with it with something like a Golang program?
What does a really ORM do? An ORM library gives us the mechanism by which to perform Object Relation Mapping. This means we end up with structs or classes that represent something like a table in our database.
In Go, we would get something like this
user := models.Users().ByID(1)
Which would generate the following SQL query:
SELECT * FROM Users WHERE id = 1;
Pros & Cons of ORMs
Pros of ORM:
Much less time spent interacting with a database in your program Abstracts away the database being used, which makes it easier to swap to another backend If you have weak SQL skills, the generated queries are at least as good as if you wrote them, if not more performant.
Cons of ORM:
If you need a very highly optimized query and can write the said query, it may perform better than the generated ones. There is some amount of mental overhead related to learning an ORM library Most ORMs require some amount of configuration It may not help you develop stronger database and/or SQL skills.
What kinds of ORM libraries exist?
From my experience, there are two primary types of ORM libraries
A code-first ORM uses the code written or generated by the user to generate the database schema and applies the schema to the database.
Some examples of code first ORMs:
Gorm (Go) Basically every ORM in most used frameworks Eloquent (Laravel) ActiveRecord (RoR) Whatever Django uses
A schema first ORM reads the already defined schema from the database and generates from it, all the code necessary to interact with the database.
Some examples of schema first ORMs:
When to choose which?
- Most ORM libraries in my experience are code first, so a lot of choices
- These tend to do a lot, some code generation, acts as abstraction, and manages migrations (schema changes)
Schema First ORM
- Need to get up and running quickly with an existing database (legacy data)
- Almost ALL the code will be generated, vs just some being boilerplate like most code first ORMs I've used
- You prefer a more UNIX approach, as most schema first ORMs I've seen don't handle migrations. You'll need to use a separate tool or library to manage migrations.
Did you find this article valuable?
Support Braincuber Technologies by becoming a sponsor. Any amount is appreciated!