Implement saving snapshots to a database

This commit is contained in:
2025-07-20 11:38:08 +02:00
parent 22f991e72e
commit b785d24a08
6 changed files with 60 additions and 8 deletions

View File

@@ -1,8 +1,11 @@
package utils
import (
"fmt"
"path/filepath"
"time"
"git.site.quack-lab.dev/dave/cylogger"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
@@ -10,6 +13,13 @@ import (
type DB interface {
DB() *gorm.DB
Raw(sql string, args ...any) *gorm.DB
SaveFile(filePath string, fileData []byte) error
}
type FileSnapshot struct {
Date time.Time `gorm:"primaryKey"`
FilePath string `gorm:"primaryKey"`
FileData []byte `gorm:"type:blob"`
}
type DBWrapper struct {
@@ -30,11 +40,11 @@ func GetDB() (DB, error) {
if err != nil {
return nil, err
}
db.AutoMigrate(&FileSnapshot{})
return &DBWrapper{db: db}, nil
}
// Just a wrapper
func (db *DBWrapper) Raw(sql string, args ...any) *gorm.DB {
return db.db.Raw(sql, args...)
@@ -43,3 +53,30 @@ func (db *DBWrapper) Raw(sql string, args ...any) *gorm.DB {
func (db *DBWrapper) DB() *gorm.DB {
return db.db
}
func (db *DBWrapper) FileExists(filePath string) (bool, error) {
var count int64
err := db.db.Model(&FileSnapshot{}).Where("file_path = ?", filePath).Count(&count).Error
return count > 0, err
}
func (db *DBWrapper) SaveFile(filePath string, fileData []byte) error {
log := cylogger.Default.WithPrefix(fmt.Sprintf("SaveFile: %q", filePath))
exists, err := db.FileExists(filePath)
if err != nil {
log.Error("Error checking if file exists: %v", err)
return err
}
log.Debug("File exists: %t", exists)
// Nothing to do, file already exists
if exists {
log.Debug("File already exists, skipping save")
return nil
}
log.Debug("Saving file to database")
return db.db.Create(&FileSnapshot{
Date: time.Now(),
FilePath: filePath,
FileData: fileData,
}).Error
}

View File

@@ -16,7 +16,6 @@ type ModifyCommand struct {
Regex string `yaml:"regex"`
Lua string `yaml:"lua"`
Files []string `yaml:"files"`
Git bool `yaml:"git"`
Reset bool `yaml:"reset"`
LogLevel string `yaml:"loglevel"`
Isolate bool `yaml:"isolate"`