Get structs in a package for go-gorm migrations

291 Views Asked by At

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

0

There are 0 best solutions below