backup-notify/database/backups.go

96 lines
2.0 KiB
Go
Raw Normal View History

2024-04-21 21:46:40 -04:00
package database
import (
"database/sql"
"log"
"time"
)
type Backup struct {
Hostname string
ReceivedOn time.Time
}
func ListBackups(dbConn *sql.DB) ([]Backup, error) {
log.Println("listing backups")
rows, err := dbConn.Query(`SELECT hostname, received_on FROM backups;`)
if err != nil {
return nil, err
}
defer rows.Close()
backups := []Backup{}
for rows.Next() {
var backup Backup
err := rows.Scan(&backup.Hostname, &backup.ReceivedOn)
if err != nil {
return nil, err
}
backups = append(backups, backup)
}
return backups, nil
}
func DeleteOldBackups(dbConn *sql.DB, days int) error {
log.Println("deleting old backups")
duration := time.Duration(days) * 24 * time.Hour
_, err := dbConn.Exec(`DELETE FROM backups WHERE received_on < ?;`, time.Now().Add(-duration))
return err
}
func ReceivedBackup(dbConn *sql.DB, hostname string) error {
log.Println("received backup for", hostname)
_, err := dbConn.Exec(`INSERT INTO backups (hostname) VALUES (?);`, hostname)
return err
}
func BackupedHostnamesInTheLastDay(dbConn *sql.DB) ([]string, error) {
log.Println("listing hostnames that have been backed up in the last day")
rows, err := dbConn.Query(`SELECT DISTINCT hostname FROM backups WHERE received_on > ?;`, time.Now().Add(-24*time.Hour))
if err != nil {
return nil, err
}
defer rows.Close()
hostnames := []string{}
for rows.Next() {
var hostname string
err := rows.Scan(&hostname)
if err != nil {
return nil, err
}
hostnames = append(hostnames, hostname)
}
return hostnames, nil
}
func ReceivedHostnames(dbConn *sql.DB) ([]string, error) {
log.Println("listing received hostnames")
rows, err := dbConn.Query(`SELECT DISTINCT hostname FROM backups;`)
if err != nil {
return nil, err
}
defer rows.Close()
hostnames := []string{}
for rows.Next() {
var hostname string
err := rows.Scan(&hostname)
if err != nil {
return nil, err
}
hostnames = append(hostnames, hostname)
}
return hostnames, nil
}