query

package
v0.14.2 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2020 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package query is the package used that defines the neuron query it's structure, processor, transactions. The package is used to create new queries, allow to set proper query parameters like: filters, pagination, sort order and includes. It also defines the query processes with their config names.

Index

Constants

View Source
const (
	// ParamInclude is the url.Query parameter name for the included fields.
	ParamInclude string = "include"
	// ParamFields is the url.Query parameter name for the fieldset.
	ParamFields string = "fields"
)
View Source
const (
	// ParamLanguage is the language query parameter used in the url values.
	ParamLanguage = "lang"
	// ParamFilter is the filter query parameter used as the key in the url values.
	ParamFilter = "filter"
)
View Source
const (
	ProcessHookBeforeCreate          = internal.ProcessHookBeforeCreate
	ProcessSetBelongsToRelations     = internal.ProcessSetBelongsToRelations
	ProcessSetCreatedAt              = internal.ProcessSetCreatedAt
	ProcessCreate                    = internal.ProcessCreate
	ProcessStoreScopePrimaries       = internal.ProcessStoreScopePrimaries
	ProcessPatchForeignRelations     = internal.ProcessPatchForeignRelations
	ProcessPatchForeignRelationsSafe = internal.ProcessPatchForeignRelationsSafe
	ProcessHookAfterCreate           = internal.ProcessHookAfterCreate

	ProcessDeletedAtFilter            = internal.ProcessDeletedAtFilter
	ProcessFillEmptyFieldset          = internal.ProcessFillEmptyFieldset
	ProcessConvertRelationFilters     = internal.ProcessConvertRelationFilters
	ProcessConvertRelationFiltersSafe = internal.ProcessConvertRelationFiltersSafe
	ProcessHookBeforeGet              = internal.ProcessHookBeforeGet
	ProcessGet                        = internal.ProcessGet
	ProcessGetForeignRelations        = internal.ProcessGetForeignRelations
	ProcessGetForeignRelationsSafe    = internal.ProcessGetForeignRelationsSafe
	ProcessHookAfterGet               = internal.ProcessHookAfterGet

	ProcessCheckPagination = internal.ProcessCheckPagination
	ProcessHookBeforeList  = internal.ProcessHookBeforeList
	ProcessList            = internal.ProcessList
	ProcessHookAfterList   = internal.ProcessHookAfterList
	ProcessGetIncluded     = internal.ProcessGetIncluded
	ProcessGetIncludedSafe = internal.ProcessGetIncludedSafe

	ProcessHookBeforePatch         = internal.ProcessHookBeforePatch
	ProcessSetUpdatedAt            = internal.ProcessSetUpdatedAt
	ProcessPatch                   = internal.ProcessPatch
	ProcessHookAfterPatch          = internal.ProcessHookAfterPatch
	ProcessPatchBelongsToRelations = internal.ProcessPatchBelongsToRelations

	ProcessReducePrimaryFilters       = internal.ProcessReducePrimaryFilters
	ProcessHookBeforeDelete           = internal.ProcessHookBeforeDelete
	ProcessSetDeletedAt               = internal.ProcessSetDeletedAt
	ProcessDelete                     = internal.ProcessDelete
	ProcessHookAfterDelete            = internal.ProcessHookAfterDelete
	ProcessDeleteForeignRelations     = internal.ProcessDeleteForeignRelations
	ProcessDeleteForeignRelationsSafe = internal.ProcessDeleteForeignRelationsSafe

	ProcessTxBegin            = internal.ProcessTxBegin
	ProcessTxCommitOrRollback = internal.ProcessTxCommitOrRollback

	ProcessCount           = internal.ProcessCount
	ProcessHookBeforeCount = internal.ProcessHookBeforeCount
	ProcessHookAfterCount  = internal.ProcessHookAfterCount
)

Processes constant names.

View Source
const (
	// ParamPage is a JSON API query parameter used as for pagination.
	ParamPage = "page"
	// ParamPageNumber is a JSON API query parameter used in a page based
	// pagination strategy in conjunction with ParamPageSize.
	ParamPageNumber = "page[number]"
	// ParamPageSize is a JSON API query parameter used in a page based
	// pagination strategy in conjunction with ParamPageNumber.
	ParamPageSize = "page[size]"
	// ParamPageOffset is a JSON API query parameter used in an offset based
	// pagination strategy in conjunction with ParamPageLimit.
	ParamPageOffset = "page[offset]"
	// ParamPageLimit is a JSON API query parameter used in an offset based
	// pagination strategy in conjunction with ParamPageOffset.
	ParamPageLimit = "page[limit]"
)

Pagination defined constants used for formatting the query.

View Source
const ParamSort = "sort"

ParamSort is the url query parameter name for the sorting fields.

Variables

View Source
var (
	// Logical Operators
	OpEqual        = &Operator{Raw: operatorEqualRaw, Name: "Equal"}
	OpIn           = &Operator{Raw: operatorInRaw, Name: "In"}
	OpNotEqual     = &Operator{Raw: operatorNotEqualRaw, Name: "NotEqual"}
	OpNotIn        = &Operator{Raw: operatorNotInRaw, Name: "NotIn"}
	OpGreaterThan  = &Operator{Raw: operatorGreaterThanRaw, Name: "GreaterThan"}
	OpGreaterEqual = &Operator{Raw: operatorGreaterEqualRaw, Name: "GreaterThanOrEqualTo"}
	OpLessThan     = &Operator{Raw: operatorLessThanRaw, Name: "LessThan"}
	OpLessEqual    = &Operator{Raw: operatorLessEqualRaw, Name: "LessThanOrEqualTo"}

	// Strings Only operators.
	OpContains   = &Operator{Raw: operatorContainsRaw, Name: "Contains"}
	OpStartsWith = &Operator{Raw: operatorStartsWithRaw, Name: "StartsWith"}
	OpEndsWith   = &Operator{Raw: operatorEndsWithRaw, Name: "EndsWith"}

	// Null and Existence operators.
	OpIsNull    = &Operator{Raw: operatorIsNullRaw, Name: "IsNull"}
	OpNotNull   = &Operator{Raw: operatorNotNullRaw, Name: "NotNull"}
	OpExists    = &Operator{Raw: operatorExistsRaw, Name: "Exists"}
	OpNotExists = &Operator{Raw: operatorNotExistsRaw, Name: "NotExists"}
)

Operator definitions variables.

View Source
var FilterOperators = newOpContainer()

FilterOperators is the container that stores all query filter operators.

View Source
var MaxNestedRelLevel = 1

MaxNestedRelLevel is a temporary maximum nested check while creating sort fields TODO: change the variable into config settable.

View Source
var MaxPermissibleDuplicates = 3

MaxPermissibleDuplicates is the maximum permissible dupliactes value used for errors TODO: get the value from config

Functions

func RegisterMultipleOperators added in v0.6.0

func RegisterMultipleOperators(operators ...*Operator) error

RegisterMultipleOperators registers multiple operators at once

func RegisterOperator added in v0.6.0

func RegisterOperator(o *Operator) error

RegisterOperator registers the operator in the provided container

func RegisterProcess

func RegisterProcess(name string, p ProcessFunc)

RegisterProcess registers the process with it's unique name. If the process is already registered the function panics.

func SplitBracketParameter added in v0.6.0

func SplitBracketParameter(bracketed string) (values []string, err error)

SplitBracketParameter splits the parameters within the '[' and ']' brackets.

Types

type AfterCounter added in v0.7.0

type AfterCounter interface {
	AfterCount(ctx context.Context, s *Scope) error
}

AfterCounter is the interface used for before count hook.

type AfterCreator

type AfterCreator interface {
	AfterCreate(ctx context.Context, s *Scope) error
}

AfterCreator is the interface that has a method used as a hook after the creation process.

type AfterDeleter

type AfterDeleter interface {
	AfterDelete(ctx context.Context, s *Scope) error
}

AfterDeleter is the interface used as an after delete hook.

type AfterGetter

type AfterGetter interface {
	AfterGet(ctx context.Context, s *Scope) error
}

AfterGetter is the interface used as a hook after getting the value.

type AfterLister

type AfterLister interface {
	AfterList(ctx context.Context, s *Scope) error
}

AfterLister is the interface used as a after list hook.

type AfterPatcher

type AfterPatcher interface {
	AfterPatch(ctx context.Context, s *Scope) error
}

AfterPatcher is the interface used as a after patch hook.

type BeforeCounter added in v0.7.0

type BeforeCounter interface {
	BeforeCount(ctx context.Context, s *Scope) error
}

BeforeCounter is the interface used for before count hook.

type BeforeCreator

type BeforeCreator interface {
	BeforeCreate(ctx context.Context, s *Scope) error
}

BeforeCreator is the interface used for hooks before the creation process.

type BeforeDeleter

type BeforeDeleter interface {
	BeforeDelete(ctx context.Context, s *Scope) error
}

BeforeDeleter is the interface used as a before delete hook.

type BeforeGetter

type BeforeGetter interface {
	BeforeGet(ctx context.Context, s *Scope) error
}

BeforeGetter is the interface used as a hook before getting value.

type BeforeLister

type BeforeLister interface {
	BeforeList(ctx context.Context, s *Scope) error
}

BeforeLister is the interface used for before list hook.

type BeforePatcher

type BeforePatcher interface {
	BeforePatch(ctx context.Context, s *Scope) error
}

BeforePatcher is the interface used as a before patch hook.

type Builder added in v0.12.0

type Builder interface {
	Scope() *Scope
	Err() error
	Ctx() context.Context

	Count() (int64, error)
	Create() error
	Patch() error
	List() error
	Get() error
	Delete() error

	AddFilterField(filter *FilterField) Builder
	Filter(filter string, values ...interface{}) Builder
	Limit(limit int64) Builder
	Offset(offset int64) Builder
	PageSize(pageSize int64) Builder
	PageNumber(pageNumber int64) Builder
	SetFields(fields ...interface{}) Builder
	Sort(fields ...string) Builder
}

Builder is the interface used to build queries.

type CRUDRepository added in v0.12.0

type CRUDRepository interface {
	Counter
	Creator
	Getter
	Lister
	Patcher
	Deleter
}

CRUDRepository is an interface that implements all possible repository methods interfaces.

type Counter added in v0.7.0

type Counter interface {
	Count(ctx context.Context, s *Scope) (int64, error)
}

Counter is the interface used for query repositories that allows to count the result number for the provided query.

type Creator added in v0.2.2

type Creator interface {
	Create(ctx context.Context, s *Scope) error
}

Creator is the repository interface that creates the value within the query.Scope.

type Deleter

type Deleter interface {
	Delete(ctx context.Context, s *Scope) error
}

Deleter is the interface for the repositories that deletes provided query value.

type Factory added in v0.6.0

type Factory struct {
	mock.Mock
}

Factory is the repository.Factory mock implementation

func (*Factory) Close added in v0.6.0

func (f *Factory) Close(ctx context.Context, done chan<- interface{})

Close closes the factory

func (*Factory) DriverName added in v0.6.0

func (f *Factory) DriverName() string

DriverName returns the factory repository name Implements repository.Repository

func (*Factory) New added in v0.6.0

func (f *Factory) New(model *config.Repository) (repository.Repository, error)

New creates new repository Implements repository.Factory method

type FilterField added in v0.6.0

type FilterField struct {
	StructField *mapping.StructField
	// Key is used for the map type filters as a nested argument.
	Key string
	// Values are the filter values for given attribute FilterField
	Values []*OperatorValues
	// if given filterField is a relationship type it should be filter by it's
	// subfields (for given relation type).
	// Relationships are the filter values for given relationship FilterField
	Nested []*FilterField
}

FilterField is a struct that keeps information about given query filters. It is based on the mapping.StructField.

func NewFilter added in v0.6.0

func NewFilter(field *mapping.StructField, op *Operator, values ...interface{}) *FilterField

