-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
126 lines (108 loc) · 1.85 KB
/
db.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"database/sql"
"errors"
"fmt"
"log"
)
type DB struct {
Config Config
conn *sql.DB
}
func (d *DB) CreateConn() (*sql.DB, error) {
var err error
conn, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s:%s/%s",
d.Config.DB.Username,
d.Config.DB.Password,
d.Config.DB.Host,
d.Config.DB.Port,
d.Config.DB.Database,
))
if err != nil {
return nil, err
}
log.Println("[v] database connected...")
d.conn = conn
return conn, nil
}
func (d *DB) Migrate() (err error) {
if d.conn == nil {
return errors.New("connection is empty")
}
tx, err := d.conn.Begin()
if err != nil {
return
}
// drop table
var dropTableSql = `DROP TABLE IF EXISTS products`
_, err = tx.Exec(dropTableSql)
if err != nil {
if e := tx.Rollback(); e != nil {
return e
}
return
}
// create table
var createTableSql = `CREATE TABLE IF NOT EXISTS products (
id BIGSERIAL NOT NULL PRIMARY KEY,
name VARCHAR(63) NOT NULL,
quantity INTEGER NOT NULL
)`
_, err = tx.Exec(createTableSql)
if err != nil {
if e := tx.Rollback(); e != nil {
return e
}
return
}
// create dummy data
stmt, err := tx.Prepare(`INSERT INTO products (name, quantity) VALUES ($1, $2)`)
if err != nil {
if e := tx.Rollback(); e != nil {
return e
}
return
}
rows := []struct {
name string
quantity int
}{
{
name: "Hat",
quantity: 90,
},
{
name: "T-shirt",
quantity: 100,
},
{
name: "Hoodie",
quantity: 50,
},
{
name: "Pants",
quantity: 30,
},
{
name: "Dress",
quantity: 50,
},
}
for _, row := range rows {
_, err = tx.Stmt(stmt).Exec(row.name, row.quantity)
if err != nil {
if e := tx.Rollback(); e != nil {
return e
}
return
}
}
err = tx.Commit()
if err != nil {
if e := tx.Rollback(); e != nil {
return e
}
return
}
return
}