0

There is a way to get all structs in package (entity in this case) to generate an automatic migrations list?

I split entities and migration package and now we have a package dedicated to all entities used by gorm and this is how I manage migration currently, completely manual to each new entity added we have to modify the migration main code adding the new entity to the migrationsList

package entity

type ClockOffset struct {
    Model
    ID        string `json:"id" gorm:"primarykey"`
    LastSyncClock     uint32 `json:"last_sync_clock" gorm:"not null"`
    LastSyncTimestamp uint32 `json:"last_sync_timestamp" gorm:"not null"`
}

type InflightMessage struct {
    Model
    ID        string `json:"id" gorm:"primarykey"`
    Token     uint8  `gorm:"not null;uniqueIndex:idx_gateway_id_token"`
    Tag       string `gorm:"not null"`
}

// ... other entities ...

package main

func main() {

    var migrationsList []*gormigrate.Migration

    migrationsList = append(migrationsList, &gormigrate.Migration{
        ID: "001-ClockOffset-CreateTable",
        Migrate: func(tx repo.Database) error {
            return tx.Migrator().CreateTable(&entity.ClockOffset{})
        },
        Rollback: func(tx repo.Database) error {
            return tx.Migrator().DropTable(&entity.ClockOffset{})
        },
    })

    migrationsList = append(migrationsList, &gormigrate.Migration{
        ID: "002-InflightMessage-CreateTable",
        Migrate: func(tx repo.Database) error {
            return tx.Migrator().CreateTable(&entity.InflightMessage{})
        },
        Rollback: func(tx repo.Database) error {
            return tx.Migrator().DropTable(&entity.InflightMessage{})
        },
    })

    m := gormigrate.New(repo.Db(), gormigrate.DefaultOptions, migrationsList)

    if err := m.Migrate(); err != nil {
        panic(err)
    }
}

I'd like to find an automatic way to read all the structures present on the package entity loop and append them to migrationsList

  • nobody wants to write automatic migrations as a step of the workflow. –  Jul 15 '21 at 10:25
  • you can use importer / packages package to load go source code and programatically manipulate it. see https://stackoverflow.com/a/57455287/4466350 –  Jul 15 '21 at 10:32
  • you want to read about https://pkg.go.dev/go/types –  Jul 15 '21 at 10:33
  • and https://pkg.go.dev/golang.org/x/tools/go/packages –  Jul 15 '21 at 10:33
  • most importantly https://go.googlesource.com/example/+/HEAD/gotypes/go-types.md –  Jul 15 '21 at 10:35
  • once you figured out how to list defined types within a package, you might write a template to generate the source code and write to some file (ie not main) –  Jul 15 '21 at 10:36

0 Answers0