add flag for outputting multiple events

This commit is contained in:
Nick Griffey 2024-02-23 23:04:35 -06:00
parent bafbc3578c
commit 1260930b76
1 changed files with 30 additions and 12 deletions

32
main.go
View File

@ -33,24 +33,39 @@ func formula(p float64) int64 {
return int64(yearsAgo * 31556926) return int64(yearsAgo * 31556926)
} }
func (db *TimelineDB) closestEvent(t int64) (EventsRow, error) { func (db *TimelineDB) closestEvents(t int64, n int) ([]EventsRow, error) {
query := ` query := `
select description, timestamp, yearknown, monthknown, dayknown, hourknown, minuteknown, secondknown select description, timestamp, yearknown, monthknown, dayknown, hourknown, minuteknown, secondknown
from events from events
where timestamp is not null where timestamp is not null
order by abs(? - timestamp) asc order by abs(? - timestamp) asc
limit 1 limit ?
` `
var event EventsRow events := make([]EventsRow, n)
stmt, err := db.Prepare(query) stmt, err := db.Prepare(query)
if err != nil { if err != nil {
return event, err return events, err
} }
defer stmt.Close() defer stmt.Close()
err = stmt.QueryRow(t).Scan(&event.description, &event.timestamp, &event.yearknown, &event.monthknown, &event.dayknown, &event.hourknown, &event.minuteknown, &event.secondknown) rows, err := stmt.Query(t, n)
return event, err if err != nil {
return events, err
}
defer rows.Close()
for i := 0; rows.Next(); i++ {
var event EventsRow
err = rows.Scan(&event.description, &event.timestamp, &event.yearknown, &event.monthknown, &event.dayknown, &event.hourknown, &event.minuteknown, &event.secondknown)
if err != nil {
return events, err
}
events[i] = event
}
return events, err
} }
func (event *EventsRow) Output() (int64, string, string, error) { func (event *EventsRow) Output() (int64, string, string, error) {
@ -83,6 +98,7 @@ func (event *EventsRow) Output() (int64, string, string, error) {
func main() { func main() {
percent := flag.Float64("p", -1, "percentage") percent := flag.Float64("p", -1, "percentage")
nevents := flag.Int("n", 1, "number of events")
flag.Parse() flag.Parse()
if *percent < 0 || *percent > 1 { if *percent < 0 || *percent > 1 {
@ -99,15 +115,17 @@ func main() {
} }
defer db.Close() defer db.Close()
event, err := db.closestEvent(t) events, err := db.closestEvents(t, *nevents)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
for _, event := range events {
timestamp, date, desc, err := event.Output() timestamp, date, desc, err := event.Output()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
fmt.Printf("%v\t%v\t%v\n", timestamp, date, desc) fmt.Printf("%v\t%v\t%v\n", timestamp, date, desc)
}
} }