Open In App

Setting Up Gorm With MySQL

Last Updated : 04 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we’ll set up GORM, an ORM library, with MySQL using the Gin web framework in Go. GORM provides features that make database interactions easier by allowing the use of Go structs instead of raw SQL queries, which helps reduce boilerplate code and keeps the codebase cleaner.

We’ll take a step-by-step approach to establishing a database connection, implementing basic CRUD operations, and managing database migrations. Additionally, we’ll perform a simple query using the Gin API and GORM while maintaining a clear and simple folder structure for easier understanding.

What Is Go ?

Go is a simple and efficient programming language designed for fast performance and concurrency, making it ideal for robust applications. Developed by Google, it emphasizes clean syntax and ease of use, which speeds up development and improves maintainability.

What is Gin ?

Gin is a web framework built on Go's net/http package, offering high speed. Combined with Go's concurrency, it is widely used in efficient cloud-based applications. Understanding Gin's interaction with databases like MySQL is crucial for building web applications efficiently.

Features Provided By Gorm

  • Makes tasks handling easier, such as: CRUD (Create, Read, Update, Delete) operations, associations, transactions, and migrations.
  • GORM manages database connection pooling by default which is a more optimized and scalable approach than a single connection.
  • Share similar functional and database interaction logic to other ORM libraries like Sequelize (for Node.js) or Prisma.

Step-by-Step Guide to Setting Up GORM with MySQL in Gin

1. Setting Up the Gin Module

Initialize Gin using the following command:

go mod init MODULE_NAME
go get -u github.com/gin-gonic/gin

2. Installing GORM and MySQL driver package

Install GORM and MySQL driver package using the following command:

go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql

3. Structuring the Project

  • We will keep the folder structure simple.
  • Database directory to hold the database configurations and table structures
    .
  • We will define a struct named Countries, which will correspond to the countries table in our MySQL database.

mainDirectory

│ go.mod

│ go.sum

│ main.go

└───database

│ dbConfig.go

└───models

countries.go

4. Setting Up main.go

  • Initialize the database by calling the Init function, which is imported from the database package within the project.
  • Initialize the Gin router using the gin.Default() function and define endpoints to handle API requests.
  • Perform database interactions according to the project's requirements. In this case, we will execute two simple operations using GORM: first, adding a row to the countries table, and second, fetching all records from the countries table.
  • In the /add-country API, we will convert the incoming payload into a struct using BindJSON, then use the Create function to insert the entry into the database table, returning the inserted row as the response.
  • In the /get-all-countries API, we will declare an allCountries array to hold models. Countries structs will be used to store all the query results.
  • Make sure to explicitly check for potential errors and send appropriate status responses to enhance the application's readability and maintainability.
  • Run the router using the router.Run() command, which listens on port 8080 by default.

Example structure for main.go:

package main
import (
"net/http"
"github.com/gin-gonic/gin"
"MODULE_NAME/database"
"MODULE_NAME/database/models"
)

