15

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)

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
flemadap
  • 639
  • 8
  • 18
  • 1
    Is this what you are looking for https://gorm.io/docs/migration.html#Auto-Migration? It says this: "AutoMigrate will create tables, missing foreign keys, constraints, columns and indexes. It will change existing column’s type if its size, precision, nullable changed. It WON’T delete unused columns to protect your data." – Emin Laletovic Aug 26 '21 at 15:23
  • hey man! did you manage to run the migrations using CLI? – Lucas Dalmarco Oct 20 '21 at 23:56

6 Answers6

2

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.

Pitchinnate
  • 7,517
  • 1
  • 20
  • 37
1

Atlas supports automatic migration planning for GORM.

Using Atlas you can automatically generate versioned migrations from your GORM models. You can generate migrations in Atlas's format to apply using Atlas, or if you want to use golang-migrate, Atlas can generate in that format as well.

Cheers,

(Full disclosure: I'm one of the authors)

Rotem Tamir
  • 1,397
  • 2
  • 11
  • 26
0

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)

Look at Declaring Models paragraph:

column data type, prefer to use compatible general type, e.g: bool, int, uint, float, string, time, bytes, which works for all databases, and can be used with other tags together, like not null, size, autoIncrement… specified database data type like varbinary(8) also supported, when using specified database data type, it needs to be a full database data type, for example: MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT

For example

type Post struct {
  ID     uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4()"`
  Title  string
  Tags   pq.StringArray `gorm:"type:text[]"`
}

Also, look at Customize Data Types paragraph.

kozmo
  • 4,024
  • 3
  • 30
  • 48
0

There is no straight forward solution for automatic SQL generation from your model in gorm. In golang-migrate/migrate you should write up and down SQL script for each version for upgrade/downgrade migration version and you can't use gorm to generate those files.

You should keep your gorm models with migration scripts sync manually.

Ali Tavakoli
  • 301
  • 2
  • 8
0

There is a hacky way to get SQL-code from Gorm automigrations. You can inject your logger in the Gorm on the stage of its creation (see docs) and then compile your your app after all models changes. Don't forget to set Info severity for the logger. Then automigrate sql should be in a logger output. You then need to copy-paste it to migrate files.

Vasiliy Toporov
  • 814
  • 12
  • 27
-1

Oh i understand, because i new in go too, If you migrated from framework like laravel or django, ... you feel it you can design scheme in another application like https://dbdiagram.io/home and export sql