-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
129 lines (120 loc) · 2.52 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
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
package main
import (
"context"
"database/sql"
"fmt"
)
type database struct {
db *sql.DB
}
func (d *database) newLot (name string, price string) error {
ctx := context.Background()
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, "INSERT INTO allLots (name, status, price) VALUES($1, $2, $3)", name, true, price)
if err != nil {
tx.Rollback()
return err
}
err = tx.Commit()
if err != nil {
return err
}
return err
}
func (d *database) getAllLots() ([]*lot, error) {
ctx := context.Background()
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
rows, err := tx.Query("SELECT * FROM allLots WHERE allLots.Status = true")
if err != nil {
tx.Rollback()
return nil, err
}
lots := []*lot{}
for rows.Next(){
p := &lot{}
err := rows.Scan(&p.ID, &p.Name, &p.Price, &p.Status)
if err != nil{
fmt.Println(err)
continue
}
lots = append(lots, p)
}
err = tx.Commit()
if err != nil {
return nil, err
}
return lots, err
}
func (d *database) closeLot (id int) error {
ctx := context.Background()
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, "UPDATE allLots SET status = $1 WHERE id = $2", false, id)
if err != nil {
tx.Rollback()
return err
}
err = tx.Commit()
if err != nil {
return err
}
return err
}
func (d *database) updatePrice (id int, price string, name string) error {
ctx := context.Background()
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
return err
}
_, err = tx.ExecContext(ctx,"UPDATE allLots SET price = $1, name = $3 WHERE id = $2", price, id, name)
if err != nil {
tx.Rollback()
return err
}
_, err = tx.ExecContext(ctx, "INSERT INTO history (customer_name, lot_id, new_price, time_now) VALUES ($1, $2, $3, clock_timestamp())", name, id, price)
if err != nil {
tx.Rollback()
return err
}
err = tx.Commit()
if err != nil {
return err
}
return err
}
func (d *database) getHistory(id int) ([]*history_id, error) {
ctx := context.Background()
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
rows, err := tx.Query("SELECT * FROM history WHERE lot_id = $1", id)
if err != nil {
tx.Rollback()
return nil, err
}
lots := []*history_id{}
for rows.Next(){
p := &history_id{}
err := rows.Scan(&p.ID, &p.CustomerName, &p.LotID, &p.NewPrice, &p.TimeNow)
if err != nil{
fmt.Println(err)
continue
}
lots = append(lots, p)
}
fmt.Println(lots)
err = tx.Commit()
if err != nil {
return nil, err
}
return lots, err
}