Setting Up Gorm With MySQL
Last Updated :
04 Nov, 2024
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.
Similar Reads
How to Use Go with MySQL? MySQL is an open-source relational database management system based on Structured Query Language(SQL). It is a relational database that organizes data into one or more tables in which data are related to each other. Database Driver: A Database Driver implements a protocol for a database connection.
4 min read
Setting up Google Cloud SQL with Flask Setting up a database can be very tricky, yet some pretty simple and scalable solutions are available and one such solution is Google Cloud SQL. Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, and administer your relational PostgreSQL and MySQL databases in the
6 min read
MySQL Security MySQL is one crucial database system that aids in talking to and managing the storage of data for innumerable websites and applications. By that, the way you lock your front door to protect the house, the same way you secure your MySQL Database in the hope that in case your data is hacked, only conc
5 min read
Implementing Pagination in MySQL Queries with Go Pagination is an important method in web applications and APIs in the task of working with extensive data. Pagination reveals data in reasonable portions instead of a complete set because the later consumes time, slows website functionality, and may present numerous records to the user. This makes t
6 min read
MySQL USE Statement MySQL is a very flexible and user-friendly Database. The USE command is used when there are multiple databases and we need to SELECT or USE one among them. We can also change to another database with this statement. Thus, the USE statement selects a specific database and then performs queries and op
4 min read
MySQL CREATE USER Statement The CREATE USER statement in MySQL is an essential command used to create new user accounts for database access. It enables database administrators to define which users can connect to the MySQL database server and specify their login credentials.In this article, We will learn about MySQL CREATE USE
4 min read
npm mysql Command npm MySQL integrates MySQL, a popular open-source relational database, with Node.js applications using Node Package Manager (npm). MySQL is widely used to manage structured data. When combined with Node.js, it allows developers to build dynamic, scalable, and powerful web applications that interact
8 min read
Best Practices For MySQL Security Securing your MySQL database is essential to protect your data and ensure your applications run smoothly. With increasing cyber threats, it's important to follow best practices to keep your database safe. This article will provides simple, effective steps to secure your MySQL database, helping you p
5 min read
How to make a connection with MySQL server using PHP ? MySQL is a widely used database management system that may be used to power a wide range of projects. One of its main selling features is its capacity to manage large amounts of data without breaking a sweat. There are two approaches that can be used to connect MySQL and PHP code, which are mentione
3 min read
How to Use Go With MongoDB? MongoDB is an open-source NoSQL database. It is a document-oriented database that uses a JSON-like structure called BSON to store documents like key-value pairs. MongoDB provides the concept of collection to group documents. In this article, we will learn about How to Use Go With MongoDB by understa
15+ min read