statping/database/time.go

44 lines
1.3 KiB
Go
Raw Permalink Normal View History

2020-02-22 23:52:05 +00:00
package database
import (
"fmt"
"time"
)
type TimeGroup interface {
}
func (it *Db) ParseTime(t string) (time.Time, error) {
switch it.Type {
case "mysql":
return time.Parse("2006-01-02T15:04:05Z", t)
2020-02-22 23:52:05 +00:00
case "postgres":
return time.Parse("2006-01-02T15:04:05Z", t)
default:
return time.Parse("2006-01-02 15:04:05", t)
}
}
2020-08-20 02:50:52 +00:00
// FormatTime returns the timestamp in the same format as the DATETIME column in database
2020-02-22 23:52:05 +00:00
func (it *Db) FormatTime(t time.Time) string {
switch it.Type {
case "postgres":
2020-03-04 10:29:00 +00:00
return t.Format("2006-01-02 15:04:05.999999999")
2020-02-22 23:52:05 +00:00
default:
2020-03-04 10:29:00 +00:00
return t.Format("2006-01-02 15:04:05")
2020-02-22 23:52:05 +00:00
}
}
2020-08-20 02:50:52 +00:00
// SelectByTime returns an SQL query that will group "created_at" column by x seconds and returns as "timeframe"
2020-03-06 09:33:46 +00:00
func (it *Db) SelectByTime(increment time.Duration) string {
seconds := int64(increment.Seconds())
2020-02-22 23:52:05 +00:00
switch it.Type {
case "mysql":
2020-03-06 09:33:46 +00:00
return fmt.Sprintf("FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(created_at) / %d) * %d) AS timeframe", seconds, seconds)
2020-02-22 23:52:05 +00:00
case "postgres":
2020-04-16 09:57:00 +00:00
return fmt.Sprintf("date_trunc('minute', created_at) - (CAST(EXTRACT(MINUTE FROM created_at) AS integer) %% %d) * interval '1 minute' AS timeframe", seconds)
2020-02-22 23:52:05 +00:00
default:
2020-03-06 09:33:46 +00:00
return fmt.Sprintf("datetime((strftime('%%s', created_at) / %d) * %d, 'unixepoch') as timeframe", seconds, seconds)
2020-02-22 23:52:05 +00:00
}
}