· 6 years ago · Aug 02, 2019, 06:30 PM
1func CreateSchema(db *DB, modelsList []interface{}, dropExisting bool) error {
2 for _, model := range modelsList {
3 if dropExisting {
4 err := DropTable(db, model.(models.User).Name)
5 if err != nil {
6 fmt.Println(err)
7 }
8 }
9
10 err := CreateTable(db, model.(models.User).Name)
11 if err != nil {
12 return err
13 }
14 }
15 return nil
16}
17
18// CreateTable creates a new table in the database
19func CreateTable(db *DB, model interface{}) error {
20 _, err := db.Conn.Exec("CREATE TABLE IF NOT EXISTS "+model.(string))
21 if err != nil {
22 return err
23 }
24 return nil
25}
26
27// DropTable deletes the existing tables
28func DropTable(db *DB, model interface{}) error {
29 _, err := db.Conn.Exec("DROP TABLE IF EXISTS "+model.(string))
30 if err != nil {
31 panic(err)
32 }
33 return nil
34}
35
36type User struct {
37 ID int64
38 Email string
39 Name string
40 LastName string
41 Phone string
42 PasswordHash string
43 Status UserStatus
44 VerificationCode string
45 VerificationCodeExpiration time.Time
46}
47
48func main () {
49
50intfs := []interface{}{
51 models.User{},
52 }
53
54
55_ = database.CreateSchema(&db, intfs, dropExistingTables)
56 if err != nil {
57 log.Error("Failed to create database schema", "error", err)
58 }
59
60}
61RAW Paste Data
62func CreateSchema(db *DB, modelsList []interface{}, dropExisting bool) error {
63 for _, model := range modelsList {
64 if dropExisting {
65 err := DropTable(db, model)
66 if err != nil {
67 fmt.Println(err)
68 }
69 }
70
71 err := CreateTable(db, model)
72 if err != nil {
73 return err
74 }
75 }
76 return nil
77}
78
79// CreateTable creates a new table in the database
80func CreateTable(db *DB, model interface{}) error {
81 name := reflect.TypeOf(model).Name()
82 _, err := db.Conn.Exec("CREATE TABLE IF NOT EXISTS "+name)
83 if err != nil {
84 return err
85 }
86 return nil
87}
88
89// DropTable deletes the existing tables
90func DropTable(db *DB, model interface{}) error {
91 name := reflect.TypeOf(model).Name()
92 _, err := db.Conn.Exec("DROP TABLE IF EXISTS "+name)
93 if err != nil {
94 panic(err)
95 }
96 return nil
97}
98
99type User struct {
100 ID int64
101 Email string
102 Name string
103 LastName string
104 Phone string
105 PasswordHash string
106 Status UserStatus
107 VerificationCode string
108 VerificationCodeExpiration time.Time
109}
110
111func main () {
112
113intfs := []interface{}{
114 models.User{},
115 }
116
117
118_ = database.CreateSchema(&db, intfs, dropExistingTables)
119 if err != nil {
120 log.Error("Failed to create database schema", "error", err)
121 }
122
123}