-
Notifications
You must be signed in to change notification settings - Fork 0
/
record.go
73 lines (63 loc) · 1.64 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
68
69
70
71
72
73
// 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 (
ErrActiveRecordExists = errors.New("active record already exists")
ErrNoActiveRecord = errors.New("no active record exists")
)
type Record struct {
id int
Start *time.Time
End *time.Time
Absence string
}
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", ErrActiveRecordExists)
} 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", ErrNoActiveRecord)
}
}
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
}
func (t *TimeTrackingDb) AddAbsence(time time.Time, absence string) error {
_, err := t.db.Exec("INSERT INTO records (start,end,absence) VALUES(?,?,?);", time, time, absence)
return err
}