-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpost05.go
233 lines (214 loc) · 5.25 KB
/
post05.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
The package works on 2 tables on a PostgreSQL database server
The names of the tables are:
* users
* Userdata
The definitions of the tables in the PostgreSQL server are:
CREATE TABLE Users (
ID SERIAL,
Username VARCHAR(100) PRIMARY KEY
);
CREATE TABLE Userdata (
UserID Int NOT NULL,
Name VARCHAR(100),
Surname VARCHAR(100),
Description VARCHAR(200)
);
*/
package post05
import (
"database/sql"
"errors"
"fmt"
"strings"
_ "github.com/lib/pq"
)
// The Userdata structure is for holding full user data
// from the Userdata table and the Username from the
// Users table
type Userdata struct {
ID int
Username string
Name string
Surname string
Description string
}
/*
This block of global variables holds the connection details to the Postgres server
Hostname: is the IP or the hostname of the server
Port: is the TCP port the DB server listens to
Username: is the username of the database user
Password: is the password of the database user
Database: is the name of the Database in PostgreSQL
*/
var (
Hostname = ""
Port = 2345
Username = ""
Password = ""
Database = ""
)
// openConnection() is for opening the Postgres connection
// in order to be used by the other functions of the package.
func openConnection() (*sql.DB, error) {
// connection string
conn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
Hostname, Port, Username, Password, Database)
// open database
db, err := sql.Open("postgres", conn)
if err != nil {
return nil, err
}
return db, nil
}
// The function returns the User ID of the username
// -1 if the user does not exist
func exists(username string) int {
username = strings.ToLower(username)
db, err := openConnection()
if err != nil {
fmt.Println(err)
return -1
}
defer db.Close()
userID := -1
statement := fmt.Sprintf(`SELECT "id" FROM "users" WHERE username = '%s'`, username)
rows, _ := db.Query(statement)
for rows.Next() {
var id int
err = rows.Scan(&id)
if err != nil {
fmt.Println("Scan", err)
return -1
}
userID = id
}
defer rows.Close()
return userID
}
// AddUser adds a new user to the database
//
// Returns new User ID
// -1 if there was an error
func AddUser(d Userdata) int {
d.Username = strings.ToLower(d.Username)
db, err := openConnection()
if err != nil {
fmt.Println(err)
return -1
}
defer db.Close()
userID := exists(d.Username)
if userID != -1 {
fmt.Println("User already exists:", Username)
return -1
}
insertStatement := `INSERT INTO "users" ("username") values ($1)`
_, err = db.Exec(insertStatement, d.Username)
if err != nil {
fmt.Println(err)
return -1
}
userID = exists(d.Username)
if userID == -1 {
return userID
}
insertStatement = `INSERT INTO "userdata" ("userid", "name", "surname", "description") values ($1, $2, $3, $4)`
_, err = db.Exec(insertStatement, userID, d.Name, d.Surname, d.Description)
if err != nil {
fmt.Println("db.Exec()", err)
return -1
}
return userID
}
/*
DeleteUser deletes an existing userl if the user exists.
If requires the User ID of the user to be deleted.
*/
func DeleteUser(id int) error {
db, err := openConnection()
if err != nil {
return err
}
defer db.Close()
// Does the ID exist?
statement := fmt.Sprintf(`SELECT "username" FROM "users" WHERE id = %d`, id)
rows, _ := db.Query(statement)
var username string
for rows.Next() {
err = rows.Scan(&username)
if err != nil {
return err
}
}
defer rows.Close()
if exists(username) != id {
return fmt.Errorf("user with ID %d does not exist", id)
}
// Delete from Userdata
deleteStatement := `DELETE FROM "userdata" WHERE userid=$1`
_, err = db.Exec(deleteStatement, id)
if err != nil {
return err
}
// Delete from Users
deleteStatement = `DELETE FROM "users" WHERE id=$1`
_, err = db.Exec(deleteStatement, id)
if err != nil {
return err
}
return nil
}
// ListUsers lists all users in the database
// and returns a slice of Userdata.
func ListUsers() ([]Userdata, error) {
Data := []Userdata{}
db, err := openConnection()
if err != nil {
return Data, err
}
defer db.Close()
rows, err := db.Query(`SELECT "id", "username", "name", "surname", "description"
FROM "users", "userdata"
WHERE users.id = userdata.userid`)
if err != nil {
return Data, err
}
for rows.Next() {
var id int
var username string
var name string
var surname string
var description string
err = rows.Scan(&id, &username, &name, &surname, &description)
temp := Userdata{ID: id, Username: username, Name: name, Surname: surname, Description: description}
Data = append(Data, temp)
if err != nil {
return Data, err
}
}
defer rows.Close()
return Data, nil
}
// UpdateUser is for updating an existing user
// given a Userdata structure
// The user ID of the user to be updated is found
// inside the functionb
func UpdateUser(d Userdata) error {
db, err := openConnection()
if err != nil {
return err
}
defer db.Close()
userID := exists(d.Username)
if userID == -1 {
return errors.New("user does not exist")
}
d.ID = userID
updateStatement := `UPDATE "userdata" set "name"=$1, "surname"=$2, "description"=$3 WHERE "userid"=$4`
_, err = db.Exec(updateStatement, d.Name, d.Surname, d.Description, d.ID)
if err != nil {
return err
}
return nil
}