GORM: Managing Audit Fields

Sumit Agarwal
2 min readAug 15, 2020

--

Image Source: Google

GORM is the ORM library for Golang, built and maintained by Jinzhu. Since you have stumbled upon this article I would safely assume that you have been coding using GoLang for a while now and are a GORM user already.

I have been working with gorm for a while now and recently had a use case where I wanted to update the audit columns (who, when fields) without exclusively defining it for all the DB calls. Essentially what I was looking for is a way to handle the setting of audit for my queries behind the scenes without me writing the boilerplate code every time. However, I struggled with it due to the lack of easy documentation around the same. Also, coming from a Spring JPA background I was expecting this to be quite simple, but as with other GoLang libraries, gorm is not very mature on this front and I ended up going through the library code to make it work.

To set some context around what exactly audit fields mean is, your table has four default columns, namely createdAt, createdBy, updatedAt & updatedBy which need to be upserted based on various DML queries.

Updating the WHO fields (createdBy & UpdatedBy)

I was able to find that gorm supported defining custom callbacks, but this wasn’t documented properly. On googling around in order to figure out how exactly to configure the callbacks, I found this GitHub repo qor/audited which explained how the callbacks worked in gorm and how the same can be used in this particular use case. Although the repo is quite old, it does the intended job well. Kudos to the qor team.

Updating the WHEN fields (createdAt & UpdatedAt)

GORM provides default support for maintaining the time-related audit fields out of the box, given you follow the naming convention here on the fields. The go struct of the gorm model should look something like this:

type MyTable struct {
gorm.Model

// table fields
CreatedAt *time.Time
UpdatedAt *time.Time
}

In order to capture the whole idea into one, I have prepared a small git repo named gorm-plugins and have added the sample code here. Hope this helps.

Happy Coding!

--

--

Sumit Agarwal
Sumit Agarwal

Written by Sumit Agarwal

I am a software developer at heart who likes to travel and has a profound interest in design, art, and literature.

No responses yet