Skip to content

Instantly share code, notes, and snippets.

@angch
Created July 8, 2020 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angch/ba340235c95f01f01433be4cda410925 to your computer and use it in GitHub Desktop.
Save angch/ba340235c95f01f01433be4cda410925 to your computer and use it in GitHub Desktop.
A quickie Go script to populate a database with two tables with test data
package main
// A quickie script to populate a database with two tables with test data
import (
"log"
"reflect"
"github.com/bxcodec/faker/v3"
"github.com/icrowley/fake"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type Customer struct {
ID int `gorm:"custid,PRIMARY_KEY" json:"id,omitempty"`
Name string `gorm:"custname" faker:"name" json:"name,omitempty"`
Address string `gorm:"custaddress" faker:"address" json:"address,omitempty"`
Phone string `gorm:"custphone" faker:"phone_number" json:"phone,omitempty"`
Email string `gorm:"custemail" faker:"email" json:"email,omitempty"`
}
type Restaurant struct {
ID int `gorm:"restid,PRIMARY_KEY" json:"id,omitempty"`
Name string `gorm:"restname" json:"name,omitempty"`
Type string `gorm:"resttype" faker:"oneof: japanese, malay, italian" json:"type,omitempty"`
Address string `gorm:"restaddress" faker:"address" json:"address,omitempty"`
Phone string `gorm:"restphone" faker:"phone_number" json:"phone,omitempty"`
Email string `gorm:"restemail" faker:"email" json:"email,omitempty"`
PersonInCharge string `gorm:"restpic" faker:"name" json:"person_in_charge,omitempty"`
}
func main() {
db, err := gorm.Open("sqlite3", "mco.sqlite")
if err != nil {
log.Fatal(err)
}
db.AutoMigrate(Customer{}, Restaurant{})
defer db.Close()
customers := make([]Customer, 0)
_ = faker.AddProvider("address", func(v reflect.Value) (interface{}, error) {
a := "12 Jalan Foo" // FIXME
return string(a), nil
})
db.Find(&customers)
minCustomers := 100
for len(customers) < minCustomers {
customer := Customer{}
db.NewRecord(&customer)
err := faker.FakeData(&customer)
if err != nil {
log.Fatal(err)
}
db.Save(customer)
customers = append(customers, customer)
}
restaurants := make([]Restaurant, 0)
db.Find(&restaurants)
minRestaurants := 10
for len(restaurants) < minRestaurants {
r := Restaurant{}
db.NewRecord(&r)
err := faker.FakeData(&r)
if err != nil {
log.Fatal(err)
}
r.Name = fake.Company()
db.Save(&r)
restaurants = append(restaurants, r)
}
log.Println(customers)
log.Println(restaurants)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment