Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Once the InitSchema function is called, the contents of []*gormigrate.Migration are not executed as expected. #212

Open
shi-yang opened this issue Jul 16, 2023 · 2 comments

Comments

@shi-yang
Copy link

My database is clean, without any tables.

I want to InitSchema and do some other migrations, just like this:

	m := gormigrate.New(db, gormigrate.DefaultOptions, []*gormigrate.Migration{
		&gormigrate.Migration{
			ID: "20230716",
			Migrate: func(tx *gorm.DB) error {
				return tx.Exec("INSERT INTO user (username) VALUES ('admin')").Error
			},
			Rollback: func(tx *gorm.DB) error {
				return tx.Exec("DELETE FROM user WHERE username='admin'").Error
			},
		},
	})
	m.InitSchema(func(tx *gorm.DB) error {
		err := tx.AutoMigrate(
			&User{},
			// all other tables of you app
		)
		return err
	})
	if err := m.Migrate(); err != nil {
		log.Fatalf("Migration failed: %v", err)
	}
	log.Println("Migration did run successfully")

However, the sql INSERT INTO user (username) VALUES ('admin') was not executed as expected.

I then checked the source code of this library. There is only insertMigration in this place:

gormigrate/gormigrate.go

Lines 347 to 351 in 293e5ee

for _, migration := range g.migrations {
if err := g.insertMigration(migration.ID); err != nil {
return err
}
}

Is migration.Migrate(g.tx) missing. Or should it be call g.runMigration(migration.ID) instead of g.insertMigration(migration.ID)?

@jvfrodrigues
Copy link

The problem seems to be on the actual migrate function

https://github.com/go-gormigrate/gormigrate/blob/56c66f9d1f074e78fd0ce4693399347385a746c2/gormigrate.go#L186C2-L207

After it runs the initSchema it returns before doing the actual migration that was supposed to run

@ktrieu
Copy link

ktrieu commented Apr 19, 2024

To confirm, is this a bug or intended behaviour? We have a lot of duplication between initSchema and our regular migrations because only one of them runs at any given time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants