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

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

	_ "github.com/lib/pq"
)

// setup the Database
func setupDatabase() *sql.DB {
	connStr := "user=postgres dbname=postgres sslmode=disable"
	db, err := sql.Open("postgres", connStr)
	if err != nil {
		log.Fatal(err)
	}

	return db
}

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

	// get the current name of the challenges
	query := fmt.Sprintf("SELECT name FROM challenges WHERE points=200")
	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 getAllChallenges(db *sql.DB) []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 name, description, flag, container, category string
		var points int
		var static bool

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

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

		challenges = append(challenges, newChallenge)
	}

	return challenges
}