I decided to use gorm as my ORM. I wanted to do a migration using golang-migrate/migrate because, it looks like, GORM does not have versioned migration files. And I rather, do migration using CLI, than using auto-migration.
I read the gorm documentation, but I didn't see how gorm translate the models into SQL Table. Is there any example or documentation about the generated SQL table for gorm?? (especially how types or association mapped to SQL)
I was looking for something similar to what you are looking for when I first started using Gorm a few years ago. I ended up using a package called goose (https://github.com/pressly/goose) to create migration files and run migrations from the CLI. It actually works really well. Basically on your up and down functions you can use gorm's built in migration functions (https://gorm.io/docs/migration.html).
Here is an example of a goose migration file utilizing gorm.
package main
import (
"database/sql"
"encoding/json"
"my-api/internal/pkg/db"
"time"
"my-api/internal/pkg/private/models"
"github.com/pressly/goose"
)
func init() {
goose.AddMigration(Up00007, Down00007)
}
type Event struct {
models.DefaultModel
VenueID uint `gorm:"not null"`
Tags json.RawMessage `gorm:"not null;type:json" sql:"type:json"`
Name string `gorm:"not null"`
Details string `gorm:"not null"`
Picture string `gorm:"not null"`
StartDate time.Time
EndDate time.Time
}
func Up00007(tx *sql.Tx) error {
// This code is executed when the migration is applied.
return db.Get().CreateTable(&Event{}).Error
}
func Down00007(tx *sql.Tx) error {
// This code is executed when the migration is rolled back.
return db.Get().DropTable(&Event{}).Error
}
Fyi db.Get() gets a gorm database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With