Getting Started on Golang Gorm

Kenzy Limon
4 min readAug 14, 2022

--

GORM is a great ORM library for Go developers. with incredible feature lists and speed, it is considered the standard GO ORM.

Apart from being an excellent ORM for Go developers, its built to be developer-friendly and easy to comprehend. Gorm is built on top of the database/sql packages.

overview and features of the ORM are:

  • Developer Friendly
  • Every feature comes with a tests
  • Hooks / Callbacks (Before/After Create/Save/Update/Delete/Find)
  • Eager loading with Preload, Joins
  • Context, Prepared Statement Mode, DryRun Mode
  • SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, Named Argument, SubQuery
  • Transactions, Nested Transactions, Save Point, Rollback To to Saved Point
  • Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism)
  • SQL Builder
  • Logger

To install GORM run the following command :

go get -u gorm.io/gorm

Database Setup and Connection

GORM officially supports most databases with easy setup.

  1. PostgreSQL
  2. MySQL
  3. SQLite
  4. SQL Server

To get started import your desired database package into your project along with the database drivers.

PostgreSQL Setup

By default GORM uses pgx as postgres database/SQL driver, it also allows prepared statement cache.

MySQL Setup

SQLite Setup

SQL Server Setup

Declaring Data Models

GORM allows normal structs as models with basic Go types, pointers/alias, or custom types implementing Scanner and Valuer interfaces. GORM allows you to Define the models before creating tables and the table will be created based on the model, it pluralize the struct name to snake_cases as table name, snake_case as column name, and uses CreatedAt, UpdatedAt to track creating/updating time.

For Example:

GORM prefers convention over configuration, by default, GORM uses ID as the primary key. Primary key can be both numbers or strings depending on the developers choice.

Hooks & Object Life Cycle

Hooks are functions that are called before or after creation/querying /updating/deletion action on the database thus allowing developers to define specified methods for each model.

The type of hook methods should be func(*gorm.DB) error

NOTE GORM runs transactions by default whenSave/Delete operations are performed , so changes made in that transaction are not visible until it is committed, if you return any error in your hooks, the change will be rollbacked

Auto Migration

AutoMigrate will create tables, missing foreign keys, constraints, columns, and indexes. It will change the existing column’s type size, and precision. It WON’T delete unused columns to protect your data.

db.AutoMigrate(&User{})db.AutoMigrate(&User{}, &Product{}, &Order{})// You can add table suffix when creating tables
db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})

GORM provides a migrator interface, which contains unified API interfaces for each database that could be used to build your database-independent migrations, for example:

SQLite doesn’t support ALTER COLUMN, DROP COLUMN, GORM will create a new table as the one you are trying to change, copy all data, drop the old table, rename the new table

NOTE MySQL doesn’t support renaming columns, indexes for some versions, GORM will perform different SQL based on the MySQL version you are using

CRUD Operations

create ( Create record/records )

Create a record and assign a value to the fields specified.

To efficiently insert a large number of records, pass a slice to the Create method. GORM will generate a single SQL statement to insert all the data and backfill primary key values, hook methods will be invoked too.

NOTE When creating from a map, hooks won’t be invoked, associations won’t be saved and primary key values won’t be backfilled.

querying ( Get record/records)

GORM provides First, Take, Last methods to retrieve a single object from the database, it adds LIMIT 1 condition when querying the database, and it will return the error ErrRecordNotFound if no record is found.

Objects can be retrieved using the primary key by using Inline Conditions if the primary key is a number. When working with strings, extra care needs to be taken to avoid SQL Injection; check out the Security section for details.

updating ( update record/records )

Save will save all fields when performing the Updating SQL

When updating a single column with Update, it needs to have any conditions or it will raise an error ErrMissingWhereClause, checkout Block Global Updates for details When using the Model method and its value have a primary value, the primary key will be used to build the condition, for example:

Updates supports update with struct or map[string]interface{}, when updating with struct it will only update non-zero fields by default

If you want to update selected fields or ignore some fields when updating, you can use Select, Omit

Delete ( Deletion of record/records )

When deleting a record, the deleted value needs to have a primary key or it will trigger a Batch Delete, for example:

// Email's ID is `10`
db.Delete(&email)
// This will output: DELETE from emails where id = 10;
// Delete with additional conditions
db.Where("name = ?", "jinzhu").Delete(&email)
// This will output: DELETE from emails where id = 10 AND name = "jinzhu";

GORM allows to delete objects using the primary key(s) with the inline conditions, it works with numbers, check out Query Inline Conditions for details

// Delete with primary keydb.Delete(&User{}, 10)
// This will output: DELETE FROM users WHERE id = 10;
db.Delete(&User{}, "10")
// This will output: DELETE FROM users WHERE id = 10;
db.Delete(&users, []int{1,2,3})
// This will output: DELETE FROM users WHERE id IN (1,2,3);

Conclusion

We have only covered most of the features, you can find the complete documentation about GORM at http://jinzhu.me/gorm/ and really get in-depth knowledge of how cool GORM is.

GORM Community as of Mid 2022.

Want to keep in touch online? Medium | Twitter | Instagram | Behance

--

--