github.com/aacfactory/fns-contrib/databases/sql@v1.2.84/dac/view.go (about)

     1  package dac
     2  
     3  import (
     4  	"github.com/aacfactory/errors"
     5  	"github.com/aacfactory/fns-contrib/databases/sql"
     6  	"github.com/aacfactory/fns-contrib/databases/sql/dac/specifications"
     7  	"github.com/aacfactory/fns/context"
     8  )
     9  
    10  func Views[V View](ctx context.Context, offset int, length int, options ...QueryOption) (entries []V, err error) {
    11  	opt := QueryOptions{}
    12  	for _, option := range options {
    13  		option(&opt)
    14  	}
    15  
    16  	_, query, arguments, fields, buildErr := specifications.BuildView[V](
    17  		ctx,
    18  		specifications.Condition{Condition: opt.cond},
    19  		specifications.Orders(opt.orders),
    20  		specifications.GroupBy{GroupBy: opt.groupBy},
    21  		offset, length,
    22  	)
    23  	if buildErr != nil {
    24  		err = errors.Warning("sql: view failed").WithCause(buildErr)
    25  		return
    26  	}
    27  
    28  	rows, queryErr := sql.Query(ctx, query, arguments...)
    29  	if queryErr != nil {
    30  		err = errors.Warning("sql: view failed").WithCause(queryErr)
    31  		return
    32  	}
    33  
    34  	entries, err = specifications.ScanRows[V](ctx, rows, fields)
    35  	_ = rows.Close()
    36  	if err != nil {
    37  		err = errors.Warning("sql: view failed").WithCause(err)
    38  		return
    39  	}
    40  	return
    41  }
    42  
    43  func ViewOne[V View](ctx context.Context, options ...QueryOption) (entry V, has bool, err error) {
    44  	entries, queryErr := Views[V](ctx, 0, 1, options...)
    45  	if queryErr != nil {
    46  		err = queryErr
    47  		return
    48  	}
    49  	has = len(entries) == 1
    50  	if has {
    51  		entry = entries[0]
    52  	}
    53  	return
    54  }
    55  
    56  func ViewALL[V View](ctx context.Context, options ...QueryOption) (entries []V, err error) {
    57  	entries, err = Views[V](ctx, 0, 0, options...)
    58  	return
    59  }