github.com/acoshift/pgsql@v0.15.3/pgmodel/filter.go (about)

     1  package pgmodel
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/acoshift/pgsql/pgstmt"
     7  )
     8  
     9  type Cond interface {
    10  	Where(f func(b pgstmt.Cond))
    11  	Having(f func(b pgstmt.Cond))
    12  	OrderBy(col string) pgstmt.OrderBy
    13  	Limit(n int64)
    14  	Offset(n int64)
    15  }
    16  
    17  type Filter interface {
    18  	Apply(ctx context.Context, b Cond) error
    19  }
    20  
    21  type FilterFunc func(ctx context.Context, b Cond) error
    22  
    23  func (f FilterFunc) Apply(ctx context.Context, b Cond) error { return f(ctx, b) }
    24  
    25  func Equal(field string, value any) Filter {
    26  	return Where(func(b pgstmt.Cond) {
    27  		b.Eq(field, value)
    28  	})
    29  }
    30  
    31  func Where(f func(b pgstmt.Cond)) Filter {
    32  	return FilterFunc(func(_ context.Context, b Cond) error {
    33  		b.Where(f)
    34  		return nil
    35  	})
    36  }
    37  
    38  func Having(f func(b pgstmt.Cond)) Filter {
    39  	return FilterFunc(func(_ context.Context, b Cond) error {
    40  		b.Having(f)
    41  		return nil
    42  	})
    43  }
    44  
    45  func OrderBy(col string) Filter {
    46  	return FilterFunc(func(_ context.Context, b Cond) error {
    47  		b.OrderBy(col)
    48  		return nil
    49  	})
    50  }
    51  
    52  func Limit(n int64) Filter {
    53  	return FilterFunc(func(_ context.Context, b Cond) error {
    54  		b.Limit(n)
    55  		return nil
    56  	})
    57  }
    58  
    59  func Offset(n int64) Filter {
    60  	return FilterFunc(func(_ context.Context, b Cond) error {
    61  		b.Offset(n)
    62  		return nil
    63  	})
    64  }
    65  
    66  type condUpdateWrapper struct {
    67  	pgstmt.UpdateStatement
    68  }
    69  
    70  func (c condUpdateWrapper) Having(f func(b pgstmt.Cond)) {}
    71  
    72  func (c condUpdateWrapper) OrderBy(col string) pgstmt.OrderBy { return noopOrderBy{} }
    73  
    74  func (c condUpdateWrapper) Limit(n int64) {}
    75  
    76  func (c condUpdateWrapper) Offset(n int64) {}
    77  
    78  type noopOrderBy struct{}
    79  
    80  func (n noopOrderBy) Asc() pgstmt.OrderBy { return n }
    81  
    82  func (n noopOrderBy) Desc() pgstmt.OrderBy { return n }
    83  
    84  func (n noopOrderBy) NullsFirst() pgstmt.OrderBy { return n }
    85  
    86  func (n noopOrderBy) NullsLast() pgstmt.OrderBy { return n }