Search code examples
gogo-gormauto-migration

Insert seed data at the first time of migration in GORM


I want to insert seed data when AutoMigrate creates a table in the database.

When I execute db.AutoMigrate(&User{}), it doesn't return any information related to the table creation, so I can't confirm that table has been created, updated, or doesn't do anything.

Is there any way to know the table creation information from GORM to insert seed data?

So that I can insert seed data like:

if err = db.AutoMigrate(&User{}); err != nil {
    if db.CreatedFirstTime {
        //Insert seed data
    }
}

Solution

  • According to docs, you can't get the table creation information from db.AutoMigrate(&User{}). Try to use Migrator with queries combination to get table's info.

    For example:

    if err = db.AutoMigrate(&User{}); err == nil && db.Migrator().HasTable(&User{}) {
        if err := db.First(&User{}).Error; errors.Is(err, gorm.ErrRecordNotFound) {
            //Insert seed data
        }
    }