Go with GORM

In Chapter-9 of our Golang Tutorial, we touched upon ‘Go Database/SQL’. In this chapter, let’s explore ‘Go with GORM’. 
The GORM is fantastic ORM library for Golang, aims to be developer friendly. It is an ORM library for dealing with relational databases. This gorm library is developed on the top of database/sql package.
The overview and feature of ORM are:
  • Full-Featured ORM (almost)
  • Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism)
  • Callbacks (Before/After Create/Save/Update/Delete/Find)
  • Preloading (eager loading)
  • Transactions
  • Composite Primary Key
  • SQL Builder
  • Logger
  • Developer Friendly
To install GORM just use the following command :
go  get “github.com/jinzhu/gorm”
In order to use, just import this package into your project along with the database drivers as you want

Now use the gorm to do the operations on the database.
In order to connect to the database, just use the following syntax.
db, err := gorm.Open(“mysql”, “user:password@/dbname?charset=utf8&parseTime=True&loc=Local”)
NOTE: In order to handle time.Time, you need to use parseTime parameter
Here you have to manually create the database before you connect.
For PostgreSQL, db, err := gorm.Open(“postgres”, “user=gorm dbname=gorm sslmode=disable”)
And remember to close the database when it is not in use using defer defer db.Close()

Creating Models and Tables
Define the models before creating tables and based on the model the table will be created.

Auto Migration
This Auto Migration feature will automatically migrate your schema. It will automatically create the table based on your model. We don’t need to create the table manually.

Now just go and check the ormdemo database, there you will find the table along with the columns.
Note: You need to create the database manually.
The gorm also has given model definition including fields like Id, CreatedAt, UpdatedAt, DeletedAt. If you want to use just embed gorm.Model in your model/struct.

In the gorm.Model the fields
CreatedAt – used to store records created time
UpdatedAt – used to store records updated time
DeletedAt  – used to store records deleted time, It won’t delete the records just set the value of DeletedAt’s field to the current time and you won’t find the record when querying i.e. what we call soft deletion.
If you want to set some SQL parameters to the model fields then you can do like this

Gorm is creating a table with the plural version of the model name like if your model name is UserModel then gorm is creating the tables in its plural version user_models. So in order to avoid this just do db.SingularTable(true).
In gorm, ID field is automatically set to a Primary key field with auto increment property.
CRUD Operations
The query for the SQL using gorm can be specified like this
Create/Insert
In order to create or insert a record, you need to use the Create() function. The save() is also there to that will return the primary key of the inserted record.

Update
In order to update the records in the table using gorm, look into the below sample example.

Delete
In order to delete the record from the table, gorm has provided Delete() as given in below examples

Queries
In order to fetch the records from the database and do some SQL stuffs gorm has given some query functions. We’ll now do a quick discussion on it.

Now just go through the program.

Transaction

Associations
The relationship defines how the structs or models interact with each other. So for this, you need to create/define what kind of relationship at both ends.
One To One Relationship
One to One Relationship specifies how the fields of one models are related with other by specifying one to one mapping. For now, I’ve considered and done one to one mapping between Place and Town struct/model. Here one Town belongs to one Place relational mapping I’ve created.

Note: Here in the example, you need to create the foreign keys manually using AddForeignKey() function because auto-migration of the foreign key is not happening.
One To Many Relationship
In One to Many relationships, models of two classes are related by specifying one to many mapping. Here in the example, I’ve created the mapping like one customer has many contacts.

Many To Many Relationship
User belongs to many languages and ‘user_languages’ will be a join table.

Here, you will find the complete documentation about gorm http://jinzhu.me/gorm/

Related Post

Mindbowser
Mindbowser
MindBowser Info Solutions is a one stop shop for all your IT needs, providing a wide array of software services – offshore, onshore as well as a blend of the two. Our commitment to quality and best development practices allows us to deliver certainty in results with a greater ROI, which is both tangible and measurable. We create value by successfully integrating technology with business and people.

Leave a Comment