NewFilter creates new filterfield for given field, operator and values.

func NewRelationshipFilter added in v0.6.0

func NewRelationshipFilter(relation *mapping.StructField, relFilters ...*FilterField) *FilterField

NewRelationshipFilter creates new relationship filter for the 'relation' StructField. It adds all the nested relation subfilters 'relFilters'.

func NewStringFilter added in v0.6.0

func NewStringFilter(c *controller.Controller, filter string, values ...interface{}) (*FilterField, error)

NewStringFilter creates the filter field based on the provided 'filter' and 'values'. Example:

  • 'fitler': "filter[collection][fieldName][operator]"
  • 'values': 5, 13

This function doesn't allow to filter over foreign keys.

func NewStringFilterWithForeignKey added in v0.6.0

func NewStringFilterWithForeignKey(c *controller.Controller, filter string, values ...interface{}) (*FilterField, error)

NewStringFilterWithForeignKey creates the filter field based on the provided filter, schemaName and values. Example:

  • 'fitler': "filter[collection][fieldName][operator]"
  • 'schema': "schemaName"
  • 'values': 5, 13

This function allow to filter over the foreign key fields.

func (*FilterField) Copy added in v0.9.0

func (f *FilterField) Copy() *FilterField

Copy returns the copy of the filter field.

func (*FilterField) FormatQuery added in v0.6.0

func (f *FilterField) FormatQuery(q ...url.Values) url.Values

FormatQuery formats the filter field into url.Values. If the 'q' optional parameter is set, then the function would add the values into the provided argument 'q' url.Values. Otherwise it creates new url.Values. Returns updated (new) url.Values.

func (*FilterField) NestedFilters added in v0.6.0

func (f *FilterField) NestedFilters() []*FilterField

NestedFilters returns the nested filters for given filter fields. Nested filters are the filters used for relationship or composite attribute filters.

func (*FilterField) String added in v0.6.0

func (f *FilterField) String() string

String implements fmt.Stringer interface.

type Filters added in v0.6.0

type Filters []*FilterField

Filters is the wrapper over the slice of filter fields.

func (Filters) String added in v0.6.0

func (f Filters) String() string

String implements fmt.Stringer interface.

type FullRepository

type FullRepository interface {
	CRUDRepository
	Transactioner
}

FullRepository is the interface that implements both repository CRUDRepository and the transactioner interfaces.

type Getter

type Getter interface {
	Get(ctx context.Context, s *Scope) error
}

Getter is the repository interface that Gets single query value.

type IncludeField added in v0.6.0

type IncludeField struct {
	*mapping.StructField
	// Scope is the query scope that contains the values and filters for given
	// include field
	Scope *Scope
	// RelatedScope is a pointer to the main scope where the IncludedField is stored.
	RelatedScope  *Scope
	NotInFieldset bool
}

IncludeField is the includes information scope it contains the field to include from the root scope related subScope, and subfields to include.

func (*IncludeField) GetMissingPrimaries added in v0.6.0

func (i *IncludeField) GetMissingPrimaries() ([]interface{}, error)

GetMissingPrimaries gets the id values from the RelatedScope, checks which id values were already stored within the collection root scope and return new ones.

type IsolationLevel

type IsolationLevel int

IsolationLevel is the

const (
	LevelDefault IsolationLevel = iota
	LevelReadUncommitted
	LevelReadCommitted
	LevelWriteCommitted
	LevelRepeatableRead
	LevelSnapshot
	LevelSerializable
	LevelLinearizable
)

Isolation level enums

func (*IsolationLevel) MarshalJSON

func (i *IsolationLevel) MarshalJSON() ([]byte, error)

MarshalJSON marshals the isolation level into json encoding Implements the json.Marshaller interface

func (IsolationLevel) String

func (i IsolationLevel) String() string

func (*IsolationLevel) UnmarshalJSON

func (i *IsolationLevel) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshal isolation level from the provided data Implements json.Unmarshaler

type Kind added in v0.6.0

type Kind int

Kind is the enum defining the kind of scope.

const (
	RootKind Kind = iota
	IncludedKind
	RelationshipKind
	RelatedKind
	SubscopeKind
)

Enums for the scope kind.

type Lister

type Lister interface {
	List(ctx context.Context, s *Scope) error
}

Lister is the repository interface that Lists provided query values.

type Operator added in v0.6.0

type Operator struct {
	// ID is the filter operator id used for comparing the operator type.
	ID uint16
	// Raw is the filtering string value of the current operator.
	Raw string
	// Name is the human readable filter operator name.
	Name string
}

Operator is the operator used for filtering the query.

func (Operator) IsBasic added in v0.6.0

func (f Operator) IsBasic() bool

IsBasic checks if the operator is 'OpEqual' or OpNotEqual.

func (Operator) IsRangeable added in v0.6.0

func (f Operator) IsRangeable() bool

IsRangeable checks if the operator allows to have value ranges.

func (Operator) IsStandard added in v0.6.0

func (f Operator) IsStandard() bool

IsStandard checks if the operator is standard.

func (Operator) IsStringOnly added in v0.6.0

func (f Operator) IsStringOnly() bool

IsStringOnly checks if the operator is 'string only'.

func (Operator) String added in v0.6.0

func (f Operator) String() string

String implements Stringer interface.

type OperatorValues added in v0.6.0

type OperatorValues struct {
	Values   []interface{}
	Operator *Operator
}

OperatorValues is a struct that holds the Operator with the filter values.

type Pagination added in v0.2.1

type Pagination struct {
	// Size is a pagination value that defines 'limit' or 'page size'
	Size int64
	// Offset is a pagination value that defines 'offset' or 'page number'
	Offset int64
	Type   PaginationType
}

Pagination defines the query limits and offsets. It defines the maximum size (Limit) as well as an offset at which the query should start. If the pagination type is 'LimitOffsetPagination' the value of 'Size' defines the 'limit' where the value of 'Offset' defines it's 'offset'. If the pagination type is 'PageNumberPagination' the value of 'Size' defines 'pageSize' and the value of 'Offset' defines 'pageNumber'. The page number value starts from '1'.

func NewPaginationLimitOffset added in v0.9.1

func NewPaginationLimitOffset(limit, offset int64) (*Pagination, error)

NewPaginationLimitOffset creates new Limit Offset pagination for given 'limit' and 'offset'.

func NewPaginationNumberSize added in v0.9.1

func NewPaginationNumberSize(number, size int64) (*Pagination, error)

NewPaginationNumberSize sets the pagination of the type PageNumberSize with the page 'number' and page 'size'.

func (*Pagination) First added in v0.9.0

func (p *Pagination) First() (*Pagination, error)

First gets the first pagination for provided 'p' pagination values. If the 'p' pagination is already the 'first' pagination the function returns it as the result directly.

func (*Pagination) FormatQuery added in v0.2.1

func (p *Pagination) FormatQuery(q ...url.Values) url.Values

FormatQuery formats the pagination for the url query with respect to JSONAPI specification.

func (*Pagination) GetLimitOffset added in v0.2.1

func (p *Pagination) GetLimitOffset() (limit, offset int64)

GetLimitOffset gets the 'limit' and 'offset' values from the given pagination. If the pagination type is 'LimitOffsetPagination' then the value of 'limit' = p.Size and the value of 'offset' = p.Offset. In case when pagination type is 'PageNumberPagination' the 'limit' = p.Size and the offset is a result of multiplication of (pageNumber - 1) * pageSize = (p.Offset - 1) * p.Size. If the p.Offset is zero value then the (pageNumber - 1) value would be set previously to '0'.

func (*Pagination) GetNumberSize added in v0.5.1

func (p *Pagination) GetNumberSize() (pageNumber, pageSize int64)

GetNumberSize gets the 'page number' and 'page size' from the pagination. If the pagination type is 'PageNumberPagination' the results are just the values of pagination. In case the pagination type is of 'LimitOffsetPagination' then 'limit'(Size) would be the page size and the page number would be 'offset' / limit + 1. PageNumberPagination starts it's page number counting from 1. If the offset % size != 0 - the offset is not dividable by the size without the rest - then the division rounds down it's value.

func (*Pagination) IsValid added in v0.6.1

func (p *Pagination) IsValid() error

IsValid checks if the pagination is well formed.

func (*Pagination) IsZero added in v0.6.0

func (p *Pagination) IsZero() bool

IsZero checks if the pagination is zero valued.

func (*Pagination) Last added in v0.9.0

func (p *Pagination) Last(total int64) (*Pagination, error)

Last gets the last pagination for the provided 'total' count. Returns error if current pagination is not valid, or 'total'. If current pagination 'p' is the last pagination it would be return directly as the result. In order to check if the 'p' is last pagination compare it's pointer with the 'p'.

func (*Pagination) Next added in v0.9.0

func (p *Pagination) Next(total int64) (*Pagination, error)

Next gets the next pagination for the provided 'total' count. If current pagination 'p' is the last one, then the function returns 'p' pagination directly. In order to check if there is a next pagination compare the result pointer with the 'p' pagination.

func (*Pagination) Previous added in v0.9.0

func (p *Pagination) Previous() (*Pagination, error)

Previous gets the pagination for the previous possible size and offset. If current pagination 'p' is the first page then the function returns 'p' pagination. If the previouse size would overflow the 0th offset then the previous starts from 0th offset.

func (*Pagination) String added in v0.2.1

func (p *Pagination) String() string

String implements fmt.Stringer interface.

type PaginationType added in v0.2.1

type PaginationType int

PaginationType defines the pagination type.

const (
	// LimitOffsetPagination is the pagination type that defines limit or (and) offset.
	LimitOffsetPagination PaginationType = iota
	// PageNumberPagination is the pagination type that uses page type pagination i.e. page=1 page size = 10.
	PageNumberPagination
)

type Patcher

type Patcher interface {
	Patch(ctx context.Context, s *Scope) error
}

Patcher is the repository interface that patches given query values.

type ProcessFunc

type ProcessFunc func(ctx context.Context, s *Scope) error

ProcessFunc is the function that modifies or changes the scope value

type Processor

type Processor config.Processor

Processor is the wrapper over config processor that allows to start the queries.

func (*Processor) Count added in v0.7.0

func (p *Processor) Count(ctx context.Context, s *Scope) error

Count initializes the Count Process Chain for the Scope.

func (*Processor) Create

func (p *Processor) Create(ctx context.Context, s *Scope) error

Create initializes the Create Process Chain for the Scope.

func (*Processor) Delete

func (p *Processor) Delete(ctx context.Context, s *Scope) error

Delete initializes the Delete Process Chain for the scope 's'.

func (*Processor) Get

func (p *Processor) Get(ctx context.Context, s *Scope) error

Get initializes the Get Process chain for the scope.

func (*Processor) List

func (p *Processor) List(ctx context.Context, s *Scope) error

List initializes the List Process Chain for the scope.

func (*Processor) Patch

func (p *Processor) Patch(ctx context.Context, s *Scope) error

Patch initializes the Patch Process Chain for the scope 's'.

type Query added in v0.12.0

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

Query is the query builder that allows to execute Queries in a callback manner.

func NewQuery added in v0.12.0

func NewQuery(ctx context.Context, c *controller.Controller, model interface{}) *Query

NewQuery creates new query Query for given 'model' and default controller.

func (*Query) AddFilterField added in v0.12.0

func (b *Query) AddFilterField(filter *FilterField) Builder

AddFilterField adds 'filter' *FilterField to the query.

func (*Query) Count added in v0.12.0

func (b *Query) Count() (int64, error)

Count returns the number of the values for the provided query scope.

func (*Query) Create added in v0.12.0

func (b *Query) Create() error

Create stores the values within the given scope's value repository, by starting the create process.

func (*Query) Ctx added in v0.12.0

func (b *Query) Ctx() context.Context

Ctx returns query context.

func (*Query) Delete added in v0.12.0

func (b *Query) Delete() error

Delete deletes the values provided in the query's scope.

func (*Query) Err added in v0.12.0

func (b *Query) Err() error

Err returns query error.

func (*Query) Filter added in v0.12.0

func (b *Query) Filter(filter string, values ...interface{}) Builder

Filter parses the filter into the filters.FilterField and adds it to the given scope.

func (*Query) Get added in v0.12.0

func (b *Query) Get() error

Get gets single value from the repository taking into account the scope filters and parameters.

func (*Query) Limit added in v0.12.0

func (b *Query) Limit(limit int64) Builder

Limit sets the maximum number of objects returned by the List process,

func (*Query) List added in v0.12.0

func (b *Query) List() error

List gets the values from the repository taking with respect to the query filters, sorts, pagination and included values.

func (*Query) Offset added in v0.12.0

func (b *Query) Offset(offset int64) Builder

Offset sets the query result's offset. It says to skip as many object's from the repository before beginning to return the result. 'Offset' 0 is the same as omitting the 'Offset' clause.

func (*Query) PageNumber added in v0.12.0

func (b *Query) PageNumber(pageNumber int64) Builder

PageNumber defines the pagination page number.

func (*Query) PageSize added in v0.12.0

func (b *Query) PageSize(pageSize int64) Builder

PageSize defines pagination page size - maximum amount of returned objects.

func (*Query) Patch added in v0.12.0

func (b *Query) Patch() error

Patch updates the scope's attribute and relationship values based on the scope's value and filters. In order to start patch process scope should contain a value with the non-zero primary field, or primary field filters.

func (*Query) Scope added in v0.12.0

func (b *Query) Scope() *Scope

Scope returns query scope.

func (*Query) SetFields added in v0.12.0

func (b *Query) SetFields(fields ...interface{}) Builder

SetFields adds the fields to the scope's fieldset. The fields may be a mapping.StructField as well as field's NeuronName (string) or the StructField Name (string).

func (*Query) Sort added in v0.12.0

func (b *Query) Sort(fields ...string) Builder

Sort creates the sort order of the result.

type Repository added in v0.6.0

type Repository struct {
	mock.Mock
}

Repository is an autogenerated mock type for the Repository type

func (*Repository) Begin added in v0.6.0

func (_m *Repository) Begin(ctx context.Context, tx *Tx, model *mapping.ModelStruct) error

Begin provides a mock function with given fields: ctx, s

func (*Repository) Close added in v0.6.0

func (_m *Repository) Close(ctx context.Context) error

Close closes the repository connection

func (*Repository) Commit added in v0.6.0

func (_m *Repository) Commit(ctx context.Context, tx *Tx, model *mapping.ModelStruct) error

Commit provides a mock function with given fields: ctx, s

func (*Repository) Count added in v0.7.0

func (_m *Repository) Count(ctx context.Context, s *Scope) (int64, error)

Count provides a mock function with given fields: ctx, s

func (*Repository) Create added in v0.6.0

func (_m *Repository) Create(ctx context.Context, s *Scope) error

Create provides a mock function with given fields: ctx, s

func (*Repository) Delete added in v0.6.0

func (_m *Repository) Delete(ctx context.Context, s *Scope) error

Delete provides a mock function with given fields: ctx, s

func (*Repository) Dial added in v0.12.0

func (_m *Repository) Dial(ctx context.Context) error

Dial implements repository.Repository

func (*Repository) FactoryName added in v0.6.0

func (_m *Repository) FactoryName() string

FactoryName provides a mock function that implements FactoryName method.

func (*Repository) Get added in v0.6.0

func (_m *Repository) Get(ctx context.Context, s *Scope) error

Get provides a mock function with given fields: ctx, s

func (*Repository) HealthCheck added in v0.12.0

func (_m *Repository) HealthCheck(ctx context.Context) (*repository.HealthResponse, error)

HealthCheck implements repository.Repository.

func (*Repository) List added in v0.6.0

func (_m *Repository) List(ctx context.Context, s *Scope) error

List provides a mock function with given fields: ctx, s

func (*Repository) ModelTxID added in v0.12.0

func (_m *Repository) ModelTxID(model *mapping.ModelStruct) (string, error)

ModelTxID implements Transactioner interface.

func (*Repository) Patch added in v0.6.0

func (_m *Repository) Patch(ctx context.Context, s *Scope) error

Patch provides a mock function with given fields: ctx, s

func (*Repository) RegisterModels added in v0.12.0

func (_m *Repository) RegisterModels(models ...*mapping.ModelStruct) error

RegisterModels implements repository.Repository interface.

func (*Repository) Rollback added in v0.6.0

func (_m *Repository) Rollback(ctx context.Context, tx *Tx, model *mapping.ModelStruct) error

Rollback provides a mock function with given fields: ctx, s

type Scope

type Scope struct {

	// Value is the values or / value of the queried object / objects
	Value interface{}
	// Fieldset represents fields used specified to get / update for this query scope
	Fieldset map[string]*mapping.StructField
	// PrimaryFilters contain filter for the primary field.
	PrimaryFilters Filters
	// RelationFilters contain relationship field filters.
	RelationFilters Filters
	// AttributeFilters contain filter for the attribute fields.
	AttributeFilters Filters
	// ForeignFilters contain the foreign key filter fields.
	ForeignFilters Filters
	// FilterKeyFilters are the for the 'FilterKey' field type
	FilterKeyFilters Filters
	// LanguageFilters contain information about language filters
	LanguageFilters *FilterField
	// SortFields are the query sort fields.
	SortFields []*SortField
	// Pagination is the query pagination
	Pagination *Pagination
	// Processor is current query processor.
	Processor *Processor
	// Err defines the process error.
	Err error
	// contains filtered or unexported fields
}

Scope is the query's structure that contains information required for the processor to operate. The scope has its unique 'ID', contains predefined model, operational value, fieldset, filters, sorts and pagination. It also contains the mapping of the included scopes.

func MustNew added in v0.2.3

func MustNew(model interface{}) *Scope

