-
Notifications
You must be signed in to change notification settings - Fork 0
/
record.go
67 lines (58 loc) · 1.44 KB
/
record.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
// Copyright (c) 2021, David Url
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ttt
import (
"database/sql"
"errors"
"fmt"
"time"
_ "github.com/mattn/go-sqlite3"
)
var (
ActiveRecordExistsError = errors.New("active record already exists")
NoActiveRecordError = errors.New("no active record exists")
)
type Record struct {
id int
Start *time.Time
End *time.Time
}
func (r *Record) Active() bool {
return r.Start != nil && r.End == nil
}
func (t *TimeTrackingDb) StartRecord(dts time.Time) error {
rec, err := t.GetCurrentRecord()
if err != nil {
return err
}
if rec.Active() {
return fmt.Errorf("%w", ActiveRecordExistsError)
} else {
rec.Start = &dts
_, err := t.db.Exec("INSERT INTO records (start) VALUES(?);", rec.Start)
return err
}
}
func (t *TimeTrackingDb) EndRecord(dts time.Time) error {
rec, err := t.GetCurrentRecord()
if err != nil {
return err
}
if rec.Active() {
rec.End = &dts
_, err := t.db.Exec("UPDATE records SET end=? WHERE rowid=?;", rec.End, rec.id)
return err
} else {
return fmt.Errorf("%w", NoActiveRecordError)
}
}
func (t *TimeTrackingDb) GetCurrentRecord() (Record, error) {
row := t.db.QueryRow("SELECT r.rowid, r.start, r.end FROM records AS r WHERE r.end IS NULL or r.end = '';")
rec := Record{}
err := row.Scan(&rec.id, &rec.Start, &rec.End)
if err == sql.ErrNoRows {
return rec, nil
}
return rec, err
}