Last active
September 3, 2023 14:26
-
-
Save goodylili/798829c0975a150af66a36a1cfdc8714 to your computer and use it in GitHub Desktop.
A program that generates X no of rows of fake data for database insertion/operation (just modify the struct)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/brianvoe/gofakeit/v6" | |
"gorm.io/driver/postgres" | |
"gorm.io/gorm" | |
"log" | |
"time" | |
) | |
type Human struct { | |
Name string | |
Age int | |
Height float64 | |
Username string | |
DOB string | |
Email string | |
} | |
func NewConnection() (*gorm.DB, error) { | |
dsn := "your connection string" | |
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) | |
if err != nil { | |
return db, err | |
} | |
err = db.AutoMigrate(&Human{}) | |
if err != nil { | |
return db, err | |
} | |
return db, nil | |
} | |
func GenerateFakeData(db *gorm.DB, numRows int) error { | |
gofakeit.Seed(time.Now().UnixNano()) | |
for i := 0; i < numRows; { | |
var human Human | |
// Generate unique values | |
human.Name = gofakeit.Name() | |
human.Age = gofakeit.Number(18, 65) | |
human.Height = gofakeit.Float64Range(150, 200) | |
human.Username = gofakeit.Username() | |
human.DOB = gofakeit.Date().Format("2006-01-02") | |
human.Email = gofakeit.Email() | |
// Check uniqueness | |
var count int64 | |
if err := db.Model(&Human{}).Where("email = ?", human.Email).Count(&count).Error; err != nil { | |
return err | |
} | |
if count == 0 { | |
// Insert into the database | |
if err := db.Create(&human).Error; err != nil { | |
return err | |
} | |
i++ // Only increment i if a unique entry was inserted | |
} | |
} | |
return nil | |
} | |
func main() { | |
dbConnection, err := NewConnection() | |
if err != nil { | |
log.Println(err) | |
} | |
err = GenerateFakeData(dbConnection, 50) | |
if err != nil { | |
log.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment