aboutsummaryrefslogtreecommitdiff
path: root/db.go
blob: 65f5041f40c868948cab6f7f6d4343239bc43780 (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
package main

import (
	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
)

func connect() (*sqlx.DB, error) {
	db := config.Database

	return sqlx.Connect(
		db.Adapter,
		"user="+db.Username+
			" password="+db.Password+
			" dbname="+db.Database+
			" sslmode="+db.SSLMode)
}

func getCaches() (DBCaches, error) {
	var caches DBCaches

	db, err := connect()
	if err != nil {
		return caches, err
	}

	err = db.Select(&caches, "SELECT * FROM caches ORDER BY id ASC")
	if err != nil {
		return caches, err
	}

	err = db.Close()
	return caches, err
}

func getCache(id uint64) (DBCache, error) {
	var cache DBCache

	db, err := connect()
	if err != nil {
		return cache, err
	}

	err = db.Get(&cache, "SELECT * FROM caches WHERE id=$1", id)
	if err != nil {
		return cache, err
	}

	err = db.Close()
	return cache, err
}

func postCache(incache DBCache) (DBCache, error) {
	var outcache DBCache

	db, err := connect()
	if err != nil {
		return outcache, err
	}

	rows, err := db.NamedQuery("INSERT INTO caches (latitude, longitude, created, path) VALUES (:latitude, :longitude, :created, :path) RETURNING *", incache)
	if err != nil {
		return outcache, err
	}

	rows.Next()
	err = rows.StructScan(&outcache)
	if err != nil {
		return outcache, err
	}

	err = db.Close()
	return outcache, err
}