Managing Data in Golang Using Gorm - Part 2
In my previous blog post, we have seen how to use the create and find function in gorm along with use-case driven approach. In this blog post, we will be extending our blogging platform gomidway by implementing an another interesting use case.
Use Case #3 - Publishing a new blog post
Publishing a new blog post use case involves the following
A user can publish a new blog post by providing a title, body of the post and a set of tags.
If the title already exists we need to let the user know about it.
We also need to let him know if publish went well.
Though the requirement looks simple on paper, there are some complexities regarding organizing the code and orchestrating the entire operation.
Let’s dig up and see how we can solve it!
The Database Schema
As a first step, let’s add some new tables to our existing schema which has only the
The first one is the
1 2 3 4 5 6 7
Then we need to have an another table for
1 2 3 4
And finally, a bridge table to associate
1 2 3 4
Note: a blog post can have multiple tags, and a tag can have multiple blog posts associated with it
Model Definitions - Post and Tag
The next step is defining equivalent models for
Tag in golang.
Let’s create a new folder called
tag and define the
1 2 3 4 5 6 7
Then define the
Post model in an another new folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
As we have seen in the previous blog post, the constant
UniqueConstraintTitle and the
TitleDuplicateError are required for doing unique constraint violation error check on the
title column and to communicate it to the application respectively.
The important thing to notice in this model definition is the
1 2 3 4 5
Tags field has a golang struct tag
gorm defining the association type
many2many and the name of the bridge table
Implementing new blog post use case
Now we have all the models required to enable publishing a new blog post, and it’s time to have to go at its implementation.
Let’s start by creating a new folder
post and add the scaffolding for the handler
As we have seen earlier, the folder structure represent the use case, and the handler orchestrate the use case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
The implementation of publishing a new post involves the following steps
For all the
Tagsthat are part of the request, we need to create an entry in the
tagstable. If it is already there, we don’t need to create.
The next step is creating a new entry in the
poststable with the given details.
Finally, we need to associate the
Tagswith the newly created
Postvia the bridge table.
Since it involves multiple inserts on the database side, all the three steps should happen inside a transaction.
The first two steps can be executed in any order as they are independent of each other
Code Organization (aka Responsibility Separation)
We discussed a little bit about code organization in the last blog post. One important thing which can help us, in the long run is having proper separation of concern in the code base.
There are multiple ways we can separate the concern. In our case, we are organizing by use cases with
handler driving the implementation. The handler may access the
data layer if the use case requires.
To keep things simple, we are not discussing dependency injection in
data layer interaction here. I am planning to cover this in my future blog posts.
Back to our business, the data access logic of the three steps will be in their respective packages and the
publish handler coordinate the entire use case logic.
Step 1: Create a Tag if not exists
The first step is creating a tag if it is not there in the database. For the both new tags and the existing tags we need to get its
id from the database to associate it with the
Gorm has a method called FirstOrCreate to help us to implement this step.
1 2 3 4 5 6 7 8 9 10 11 12 13
The FirstOrCreate method populates the
Id field of the tag.
Step 2: Creating a new Post
It is similar to creating a new user that we saw in the last blog post
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Step 3: Associating Tag with Post
The final step is associating the tag with the post in the database. Gorm has a decent support for Associations. The one that we needed from gorm to carry out the current step is its Append method.
Let’s define a
Post model which holds the AssociationTag
1 2 3 4 5 6 7
Then add a new file tag.go in the post folder and implement the third step as below
1 2 3 4 5 6 7 8 9 10 11 12
Publishing New Blog Post
Now we have all the individual database layer functions ready for all the three steps, and it’s time to focus on the implementation of publishing a new blog post.
We already have the scaffolding in place
1 2 3 4 5
As a first step, let’s begin a new transaction using gorm’s Begin method.
1 2 3 4 5 6 7
Then call the
Create function in
post package to create a new blog post
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Then for all the tags in the request, call the
CreateIfNotExists function in
tag package to get its respective Ids and associate it with the newly created post using the
AddTag function in the
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
A thing to note here is we are rolling back the transaction using the RollBack method in case of error.
The final step is committing the transaction and returning the newly created post id as response
1 2 3 4 5 6 7 8
Test Driving Publish New Blog Post
Let’s test drive our implementation from the
main function with some hard coded value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
if we run the program with these hard coded values, we will get the following output
if we rerun the program without changing anything, we will get the bad request error as expected
In this blog post, we have seen how to perform, create operation of a model having many to many relationship using gorm. The source code is available in my GitHub repository.