'Is there no migration file at all in GORM?
If I use GORM, there is no migration file?? So far, I googled and searched for this information, there is no migration file in GORM based on my understanding, and If I want to generate a migration file I have to use CLI. The reason why the GORM didn't generate a migration file is that " It WON’T delete unused columns to protect your data." (https://gorm.io/docs/migration.html#Auto-Migration)
How do we keep track of the changes? In Django, it generates a migration file, and we can keep track of the changes whenever we migrate.
In advance, I am sorry if I understand something wrong... I am just getting started learning golang and database a few days ago.
Solution 1:[1]
I believe GORM doesn't have the solution you want. There are some CLIs from the GORM team and from other enthusiasts but they really don't do what we actually want (Yep, I needed the same tool as well). At the end of the day, only GIT is the friend in the case of using GORM.
P.S. I found a good solution in Facebook's Ent(The entity framework for Go) which is a significantly better option for interacting with DBs in Go. They have a built-in solution for your needs - the WriteTo function which writes the schema changes to f instead of running them against the database.
func main() {
client, err := ent.Open("mysql", "root:pass@tcp(localhost:3306)/test")
if err != nil {
log.Fatalf("failed connecting to mysql: %v", err)
}
defer client.Close()
ctx := context.Background()
// Dump migration changes to an SQL script.
f, err := os.Create("migrate.sql")
if err != nil {
log.Fatalf("create migrate file: %v", err)
}
defer f.Close()
if err := client.Schema.WriteTo(ctx, f); err != nil {
log.Fatalf("failed printing schema changes: %v", err)
}
}
Or you can simply print the changes to the terminal by setting os.Stdout as a target output location for WriteTo.
client.Schema.WriteTo(ctx, os.Stdout)
The reference | Database Migration - Offline Mode
I hope, this will help you to have a better option next time by using Ent which is created, open-sourced, and maintained by Facebook for its needs and scale. Also, you might be interested in the post from Ariel Mashraki - Introducing ent.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dsha256 |
