Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 32 additions & 4 deletions pkg/database/report.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,19 @@ func (r *ReportClient) GetExpiredIPsFromReport(reportID uint) ([]*IP, error) {

func (r *ReportClient) FindById(reportID uint) (*Report, error) {
var report Report
result := r.db.Preload("IPs").Preload("StatsReport").First(&report, reportID)
result := r.db.Preload("StatsReport").First(&report, reportID)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, result.Error
}

err := r.db.Model(&report).Association("IPs").Find(&report.IPs)
if err != nil {
return nil, err
}

return &report, nil
}

Expand All @@ -85,13 +90,19 @@ func (r *ReportClient) FindByHash(filepath string) (*Report, error) {
return nil, err
}

result := r.db.Preload("IPs").Preload("StatsReport").Where("file_hash = ?", hash).First(&report)
result := r.db.Preload("StatsReport").Where("file_hash = ?", hash).First(&report)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, result.Error
}

err = r.db.Model(&report).Association("IPs").Find(&report.IPs)
if err != nil {
return nil, err
}

return &report, nil
}

Expand Down Expand Up @@ -131,10 +142,21 @@ func (r *ReportClient) Find(reportID string) (*Report, error) {

func (r *ReportClient) FindAll() ([]*Report, error) {
reports := []*Report{}
result := r.db.Preload("IPs").Preload("StatsReport").Find(&reports)

// First, get all reports with StatsReport only
result := r.db.Preload("StatsReport").Find(&reports)
if result.Error != nil {
return nil, result.Error
}

// Then load IPs using Association API for each report (GORM handles batching internally)
for _, report := range reports {
err := r.db.Model(report).Association("IPs").Find(&report.IPs)
if err != nil {
return nil, err
}
}

return reports, nil
}

Expand All @@ -158,7 +180,7 @@ func (r *ReportClient) DeleteExpiredSince(expirationDate time.Time) error {

func (r *ReportClient) FilePathExist(filePath string) (*Report, bool, error) {
var reports []Report
result := r.db.Model(&Report{}).Preload("IPs").Where("file_path = ?", filePath).Find(&reports)
result := r.db.Model(&Report{}).Where("file_path = ?", filePath).Find(&reports)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, false, nil
Expand All @@ -168,5 +190,11 @@ func (r *ReportClient) FilePathExist(filePath string) (*Report, bool, error) {
if len(reports) == 0 {
return nil, false, nil
}

err := r.db.Model(&reports[0]).Association("IPs").Find(&reports[0].IPs)
if err != nil {
return nil, false, err
}

return &reports[0], true, nil
}