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
|
package main
import (
"log"
"time"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
const schema = `
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY,
location TEXT NOT NULL,
referrer TEXT,
started_at DATETIME NOT NULL,
time_spent INTEGER NOT NULL,
scrolled_to REAL NOT NULL
);`
type Entry struct {
Id int `json:"-" db:"id"`
Location string `json:"location" db:"location"`
Referrer string `json:"referrer,omitempty" db:"referrer"`
StartedAt time.Time `json:"startedAt" db:"started_at"`
TimeSpent int `json:"timeSpent" db:"time_spent"`
ScrolledTo float32 `json:"scrolledTo" db:"scrolled_to"`
}
var db *sqlx.DB
func InitEntries(pathname string) {
var err error
db, err = sqlx.Connect("sqlite3", pathname)
if err != nil {
log.Fatalln(err)
}
_, err = db.Exec(schema)
if err != nil {
log.Fatalln("Could not initialize schema")
log.Fatalln(err)
}
}
func CloseEntries() {
db.Close()
}
func InsertEntry(entry *Entry) error {
const query = `
INSERT INTO entries (location, referrer, started_at, time_spent, scrolled_to)
VALUES (:location, :referrer, :started_at, :time_spent, :scrolled_to);`
_, err := db.NamedExec(query, entry)
log.Println("Entry recorded:", entry.Location)
return err
}
func CountEntries() (count uint, err error) {
err = db.Get(&count, "SELECT COUNT(*) FROM entries;")
return
}
func AllEntries() (entries []Entry, err error) {
err = db.Select(&entries, "SELECT * FROM entries;")
return
}
func ListEntries(from, count uint) (entries []Entry, err error) {
err = db.Select(&entries, "SELECT * FROM entries LIMIT ? OFFSET ?;", count, from)
return
}
func EntriesSince(since time.Time) (entries []Entry, err error) {
err = db.Select(&entries, "SELECT * FROM entries WHERE started_at > ?;", since)
return
}
|