-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
68 lines (57 loc) · 1.18 KB
/
database.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
package main
import (
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/lib/pq"
)
var (
dbHost = os.Getenv("DB_HOST")
dbPort = os.Getenv("DB_PORT")
dbUser = os.Getenv("DB_USER")
dbPassword = os.Getenv("DB_PWD")
dbName = os.Getenv("DB_NAME")
)
var db *sql.DB
func init() {
var err error
dbInfo := fmt.Sprintf("host=%v port=%v user=%v "+
"password=%v dbname=%v sslmode=disable",
dbHost, dbPort, dbUser, dbPassword, dbName)
db, err = sql.Open("postgres", dbInfo)
for err != nil {
panic(err)
}
if err = db.Ping(); err != nil {
try := 1
for try <= 6 && err != nil {
log.Printf("Establishing connection to the database... %d\nExiting after 5 tries.", try)
time.Sleep(10 * time.Second)
err = db.Ping()
try++
if try == 6 {
panic(err)
}
}
}
log.Println("Successfully connected to the database.")
createTable()
}
func createTable() {
query := `
CREATE TABLE IF NOT EXISTS tasks (
id SERIAL PRIMARY KEY,
title VARCHAR(20) NOT NULL,
content VARCHAR(255) NOT NULL,
urgent BOOLEAN NOT NULL
);
`
_, err := db.Exec(query)
if err != nil {
log.Println(err)
} else {
log.Println("Table 'tasks' has been created.")
}
}