-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathimage.go
More file actions
66 lines (52 loc) · 1.75 KB
/
image.go
File metadata and controls
66 lines (52 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package store
import (
"context"
"gorm.io/gorm"
"github.com/kubev2v/migration-planner/internal/store/model"
)
type ImageInfra interface {
Create(ctx context.Context, imageInfra model.ImageInfra) (*model.ImageInfra, error)
Update(ctx context.Context, imageInfra model.ImageInfra) (*model.ImageInfra, error)
UpdateAgentVersion(ctx context.Context, sourceID string, agentVersion string) error
}
type ImageInfraStore struct {
db *gorm.DB
}
func NewImageInfraStore(db *gorm.DB) ImageInfra {
return &ImageInfraStore{db: db}
}
func (i *ImageInfraStore) Create(ctx context.Context, image model.ImageInfra) (*model.ImageInfra, error) {
if err := i.getDB(ctx).WithContext(ctx).Create(&image).Error; err != nil {
return nil, err
}
return &image, nil
}
func (i *ImageInfraStore) Update(ctx context.Context, image model.ImageInfra) (*model.ImageInfra, error) {
// Exclude agent_version to prevent overwriting concurrent updates from OVA downloads
if err := i.getDB(ctx).WithContext(ctx).Omit("agent_version").Save(&image).Error; err != nil {
return nil, err
}
return &image, nil
}
// UpdateAgentVersion atomically updates only the agent_version field for a given source_id.
// This prevents race conditions when multiple concurrent downloads occur.
func (i *ImageInfraStore) UpdateAgentVersion(ctx context.Context, sourceID string, agentVersion string) error {
result := i.getDB(ctx).WithContext(ctx).
Model(&model.ImageInfra{}).
Where("source_id = ?", sourceID).
Update("agent_version", agentVersion)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return ErrRecordNotFound
}
return nil
}
func (i *ImageInfraStore) getDB(ctx context.Context) *gorm.DB {
tx := FromContext(ctx)
if tx != nil {
return tx
}
return i.db
}