github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/internal/domain/systemssync/repository.go (about)

     1  package systemssync
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/kyma-incubator/compass/components/director/internal/model"
     7  	"github.com/kyma-incubator/compass/components/director/internal/repo"
     8  	"github.com/kyma-incubator/compass/components/director/pkg/resource"
     9  )
    10  
    11  const tableName string = `public.systems_sync_timestamps`
    12  
    13  var (
    14  	tableColumns       = []string{"id", "tenant_id", "product_id", "last_sync_timestamp"}
    15  	conflictingColumns = []string{"id"}
    16  	updateColumns      = []string{"tenant_id", "product_id", "last_sync_timestamp"}
    17  )
    18  
    19  // EntityConverter converts between the service model and entity
    20  //
    21  //go:generate mockery --name=EntityConverter --output=automock --outpkg=automock --case=underscore --disable-version-string
    22  type EntityConverter interface {
    23  	ToEntity(in *model.SystemSynchronizationTimestamp) *Entity
    24  	FromEntity(entity *Entity) *model.SystemSynchronizationTimestamp
    25  }
    26  
    27  type repository struct {
    28  	upserter     repo.UpserterGlobal
    29  	listerGlobal repo.ListerGlobal
    30  	conv         EntityConverter
    31  }
    32  
    33  // NewRepository creates a new SystemsSync repository
    34  func NewRepository(conv EntityConverter) *repository {
    35  	return &repository{
    36  		upserter:     repo.NewUpserterGlobal(resource.SystemsSync, tableName, tableColumns, conflictingColumns, updateColumns),
    37  		listerGlobal: repo.NewListerGlobal(resource.SystemsSync, tableName, tableColumns),
    38  		conv:         conv,
    39  	}
    40  }
    41  
    42  // List returns all system sync timestamps from database
    43  func (r *repository) List(ctx context.Context) ([]*model.SystemSynchronizationTimestamp, error) {
    44  	var entityCollection EntityCollection
    45  
    46  	err := r.listerGlobal.ListGlobal(ctx, &entityCollection)
    47  
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	return r.multipleFromEntities(entityCollection), nil
    53  }
    54  
    55  // Upsert updates sync timestamp or creates new one if it doesn't exist
    56  func (r *repository) Upsert(ctx context.Context, in *model.SystemSynchronizationTimestamp) error {
    57  	sync := r.conv.ToEntity(in)
    58  
    59  	return r.upserter.UpsertGlobal(ctx, sync)
    60  }
    61  
    62  func (r *repository) multipleFromEntities(entities EntityCollection) []*model.SystemSynchronizationTimestamp {
    63  	items := make([]*model.SystemSynchronizationTimestamp, 0, len(entities))
    64  
    65  	for _, entity := range entities {
    66  		sModel := r.conv.FromEntity(entity)
    67  		items = append(items, sModel)
    68  	}
    69  
    70  	return items
    71  }