refac: removed ugly multi-line method chaining

This commit is contained in:
fsylvain committed 2026-10-10 20:49:05 +02:00
1 parent e8dff6bb5f
commit ce9c876db6
6 files changed
+72 -67

No files matched your search

@@ -64,22 +64,24 @@ func (a *APIKeyRepository) list(query *gorm.DB) ([]domainAPIKey.APIKey, error) {
} }
func (a *APIKeyRepository) Revoke(id uint32, at time.Time) error { func (a *APIKeyRepository) Revoke(id uint32, at time.Time) error {
result := a.db.Model(&entity.APIKey{}). query := a.db.Model(&entity.APIKey{})
Where("id = ? AND revoked_at IS NULL", id). query = query.Where("id = ? AND revoked_at IS NULL", id)
Update("revoked_at", at) result := query.Update("revoked_at", at)
return result.Error return result.Error
} }
func (a *APIKeyRepository) RevokeAllByUser(userId uint32, at time.Time) error { func (a *APIKeyRepository) RevokeAllByUser(userId uint32, at time.Time) error {
return a.db.Model(&entity.APIKey{}). query := a.db.Model(&entity.APIKey{})
Where("user_id = ? AND revoked_at IS NULL", userId). query = query.Where("user_id = ? AND revoked_at IS NULL", userId)
Update("revoked_at", at).Error result := query.Update("revoked_at", at)
return result.Error
} }
func (a *APIKeyRepository) TouchLastUsed(id uint32, at time.Time) error { func (a *APIKeyRepository) TouchLastUsed(id uint32, at time.Time) error {
return a.db.Model(&entity.APIKey{}). query := a.db.Model(&entity.APIKey{})
Where("id = ?", id). query = query.Where("id = ?", id)
Update("last_used_at", at).Error result := query.Update("last_used_at", at)
return result.Error
} }
var _ domainAPIKey.Repository = &APIKeyRepository{} var _ domainAPIKey.Repository = &APIKeyRepository{}
@@ -131,21 +131,21 @@ type countsRow struct {
func (a *AuditEventRepository) countsBetween(from time.Time, to time.Time) (countsRow, error) { func (a *AuditEventRepository) countsBetween(from time.Time, to time.Time) (countsRow, error) {
var row countsRow var row countsRow
err := a.db.Model(&entity.AuditEvent{}). query := a.db.Model(&entity.AuditEvent{})
Select("COUNT(*) AS total, "+ query = query.Select("COUNT(*) AS total, "+
"COALESCE(SUM(CASE WHEN outcome = ? THEN 1 ELSE 0 END), 0) AS failed, "+ "COALESCE(SUM(CASE WHEN outcome = ? THEN 1 ELSE 0 END), 0) AS failed, "+
"COALESCE(SUM(CASE WHEN security = ? THEN 1 ELSE 0 END), 0) AS security", string(audit.OutcomeFailed), true). "COALESCE(SUM(CASE WHEN security = ? THEN 1 ELSE 0 END), 0) AS security", string(audit.OutcomeFailed), true)
Where("created_at >= ? AND created_at < ?", from.UTC(), to.UTC()). query = query.Where("created_at >= ? AND created_at < ?", from.UTC(), to.UTC())
Scan(&row).Error err := query.Scan(&row).Error
return row, err return row, err
} }
func (a *AuditEventRepository) distinctActors(actorType audit.ActorType, from time.Time, to time.Time) (int, error) { func (a *AuditEventRepository) distinctActors(actorType audit.ActorType, from time.Time, to time.Time) (int, error) {
var count int64 var count int64
err := a.db.Model(&entity.AuditEvent{}). query := a.db.Model(&entity.AuditEvent{})
Where("actor_type = ? AND created_at >= ? AND created_at < ?", string(actorType), from.UTC(), to.UTC()). query = query.Where("actor_type = ? AND created_at >= ? AND created_at < ?", string(actorType), from.UTC(), to.UTC())
Distinct("actor_id"). query = query.Distinct("actor_id")
Count(&count).Error err := query.Count(&count).Error
return int(count), err return int(count), err
} }
@@ -215,11 +215,11 @@ func (a *AuditEventRepository) DeleteOldest(limit int, before time.Time) (int, e
return 0, nil return 0, nil
} }
var ids []uint64 var ids []uint64
err := a.db.Model(&entity.AuditEvent{}). query := a.db.Model(&entity.AuditEvent{})
Where("created_at < ?", before.UTC()). query = query.Where("created_at < ?", before.UTC())
Order("created_at ASC, id ASC"). query = query.Order("created_at ASC, id ASC")
Limit(limit). query = query.Limit(limit)
Pluck("id", &ids).Error err := query.Pluck("id", &ids).Error
if err != nil { if err != nil {
return 0, err return 0, err
} }
@@ -123,11 +123,12 @@ func (i ImageRepository) ListByStoredNames(storedNames []string) ([]domain.Image
} }
func (i ImageRepository) duplicatedHashes() *gorm.DB { func (i ImageRepository) duplicatedHashes() *gorm.DB {
return i.db.Model(&entity.Image{}). query := i.db.Model(&entity.Image{})
Select("sha256"). query = query.Select("sha256")
Where("sha256 <> ''"). query = query.Where("sha256 <> ''")
Group("sha256"). query = query.Group("sha256")
Having("COUNT(*) > 1") query = query.Having("COUNT(*) > 1")
return query
} }
func imagesToDomain(models []entity.Image) []domain.Image { func imagesToDomain(models []entity.Image) []domain.Image {
@@ -36,10 +36,12 @@ func (v *VariantFileRepository) Find(variantName string, sourceName string) (dom
func (v *VariantFileRepository) Save(file domain.VariantFile) (domain.VariantFile, error) { func (v *VariantFileRepository) Save(file domain.VariantFile) (domain.VariantFile, error) {
model := mappers.VariantFileToModel(file) model := mappers.VariantFileToModel(file)
model.ID = 0 model.ID = 0
err := v.db.Clauses(clause.OnConflict{ upsert := clause.OnConflict{
Columns: []clause.Column{{Name: "variant_name"}, {Name: "source_name"}}, Columns: []clause.Column{{Name: "variant_name"}, {Name: "source_name"}},
DoUpdates: clause.AssignmentColumns([]string{"cached_name", "content_type", "size", "fingerprint"}), DoUpdates: clause.AssignmentColumns([]string{"cached_name", "content_type", "size", "fingerprint"}),
}).Create(&model).Error }
query := v.db.Clauses(upsert)
err := query.Create(&model).Error
if err != nil { if err != nil {
return domain.VariantFile{}, err return domain.VariantFile{}, err
} }
@@ -77,10 +79,10 @@ func (v *VariantFileRepository) TotalsBySource() (map[string]domain.VariantFileT
Files int Files int
Bytes int64 Bytes int64
} }
err := v.db.Model(&entity.ImageVariantFile{}). query := v.db.Model(&entity.ImageVariantFile{})
Select("source_name, COUNT(*) AS files, COALESCE(SUM(size), 0) AS bytes"). query = query.Select("source_name, COUNT(*) AS files, COALESCE(SUM(size), 0) AS bytes")
Group("source_name"). query = query.Group("source_name")
Scan(&rows).Error err := query.Scan(&rows).Error
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -104,10 +106,10 @@ func (v *VariantFileRepository) UnusedTotals(filter domain.UnusedFilter) (domain
Files int Files int
Bytes int64 Bytes int64
} }
err := v.db.Model(&entity.ImageVariantFile{}). query := v.db.Model(&entity.ImageVariantFile{})
Select("COUNT(*) AS files, COALESCE(SUM(size), 0) AS bytes"). query = query.Select("COUNT(*) AS files, COALESCE(SUM(size), 0) AS bytes")
Where(unusedCondition, filter.VariantNames, filter.Cutoff.UTC()). query = query.Where(unusedCondition, filter.VariantNames, filter.Cutoff.UTC())
Scan(&row).Error err := query.Scan(&row).Error
if err != nil { if err != nil {
return domain.VariantFileTotals{}, err return domain.VariantFileTotals{}, err
} }
@@ -120,12 +122,12 @@ func (v *VariantFileRepository) TopSources(limit int) ([]domain.SourceTotals, er
Files int Files int
Bytes int64 Bytes int64
} }
err := v.db.Model(&entity.ImageVariantFile{}). query := v.db.Model(&entity.ImageVariantFile{})
Select("source_name, COUNT(*) AS files, COALESCE(SUM(size), 0) AS bytes"). query = query.Select("source_name, COUNT(*) AS files, COALESCE(SUM(size), 0) AS bytes")
Group("source_name"). query = query.Group("source_name")
Order(topSourcesOrder). query = query.Order(topSourcesOrder)
Limit(limit). query = query.Limit(limit)
Scan(&rows).Error err := query.Scan(&rows).Error
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -167,10 +169,10 @@ func (v *VariantFileRepository) Totals() (map[string]domain.VariantFileTotals, e
Files int Files int
Bytes int64 Bytes int64
} }
err := v.db.Model(&entity.ImageVariantFile{}). query := v.db.Model(&entity.ImageVariantFile{})
Select("variant_name, COUNT(*) AS files, COALESCE(SUM(size), 0) AS bytes"). query = query.Select("variant_name, COUNT(*) AS files, COALESCE(SUM(size), 0) AS bytes")
Group("variant_name"). query = query.Group("variant_name")
Scan(&rows).Error err := query.Scan(&rows).Error
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -40,10 +40,10 @@ func (v *VariantUsageRepository) Record(batch domain.VariantUsageBatch) error {
func recordHit(tx *gorm.DB, hit domain.VariantHit) error { func recordHit(tx *gorm.DB, hit domain.VariantHit) error {
at := hit.At.UTC() at := hit.At.UTC()
return tx.Model(&entity.ImageVariantFile{}). query := tx.Model(&entity.ImageVariantFile{})
Where("variant_name = ? AND source_name = ?", hit.VariantName, hit.SourceName). query = query.Where("variant_name = ? AND source_name = ?", hit.VariantName, hit.SourceName)
Where("last_requested_at IS NULL OR last_requested_at < ?", at). query = query.Where("last_requested_at IS NULL OR last_requested_at < ?", at)
Update("last_requested_at", at).Error return query.Update("last_requested_at", at).Error
} }
func recordRejections(tx *gorm.DB, rejection domain.RejectionCount) error { func recordRejections(tx *gorm.DB, rejection domain.RejectionCount) error {
@@ -56,9 +56,9 @@ func recordRejections(tx *gorm.DB, rejection domain.RejectionCount) error {
func (v *VariantUsageRepository) RejectedSince(day time.Time) (int, error) { func (v *VariantUsageRepository) RejectedSince(day time.Time) (int, error) {
var total int var total int
err := v.db.Model(&entity.ImageVariantRejectionDay{}). query := v.db.Model(&entity.ImageVariantRejectionDay{})
Select("COALESCE(SUM(count), 0)"). query = query.Select("COALESCE(SUM(count), 0)")
Where("day >= ?", day.UTC().Format(domain.RejectionDayLayout)). query = query.Where("day >= ?", day.UTC().Format(domain.RejectionDayLayout))
Scan(&total).Error err := query.Scan(&total).Error
return total, err return total, err
} }
@@ -46,13 +46,13 @@ func (i *InviteRepository) Delete(id uint32) error {
} }
func (i *InviteRepository) Renew(id uint32, hashedCode string, expiresAt time.Time, createdAt time.Time) (domainInvite.Invite, error) { func (i *InviteRepository) Renew(id uint32, hashedCode string, expiresAt time.Time, createdAt time.Time) (domainInvite.Invite, error) {
result := i.db.Model(&entity.Invite{}). query := i.db.Model(&entity.Invite{})
Where("id = ? AND accepted_at IS NULL", id). query = query.Where("id = ? AND accepted_at IS NULL", id)
Updates(map[string]any{ result := query.Updates(map[string]any{
"hashed_code": hashedCode, "hashed_code": hashedCode,
"expires_at": expiresAt, "expires_at": expiresAt,
"created_at": createdAt, "created_at": createdAt,
}) })
if err := deleteOrNotFound(result, domainInvite.ErrInviteNotFound); err != nil { if err := deleteOrNotFound(result, domainInvite.ErrInviteNotFound); err != nil {
return domainInvite.Invite{}, err return domainInvite.Invite{}, err
} }
@@ -67,9 +67,9 @@ func (i *InviteRepository) Renew(id uint32, hashedCode string, expiresAt time.Ti
func (i *InviteRepository) AcceptWithUser(inviteID uint32, acceptedAt time.Time, newUser domainUser.User) (domainUser.User, error) { func (i *InviteRepository) AcceptWithUser(inviteID uint32, acceptedAt time.Time, newUser domainUser.User) (domainUser.User, error) {
createdModel := mappers.UserToModel(newUser) createdModel := mappers.UserToModel(newUser)
err := i.db.Transaction(func(tx *gorm.DB) error { err := i.db.Transaction(func(tx *gorm.DB) error {
marked := tx.Model(&entity.Invite{}). query := tx.Model(&entity.Invite{})
Where("id = ? AND accepted_at IS NULL", inviteID). query = query.Where("id = ? AND accepted_at IS NULL", inviteID)
Update("accepted_at", acceptedAt) marked := query.Update("accepted_at", acceptedAt)
if err := deleteOrNotFound(marked, domainInvite.ErrInviteNotFound); err != nil { if err := deleteOrNotFound(marked, domainInvite.ErrInviteNotFound); err != nil {
return err return err
} }