· 6 years ago · Aug 02, 2019, 05:58 PM
1func CreateSchema(db *DB, modelsList []interface{}, dropExisting bool) error {
2 for _, model := range modelsList {
3 if dropExisting {
4 err := DropTable(db, model)
5 if err != nil {
6 fmt.Println(err)
7 }
8 }
9
10 err := CreateTable(db, model)
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 name := reflect.TypeOf(model).Name()
21 _, err := db.Conn.Exec("CREATE TABLE IF NOT EXISTS "+name)
22 if err != nil {
23 return err
24 }
25 return nil
26}
27
28// DropTable deletes the existing tables
29func DropTable(db *DB, model interface{}) error {
30 name := reflect.TypeOf(model).Name()
31 _, err := db.Conn.Exec("DROP TABLE IF EXISTS "+name)
32 if err != nil {
33 panic(err)
34 }
35 return nil
36}
37
38type User struct {
39 ID int64
40 Email string
41 Name string
42 LastName string
43 Phone string
44 PasswordHash string
45 Status UserStatus
46 VerificationCode string
47 VerificationCodeExpiration time.Time
48}
49
50func main () {
51
52intfs := []interface{}{
53 models.User{},
54 }
55
56
57_ = database.CreateSchema(&db, intfs, dropExistingTables)
58 if err != nil {
59 log.Error("Failed to create database schema", "error", err)
60 }
61
62}