query_options.gno

1.24 Kb ยท 55 lines
 1package datastore
 2
 3import (
 4	"errors"
 5	"strings"
 6)
 7
 8var (
 9	ErrEmptyQueryIndexName = errors.New("query index name is empty")
10	ErrInvalidQueryOffset  = errors.New("minimum allowed query offset is 0")
11	ErrInvalidQuerySize    = errors.New("minimum allowed query size is 1")
12)
13
14// QueryOption configures queries.
15type QueryOption func(*Query) error
16
17// WithOffset assigns the offset or position of the first record that query must return.
18// The minimum allowed offset is 0.
19func WithOffset(offset int) QueryOption {
20	return func(q *Query) error {
21		if offset < 0 {
22			return ErrInvalidQueryOffset
23		}
24
25		q.offset = offset
26		return nil
27	}
28}
29
30// WithSize assigns the maximum number of records that query can return.
31// The minimum allowed size is 1.
32func WithSize(size int) QueryOption {
33	return func(q *Query) error {
34		if size < 1 {
35			return ErrInvalidQuerySize
36		}
37
38		q.size = size
39		return nil
40	}
41}
42
43// UseIndex assigns the index that the query must use to get the records.
44// Using an index requires a key value to locate the records within the index.
45func UseIndex(name, key string) QueryOption {
46	return func(q *Query) error {
47		q.indexName = strings.TrimSpace(name)
48		if q.indexName == "" {
49			return ErrEmptyQueryIndexName
50		}
51
52		q.indexKey = key
53		return nil
54	}
55}