This repository has been archived by the owner on Oct 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.go
128 lines (102 loc) · 2.06 KB
/
storage.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
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
type storage interface {
createAccount(*account) error
deleteAccount(int) error
updateAccount(*account) error
getAccountByID(int) (*account, error)
getAccounts() ([] *account, error)
}
type postgresStore struct {
db *sql.DB
}
func newPostgresStore() (*postgresStore, error) {
connStr := "user=postgres dbname=postgres password=go_bank sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
return nil, err
}
if err := db.Ping(); err != nil {
return nil, err
}
return &postgresStore{
db: db,
}, nil
}
func (s *postgresStore) init() error {
return s.createAccountTable()
}
func (s *postgresStore) createAccountTable() error {
query := `create table if not exists account (
id serial primary key,
first_name varchar(50),
last_name varchar(50),
number serial,
balance serial,
created_at timestamp
)`
_, err := s.db.Exec(query)
return err
}
func (s *postgresStore) createAccount(account *account) error {
query := `
insert into account (
first_name,
last_name,
number,
balance,
created_at
)
values (
$1, $2, $3, $4, $5
)
`
response, err := s.db.Query(
query,
account.FirstName,
account.LastName,
account.Number,
account.Balance,
account.CreatedAt,
)
if err != nil {
return err
}
fmt.Printf("%+v/n", response)
return nil
}
func (s *postgresStore) updateAccount(*account) error {
return nil
}
func (s *postgresStore) deleteAccount(id int) error {
return nil
}
func (s *postgresStore) getAccountByID(id int) (*account, error) {
return nil, nil
}
func (s *postgresStore) getAccounts() ([] *account, error) {
rows, err := s.db.Query("select * from account")
if err != nil {
return nil, err
}
accounts := [] *account {}
for rows.Next() {
account := new(account)
err := rows.Scan(
&account.ID,
&account.FirstName,
&account.LastName,
&account.Number,
&account.Balance,
);
if err != nil {
return nil, err
}
accounts = append(accounts, account)
}
return accounts, nil
}