✨ Database Cleaner
This commit is contained in:
@ -3,6 +3,8 @@ package main
|
||||
import (
|
||||
"git.solsynth.dev/hydrogen/interactive/pkg/grpc"
|
||||
"git.solsynth.dev/hydrogen/interactive/pkg/server"
|
||||
"git.solsynth.dev/hydrogen/interactive/pkg/services"
|
||||
"github.com/robfig/cron/v3"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
@ -45,6 +47,11 @@ func main() {
|
||||
}
|
||||
}()
|
||||
|
||||
// Configure timed tasks
|
||||
quartz := cron.New(cron.WithLogger(cron.VerbosePrintfLogger(&log.Logger)))
|
||||
quartz.AddFunc("@every 60m", services.DoAutoDatabaseCleanup)
|
||||
quartz.Start()
|
||||
|
||||
// Server
|
||||
server.NewServer()
|
||||
go server.Listen()
|
||||
@ -57,4 +64,6 @@ func main() {
|
||||
<-quit
|
||||
|
||||
log.Info().Msgf("Interactive v%s is quitting...", interactive.AppVersion)
|
||||
|
||||
quartz.Stop()
|
||||
}
|
||||
|
@ -5,19 +5,24 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var DatabaseAutoActionRange = []any{
|
||||
&models.Account{},
|
||||
&models.Realm{},
|
||||
&models.RealmMember{},
|
||||
&models.Category{},
|
||||
&models.Tag{},
|
||||
&models.Moment{},
|
||||
&models.Article{},
|
||||
&models.Comment{},
|
||||
&models.Reaction{},
|
||||
&models.Attachment{},
|
||||
}
|
||||
|
||||
func RunMigration(source *gorm.DB) error {
|
||||
if err := source.AutoMigrate(
|
||||
&models.Account{},
|
||||
&models.AccountMembership{},
|
||||
&models.Realm{},
|
||||
&models.RealmMember{},
|
||||
&models.Category{},
|
||||
&models.Tag{},
|
||||
&models.Moment{},
|
||||
&models.Article{},
|
||||
&models.Comment{},
|
||||
&models.Reaction{},
|
||||
&models.Attachment{},
|
||||
append([]any{
|
||||
&models.AccountMembership{},
|
||||
}, DatabaseAutoActionRange...)...,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
23
pkg/services/cleaner.go
Normal file
23
pkg/services/cleaner.go
Normal file
@ -0,0 +1,23 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hydrogen/interactive/pkg/database"
|
||||
"github.com/rs/zerolog/log"
|
||||
"time"
|
||||
)
|
||||
|
||||
func DoAutoDatabaseCleanup() {
|
||||
deadline := time.Now().Add(60 * time.Minute)
|
||||
log.Debug().Time("deadline", deadline).Msg("Now cleaning up entire database...")
|
||||
|
||||
var count int64
|
||||
for _, model := range database.DatabaseAutoActionRange {
|
||||
tx := database.C.Unscoped().Delete(model, "deleted_at >= ?", deadline)
|
||||
if tx.Error != nil {
|
||||
log.Error().Err(tx.Error).Msg("An error occurred when running auth context cleanup...")
|
||||
}
|
||||
count += tx.RowsAffected
|
||||
}
|
||||
|
||||
log.Debug().Int64("affected", count).Msg("Clean up entire database accomplished.")
|
||||
}
|
Reference in New Issue
Block a user