Golang has been gaining popularity since its inception. It is a simple language with performance as good as a low-level language like C++. Acceptance of Golang in web development is booming at a high rate.
I started my web-development journey with Ruby on Rails. I fell in love with Active Record. I was amazed to see an ORM that was so simple to use. It handles database migrations wonderfully by making them part of your code.
Truly speaking, Rails and Active Record made me lazy. Active Record and its DB migrations were so easy to use that I stopped writing SQL Queries directly.
To create a table you create a new migration that looks like this:
It is easy enough to alter the table by writing a similar migration.
Apart from migrations, Active Record has the most simple models to interact with the database. You don’t have to specify each and every column in the model, it takes the column names from the table.
There are many ORM libraries for Go like — gorm, xorm, sqlboiler, reform, and many more. GORM is the most popular ORM for Go. It has a lot of similarities with Active Record.
Unlike Active Record, you specify a structure in the model that defines the table. e.g. blogs table can be specified like this —
Just specifying a struct does not make changes in the database. You need to explicitly call AutoMigrate method for each model to run DB migrations.
What happens when you change the struct?
There are ways to handle scenarios like —
For more details please check this documentation.
There is no right or wrong way to do this. Developers have their preferences and skills that help them make such decisions.
Though data migration features of GORM are capable to handle any scenario, there is a learning curve. And if you are using auto migration you need to be aware of how it works.
Due to these reasons, I prefer to write SQL statements to manage DB schema. I know this is old school, but I find it easy.
In one of the projects, which is an offspring of a Rails project I use Active Record migrations to maintain the DB schema of the Golang project as well.