Seeds

Seeds are very similar to migrations, but seeds do not implement the Rollback function.

Just like migrations, seeds are applied once and tracked using their unique identifier ID by GoMigrate.

Seeds are part of the whole package which allows you to access models, clients and other components directly to configure the application, and perhaps provide dummy data to help with development.

Here's a seed skeleton to get you started. Copy the following structure into a new file under seeds and change the s.ID property.

func init() {

	var s = &gormigrate.Migration{}
	s.ID = "2022081801_new_seed"

	s.Migrate = func(db *gorm.DB) error {

		logSuccess(s.ID)
		return nil
	}

	AddSeed(s)
}

And here's a sample seed to give an idea of how you can utilise seeds.

func init() {

	var s = &gormigrate.Migration{}
	s.ID = "2022081801_seed_cats_data"

	s.Migrate = func(db *gorm.DB) error {

		var err error
    var cats []*models.Cat

		cats = append(cats, &models.Cat{
			Name: "Kitty",
			Type: "Persian",
		})

		cats = append(cats, &models.Cat{
			Name: "Tom",
			Type: "Siamese",
		})

    for _, cat := range cats {
      err = cat.Save()
      if err != nil {
        logFail(s.ID, err)
        return err
      }
    }

		logSuccess(s.ID)
		return nil
	}

	AddSeed(s)
}

Was this page helpful?

Consider supporting my work if you find it useful

Buy me a coffee