-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
192 lines (177 loc) · 4.67 KB
/
main.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package main
import (
"context"
"database/sql"
"fmt"
"log"
"strings"
"time"
_ "github.com/go-sql-driver/mysql"
)
const (
username = "root"
password = "password"
hostname = "127.0.0.1:3306"
dbname = "ecommerce"
)
type product struct {
name string
price int
}
func dsn(dbName string) string {
return fmt.Sprintf("%s:%s@tcp(%s)/%s", username, password, hostname, dbName)
}
func dbConnection() (*sql.DB, error) {
db, err := sql.Open("mysql", dsn(""))
if err != nil {
log.Printf("Error %s when opening DB\n", err)
return nil, err
}
ctx, cancelfunc := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelfunc()
res, err := db.ExecContext(ctx, "CREATE DATABASE IF NOT EXISTS "+dbname)
if err != nil {
log.Printf("Error %s when creating DB\n", err)
return nil, err
}
no, err := res.RowsAffected()
if err != nil {
log.Printf("Error %s when fetching rows", err)
return nil, err
}
log.Printf("rows affected: %d\n", no)
db.Close()
db, err = sql.Open("mysql", dsn(dbname))
if err != nil {
log.Printf("Error %s when opening DB", err)
return nil, err
}
//defer db.Close()
db.SetMaxOpenConns(20)
db.SetMaxIdleConns(20)
db.SetConnMaxLifetime(time.Minute * 5)
ctx, cancelfunc = context.WithTimeout(context.Background(), 5*time.Second)
defer cancelfunc()
err = db.PingContext(ctx)
if err != nil {
log.Printf("Errors %s pinging DB", err)
return nil, err
}
log.Printf("Connected to DB %s successfully\n", dbname)
return db, nil
}
func createProductTable(db *sql.DB) error {
query := `CREATE TABLE IF NOT EXISTS product(product_id int primary key auto_increment, product_name text,
product_price int, created_at datetime default CURRENT_TIMESTAMP, updated_at datetime default CURRENT_TIMESTAMP)`
ctx, cancelfunc := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelfunc()
res, err := db.ExecContext(ctx, query)
if err != nil {
log.Printf("Error %s when creating product table", err)
return err
}
rows, err := res.RowsAffected()
if err != nil {
log.Printf("Error %s when getting rows affected", err)
return err
}
log.Printf("Rows affected when creating table: %d", rows)
return nil
}
func insert(db *sql.DB, p product) error {
query := "INSERT INTO product(product_name, product_price) VALUES (?, ?)"
ctx, cancelfunc := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelfunc()
stmt, err := db.PrepareContext(ctx, query)
if err != nil {
log.Printf("Error %s when preparing SQL statement", err)
return err
}
defer stmt.Close()
res, err := stmt.ExecContext(ctx, p.name, p.price)
if err != nil {
log.Printf("Error %s when inserting row into products table", err)
return err
}
rows, err := res.RowsAffected()
if err != nil {
log.Printf("Error %s when finding rows affected", err)
return err
}
log.Printf("%d products created ", rows)
prdID, err := res.LastInsertId()
if err != nil {
log.Printf("Error %s when getting last inserted product", err)
return err
}
log.Printf("Product with ID %d created", prdID)
return nil
}
func multipleInsert(db *sql.DB, products []product) error {
query := "INSERT INTO product(product_name, product_price) VALUES "
var inserts []string
var params []interface{}
for _, v := range products {
inserts = append(inserts, "(?, ?)")
params = append(params, v.name, v.price)
}
queryVals := strings.Join(inserts, ",")
query = query + queryVals
log.Println("query is", query)
ctx, cancelfunc := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelfunc()
stmt, err := db.PrepareContext(ctx, query)
if err != nil {
log.Printf("Error %s when preparing SQL statement", err)
return err
}
defer stmt.Close()
res, err := stmt.ExecContext(ctx, params...)
if err != nil {
log.Printf("Error %s when inserting row into products table", err)
return err
}
rows, err := res.RowsAffected()
if err != nil {
log.Printf("Error %s when finding rows affected", err)
return err
}
log.Printf("%d products created simultaneously", rows)
return nil
}
func main() {
db, err := dbConnection()
if err != nil {
log.Printf("Error %s when getting db connection", err)
return
}
defer db.Close()
log.Printf("Successfully connected to database")
err = createProductTable(db)
if err != nil {
log.Printf("Create product table failed with error %s", err)
return
}
p := product{
name: "iphone",
price: 950,
}
err = insert(db, p)
if err != nil {
log.Printf("Insert product failed with error %s", err)
return
}
p1 := product{
name: "Galaxy",
price: 990,
}
p2 := product{
name: "iPad",
price: 500,
}
err = multipleInsert(db, []product{p1, p2})
if err != nil {
log.Printf("Multiple insert failed with error %s", err)
return
}
}