forked from vindecodex/msgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_init.go
80 lines (67 loc) · 1.69 KB
/
db_init.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
package main
import (
"fmt"
"log"
"time"
"github.com/jmoiron/sqlx"
"github.com/vindecodex/msgo/config"
"github.com/vindecodex/msgo/logger"
)
var (
dbUser = config.GETSTRING("DB_USER")
dbPwd = config.GETSTRING("DB_PWD")
dbHost = config.GETSTRING("DB_HOST")
dbName = config.GETSTRING("DB_NAME")
)
var schemaBooks = `
CREATE TABLE IF NOT EXISTS books (
id int(11) NOT NULL AUTO_INCREMENT,
title varchar(90),
author varchar(60),
length int(11),
PRIMARY KEY (id)
);`
var schemaUsers = `
CREATE TABLE IF NOT EXISTS users (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(40) UNIQUE,
password varchar(40),
role varchar(10),
PRIMARY KEY (id)
);`
func initializeDatabase() {
logger.Info("initializeDatabase")
client, err := dbClient()
if err != nil {
log.Printf("Error %s when opening database\n", err)
return
}
client.Exec("CREATE DATABASE IF NOT EXISTS msgo")
tx := client.MustBegin()
client.MustExec(schemaBooks)
client.MustExec(schemaUsers)
tx.MustExec("INSERT IGNORE INTO users (username, password, role) VALUES (\"admin\", \"admin\", \"owner\")")
tx.Commit()
}
func dbClient() (*sqlx.DB, error) {
logger.Info("dbClient")
dataSource := getDataSource("")
client, err := sqlx.Connect("mysql", dataSource)
if err != nil {
logger.Error(err.Error())
return nil, err
}
client.Exec("CREATE DATABASE IF NOT EXISTS msgo")
client, err = sqlx.Open("mysql", getDataSource(dbName))
if err != nil {
logger.Error(err.Error())
return nil, err
}
client.SetConnMaxLifetime(time.Minute * 3)
client.SetMaxOpenConns(10)
client.SetMaxIdleConns(10)
return client, nil
}
func getDataSource(dbname string) string {
return fmt.Sprintf("%s:%s@tcp(%s:3306)/%s", dbUser, dbPwd, dbHost, dbname)
}