Skip to content

Commit

Permalink
Make cleanup database agnostic, fixed #3
Browse files Browse the repository at this point in the history
  • Loading branch information
lixmal committed Feb 25, 2024
1 parent 3d2a611 commit f6b2fb3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
7 changes: 3 additions & 4 deletions pkg/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import (
"fmt"

"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/postgres"
_ "github.com/jinzhu/gorm/dialects/sqlite"
// _ "github.com/jinzhu/gorm/dialects/postgres"
// _ "github.com/jinzhu/gorm/dialects/mysql"
// _ "github.com/jinzhu/gorm/dialects/mssql"

"github.com/lixmal/gdprshare/pkg/config"
)
Expand Down Expand Up @@ -43,4 +42,4 @@ func New(config *config.Config) (*Database, error) {

func (*Database) IsRecordNotFoundError(err error) bool {
return gorm.IsRecordNotFoundError(err)
}
}
22 changes: 12 additions & 10 deletions pkg/misc/misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
"time"

"github.com/lixmal/gdprshare/pkg/config"
"github.com/lixmal/gdprshare/pkg/database"
Expand Down Expand Up @@ -39,20 +40,21 @@ func DeleteStoredFile(f *database.StoredFile, db *database.Database, config *con
}

func Cleanup(db *database.Database, config *config.Config) []error {
var expired []database.StoredFile
now := time.Now()
var errors []error

if errs := db.Where("datetime(created_at, expiry || ' days') < datetime('now')").Find(&expired).GetErrors(); errs != nil {
for _, err := range errs {
if !db.IsRecordNotFoundError(err) {
errors = append(errors, err)
}
}
var files []database.StoredFile
if err := db.Find(&files).Error; err != nil && !db.IsRecordNotFoundError(err) {
return append(errors, fmt.Errorf("fetch files from database: %w", err))
}

for _, v := range expired {
if errs := DeleteStoredFile(&v, db, config); len(errs) > 0 {
errors = append(errors, errs...)
for _, f := range files {
expiryTime := f.CreatedAt.AddDate(0, 0, int(f.Expiry))

if now.After(expiryTime) {
if errs := DeleteStoredFile(&f, db, config); len(errs) > 0 {
errors = append(errors, errs...)
}
}
}

Expand Down

0 comments on commit f6b2fb3

Please sign in to comment.