Implement saving snapshots to a database
This commit is contained in:
39
utils/db.go
39
utils/db.go
@@ -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
|
||||
}
|
||||
|
Reference in New Issue
Block a user