statping/database.go

86 lines
1.8 KiB
Go
Raw Normal View History

2018-06-10 01:31:13 +00:00
package main
import (
"fmt"
2018-06-24 06:17:31 +00:00
"time"
"upper.io/db.v3"
2018-06-15 04:30:10 +00:00
"upper.io/db.v3/lib/sqlbuilder"
"upper.io/db.v3/mysql"
"upper.io/db.v3/postgresql"
"upper.io/db.v3/sqlite"
)
var (
dbServer string
sqliteSettings sqlite.ConnectionURL
postgresSettings postgresql.ConnectionURL
mysqlSettings mysql.ConnectionURL
dbSession sqlbuilder.Database
2018-06-10 01:31:13 +00:00
)
2018-06-14 15:24:58 +00:00
func DbConnection(dbType string) error {
2018-06-10 01:31:13 +00:00
var err error
2018-06-15 04:30:10 +00:00
if dbType == "sqlite" {
sqliteSettings = sqlite.ConnectionURL{
Database: "statup.db",
}
dbSession, err = sqlite.Open(sqliteSettings)
if err != nil {
return err
}
} else if dbType == "mysql" {
2018-06-19 04:48:25 +00:00
if configs.Port == "" {
configs.Port = "3306"
}
2018-06-15 04:30:10 +00:00
mysqlSettings = mysql.ConnectionURL{
Database: configs.Database,
Host: configs.Host,
User: configs.User,
Password: configs.Password,
}
dbSession, err = mysql.Open(mysqlSettings)
if err != nil {
return err
}
2018-06-14 15:24:58 +00:00
} else {
2018-06-19 04:48:25 +00:00
if configs.Port == "" {
configs.Port = "5432"
}
host := fmt.Sprintf("%v:%v", configs.Host, configs.Port)
2018-06-15 04:30:10 +00:00
postgresSettings = postgresql.ConnectionURL{
Database: configs.Database,
2018-06-19 04:48:25 +00:00
Host: host,
2018-06-15 04:30:10 +00:00
User: configs.User,
Password: configs.Password,
}
dbSession, err = postgresql.Open(postgresSettings)
if err != nil {
return err
}
2018-06-10 01:31:13 +00:00
}
2018-06-15 04:30:10 +00:00
//dbSession.SetLogging(true)
dbServer = dbType
2018-06-19 04:48:25 +00:00
OnLoad(dbSession)
2018-06-14 06:50:47 +00:00
return err
2018-06-10 01:31:13 +00:00
}
2018-06-23 04:17:57 +00:00
2018-06-24 06:17:31 +00:00
func DatabaseMaintence() {
defer DatabaseMaintence()
since := time.Now().AddDate(0, 0, -7)
DeleteAllSince("failures", since)
DeleteAllSince("hits", since)
time.Sleep(60 * time.Minute)
}
func DeleteAllSince(table string, date time.Time) {
sql := fmt.Sprintf("DELETE FROM %v WHERE created_at < '%v';", table, date.Format("2006-01-02"))
_, err := dbSession.Exec(db.Raw(sql))
if err != nil {
fmt.Println(err)
}
}
2018-06-23 04:17:57 +00:00
func Backup() {
}