-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
78 lines (65 loc) · 2.02 KB
/
cache.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
package main
import (
"database/sql"
_ "modernc.org/sqlite"
)
func NewCacheDatabase(dbFile string) (*CacheDatabase, error) {
sqliteDb, err := sql.Open("sqlite", dbFile)
if err != nil {
return nil, err
}
cache := &CacheDatabase{DB: sqliteDb}
err = cache.initCache()
if err != nil {
return nil, err
}
return cache, nil
}
func (cache *CacheDatabase) initCache() error {
// Create table if it doesn't exist
createTableSql := `CREATE TABLE IF NOT EXISTS locations (
geohash TEXT PRIMARY KEY,
latitude REAL NOT NULL,
longitude REAL NOT NULL,
country TEXT NOT NULL,
division TEXT NOT NULL,
city TEXT NOT NULL,
place TEXT NOT NULL,
url TEXT NOT NULL,
json JSON NOT NULL
);`
_, err := cache.DB.Exec(createTableSql)
checkErr(err, "Failed to create locations table")
return err
}
func (cache *CacheDatabase) InsertLocation(url string, location GeoLocationMetadata) error {
stmt, err := cache.DB.Prepare("INSERT INTO locations(geohash, latitude, longitude, country, division, city, place, url, json) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)")
_, err = stmt.Exec(location.Geohash, location.Latitude, location.Longitude, location.Country, location.Division, location.City, location.Place, url, location.Json)
return err
}
func (cache *CacheDatabase) GetLocation(geohash string) (*GeoLocationMetadata, error) {
var rowGeohash string
var rowLatitude float64
var rowLongitude float64
var rowCountry string
var rowDivision string
var rowCity string
var rowPlace string
var rowUrl string
var rowJson string
if err := cache.DB.QueryRow("SELECT * FROM locations WHERE geohash = ?", geohash).Scan(&rowGeohash, &rowLatitude, &rowLongitude, &rowCountry, &rowDivision, &rowCity, &rowPlace, &rowUrl, &rowJson); err != nil {
return nil, err
}
var location *GeoLocationMetadata
location = &GeoLocationMetadata{
Geohash: rowGeohash,
Latitude: rowLatitude,
Longitude: rowLongitude,
Country: rowCountry,
Division: rowDivision,
City: rowCity,
Place: rowPlace,
Json: rowJson,
}
return location, nil
}