MustNew creates new scope with given 'model' for the default controller. Panics on error.

func MustNewC added in v0.2.1

func MustNewC(c *controller.Controller, model interface{}) *Scope

MustNewC creates new scope with given 'model' for the given controller 'c'. Panics on error.

func New

func New(model interface{}) (*Scope, error)

New creates the scope on the base of the given 'model' it uses default internalController.

func NewC

func NewC(c *controller.Controller, model interface{}) (*Scope, error)

NewC creates the scope for the provided model with respect to the provided internalController 'c'.

func NewModelC

func NewModelC(c *controller.Controller, mStruct *mapping.ModelStruct, isMany bool) *Scope

NewModelC creates new scope on the base of the provided model struct with the value. The value might be a slice of instances if 'isMany' is true.

func (*Scope) AutoSelectedFields added in v0.11.23

func (s *Scope) AutoSelectedFields() bool

AutoSelectedFields checks if the scope fieldset was set automatically. This function returns false if a user had defined any field in the Fieldset.

func (*Scope) ClearFilters added in v0.6.0

func (s *Scope) ClearFilters()

ClearFilters clears all scope filters.

func (*Scope) Controller

func (s *Scope) Controller() *controller.Controller

Controller gets the scope's internalController.

func (*Scope) Copy added in v0.9.0

func (s *Scope) Copy() *Scope

Copy creates a copy of the given scope.

func (*Scope) Count added in v0.7.0

func (s *Scope) Count() (int64, error)

Count returns the number of the values for the provided query scope.

func (*Scope) CountContext added in v0.7.0

func (s *Scope) CountContext(ctx context.Context) (int64, error)

CountContext returns the number of the values for the provided query scope, with the provided 'ctx' context.

func (*Scope) Create

func (s *Scope) Create() error

Create stores the values within the given scope's value repository, by starting the create process.

func (*Scope) CreateContext

func (s *Scope) CreateContext(ctx context.Context) error

CreateContext creates the scope values with the provided 'ctx' context.Context.

func (*Scope) Delete

func (s *Scope) Delete() error

Delete deletes the values provided in the query's scope.

func (*Scope) DeleteContext

func (s *Scope) DeleteContext(ctx context.Context) error

DeleteContext deletes the values provided in the scope's value with the context.

func (*Scope) Filter added in v0.3.0

func (s *Scope) Filter(rawFilter string, values ...interface{}) error

Filter parses the filter into the filters.FilterField and adds it to the given scope.

func (*Scope) FilterField added in v0.3.0

func (s *Scope) FilterField(filter *FilterField) error

FilterField adds the filter field to the given query.

func (*Scope) FormatQuery

func (s *Scope) FormatQuery() url.Values

FormatQuery formats the scope's query into the url.Values.

func (*Scope) Get

func (s *Scope) Get() error

Get gets single value from the repository taking into account the scope filters and parameters.

func (*Scope) GetContext

func (s *Scope) GetContext(ctx context.Context) error

GetContext gets single value from repository taking into account the scope filters, parameters and the context.

func (*Scope) ID

func (s *Scope) ID() uuid.UUID

ID returns the scope's identity number stored as the UUID.

func (*Scope) InFieldset

func (s *Scope) InFieldset(field interface{}) (*mapping.StructField, bool)

InFieldset checks if the provided field is in the scope's fieldset.

func (*Scope) IncludeFields added in v0.3.0

func (s *Scope) IncludeFields(fields ...string) error

IncludeFields adds the included fields into query scope.

func (*Scope) IncludedModelValues added in v0.3.0

func (s *Scope) IncludedModelValues(model interface{}) (map[interface{}]interface{}, error)

IncludedModelValues gets the scope's included values for the given 'model'. Returns the map of primary keys to the model values.

func (*Scope) IncludedScope added in v0.5.1

func (s *Scope) IncludedScope(model interface{}) (*Scope, error)

IncludedScope gets included scope if exists for the 'model'. NOTE: included scope contains no resultant values. This function is used only to set the included models fieldset and filters.

func (*Scope) IncludedScopes added in v0.6.0

func (s *Scope) IncludedScopes() (scopes []*Scope)

IncludedScopes returns the slice of included scopes if exists.

func (*Scope) IncludedValues added in v0.6.0

func (s *Scope) IncludedValues() map[interface{}]interface{}

IncludedValues returns included scope unique values, where the map key is unique primary field value, and the map value a model instance.

func (*Scope) IsMany added in v0.6.0

func (s *Scope) IsMany() bool

IsMany checks if the scope's value is of slice type.

func (*Scope) IsSubscope added in v0.6.0

func (s *Scope) IsSubscope() bool

IsSubscope checks if the given scope is a subscope

func (*Scope) Kind added in v0.6.0

func (s *Scope) Kind() Kind

Kind returns scope's kind

func (*Scope) Limit added in v0.2.1

func (s *Scope) Limit(limit int64) error

Limit sets the maximum number of objects returned by the List process, Returns error if the given scope has already different type of pagination.

func (*Scope) List

func (s *Scope) List() error

List gets the values from the repository taking with respect to the query filters, sorts, pagination and included values.

func (*Scope) ListContext

func (s *Scope) ListContext(ctx context.Context) error

ListContext gets the values from the repository taking with respect to the query filters, sorts, pagination and included values. Provided context.Context 'ctx' would be used while querying the repositories.

func (*Scope) Offset added in v0.12.0

func (s *Scope) Offset(offset int64) error

Offset sets the query result's offset. It says to skip as many object's from the repository before beginning to return the result. 'Offset' 0 is the same as omitting the 'Offset' clause. Returns error if the given scope has already different type of pagination.

func (*Scope) OrderedFieldset added in v0.8.1

func (s *Scope) OrderedFieldset() (ordered mapping.OrderedFields)

OrderedFieldset gets the fieldset fields sorted by the struct field's index.

func (*Scope) PageNumber added in v0.12.0

func (s *Scope) PageNumber(number int64) error

PageNumber defines the pagination page number. Returns error if given scope already has a pagination of LimitOffsetPagination type.

