xbit/main.go

97 lines
1.9 KiB
Go
Raw Normal View History

2024-02-22 03:35:55 +00:00
package main
import (
"database/sql"
"flag"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"math"
"time"
)
2024-02-23 04:24:32 +00:00
type EventsRow struct {
description sql.NullString
timestamp sql.NullInt64
interval sql.NullString
period sql.NullString
yearknown sql.NullBool
monthknown sql.NullBool
dayknown sql.NullBool
hourknown sql.NullBool
minuteknown sql.NullBool
secondknown sql.NullBool
}
type TimelineDB struct {
*sql.DB
2024-02-22 03:35:55 +00:00
}
func formula(p float64) int64 {
yearsAgo := math.Exp(20.3444*math.Pow(p, 3)+3) - math.Exp(3)
return int64(yearsAgo * 31556926)
}
2024-02-23 04:24:32 +00:00
func (db *TimelineDB) closestEvent(t int64) (EventsRow, error) {
var event EventsRow
2024-02-22 03:35:55 +00:00
query := `
2024-02-23 04:24:32 +00:00
select description, timestamp, yearknown, monthknown, dayknown, hourknown, minuteknown, secondknown
2024-02-22 03:35:55 +00:00
from events
where timestamp is not null
order by abs(? - timestamp) asc
limit 1
`
stmt, err := db.Prepare(query)
if err != nil {
return event, err
}
defer stmt.Close()
2024-02-23 04:24:32 +00:00
err = stmt.QueryRow(t).Scan(&event.description, &event.timestamp, &event.yearknown, &event.monthknown, &event.dayknown, &event.hourknown, &event.minuteknown, &event.secondknown)
2024-02-22 03:35:55 +00:00
return event, err
}
2024-02-23 04:33:54 +00:00
func (event *EventsRow) Output() (int64, string, string) {
timestamp, err := event.timestamp.Value()
if err != nil {
log.Fatal(err)
}
desc, err := event.description.Value()
if err != nil {
log.Fatal(err)
}
date := time.Unix(timestamp.(int64), 0)
return timestamp.(int64), date.String(), desc.(string)
}
2024-02-22 03:35:55 +00:00
func main() {
percent := flag.Float64("p", -1, "percentage")
flag.Parse()
if *percent < 0 || *percent > 1 {
log.Fatal("invalid percentage")
}
t := time.Now().Unix() - formula(*percent)
2024-02-23 04:24:32 +00:00
var db TimelineDB
var err error
db.DB, err = sql.Open("sqlite3", "./timeline.db")
2024-02-22 03:35:55 +00:00
if err != nil {
log.Fatal(err)
}
defer db.Close()
2024-02-23 04:24:32 +00:00
event, err := db.closestEvent(t)
if err != nil {
log.Fatal(err)
}
2024-02-23 04:33:54 +00:00
timestamp, date, desc := event.Output()
2024-02-23 04:24:32 +00:00
fmt.Printf("%v\t%v\t%v\n", timestamp, date, desc)
2024-02-22 03:35:55 +00:00
}