64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
package database
|
||
|
||
import (
|
||
"fmt"
|
||
"strings"
|
||
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
// DriverName 从 GORM 连接获取驱动名(sqlite / mysql / postgres)// Logan.Li
|
||
func DriverName(db *gorm.DB) string {
|
||
if db == nil || db.Dialector == nil {
|
||
return "mysql"
|
||
}
|
||
name := strings.ToLower(db.Dialector.Name())
|
||
switch {
|
||
case strings.Contains(name, "sqlite"):
|
||
return "sqlite"
|
||
case strings.Contains(name, "postgres"):
|
||
return "postgres"
|
||
default:
|
||
return "mysql"
|
||
}
|
||
}
|
||
|
||
// HourBucketExpr 按小时分桶表达式(跨 SQLite / MySQL)// Logan.Li
|
||
func HourBucketExpr(driver string) string {
|
||
switch driver {
|
||
case "sqlite":
|
||
return "cast(strftime('%s', report_time) as integer) / 3600"
|
||
default:
|
||
return "UNIX_TIMESTAMP(report_time) DIV 3600"
|
||
}
|
||
}
|
||
|
||
// CleanupAgentReportsSQL 清理 7 天前 Agent 上报 // Logan.Li
|
||
func CleanupAgentReportsSQL(driver string) string {
|
||
switch driver {
|
||
case "sqlite":
|
||
return "DELETE FROM monitor_agent_reports WHERE report_time < datetime('now', '-7 days')"
|
||
default:
|
||
return "DELETE FROM monitor_agent_reports WHERE report_time < DATE_SUB(NOW(), INTERVAL 7 DAY)"
|
||
}
|
||
}
|
||
|
||
// CleanupSNMPMetricsSQL 清理超期 SNMP 采集指标 // Logan.Li
|
||
func CleanupSNMPMetricsSQL(driver string, retentionDays int) string {
|
||
if retentionDays <= 0 {
|
||
retentionDays = 7
|
||
}
|
||
switch driver {
|
||
case "sqlite":
|
||
return fmt.Sprintf(
|
||
"DELETE FROM monitor_snmp_samples WHERE timestamp < CAST(strftime('%%s', 'now', '-%d days') AS INTEGER)",
|
||
retentionDays,
|
||
)
|
||
default:
|
||
return fmt.Sprintf(
|
||
"DELETE FROM monitor_snmp_samples WHERE timestamp < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL %d DAY))",
|
||
retentionDays,
|
||
)
|
||
}
|
||
}
|