func main(){
databaseInstance:= database.InIt()

router:=gin.Default()

router.POST("/add-country", func(c *gin.Context){ // Payload: {"Country":"India", "CountryCode":"+91"}

var newCountry models.Countries

if err := c.BindJSON(&newCountry); err != nil{
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}

if err:= databaseInstance.Create(&newCountry).Error; err!=nil{
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}

c.JSON(200, gin.H{
"success": true,
"message":"Country Added Successfully",
"newCountry":newCountry,
})
})


router.GET("/get-all-countries", func(c *gin.Context){

allCountries:= [] models.Countries{};

if err:= databaseInstance.Find(&allCountries).Error; err!=nil{
c.JSON(http.StatusInternalServerError, gin.H{"success":false, "error":err.Error()})
return
}

c.JSON(http.StatusOK, gin.H{"success":true, "allCountries": allCountries})
})

router.Run(":8080")


5. Setting Up dbConfig.go

  • We will use the os, log, and time packages to log and record any errors to the console, and the strconv package to convert string environment variables to integers, ensuring we maintain the correct data type constraints.
  • The Init() function connects to the database, creates an instance from the connection pool for database interactions, and automatically migrates the database tables based on the structs, specifically &models.Countries{}.
  • The connectionDatabase() function establishes a connection to the database and configures the connection pool settings using credentials retrieved from environment variables.
  • The performMigration() function migrates the struct and synchronizes it with the database table to address any configuration mismatches.
  • The getEnv() function retrieves environment variables and returns a default value if the specified key is not found.

Example dbConfig.go:

package database

import (
"fmt"
"os"
"log"
"time"
"strconv"

"gorm.io/gorm"
"gorm.io/driver/mysql"
"gorm.io/gorm/logger"
"MODULE_NAME/database/models"
)

var databaseInstance *gorm.DB

func InIt() *gorm.DB{

var err error
databaseInstance, err = connectionDatabase()
if err!=nil{
log.Fatalf("Could not connect to the database: %v", err)
}

err = performMigration()
if err!=nil{
log.Fatalf("Could not auto migrate: %v", err)
}

return databaseInstance

}

func connectionDatabase() (*gorm.DB, error){

dbUsername := getEnv("DB_USERNAME", "root")
dbPassword := getEnv("DB_PASSWORD", "")
dbName := getEnv("DB_NAME", "gorm")
dbHost := getEnv("DB_HOST", "localhost")
dbPort := getEnv("DB_PORT", "3306")

connectionString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true&loc=Local", dbUsername, dbPassword, dbHost, dbPort, dbName)

databaseConnection, err := gorm.Open(mysql.Open(connectionString), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info), // Enable logging for debugging
})

if err!=nil{
return nil, err
}

sqlDatabase, err :=databaseConnection.DB()
if err!=nil{
return nil,err
}

// Connection pool settings from environment variables
maxIdleConns, _ := strconv.Atoi(getEnv("DB_MAX_IDLE_CONNS", "10"))
maxOpenConns, _ := strconv.Atoi(getEnv("DB_MAX_OPEN_CONNS", "25"))
connMaxLifetime, _ := strconv.Atoi(getEnv("DB_CONN_MAX_LIFETIME", "3600")) // in seconds

sqlDatabase.SetMaxIdleConns(maxIdleConns)
sqlDatabase.SetMaxOpenConns(maxOpenConns)
sqlDatabase.SetConnMaxLifetime(time.Duration(connMaxLifetime) * time.Second)

return databaseConnection, nil
}

func performMigration() error{
err:= databaseInstance.AutoMigrate(&models.Countries{})
if err!=nil{
return err
}
return nil
}

func getEnv(key string, defaultVaule string) string {
value:= os.Getenv(key)
if value==""{
return defaultVaule
}
return value
}

6. Setting Up countries.go

  • The countries.go file will define the schema for the corresponding countries table in the database. The Id field is a uint, which corresponds to the id field in the database, constrained as a primary key that auto-generates its value.
  • Country attribute is a string (VARCHAR) with a NOT NULL constraint, and the CountryCode is also a string that cannot be null.

Example countries.go:

package models

type Countries struct {
Id uint `json:"id" gorm:"primarykey;autoIncrement"`
Country *string `json:"country" gorm:"not null"`
CountryCode *string `json:"countryCode" gorm:"not null"`
}

7. Starting the Application

Start the application using the following command

go run main.go

Conclusion

In conclusion, while GORM may not achieve the raw speed of direct SQL queries due to the inherent overhead of its abstraction layer, it offers substantial advantages in terms of code readability and maintainability. By utilizing Go structs instead of raw SQL statements, GORM streamlines the coding process and makes it more intuitive.

This framework simplifies complex operations such as handling associations and transactions while significantly reducing boilerplate code, allowing for a greater focus on implementing business logic rather than managing repetitive database tasks.


Next Article
Article Tags :

Similar Reads