Seeding data is a crucial step in application development, especially when you need dummy or initial data for testing or bootstrapping a database. In this tutorial, you’ll learn how to create a data seeder using Go and GORM with a MySQL database.


Prerequisites

  1. Go Installed: Ensure Go is installed on your system.
  2. MySQL Installed: A running MySQL server and a database.
  3. Basic Knowledge of GORM: Familiarity with Go and GORM.

Step 1: Set Up Your Go Project

  1. Initialize the Go Module: mkdir gorm-seeder cd gorm-seeder go mod init gorm-seeder
  2. Install Required Packages: go get -u gorm.io/gorm go get -u gorm.io/driver/mysql

Step 2: Configure the Database Connection

Create a file database.go for database configuration:

package database

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

var DB *gorm.DB

func ConnectDB() {
	dsn := "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("Failed to connect to the database: ", err)
	}
	log.Println("Database connected successfully!")
}

Replace user, password, and dbname with your MySQL credentials and database name.


Step 3: Define Your Models

Define a model file models/user.go:

package models

import "gorm.io/gorm"

type User struct {
	gorm.Model
	Name  string `gorm:"type:varchar(100)"`
	Email string `gorm:"uniqueIndex"`
	Age   int
}

Step 4: Create Seeder Logic

Create a seeder file seeder/seeder.go:

package seeder

import (
	"gorm-seeder/models"
	"log"

	"gorm.io/gorm"
)

func SeedUsers(db *gorm.DB) {
	users := []models.User{
		{Name: "Alice", Email: "alice@example.com", Age: 25},
		{Name: "Bob", Email: "bob@example.com", Age: 30},
		{Name: "Charlie", Email: "charlie@example.com", Age: 22},
	}

	for _, user := range users {
		if err := db.Create(&user).Error; err != nil {
			log.Printf("Failed to seed user %s: %v\n", user.Name, err)
		}
	}
	log.Println("Users table seeded successfully!")
}

Step 5: Integrate Seeder with Main Function

In the main.go file:

package main

import (
	"gorm-seeder/database"
	"gorm-seeder/models"
	"gorm-seeder/seeder"
)

func main() {
	// Connect to the database
	database.ConnectDB()

	// Migrate the schema
	database.DB.AutoMigrate(&models.User{})

	// Run seeders
	seeder.SeedUsers(database.DB)
}

Step 6: Run the Application

Run the application to seed the data:

go run main.go

Check your MySQL database. You should see the users table populated with the seeded data.


Additional Tips

  1. Seed Multiple Tables: Add more seeder functions for other models.
  2. Avoid Duplicate Data: Check for existing data before inserting.
  3. Use CLI for Seeding: Create CLI commands for better control over which seeders to run.

Conclusion

By following this tutorial, you now have a basic data seeder setup using Go and GORM for a MySQL database. This setup can be expanded as your application grows, making it a handy tool for database initialization and testing.