add -a and -b flags

This commit is contained in:
Nick Griffey 2024-02-24 17:59:36 -06:00
parent cbd92a8d42
commit 2d742ce3f7
1 changed files with 23 additions and 7 deletions

30
main.go
View File

@ -34,28 +34,38 @@ func formula(p float64) int64 {
return int64(yearsAgo * 31556926)
}
func (db *TimelineDB) closestEvents(t int64, n int) ([]EventsRow, error) {
func (db *TimelineDB) closestEvents(t int64, n int, after bool, before bool) ([]EventsRow, error) {
ulimit := int64(math.MaxInt64)
llimit := int64(math.MinInt64)
if after && before {
return nil, errors.New("after and before can't both be true")
} else if after {
llimit = t
} else if before {
ulimit = t
}
query := `
select description, timestamp, yearknown, monthknown, dayknown, hourknown, minuteknown, secondknown
from events
where timestamp is not null
where timestamp between ? and ?
order by abs(? - timestamp) asc
limit ?
`
events := make([]EventsRow, n)
stmt, err := db.Prepare(query)
if err != nil {
return events, err
return nil, err
}
defer stmt.Close()
rows, err := stmt.Query(t, n)
rows, err := stmt.Query(llimit, ulimit, t, n)
if err != nil {
return events, err
return nil, err
}
defer rows.Close()
events := make([]EventsRow, n)
i := 0
for ; rows.Next(); i++ {
var event EventsRow
@ -96,8 +106,14 @@ func (event *EventsRow) Output() (int64, string, string, error) {
func main() {
percent := flag.Float64("p", -1, "percentage")
nevents := flag.Int("n", 1, "number of events")
after := flag.Bool("a", false, "only return events occurring after computed timestamp")
before := flag.Bool("b", false, "only return events occurring before computed timestamp")
flag.Parse()
if *after && *before {
log.Fatal("cannot pass both -a and -b")
}
if *percent < 0 || *percent > 1 {
log.Fatal("invalid percentage")
} else if *nevents < 0 {
@ -114,7 +130,7 @@ func main() {
}
defer db.Close()
events, err := db.closestEvents(t, *nevents)
events, err := db.closestEvents(t, *nevents, *after, *before)
if err != nil {
log.Fatal(err)
}