https://github.com/boolangery/gorm-app-migrate
https://github.com/boolangery/gorm-app-migrate
Last synced: 3 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/boolangery/gorm-app-migrate
- Owner: boolangery
- Created: 2020-10-16T19:47:14.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2020-10-18T11:28:03.000Z (almost 6 years ago)
- Last Synced: 2025-03-12T08:27:02.519Z (over 1 year ago)
- Language: Go
- Size: 9.77 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# gorm-app-migrate
A dead simple library to migrate / organize migration of web project in apps.
## usage
```go
type User struct {
ID uint `gorm:"primarykey"`
Email string `gorm:"uniqueIndex"`
FirstName string
}
// An app to manage users
type UserApp struct {}
func (a *UserApp) Name() string {
return "users"
}
func (a *UserApp) Migrations() []GormMigration {
return []GormMigration{
InlineGormMigration{
ID: "0001_add_user",
OnUp: func(db *gorm.DB) error {
// Here we are not using db.Migrator().CreateTable(&User{}) because when resetting
// migrations to zero, it will create field which would not have existed before
if err := db.Exec("CREATE TABLE `users` (`id` integer,`email` text,PRIMARY KEY (`id`))").Error; err != nil {
return err
}
if err := db.Exec("CREATE UNIQUE INDEX `idx_users_email` ON `users`(`email`)").Error; err != nil {
return err
}
return nil
},
OnDown: func(db *gorm.DB) error {
return db.Migrator().DropTable(&User{})
},
},
InlineGormMigration{
ID: "0002_add_user_first_name",
OnUp: func(db *gorm.DB) error {
return db.Migrator().AddColumn(&User{}, "FirstName")
},
OnDown: func(db *gorm.DB) error {
return db.Migrator().DropColumn(&User{}, "FirstName")
},
},
}
}
func main() {
app := &UserApp{}
if s, err := Migrate(db.Debug(), app); err != nil {
t.Error(err)
} else {
s.Print()
}
if s, err := MigrateTo(db.Debug(), app, "zero"); err != nil {
t.Error(err)
} else {
s.Print()
}
}
```