✨ Database cleaner
This commit is contained in:
parent
f2f75269d5
commit
b2719ae302
@ -1,6 +1,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hydrogen/messaging/pkg/services"
|
||||
"github.com/robfig/cron/v3"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
@ -50,6 +52,11 @@ func main() {
|
||||
server.NewServer()
|
||||
go server.Listen()
|
||||
|
||||
// Configure timed tasks
|
||||
quartz := cron.New(cron.WithLogger(cron.VerbosePrintfLogger(&log.Logger)))
|
||||
quartz.AddFunc("@every 60m", services.DoAutoDatabaseCleanup)
|
||||
quartz.Start()
|
||||
|
||||
// Messages
|
||||
log.Info().Msgf("Messaging v%s is started...", messaging.AppVersion)
|
||||
|
||||
@ -58,4 +65,6 @@ func main() {
|
||||
<-quit
|
||||
|
||||
log.Info().Msgf("Messaging v%s is quitting...", messaging.AppVersion)
|
||||
|
||||
quartz.Stop()
|
||||
}
|
||||
|
@ -5,14 +5,16 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func RunMigration(source *gorm.DB) error {
|
||||
if err := source.AutoMigrate(
|
||||
var DatabaseAutoActionRange = []any{
|
||||
&models.Account{},
|
||||
&models.Channel{},
|
||||
&models.ChannelMember{},
|
||||
&models.Message{},
|
||||
&models.Attachment{},
|
||||
); err != nil {
|
||||
}
|
||||
|
||||
func RunMigration(source *gorm.DB) error {
|
||||
if err := source.AutoMigrate(DatabaseAutoActionRange...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
33
pkg/services/cleaner.go
Normal file
33
pkg/services/cleaner.go
Normal file
@ -0,0 +1,33 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hydrogen/messaging/pkg/database"
|
||||
"git.solsynth.dev/hydrogen/messaging/pkg/models"
|
||||
"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...")
|
||||
|
||||
// Deal soft-deletion
|
||||
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
|
||||
}
|
||||
|
||||
// Clean up outdated chat history
|
||||
tx := database.C.Unscoped().Delete(&models.Message{}, "created_at < ?", time.Now().Add(30*24*time.Hour))
|
||||
if tx.Error != nil {
|
||||
log.Error().Err(tx.Error).Msg("An error occurred when running auth context cleanup...")
|
||||
} else {
|
||||
count += tx.RowsAffected
|
||||
}
|
||||
|
||||
log.Debug().Int64("affected", count).Msg("Clean up entire database accomplished.")
|
||||
}
|
Loading…
Reference in New Issue
Block a user