about summary refs log tree commit diff
path: root/src/db.go
blob: 300e55979ac6f591682ddfe9dbc235946fce5263 (plain)
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
package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"strconv"

	_ "github.com/lib/pq"
)

// setup the Database
func setupDatabase() (*sql.DB, error) {

	dbHost := os.Getenv("DBHOST")
	dbPort, _ := strconv.Atoi(os.Getenv("DBPORT"))
	dbUser := os.Getenv("DBUSER")
	dbName := os.Getenv("DBNAME")

	//connStr := "host=postgresql port=5432 user=postgres dbname=postgres sslmode=disable"
	connStr := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable", dbHost, dbPort, dbUser, dbName)

	// open a connection to the database
	db, err := sql.Open("postgres", connStr)
	if err != nil {
		log.Fatal(err)
	}

	// ping the database
	err = db.Ping()
	if err != nil {
		return nil, err
	}

	// create a challenges table if it does not exist yet
	err = dbCreateTableIfNotExist(db)
	if err != nil {
		log.Println(err)
	}

	return db, nil
}

// getNames gets the name of all the challenges
func dbGetName(db *sql.DB) string {

	// get the current name of the challenges
	query := fmt.Sprintf("SELECT name FROM challenges")
	var names string
	err := db.QueryRow(query).Scan(&names)
	if err != nil {
		log.Fatalf("[ E ] :", err)
	}

	return names
}

// getAllChallenges gets all the challenges from the server
func dbGetAllChallenges() []Challenge {

	// build the query
	query := fmt.Sprintf("SELECT * FROM challenges")

	// Execute the query
	rows, err := db.Query(query)
	defer rows.Close()
	if err != nil {
		log.Printf("[ E ] getAllChallenges query: %v\n\t\t\t query: %s\n", err, query)
		return []Challenge{}
	}

	var challenges []Challenge

	// iterate over the returned rows
	for rows.Next() {

		var uuid, name, description, flag, container, category string
		var points int
		var static bool

		scanErr := rows.Scan(&uuid, &name, &description, &flag, &container, &category, &points, &static)
		if scanErr != nil {
			log.Printf("[ E ] scan error: %v", scanErr)
			return []Challenge{}
		}

		newChallenge := Challenge{
			UUID:        uuid,
			Name:        name,
			Description: description,
			Flag:        flag,
			Container:   container,
			Category:    category,
			Points:      points,
			Static:      static,
		}

		challenges = append(challenges, newChallenge)
	}

	return challenges
}

// dbNewChallenge inserts the given challenge into the database
func dbNewChallenge(challenge Challenge) (string, error) {

	// build the query to be executed
	query := fmt.Sprintf("INSERT INTO challenges(name, description, flag, container, category, points, static) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING uuid")

	// execute the query with the challenge values given
	var uuid string
	err := db.QueryRow(query, challenge.Name, challenge.Description, challenge.Flag, challenge.Container, challenge.Category, challenge.Points, challenge.Static).Scan(&uuid)

	// handle errors
	if err != nil {
		return "", err
	}
	return uuid, nil
}

// editChallengeUUID edited the challenge with the given uuid using the values in the updatedChallenge
func dbEditChallengeUUID(uuid string, updatedChallenge Challenge) error {

	query := fmt.Sprintf("UPDATE challenges SET name = '$1', description = '$2', flag = '$3', container = '$4', category = '$5', points = $6, static = $7 WHERE uuid::text = '$8'")

	err := db.QueryRow(query, updatedChallenge.Name, updatedChallenge.Description, updatedChallenge.Flag, updatedChallenge.Container, updatedChallenge.Category, updatedChallenge.Points, updatedChallenge.Static, updatedChallenge.UUID)

	if err != nil {
		return fmt.Errorf("could not edit the challenge: %s", err)
	}

	return nil
}

// dbGetChallengeByUUID returns the challenge with the given UUID from the database
func dbGetChallengeByUUID(uuid string) (Challenge, error) {
	// build the query to be executed
	query := fmt.Sprintf("SELECT uuid, name, description, flag, container, category, points, static FROM challenges WHERE uuid::text= '$1'")

	challenge := Challenge{}

	// execute the query storing the values in the challenge struct defined above
	err := db.QueryRow(query, uuid).Scan(&challenge.UUID, &challenge.Name, &challenge.Description, &challenge.Flag, &challenge.Container, &challenge.Category, &challenge.Points, &challenge.Static)

	if err != nil {
		return Challenge{}, err
	}
	return challenge, nil
}

func dbDeleteChallengeByUUID(uuid string) error {
	query := fmt.Sprintf("DELETE FROM challenges WHERE uuid::text = '%s'")

	err := db.QueryRow(query, uuid)
	if err != nil {
		return fmt.Errorf("could not delete the challenge: %s", err)
	}

	return nil
}

func dbCreateTableIfNotExist(db *sql.DB) error {
	log.Println("Creating a table in case it doesn't exist")
	query := `CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE public.challenges
(
	uuid uuid NOT NULL DEFAULT uuid_generate_v4(),
	name character varying COLLATE pg_catalog."default" NOT NULL,
	description character varying COLLATE pg_catalog."default",
	flag character varying COLLATE pg_catalog."default",
	container character varying COLLATE pg_catalog."default",
	category character varying COLLATE pg_catalog."default",
	points integer,
	static boolean NOT NULL,
	CONSTRAINT challenges_pkey PRIMARY KEY (uuid)
)`

	_, err := db.Exec(query)
	if err != nil {
		return err
	}
	return nil
}