Total Database Control in Go with Gorm
Check out the video for some more elaboration on the topics below.
This was originally posted on my blog.
If you liked it and want to know when I post more videos, be sure to subscribe
Time to start looking at some ORMs for go, today we’re gonna start with gorm. Gorm is a code first ORM, meaning we can use go code to define our database scheme, run the migrations, and also interact with the database with the same code.
Connect to the Database
In order to connect to a database using gorm, we simply use the following:
We are opening a sqlite3 file, because I didn’t want to fiddle with something like MySQL for this.
We handle an error if one occurred, and defer a call to db.Close() to ensure the connection is cleaned up afterwards
Defining Schema with Structs
We have the following structs:
Each of these structs will have a corresponding table in our database, with the same columns as the structs have properties.
The gorm.Model
struct has some standard properties commonly used in SQL database, check out the docs to see more about it.
You’ll notice the Message struct has properties that reference other structs. These are used to map the table relations, read more about how gorm does relationship mapping here.
Migrations
The easiest way to sync up our schema to our structs it to use the AutoMigration
method defined on the db instance:
We pass in an instance of each struct and gorm does some reflection under the hood to make any schema changes, generate the queries, and run them.
Keep in mind, AutoMigrate
will only add missing tables, columns, and indexes. It will not remove unused ones, read why here.
Adding Data
To create a new row in our database, we simply create in instance of one of our structs, set the values on its properties, and pass it to the Create
method on our database connection:
Tada, data has been inserted into our table!
Finding Data
If you want to grab something from the database, the docs has alot of examples but some notable ones are as follows:
You can also build where clauses using the Where
method:
Error Handling
Gorm handles errors in a way that is a little different than idiomatic go.
After you run a gorm query, it will set a value to the Error
variable in the gorm package, if an error occurred while running the query.
Here is an example of checking if the method ended up returning an error:
Summary
Gorm makes it fairly easy to manage your database schema and acts as an abstraction over your database backend.
Thank you for reading