func (*Scope) PageSize added in v0.12.0

func (s *Scope) PageSize(size int64) error

PageSize defines pagination page size - maximum amount of returned objects. Returns error if given scope already has a pagination of LimitOffsetPagination type.

func (*Scope) Patch

func (s *Scope) Patch() error

Patch updates the scope's attribute and relationship values based on the scope's value and filters. In order to start patch process scope should contain a value with the non-zero primary field, or primary field filters.

func (*Scope) PatchContext

func (s *Scope) PatchContext(ctx context.Context) error

PatchContext updates the scope's attribute and relationship values based on the scope's value and filters with respect to the context.Context 'ctx'. In order to start patch process scope should contain a value with the non-zero primary field, or primary field filters.

func (*Scope) Query added in v0.12.0

func (s *Scope) Query(value interface{}) Builder

Query creates new sub-scope with the provided model 'value'. If the root scope is on the transaction the new one will be added to the root's transaction chain. It is a recommended way to create new scope's within hooks if the given scope should be included in the given transaction.

func (*Scope) QueryC added in v0.12.0

func (s *Scope) QueryC(c *controller.Controller, model interface{}) Builder

QueryC creates new query with the provided 'model' and controller 'c'. If the root scope is on the transaction the new one will be added to the root's transaction chain. It is a recommended way to create new scope's within hooks if the given scope should be included in the given transaction.

func (*Scope) QueryCtx added in v0.12.0

func (s *Scope) QueryCtx(ctx context.Context, model interface{}) Builder

QueryCtx creates new Query with the provided 'model' with the context.Context 'ctx'. If the root scope is on the transaction the new one will be added to the root's transaction chain. It is a recommended way to create new scope's within hooks if the given scope should be included in the given transaction.

func (*Scope) QueryCtxC added in v0.12.0

func (s *Scope) QueryCtxC(ctx context.Context, c *controller.Controller, model interface{}) Builder

QueryCtxC creates new Query with the provided 'model' with the context.Context 'ctx'. If the root scope is on the transaction the new one will be added to the root's transaction chain.

func (*Scope) RootScope added in v0.6.0

func (s *Scope) RootScope(mStruct *mapping.ModelStruct) *Scope

RootScope gets the root scope for included field queries.

func (*Scope) SetFields added in v0.3.0

func (s *Scope) SetFields(fields ...interface{}) error

SetFields adds the fields to the scope's fieldset. The fields may be a mapping.StructField as well as field's NeuronName (string) or the StructField Name (string).

func (*Scope) SetFieldset

func (s *Scope) SetFieldset(fields ...interface{}) error

SetFieldset sets the fieldset for the 'fields'. A field may be a field's name (string), NeuronName (string) or *mapping.StructField.

func (*Scope) Sort added in v0.3.0

func (s *Scope) Sort(fields ...string) error

Sort adds the sort fields into given scope. If the scope already have sorted fields the function appends newly created sort fields. If the fields are duplicated returns error.

func (*Scope) SortField added in v0.5.1

func (s *Scope) SortField(field interface{}) error

SortField adds the sort 'field' to the scope.

func (*Scope) StoreGet added in v0.2.1

func (s *Scope) StoreGet(key interface{}) (value interface{}, ok bool)

StoreGet gets the value from the scope's Store for given 'key'.

func (*Scope) StoreSet added in v0.2.1

func (s *Scope) StoreSet(key, value interface{})

StoreSet sets the 'key' and 'value' in the given scope's store.

func (*Scope) String added in v0.5.1

func (s *Scope) String() string

String implements fmt.Stringer interface.

func (*Scope) Struct

func (s *Scope) Struct() *mapping.ModelStruct

Struct returns scope's model's structure - *mapping.ModelStruct.

func (*Scope) Tx

func (s *Scope) Tx() *Tx

Tx returns the transaction for the given scope if exists.

func (*Scope) ValidateCreate

func (s *Scope) ValidateCreate() []errors.DetailedError

ValidateCreate validates the scope's value with respect to the 'create validator' and the 'create' validation tags.

func (*Scope) ValidatePatch

func (s *Scope) ValidatePatch() []errors.DetailedError

ValidatePatch validates the scope's value with respect to the 'Patch Validator'.

type SortField added in v0.2.1

type SortField struct {
	StructField *mapping.StructField
	// Order defines if the sorting order (ascending or descending)
	Order SortOrder
	// SubFields are the relationship sub field sorts
	SubFields []*SortField
}

SortField is a field that contains sorting information.

func NewSort added in v0.5.1

func NewSort(m *mapping.ModelStruct, sort string, disallowFK bool, order ...SortOrder) (*SortField, error)

NewSort creates new 'sort' field for given model 'm'. If the 'disallowFK' is set to true the function would not allow to create Sort field of foreign key field.

func NewSortFields added in v0.5.1

func NewSortFields(m *mapping.ModelStruct, disallowFK bool, sortFields ...string) ([]*SortField, error)

NewSortFields creates new 'sortFields' for given model 'm'. If the 'disallowFK' is set to true the function would not allow to create foreign key sort field. The function throws errors on duplicated field values.

func (*SortField) Copy added in v0.6.0

func (s *SortField) Copy() *SortField

Copy creates a copy of the sort field.

func (*SortField) FormatQuery added in v0.2.1

func (s *SortField) FormatQuery(q ...url.Values) url.Values

FormatQuery returns the sort field formatted for url query. If the optional argument 'q' is provided the format would be set into the provdied url.Values. Otherwise it creates new url.Values instance. Returns modified url.Values

func (*SortField) String added in v0.5.1

func (s *SortField) String() string

type SortOrder added in v0.2.1

type SortOrder int

SortOrder is the enum used as the sorting values order.

const (
	// AscendingOrder defines the sorting ascending order.
	AscendingOrder SortOrder = iota
	// DescendingOrder defines the sorting descending order.
	DescendingOrder
)

func (SortOrder) String added in v0.2.1

func (o SortOrder) String() string

