-
Notifications
You must be signed in to change notification settings - Fork 43
/
autoMigrate.go
103 lines (85 loc) · 2.26 KB
/
autoMigrate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// autoMigrate.go needs to be executed only when it is required
package main
import (
"fmt"
"github.com/jinzhu/gorm"
"github.com/pilinux/gorest/config"
"github.com/pilinux/gorest/database"
"github.com/pilinux/gorest/database/model"
)
// Load all the models
type auth model.Auth
type user model.User
type post model.Post
type hobby model.Hobby
type userHobby model.UserHobby
var db *gorm.DB
var errorState int
func main() {
/*
** 0 = default/no error
** 1 = error
**/
errorState = 0
db = database.InitDB()
defer db.Close()
// Auto migration
/*
- Automatically migrate schema
- Only create tables with missing columns and missing indexes
- Will not change/delete any existing columns and their types
*/
// Careful! It will drop all the tables!
dropAllTables()
// Automatically migrate all the tables
migrateTables()
// Manually set foreign keys for MySQL DB
setPkFk()
if errorState == 0 {
fmt.Println("Auto migration is completed!")
} else {
fmt.Println("Auto migration failed!")
}
}
func dropAllTables() {
// Careful! It will drop all the tables!
if err := db.DropTableIfExists(&userHobby{}, &hobby{}, &post{}, &user{}, &auth{}).Error; err != nil {
errorState = 1
fmt.Println(err)
} else {
fmt.Println("Old tables are deleted!")
}
}
func migrateTables() {
configureDB := config.Config()
driver := configureDB.Database.DbDriver
if driver == "mysql" {
// db.Set() --> add table suffix during auto migration
if err := db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&auth{},
&user{}, &post{}, &hobby{}, &userHobby{}).Error; err != nil {
errorState = 1
fmt.Println(err)
} else {
fmt.Println("New tables are migrated successfully!")
}
} else {
if err := db.AutoMigrate(&auth{},
&user{}, &post{}, &hobby{}, &userHobby{}).Error; err != nil {
errorState = 1
fmt.Println(err)
} else {
fmt.Println("New tables are migrated successfully!")
}
}
}
func setPkFk() {
// Manually set foreign key for MySQL DB
if err := db.Model(&user{}).AddForeignKey("id_auth", "auths(auth_id)", "CASCADE", "CASCADE").Error; err != nil {
errorState = 1
fmt.Println(err)
}
if err := db.Model(&post{}).AddForeignKey("id_user", "users(user_id)", "CASCADE", "CASCADE").Error; err != nil {
errorState = 1
fmt.Println(err)
}
}