github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/storage/predicate/predicate.go (about)

     1  package predicate
     2  
     3  import (
     4  	"sort"
     5  
     6  	"github.com/kyma-project/kyma-environment-broker/internal"
     7  
     8  	"github.com/gocraft/dbr"
     9  )
    10  
    11  // {{{ "Functional" Option Interfaces
    12  
    13  // InMemoryPredicate allows to apply predicates for InMemory queries.
    14  type InMemoryPredicate interface {
    15  	ApplyToInMemory([]internal.InstanceWithOperation)
    16  }
    17  
    18  // PostgresPredicate allows to apply predicates for Postgres queries.
    19  type PostgresPredicate interface {
    20  	ApplyToPostgres(*dbr.SelectStmt)
    21  }
    22  
    23  // Predicate defines interface which allows to make a generic func signature
    24  // between different driver implementations
    25  type Predicate interface {
    26  	PostgresPredicate
    27  	InMemoryPredicate
    28  }
    29  
    30  // }}}
    31  
    32  // {{{ Multi-Type Options
    33  
    34  // SortAscByCreatedAt sorts the query output based on CreatedAt field on Instance.
    35  func SortAscByCreatedAt() SortByCreatedAt {
    36  	return SortByCreatedAt{}
    37  }
    38  
    39  type SortByCreatedAt struct{}
    40  
    41  func (w SortByCreatedAt) ApplyToPostgres(stmt *dbr.SelectStmt) {
    42  	stmt.OrderAsc("instances.created_at")
    43  }
    44  
    45  // TODO: It can be more generic but right now there's no reason to complicate it.
    46  func (w SortByCreatedAt) ApplyToInMemory(in []internal.InstanceWithOperation) {
    47  	sort.Slice(in, func(i, j int) bool {
    48  		return in[i].CreatedAt.Before(in[j].CreatedAt)
    49  	})
    50  }
    51  
    52  var _ InMemoryPredicate = &SortByCreatedAt{}
    53  var _ PostgresPredicate = &SortByCreatedAt{}
    54  
    55  // }}}