String implements fmt.Stringer interface.

type Transactioner

type Transactioner interface {
	// Begin the scope's transaction.
	Begin(ctx context.Context, tx *Tx, model *mapping.ModelStruct) error
	// Commit the scope's transaction.
	Commit(ctx context.Context, tx *Tx, model *mapping.ModelStruct) error
	// Rollback the scope's transaction.
	Rollback(ctx context.Context, tx *Tx, model *mapping.ModelStruct) error
	// ModelTxID gets unique identification for given model - the id might be non unique for multiple models if
	// they exists within single scope of transaction (i.e. single database for multiple models).
	ModelTxID(model *mapping.ModelStruct) (string, error)
}

Transactioner is the interface used for the transactions.

type Tx

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

Tx is an in-progress transaction. A transaction must end with a call to Commit or Rollback. After a call to Commit or Rollback all operations on the transaction fail with an error of class

func Begin added in v0.12.0

func Begin() *Tx

Begin starts new transaction.

func BeginCtx added in v0.12.0

func BeginCtx(ctx context.Context, options *TxOptions) *Tx

BeginCtx starts new transaction with respect to the 'ctx' context and transaction options 'options'.

func (*Tx) Commit added in v0.2.1

func (t *Tx) Commit() error

Commit commits the transaction.

func (*Tx) Err added in v0.13.0

func (t *Tx) Err() error

Err returns current transaction runtime error.

func (*Tx) ID

func (t *Tx) ID() uuid.UUID

ID gets unique transaction uuid.

func (*Tx) Options

func (t *Tx) Options() TxOptions

Options gets transaction options.

func (*Tx) Query added in v0.11.22

func (t *Tx) Query(model interface{}) Builder

Query builds up a new query for given model. The query is executed using transaction context.

func (*Tx) QueryC added in v0.11.22

func (t *Tx) QueryC(c *controller.Controller, model interface{}) Builder

QueryC builds up a new query for given 'model' with given 'c' controller. The query is executed using transaction context.

func (*Tx) Rollback added in v0.2.1

func (t *Tx) Rollback() error

Rollback aborts the transaction.

func (*Tx) State

func (t *Tx) State() TxState

State gets current transaction state.

type TxOptions

type TxOptions struct {
	Isolation IsolationLevel `json:"isolation"`
	ReadOnly  bool           `json:"read_only"`
}

TxOptions are the options for the Transaction

type TxQuery added in v0.12.0

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

TxQuery is the query builder for the transaction.

func (*TxQuery) AddFilterField added in v0.12.0

func (b *TxQuery) AddFilterField(filterField *FilterField) Builder

AddFilterField inserts 'filterField' into the query scope.

func (*TxQuery) Count added in v0.12.0

func (b *TxQuery) Count() (int64, error)

Count returns the number of the values for the provided query scope.

func (*TxQuery) Create added in v0.12.0

func (b *TxQuery) Create() error

Create stores the values within the given scope's value repository, by starting the create process.

func (*TxQuery) Ctx added in v0.12.0

func (b *TxQuery) Ctx() context.Context

Ctx returns query context.

func (*TxQuery) Delete added in v0.12.0

func (b *TxQuery) Delete() error

Delete deletes the values provided in the query's scope.

func (*TxQuery) Err added in v0.12.0

func (b *TxQuery) Err() error

Err returns query error.

func (*TxQuery) Filter added in v0.12.0

func (b *TxQuery) Filter(filter string, values ...interface{}) Builder

Filter parses the filter into the filters.FilterField and adds it to the given scope.

func (*TxQuery) Get added in v0.12.0

func (b *TxQuery) Get() error

Get gets single value from the repository taking into account the scope filters and parameters.

func (*TxQuery) Limit added in v0.12.0

func (b *TxQuery) Limit(limit int64) Builder

Limit sets the maximum number of objects returned by the List process,

func (*TxQuery) List added in v0.12.0

func (b *TxQuery) List() error

List gets the values from the repository taking with respect to the query filters, sorts, pagination and included values.

func (*TxQuery) Offset added in v0.12.0

func (b *TxQuery) Offset(offset int64) Builder

Offset sets the query result's offset. It says to skip as many object's from the repository before beginning to return the result. 'Offset' 0 is the same as omitting the 'Offset' clause.

func (*TxQuery) PageNumber added in v0.12.0

func (b *TxQuery) PageNumber(pageNumber int64) Builder

PageNumber defines the pagination page number.

func (*TxQuery) PageSize added in v0.12.0

func (b *TxQuery) PageSize(pageSize int64) Builder

PageSize defines pagination page size - maximum amount of returned objects.

func (*TxQuery) Patch added in v0.12.0

func (b *TxQuery) Patch() error

Patch updates the scope's attribute and relationship values based on the scope's value and filters. In order to start patch process scope should contain a value with the non-zero primary field, or primary field filters.

func (*TxQuery) Scope added in v0.12.0

func (b *TxQuery) Scope() *Scope

Scope returns query scope.

func (*TxQuery) SetFields added in v0.12.0

func (b *TxQuery) SetFields(fields ...interface{}) Builder

SetFields adds the fields to the scope's fieldset. The fields may be a mapping.StructField as well as field's NeuronName (string) or the StructField Name (string).

func (*TxQuery) Sort added in v0.12.0

func (b *TxQuery) Sort(fields ...string) Builder

Sort creates the sort order of the result.

type TxState

type TxState int

TxState defines the current transaction state

const (
	TxBegin TxState = iota
	TxCommit
	TxRollback
)

Transaction state enums

func (TxState) Done added in v0.12.0

func (t TxState) Done() bool

Done checks if current transaction is already finished.

func (*TxState) MarshalJSON

func (t *TxState) MarshalJSON() ([]byte, error)

MarshalJSON marshals the state into string value Implements the json.Marshaler interface

func (TxState) String

func (t TxState) String() string

func (*TxState) UnmarshalJSON

func (t *TxState) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshal the state from the json string value Implements json.Unmarshaler interface

Jump to

Keyboard shortcuts

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