search

package
v0.22.14-rc Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 14, 2024 License: MIT Imports: 17 Imported by: 102

Documentation

Index

Constants

View Source
const (
	PageQueryParam      string = "page"
	PerPageQueryParam   string = "perPage"
	SortQueryParam      string = "sort"
	FilterQueryParam    string = "filter"
	SkipTotalQueryParam string = "skipTotal"
)

url search query params

View Source
const (
	SortAsc  string = "ASC"
	SortDesc string = "DESC"
)

sort field directions

View Source
const DefaultPerPage int = 30

DefaultPerPage specifies the default returned search result items.

View Source
const MaxPerPage int = 500

MaxPerPage specifies the maximum allowed search result items returned in a single page.

Variables

This section is empty.

Functions

This section is empty.

Types

type FieldResolver

type FieldResolver interface {
	// UpdateQuery allows to updated the provided db query based on the
	// resolved search fields (eg. adding joins aliases, etc.).
	//
	// Called internally by `search.Provider` before executing the search request.
	UpdateQuery(query *dbx.SelectQuery) error

	// Resolve parses the provided field and returns a properly
	// formatted db identifier (eg. NULL, quoted column, placeholder parameter, etc.).
	Resolve(field string) (*ResolverResult, error)
}

FieldResolver defines an interface for managing search fields.

type FilterData

type FilterData string

FilterData is a filter expression string following the `fexpr` package grammar.

The filter string can also contain dbx placeholder parameters (eg. "title = {:name}"), that will be safely replaced and properly quoted inplace with the placeholderReplacements values.

Example:

var filter FilterData = "id = null || (name = 'test' && status = true) || (total >= {:min} && total <= {:max})"
resolver := search.NewSimpleFieldResolver("id", "name", "status")
expr, err := filter.BuildExpr(resolver, dbx.Params{"min": 100, "max": 200})

func (FilterData) BuildExpr

func (f FilterData) BuildExpr(
	fieldResolver FieldResolver,
	placeholderReplacements ...dbx.Params,
) (dbx.Expression, error)

BuildExpr parses the current filter data and returns a new db WHERE expression.

The filter string can also contain dbx placeholder parameters (eg. "title = {:name}"), that will be safely replaced and properly quoted inplace with the placeholderReplacements values.

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

Provider represents a single configured search provider instance.

func NewProvider

func NewProvider(fieldResolver FieldResolver) *Provider

NewProvider creates and returns a new search provider.

Example:

baseQuery := db.Select("*").From("user")
fieldResolver := search.NewSimpleFieldResolver("id", "name")
models := []*YourDataStruct{}

result, err := search.NewProvider(fieldResolver).
	Query(baseQuery).
	ParseAndExec("page=2&filter=id>0&sort=-email", &models)

func (*Provider) AddFilter

func (s *Provider) AddFilter(filter FilterData) *Provider

AddFilter appends the provided FilterData to the existing provider's filter field.

func (*Provider) AddSort

func (s *Provider) AddSort(field SortField) *Provider

AddSort appends the provided SortField to the existing provider's sort field.

func (*Provider) CountCol added in v0.16.7

func (s *Provider) CountCol(name string) *Provider

CountCol allows changing the default column (id) that is used to generate the COUNT SQL query statement.

This field is ignored if skipTotal is true.

func (*Provider) Exec

func (s *Provider) Exec(items any) (*Result, error)

Exec executes the search provider and fills/scans the provided `items` slice with the found models.

func (*Provider) Filter

func (s *Provider) Filter(filter []FilterData) *Provider

Filter sets the `filter` field of the current search provider.

func (*Provider) Page

func (s *Provider) Page(page int) *Provider

Page sets the `page` field of the current search provider.

Normalization on the `page` value is done during `Exec()`.

func (*Provider) Parse

func (s *Provider) Parse(urlQuery string) error

Parse parses the search query parameter from the provided query string and assigns the found fields to the current search provider.

The data from the "sort" and "filter" query parameters are appended to the existing provider's `sort` and `filter` fields (aka. using `AddSort` and `AddFilter`).

func (*Provider) ParseAndExec

func (s *Provider) ParseAndExec(urlQuery string, modelsSlice any) (*Result, error)

ParseAndExec is a short convenient method to trigger both `Parse()` and `Exec()` in a single call.

func (*Provider) PerPage

func (s *Provider) PerPage(perPage int) *Provider

PerPage sets the `perPage` field of the current search provider.

Normalization on the `perPage` value is done during `Exec()`.

func (*Provider) Query

func (s *Provider) Query(query *dbx.SelectQuery) *Provider

Query sets the base query that will be used to fetch the search items.

func (*Provider) SkipTotal added in v0.17.0

func (s *Provider) SkipTotal(skipTotal bool) *Provider

SkipTotal changes the `skipTotal` field of the current search provider.

func (*Provider) Sort

func (s *Provider) Sort(sort []SortField) *Provider

Sort sets the `sort` field of the current search provider.

type ResolverResult added in v0.11.0

type ResolverResult struct {
	// Identifier is the plain SQL identifier/column that will be used
	// in the final db expression as left or right operand.
	Identifier string

	// NoCoalesce instructs to not use COALESCE or NULL fallbacks
	// when building the identifier expression.
	NoCoalesce bool

	// Params is a map with db placeholder->value pairs that will be added
	// to the query when building both resolved operands/sides in a single expression.
	Params dbx.Params

	// MultiMatchSubQuery is an optional sub query expression that will be added
	// in addition to the combined ResolverResult expression during build.
	MultiMatchSubQuery dbx.Expression

	// AfterBuild is an optional function that will be called after building
	// and combining the result of both resolved operands/sides in a single expression.
	AfterBuild func(expr dbx.Expression) dbx.Expression
}

ResolverResult defines a single FieldResolver.Resolve() successfully parsed result.

type Result

type Result struct {
	Page       int `json:"page"`
	PerPage    int `json:"perPage"`
	TotalItems int `json:"totalItems"`
	TotalPages int `json:"totalPages"`
	Items      any `json:"items"`
}

Result defines the returned search result structure.

type SimpleFieldResolver

type SimpleFieldResolver struct {
	// contains filtered or unexported fields
}

SimpleFieldResolver defines a generic search resolver that allows only its listed fields to be resolved and take part in a search query.

If `allowedFields` are empty no fields filtering is applied.

func NewSimpleFieldResolver

func NewSimpleFieldResolver(allowedFields ...string) *SimpleFieldResolver

NewSimpleFieldResolver creates a new `SimpleFieldResolver` with the provided `allowedFields`.

Each `allowedFields` could be a plain string (eg. "name") or a regexp pattern (eg. `^\w+[\w\.]*$`).

func (*SimpleFieldResolver) Resolve

func (r *SimpleFieldResolver) Resolve(field string) (*ResolverResult, error)

Resolve implements `search.Resolve` interface.

Returns error if `field` is not in `r.allowedFields`.

func (*SimpleFieldResolver) UpdateQuery

func (r *SimpleFieldResolver) UpdateQuery(query *dbx.SelectQuery) error

UpdateQuery implements `search.UpdateQuery` interface.

type SortField

type SortField struct {
	Name      string `json:"name"`
	Direction string `json:"direction"`
}

SortField defines a single search sort field.

func ParseSortFromString

func ParseSortFromString(str string) (fields []SortField)

ParseSortFromString parses the provided string expression into a slice of SortFields.

Example:

fields := search.ParseSortFromString("-name,+created")

func (*SortField) BuildExpr

func (s *SortField) BuildExpr(fieldResolver FieldResolver) (string, error)

BuildExpr resolves the sort field into a valid db sort expression.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL