query

package
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2024 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package query offers a flexible and extensible query builder for creating complex queries. It is designed to facilitate the construction of database queries in a structured and type-safe manner. The package provides various parameter types to specify different aspects of a query, such as filtering, sorting, grouping, and pagination.

The query builder supports the creation of queries with multiple conditions and configurations, allowing for precise control over the retrieved data. It is especially useful in scenarios where dynamic query generation based on user input or application logic is required.

Key Features:

  • Type-safe query parameters: Ensures that only valid query structures are created, reducing runtime errors.
  • Extensible design: Easy to extend with new parameter types as needed.
  • Readability: The query builder syntax is designed to be readable and easy to understand.
  • Integration with stores: Seamlessly integrates with various data store implementations, providing a unified querying interface.

Example Usage: The following example demonstrates the use of the query package to build a complex query with multiple parameters:

query.NewParams(
	query.Select("ID", "Name"),
	query.Filter("Status", "Active"),
	query.OrderBy("CreatedAt", true),
	query.GroupBy("Category"),
	query.Paginate(0, 10),
)

This creates a query that selects the 'ID' and 'Name' fields, filters records by 'Status', orders them by 'CreatedAt' in descending order, groups them by 'Category', and applies pagination to retrieve the first 10 records.

The query package is versatile and can be adapted to various data retrieval needs, making it a valuable tool for developers working with data stores in Go.

Index

Constants

View Source
const (
	// TypeFilter represents the type name for filter parameters in a query.
	// These parameters define conditions that data must meet to be included in the result set.
	TypeFilter = "filter"

	// TypeGroupBy represents the type name for group-by parameters in a query.
	// These parameters specify the fields that the result set should be grouped by.
	TypeGroupBy = "groupby"

	// TypeSelect represents the type name for select parameters in a query.
	// These parameters indicate the specific fields to be returned in the result set.
	TypeSelect = "select"

	// TypeOR represents the type name for OR logical operator parameters in a query.
	// These parameters are used to combine multiple conditions with OR logic, where any condition being true will
	// result in a match.
	TypeOR = "or"

	// TypeOrderBy represents the type name for order-by parameters in a query.
	// These parameters define the sorting order of the result set based on specified fields.
	TypeOrderBy = "orderby"

	// TypePaginate represents the type name for pagination parameters in a query.
	// These parameters control the slicing of the result set into manageable segments, defining the offset and limit.
	TypePaginate = "paginate"

	// TypePreload represents the type name for preload parameters in a query.
	// These parameters specify related entities or fields that should be loaded along with the primary query results.
	TypePreload = "preload"

	// TypeWithLock represents the type name for the lock-for-update clause parameters in a query.
	// These parameters specify the lock mode to be used: "FOR UPDATE".
	TypeWithLock = "withlock"
)

Variables

This section is empty.

Functions

func FilterGetter

func FilterGetter(name string) func(Params) (FilterParam, bool)

FilterGetter creates a function to retrieve a FilterParam from Params by a given name.

Parameters:

  • name: The name of the filter parameter to retrieve.

Returns: A function that takes Params and returns a FilterParam and a boolean indicating whether it was found.

Types

type FilterParam

type FilterParam struct {
	Name     string
	Operator Operator
	Value    any
}

FilterParam represents a query parameter used for filtering data. It encapsulates the necessary information to construct a part of a query that filters data based on a specific field, operator, and value.

Fields: - Name: The name of the field in the data store to apply the filter on. - Operator: The operator (e.g., equals, greater than) used for comparing the field's value with the provided value. - Value: The value to be used in comparison for filtering.

func Filter

func Filter(fieldName string, value any) FilterParam

Filter creates a new FilterParam with the specified field name and value. The default operator used for the filter is EQ (equals). To use a different operator, chain the resulting FilterParam with the WithOP method.

Parameters:

  • fieldName: The name of the field to filter on.
  • value: The value to compare against the field's value.

Returns: A new FilterParam with the specified field name, value, and default operator EQ.

Examples:

query.Filter("id", 1) // creates a filter to check if 'id' equals 1.
query.Filter("id", 1).WithOP(query.GT) // creates a filter to check if 'id' is greater than 1.

func (FilterParam) ParamType

func (p FilterParam) ParamType() string

ParamType returns the type of this parameter, which is `filter`. This method can be used to differentiate FilterParam from other types of query parameters in a system where multiple parameter types are used.

func (FilterParam) WithOP

func (p FilterParam) WithOP(op Operator) FilterParam

WithOP returns a new FilterParam instance with the specified Operator, keeping the field name and value unchanged. This method is useful for changing the comparison operator for an existing FilterParam.

Parameters:

  • op: The new Operator to be used for the filter.

Returns: A new FilterParam with the updated operator.

type GroupByParam

type GroupByParam struct {
	Names  []string
	Option string
	Having []FilterParam
}

GroupByParam represents a parameter used to group data in a query. It specifies the fields by which the data should be grouped.

This is useful in aggregate queries where you need to group data by certain fields before applying aggregate functions.

Fields:

  • Names: A slice of field names to group by.
  • Option: Additional options to apply to the group by operation, such as "ROLLUP".
  • Having: A slice of FilterParam to specify the 'HAVING' clause conditions after grouping.

Note: Using GroupByParam can make your code tightly coupled to the database's implementation of grouping, so it should be used with care to maintain database portability.

func GroupBy

func GroupBy(names ...string) GroupByParam

GroupBy creates a new GroupByParam with the specified field names for grouping. This function initializes a GroupByParam to group query results by the provided field names.

Parameters:

  • names: A variable number of strings representing the names of the fields to group by.

Returns: A new GroupByParam with the specified field names.

Example: Using GroupBy in a query:

query.NewParams(
	query.Filter("Birthday", time.Parse("2000-01-01", "2006-01-02")).WithOP(query.GT),
	query.GroupBy("Birthday"),
)

This example creates query parameters to filter records where 'Birthday' is greater than '2000-01-01' and groups the results by 'Birthday'.

func (GroupByParam) ParamType

func (p GroupByParam) ParamType() string

ParamType returns the type of this parameter, which is `groupby`. This method allows distinguishing GroupByParam from other query parameter types in contexts where multiple parameter types are used.

func (GroupByParam) WithHaving

func (p GroupByParam) WithHaving(params ...FilterParam) GroupByParam

WithHaving returns a new GroupByParam with the specified having conditions while preserving the existing group by names and options. This method is useful for adding 'HAVING' clause conditions to an existing GroupByParam.

Parameters:

  • params: A variable number of FilterParam representing the conditions to be applied in the 'HAVING' clause.

Returns: A new GroupByParam with the updated having conditions.

func (GroupByParam) WithOption

func (p GroupByParam) WithOption(option string) GroupByParam

WithOption returns a new GroupByParam instance with the specified option while preserving the existing group by names and having conditions. This method is useful for adding additional grouping options to an existing GroupByParam.

Parameters:

  • option: A string representing the additional group by option to be applied.

Returns: A new GroupByParam with the updated option.

type LockType added in v1.0.9

type LockType int
const (
	LockTypeForUpdate LockType = iota
)

type ORParam

type ORParam struct {
	Params []FilterParam
}

ORParam represents a logical OR combination of multiple filter parameters. It is used in queries to combine multiple FilterParam instances such that any of the conditions being true will result in a match.

Fields:

  • Params: A slice of FilterParam representing the filter conditions to be combined with OR logic.

func (ORParam) ParamType

func (p ORParam) ParamType() string

ParamType returns the type of this parameter, which is `or`. This method allows differentiating ORParam from other types of query parameters.

type Operator

type Operator uint8

Operator defines a set of constants representing operators used in filter expressions. These operators are used to specify the type of comparison to be performed in a query's filter condition.

const (
	// EQ represents the 'Equal' operator in a filter expression.
	EQ Operator = iota

	// NEQ represents the 'Not Equal' operator in a filter expression.
	NEQ

	// GT represents the 'Greater Than' operator in a filter expression.
	GT

	// GTE represents the 'Greater Than or Equal' operator in a filter expression.
	GTE

	// LT represents the 'Less Than' operator in a filter expression.
	LT

	// LTE represents the 'Less Than or Equal' operator in a filter expression.
	LTE
)

func (Operator) String

func (o Operator) String() string

String returns the string representation of the Operator. This method is useful for displaying or logging the operator in a human-readable format.

Returns: A string that represents the Operator. For example, it returns "EQ" for the EQ operator. If the operator does not match any predefined operator, "UNKNOWN" is returned.

type OrderByParam

type OrderByParam struct {
	Name string
	Desc bool
}

OrderByParam specifies how to sort the results when querying from a data store. It defines the field by which the results should be ordered and the direction of ordering.

Fields:

  • Name: The name of the field to be used for ordering.
  • Desc: A boolean indicating the order direction. If true, the order is descending. If false, it's ascending.

func OrderBy

func OrderBy(name string, desc bool) OrderByParam

OrderBy creates a new OrderByParam with the specified field name and order direction. This function is used in query construction to specify how the results should be sorted.

Parameters:

  • name: The name of the field to order by.
  • desc: Boolean indicating the order direction. True for descending order, false for ascending.

Returns: A new OrderByParam configured with the specified field and order direction.

Example: Ordering query results by 'Name' in ascending order and then by 'ID' in descending order:

query.NewParams(
	query.OrderBy("Name", false), // Order by 'Name' in ascending order
	query.OrderBy("ID", true),    // Then order by 'ID' in descending order
)

In this example, results will be first sorted by 'Name' in ascending order, and then by 'ID' in descending order.

func (OrderByParam) ParamType

func (p OrderByParam) ParamType() string

ParamType returns the type of this parameter, which is `orderby`. This method is used to distinguish OrderByParam from other types of query parameters.

type PaginateParam

type PaginateParam struct {
	Offset int
	Limit  int
}

PaginateParam specifies the parameters for pagination when querying a data store. It is used to define the offset (starting point) and limit (number of items to fetch) for a query result.

Fields:

  • Offset: The number of items to skip before starting to collect the result set.
  • Limit: The maximum number of items to return in the result set.

func (PaginateParam) ParamType

func (p PaginateParam) ParamType() string

ParamType returns the type of this parameter, which is `paginate`. This method helps to identify PaginateParam as the parameter type for pagination purposes.

type Param

type Param interface {
	// ParamType returns the name of the param, used to identify the type of the query parameter.
	ParamType() string
}

Param is an interface representing a query parameter. It provides a common method to identify the type of the parameter.

func OR

func OR(params ...Param) Param

OR creates a new ORParam, which is a logical OR combination of the provided filter parameters.

This function is used to build queries where you want to match records that satisfy any one of the given filter conditions.

Parameters:

  • params: A variable number of Param, each of which should be a FilterParam.

Returns: An ORParam that encapsulates the provided filter parameters in an OR logic.

Example: Using OR to combine filter conditions:

query.NewParams(
  query.OR(
    query.Filter("id", 1),
    query.Filter("id", 2),
  ),
)

This example creates query parameters that match records where 'id' is either 1 or 2.

Note: The function panics if any parameter provided is not a FilterParam.

func Paginate

func Paginate(offset, limit int) Param

Paginate creates a new PaginateParam with the specified offset and limit. This function is used to apply pagination to query results, controlling the portion of the result set to return.

Parameters:

  • offset: The number of items to skip in the result set.
  • limit: The maximum number of items to include in the result set.

Returns: A PaginateParam configured with the specified offset and limit.

Example: Applying pagination to a query:

// Fetch the next 10 items starting from the 11th item.
params := query.NewParams(
  query.Paginate(10, 10),
)

In this example, the query will skip the first 10 items and then fetch the next 10 items, effectively returning items 11 to 20.

func WithLock added in v1.0.9

func WithLock(lockType LockType) Param

WithLock creates a new WithLockParam. This function is used to add a "FOR UPDATE" clause to the main query.

Parameters: N/A

Returns: A new WithLockParam.

Example: Using WithLock in a query:

query.NewParams(
	query.Filter("Birthday", time.Parse("2000-01-01", "2006-01-02")).WithOP(query.GT),
	query.WithLock(query.LockTypeForUpdate),
)

This example creates query parameters to filter records where 'Birthday' is greater than '2000-01-01' and locks all the matching rows to be updated within the current transaction.

type Params

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

Params is a struct that aggregates multiple query parameters. It also provides methods to retrieve specific types of parameters and a caching mechanism for efficient retrieval.

func NewParams

func NewParams(params ...Param) Params

NewParams creates a new Params object with the given query parameters. It initializes a cache for filter parameters for efficient retrieval.

Parameters:

  • params: A variable number of Param to include in the Params object.

Returns: A new Params object containing the provided query parameters.

Example: Creating a new Params object with various query parameters:

query.NewParams(
	query.Select("ID", "Name"),
	query.OrderBy("ID", true),
	query.Filter("ID", 1),
	query.Filter("Name", "test"),
)

func (Params) Get

func (p Params) Get(paramType string) []Param

Get returns all query parameters of a specific type.

Parameters:

  • paramType: The type of parameters to retrieve.

Returns: A slice of Param that match the specified paramType.

func (Params) GetFilter

func (p Params) GetFilter(name string) (FilterParam, bool)

GetFilter returns the FilterParam with the given name, if it exists.

Parameters:

  • name: The name of the filter parameter to retrieve.

Returns: A FilterParam and a boolean indicating whether it was found.

func (Params) Params

func (p Params) Params() []Param

Params returns the list of all query parameters.

type PreloadParam

type PreloadParam struct {
	Name   string
	Params []Param
}

PreloadParam is used to specify related entities to be preloaded when querying from a data store. This is particularly useful in ORM frameworks to efficiently load associated data in a single query.

Fields:

  • Name: The name of the related entity (reference field) to be preloaded.
  • Params: Additional query parameters to apply to the preloading operation (e.g., filters, sorting).

func Preload

func Preload(preload string, params ...Param) PreloadParam

Preload creates a new PreloadParam for a given reference field. This function is used to specify related entities that should be preloaded along with the main query results.

Parameters:

  • preload: The name of the reference field to preload.
  • params: Optional additional query parameters to customize the preloading operation.

Returns: A new PreloadParam configured with the specified reference field and additional parameters.

Example: Preloading an 'Author' entity in an 'Article' query:

type Article struct {
    ID      int
    Title   string
    Content string
    Author  *Author
}

type Author struct {
    ID   int
    Name string
}

// Preload 'Author' data when querying 'Article'
query.NewParams(
    query.Preload("Author"),
)

In this example, when querying for 'Article', the related 'Author' data is also loaded in the same query.

func (PreloadParam) ParamType

func (p PreloadParam) ParamType() string

ParamType returns the type of this parameter, which is `preload`. This method distinguishes PreloadParam from other types of query parameters.

type SelectParam

type SelectParam struct {
	Names []string
}

SelectParam specifies the fields to be selected in the query result. This struct is useful for defining which specific fields of a data model should be retrieved in a query, allowing for more efficient data fetching and manipulation.

Fields:

  • Names: A slice of strings representing the names of the fields to be selected.

func Select

func Select(fields ...string) SelectParam

Select creates and returns a new SelectParam with the specified field names. This function is primarily used to construct query parameters that specify which fields of a data model should be included in the query's result set.

Parameters:

  • fields: A variable number of string arguments, each representing a field name to be included in the selection.

Returns: A SelectParam struct containing the provided field names.

Example: Creating a query parameter to select specific fields 'ID' and 'Name':

query.NewParams(
	query.Select("ID", "Name"),
)

func (SelectParam) ParamType

func (p SelectParam) ParamType() string

ParamType returns the type of this parameter as a string. In this case, it returns 'select', indicating that this parameter is used for selecting specific fields.

type WithLockParam added in v1.0.9

type WithLockParam struct {
	LockType LockType
}

func (WithLockParam) ParamType added in v1.0.9

func (p WithLockParam) ParamType() string

ParamType returns the type of this parameter, which is TypeWithLock. This method helps to identify WithLockParam as the parameter type for pagination purposes.

Jump to

Keyboard shortcuts

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