common

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2023 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package common provides common code for all handlers.

Index

Constants

View Source
const (
	// MinWireVersion is the minimal supported wire protocol version.
	MinWireVersion = int32(0) // needed for some apps and drivers

	// MaxWireVersion is the maximal supported wire protocol version.
	MaxWireVersion = int32(17)
)

Variables

This section is empty.

Functions

func AddFieldsIterator added in v1.4.0

func AddFieldsIterator(iter types.DocumentsIterator, closer *iterator.MultiCloser, newField *types.Document) types.DocumentsIterator

AddFieldsIterator returns an iterator that adds a new field to the underlying iterator. It will be added to the given closer.

Next method returns the next document after adding the new field to the document.

Close method closes the underlying iterator.

func AssertType added in v0.1.0

func AssertType[T types.Type](value any) (T, error)

AssertType asserts value's type, returning protocol error for unexpected types.

If a custom error is needed, use a normal Go type assertion instead:

d, ok := value.(*types.Document)
if !ok {
  return commonerrors.NewCommandErrorMsg(commonerrors.ErrBadValue, "expected document")
}

func CountIterator deprecated added in v1.1.0

func CountIterator(iter types.DocumentsIterator, closer *iterator.MultiCloser, field string) types.DocumentsIterator

CountIterator returns an iterator that returns a single document containing the number of input documents (as int32) in the specified field: {field: count}. It will be added to the given closer.

Next method returns that document, subsequent calls return ErrIteratorDone. If input iterator contains no document, it returns ErrIteratorDone.

Close method closes the underlying iterator.

Deprecated: remove this function, use iterator.ConsumeCount instead.

func FilterDistinctValues added in v0.8.1

func FilterDistinctValues(iter types.DocumentsIterator, key string) (*types.Array, error)

FilterDistinctValues returns distinct values from the given slice of documents with the given key.

If the key is not found in the document, the document is ignored.

If the key is found in the document, and the value is an array, each element of the array is added to the result. Otherwise, the value itself is added to the result.

func FilterDocument added in v0.1.0

func FilterDocument(doc, filter *types.Document) (bool, error)

FilterDocument returns true if given document satisfies given filter expression.

Passed arguments must not be modified.

func FilterIterator added in v0.9.4

func FilterIterator(iter types.DocumentsIterator, closer *iterator.MultiCloser, filter *types.Document) types.DocumentsIterator

FilterIterator returns an iterator that filters out documents that don't match the filter. It will be added to the given closer.

Next method returns the next document that matches the filter.

Close method closes the underlying iterator.

func GetFreeMonitoringStatus added in v0.7.1

func GetFreeMonitoringStatus(ctx context.Context, msg *wire.OpMsg, state *state.State) (*wire.OpMsg, error)

GetFreeMonitoringStatus is a part of common implementation of the getFreeMonitoringStatus command.

func GetLimitStageParam added in v1.0.0

func GetLimitStageParam(value any) (int64, error)

GetLimitStageParam returns $limit stage argument from the provided value. It returns the proper error if value doesn't meet requirements.

func GetMore added in v1.0.0

func GetMore(ctx context.Context, msg *wire.OpMsg, registry *cursor.Registry) (*wire.OpMsg, error)

GetMore is a part of common implementation of the getMore command.

func GetOptionalNullParam added in v1.1.0

func GetOptionalNullParam[T types.Type](doc *types.Document, key string, defaultValue T) (T, error)

GetOptionalNullParam returns doc's value for key, default value for missing parameter or null, or protocol error for other invalid type.

func GetOptionalParam added in v0.1.0

func GetOptionalParam[T types.Type](doc *types.Document, key string, defaultValue T) (T, error)

GetOptionalParam returns doc's value for key, default value for missing parameter, or protocol error for invalid type.

func GetRequiredParam added in v0.1.0

func GetRequiredParam[T types.Type](doc *types.Document, key string) (T, error)

GetRequiredParam returns doc's value for key or protocol error for missing key or invalid type.

func GetSkipStageParam added in v1.0.0

func GetSkipStageParam(value any) (int64, error)

GetSkipStageParam returns $skip stage argument from the provided value. It returns the proper error if value doesn't meet requirements.

func GetSortType added in v1.1.0

func GetSortType(key string, value any) (types.SortType, error)

GetSortType determines SortType from input sort value.

func HasSupportedUpdateModifiers added in v0.5.3

func HasSupportedUpdateModifiers(command string, update *types.Document) (bool, error)

HasSupportedUpdateModifiers checks that update document contains supported update operators. If no update operators are found it returns false. If update document contains unsupported update operators it returns an error.

func Ignored added in v0.0.6

func Ignored(doc *types.Document, l *zap.Logger, fields ...string)

Ignored logs a message if doc has any of the given fields.

func LimitDocuments added in v0.1.0

func LimitDocuments(docs []*types.Document, limit int64) ([]*types.Document, error)

LimitDocuments returns a subslice of given documents according to the given limit value.

func LimitIterator added in v1.0.0

func LimitIterator(iter types.DocumentsIterator, closer *iterator.MultiCloser, limit int64) types.DocumentsIterator

LimitIterator returns an iterator that limits a number of documents returned by the underlying iterator. It will be added to the given closer.

Next method returns the next document until the limit is reached, then it returns iterator.ErrIteratorDone.

Close method closes the underlying iterator.

func MsgLogout added in v1.3.0

func MsgLogout(ctx context.Context, msg *wire.OpMsg) (*wire.OpMsg, error)

MsgLogout is a common implementation of the logout command.

func ProjectDocument added in v1.1.0

func ProjectDocument(doc, projection, filter *types.Document, inclusion bool) (*types.Document, error)

ProjectDocument applies projection to the copy of the document. It returns proper CommandError that can be returned by $project aggregation stage.

Command error codes: - ErrEmptySubProject when operator value is empty. - ErrFieldPathInvalidName when FieldPath is invalid. - ErrNotImplemented when the operator is not implemented yet. - ErrOperatorWrongLenOfArgs when the operator has an invalid number of arguments. - ErrInvalidPipelineOperator when an the operator does not exist.

func ProjectionIterator added in v1.0.0

func ProjectionIterator(iter types.DocumentsIterator, closer *iterator.MultiCloser, projection, filter *types.Document) (types.DocumentsIterator, error)

ProjectionIterator returns an iterator that projects documents returned by the underlying iterator. It will be added to the given closer.

Next method returns the next projected document.

Close method closes the underlying iterator.

func SASLStartPlain added in v0.9.3

func SASLStartPlain(doc *types.Document) (string, string, error)

SASLStartPlain extracts username and password from PLAIN `saslStart` payload.

func ServerStatus added in v0.6.0

func ServerStatus(state *state.State, cm *connmetrics.ConnMetrics) (*types.Document, error)

ServerStatus returns a common part of serverStatus command response.

func SetFreeMonitoring added in v0.7.1

func SetFreeMonitoring(_ context.Context, msg *wire.OpMsg, provider *state.Provider) (*wire.OpMsg, error)

SetFreeMonitoring is a part of common implementation of the setFreeMonitoring command.

func SkipDocuments added in v1.0.0

func SkipDocuments(docs []*types.Document, skip int64) ([]*types.Document, error)

SkipDocuments returns a subslice of given documents according to the given skip value.

func SkipIterator added in v1.0.0

func SkipIterator(iter types.DocumentsIterator, closer *iterator.MultiCloser, skip int64) types.DocumentsIterator

SkipIterator returns an iterator that skips a number of documents returned by the underlying iterator. It will be added to the given closer.

Next method returns the next document after skipping a number of documents.

Close method closes the underlying iterator.

func SortArray added in v0.8.1

func SortArray(arr *types.Array, sortType types.SortType)

SortArray sorts the values of given array.

func SortDocuments added in v0.1.0

func SortDocuments(docs []*types.Document, sortDoc *types.Document) error

SortDocuments sorts given documents in place according to the given sorting conditions.

If sort path is invalid, it returns a possibly wrapped types.DocumentPathError.

func SortIterator added in v1.0.0

SortIterator returns an iterator of sorted documents. It will be added to the given closer.

Since sorting iterator is impossible, this function fully consumes and closes the underlying iterator, sorts documents in memory and returns a new iterator over the sorted slice.

func Unimplemented added in v0.0.6

func Unimplemented(doc *types.Document, fields ...string) error

Unimplemented returns commonerrors.ErrNotImplemented if doc has any of the given fields.

func UnimplementedNonDefault added in v0.0.6

func UnimplementedNonDefault(doc *types.Document, field string, isDefault func(v any) bool) error

UnimplementedNonDefault returns commonerrors.ErrNotImplemented if doc has given field, and isDefault, called with the actual value, returns false.

func UpdateDocument added in v0.1.1

func UpdateDocument(command string, doc, update *types.Document) (bool, error)

UpdateDocument updates the given document with a series of update operators. Returns true if document was changed. To validate update document, must call ValidateUpdateOperators before calling UpdateDocument. UpdateDocument returns CommandError for findAndModify case-insensitive command name, WriteError for other commands.

func Validate added in v0.7.1

func Validate(ctx context.Context, msg *wire.OpMsg, l *zap.Logger) (*wire.OpMsg, error)

Validate is a part of a common implementation of the validate command.

func ValidateProjection added in v1.1.0

func ValidateProjection(projection *types.Document) (*types.Document, bool, error)

ValidateProjection check projection document. Document fields could be either included or excluded but not both. Exception is for the _id field that could be included or excluded. ValidateProjection returns errProjectionEmpty for empty projection and CommandError for invalid projection fields.

Command error codes:

  • `ErrProjectionExIn` when there is exclusion in inclusion projection;
  • `ErrProjectionInEx` when there is inclusion in exclusion projection;
  • `ErrEmptyFieldPath` when projection path is empty;
  • `ErrInvalidFieldPath` when positional projection path contains empty key;
  • `ErrPathContainsEmptyElement` when projection path contains empty key;
  • `ErrFieldPathInvalidName` when `$` is at the prefix of a key in the path;
  • `ErrWrongPositionalOperatorLocation` when there are multiple `$`;
  • `ErrExclusionPositionalProjection` when positional projection is used for exclusion;
  • `ErrBadPositionalProjection` when array or filter at positional projection path is empty;
  • `ErrBadPositionalProjection` when there is no filter field key for positional projection path;
  • `ErrElementMismatchPositionalProjection` when unexpected array was found on positional projection path;
  • `ErrNotImplemented` when there is unimplemented projection operators and expressions.

func ValidateUpdateOperators added in v0.4.0

func ValidateUpdateOperators(command string, update *types.Document) error

ValidateUpdateOperators validates update statement. ValidateUpdateOperators returns CommandError for findAndModify case-insensitive command name, WriteError for other commands.

Types

type CountParams added in v1.1.0

type CountParams struct {
	Filter     *types.Document `ferretdb:"query,opt"`
	DB         string          `ferretdb:"$db"`
	Collection string          `ferretdb:"collection"`

	Skip  int64 `ferretdb:"skip,opt,positiveNumber"`
	Limit int64 `ferretdb:"limit,opt,positiveNumber"`

	Collation *types.Document `ferretdb:"collation,unimplemented"`

	Hint        any             `ferretdb:"hint,ignored"`
	ReadConcern *types.Document `ferretdb:"readConcern,ignored"`
	Comment     string          `ferretdb:"comment,ignored"`
	LSID        any             `ferretdb:"lsid,ignored"`
}

CountParams represents parameters for the count command.

func GetCountParams added in v1.1.0

func GetCountParams(document *types.Document, l *zap.Logger) (*CountParams, error)

GetCountParams returns the parameters for the count command.

type Delete added in v1.1.0

type Delete struct {
	Filter  *types.Document `ferretdb:"q"`
	Limited bool            `ferretdb:"limit,zeroOrOneAsBool"`
	// TODO: https://github.com/FerretDB/FerretDB/issues/2627
	Comment string `ferretdb:"comment,opt"`

	Collation *types.Document `ferretdb:"collation,unimplemented"`

	Hint string `ferretdb:"hint,ignored"`
}

Delete represents single delete operation parameters.

type DeleteParams added in v1.1.0

type DeleteParams struct {
	DB         string `ferretdb:"$db"`
	Collection string `ferretdb:"collection"`

	Comment string   `ferretdb:"comment,opt"`
	Deletes []Delete `ferretdb:"deletes,opt"`
	Ordered bool     `ferretdb:"ordered,opt"`

	Let *types.Document `ferretdb:"let,unimplemented"`

	WriteConcern *types.Document `ferretdb:"writeConcern,ignored"`
	LSID         any             `ferretdb:"lsid,ignored"`
}

DeleteParams represents parameters for the delete command.

func GetDeleteParams added in v1.1.0

func GetDeleteParams(document *types.Document, l *zap.Logger) (*DeleteParams, error)

GetDeleteParams returns parameters for delete operation.

type DistinctParams added in v0.8.1

type DistinctParams struct {
	DB         string          `ferretdb:"$db"`
	Collection string          `ferretdb:"collection"`
	Key        string          `ferretdb:"key"`
	Filter     *types.Document `ferretdb:"-"`
	Comment    string          `ferretdb:"comment,opt"`

	Query any `ferretdb:"query,opt"`

	Collation *types.Document `ferretdb:"collation,unimplemented"`

	ReadConcern *types.Document `ferretdb:"readConcern,ignored"`
}

DistinctParams contains `distinct` command parameters supported by at least one handler.

func GetDistinctParams added in v0.8.1

func GetDistinctParams(document *types.Document, l *zap.Logger) (*DistinctParams, error)

GetDistinctParams returns `distinct` command parameters.

type ExplainParams added in v1.1.0

type ExplainParams struct {
	DB         string `ferretdb:"$db"`
	Collection string `ferretdb:"collection"`

	Explain *types.Document `ferretdb:"explain"`

	Filter *types.Document `ferretdb:"filter,opt"`
	Sort   *types.Document `ferretdb:"sort,opt"`

	StagesDocs []any           `ferretdb:"-"`
	Aggregate  bool            `ferretdb:"-"`
	Command    *types.Document `ferretdb:"-"`

	Verbosity string `ferretdb:"verbosity,ignored"`
}

ExplainParams represents the parameters for the explain command.

func GetExplainParams added in v1.1.0

func GetExplainParams(document *types.Document, l *zap.Logger) (*ExplainParams, error)

GetExplainParams returns the parameters for the explain command.

type FindAndModifyParams added in v0.5.3

type FindAndModifyParams struct {
	DB                string          `ferretdb:"$db"`
	Collection        string          `ferretdb:"collection"`
	Comment           string          `ferretdb:"comment,opt"`
	Query             *types.Document `ferretdb:"query,opt"`
	Sort              *types.Document `ferretdb:"sort,opt"`
	UpdateValue       any             `ferretdb:"update,opt"`
	Remove            bool            `ferretdb:"remove,opt"`
	Upsert            bool            `ferretdb:"upsert,opt"`
	ReturnNewDocument bool            `ferretdb:"new,opt,numericBool"`
	MaxTimeMS         int64           `ferretdb:"maxTimeMS,opt,wholePositiveNumber"`

	Update      *types.Document `ferretdb:"-"`
	Aggregation *types.Array    `ferretdb:"-"`

	HasUpdateOperators bool `ferretdb:"-"`

	Let          *types.Document `ferretdb:"let,unimplemented"`
	Collation    *types.Document `ferretdb:"collation,unimplemented"`
	Fields       *types.Document `ferretdb:"fields,unimplemented"`
	ArrayFilters *types.Array    `ferretdb:"arrayFilters,unimplemented"`

	Hint                     string          `ferretdb:"hint,ignored"`
	WriteConcern             *types.Document `ferretdb:"writeConcern,ignored"`
	BypassDocumentValidation bool            `ferretdb:"bypassDocumentValidation,ignored"`
}

FindAndModifyParams represent parameters for the findAndModify command.

func GetFindAndModifyParams added in v0.9.4

func GetFindAndModifyParams(doc *types.Document, l *zap.Logger) (*FindAndModifyParams, error)

GetFindAndModifyParams returns `findAndModifyParams` command parameters.

type FindParams added in v0.7.0

type FindParams struct {
	DB          string          `ferretdb:"$db"`
	Collection  string          `ferretdb:"collection"`
	Filter      *types.Document `ferretdb:"filter,opt"`
	Sort        *types.Document `ferretdb:"sort,opt"`
	Projection  *types.Document `ferretdb:"projection,opt"`
	Skip        int64           `ferretdb:"skip,opt,positiveNumber"`
	Limit       int64           `ferretdb:"limit,opt,positiveNumber"`
	BatchSize   int64           `ferretdb:"batchSize,opt,positiveNumber"`
	SingleBatch bool            `ferretdb:"singleBatch,opt"`
	Comment     string          `ferretdb:"comment,opt"`
	MaxTimeMS   int64           `ferretdb:"maxTimeMS,opt,wholePositiveNumber"`

	Collation *types.Document `ferretdb:"collation,unimplemented"`
	Let       *types.Document `ferretdb:"let,unimplemented"`

	AllowDiskUse bool            `ferretdb:"allowDiskUse,ignored"`
	ReadConcern  *types.Document `ferretdb:"readConcern,ignored"`
	Max          *types.Document `ferretdb:"max,ignored"`
	Min          *types.Document `ferretdb:"min,ignored"`
	Hint         any             `ferretdb:"hint,ignored"`
	LSID         any             `ferretdb:"lsid,ignored"`

	ReturnKey           bool `ferretdb:"returnKey,unimplemented-non-default"`
	ShowRecordId        bool `ferretdb:"showRecordId,unimplemented-non-default"`
	Tailable            bool `ferretdb:"tailable,unimplemented-non-default"`
	OplogReplay         bool `ferretdb:"oplogReplay,unimplemented-non-default"`
	NoCursorTimeout     bool `ferretdb:"noCursorTimeout,unimplemented-non-default"`
	AwaitData           bool `ferretdb:"awaitData,unimplemented-non-default"`
	AllowPartialResults bool `ferretdb:"allowPartialResults,unimplemented-non-default"`
}

FindParams represents parameters for the find command.

func GetFindParams added in v0.7.0

func GetFindParams(doc *types.Document, l *zap.Logger) (*FindParams, error)

GetFindParams returns `find` command parameters.

type InsertParams added in v1.1.0

type InsertParams struct {
	Docs       *types.Array `ferretdb:"documents,opt"`
	DB         string       `ferretdb:"$db"`
	Collection string       `ferretdb:"collection"`
	Ordered    bool         `ferretdb:"ordered,opt"`

	WriteConcern             any    `ferretdb:"writeConcern,ignored"`
	BypassDocumentValidation bool   `ferretdb:"bypassDocumentValidation,ignored"`
	Comment                  string `ferretdb:"comment,ignored"`
	LSID                     any    `ferretdb:"lsid,ignored"`
}

InsertParams represents the parameters for an insert command.

func GetInsertParams added in v1.1.0

func GetInsertParams(document *types.Document, l *zap.Logger) (*InsertParams, error)

GetInsertParams returns the parameters for an insert command.

type UpdateParams added in v1.1.0

type UpdateParams struct {
	// TODO: https://github.com/FerretDB/FerretDB/issues/2627
	// get comment from query, e.g. db.collection.UpdateOne({"_id":"string", "$comment: "test"},{$set:{"v":"foo""}})
	Filter *types.Document `ferretdb:"q,opt"`
	Update *types.Document `ferretdb:"u,opt"` // TODO https://github.com/FerretDB/FerretDB/issues/2742
	Multi  bool            `ferretdb:"multi,opt"`
	Upsert bool            `ferretdb:"upsert,opt,numericBool"`

	C            *types.Document `ferretdb:"c,unimplemented"`
	Collation    *types.Document `ferretdb:"collation,unimplemented"`
	ArrayFilters *types.Array    `ferretdb:"arrayFilters,unimplemented"`

	Hint string `ferretdb:"hint,ignored"`
}

UpdateParams represents a single update operation parameters.

type UpdatesParams added in v1.1.0

type UpdatesParams struct {
	DB         string         `ferretdb:"$db"`
	Collection string         `ferretdb:"collection"`
	Updates    []UpdateParams `ferretdb:"updates"`

	Comment string `ferretdb:"comment,opt"`

	Let *types.Document `ferretdb:"let,unimplemented"`

	Ordered                  bool            `ferretdb:"ordered,ignored"`
	BypassDocumentValidation bool            `ferretdb:"bypassDocumentValidation,ignored"`
	WriteConcern             *types.Document `ferretdb:"writeConcern,ignored"`
}

UpdatesParams represents parameters for the update command.

func GetUpdateParams added in v1.1.0

func GetUpdateParams(document *types.Document, l *zap.Logger) (*UpdatesParams, error)

GetUpdateParams returns parameters for update command.

type UpsertOperation added in v1.1.0

type UpsertOperation uint8

UpsertOperation represents operation type of upsert.

const (

	// UpsertOperationInsert indicates that upsert is an insert operation.
	UpsertOperationInsert UpsertOperation

	// UpsertOperationUpdate indicates that upsert is a update operation.
	UpsertOperationUpdate
)

func (UpsertOperation) String added in v1.1.0

func (i UpsertOperation) String() string

type UpsertParams added in v1.1.0

type UpsertParams struct {
	// ReturnValue is the value set on the command response.
	// It returns original document for update operation, and null for insert operation.
	// If FindAndModifyParams.ReturnNewDocument is true, it returns upserted document.
	ReturnValue any

	// Upsert is a document used for insert or update operation.
	Upsert *types.Document

	// Operation is the type of upsert to perform.
	Operation UpsertOperation
}

UpsertParams represents parameters for upsert, if the document exists UpdateParams is set. Otherwise, Insert is set. It returns ReturnValue to return to the client.

func PrepareDocumentForUpsert added in v1.1.0

func PrepareDocumentForUpsert(docs []*types.Document, params *FindAndModifyParams) (*UpsertParams, error)

PrepareDocumentForUpsert prepares the document used for upsert operation. If docs is empty it prepares a document for insert using params. Otherwise, it takes the first document of docs and prepare document for update. It sets the value to return on the command response using ReturnNewDocument param.

Directories

Path Synopsis
Package aggregations provides aggregation pipelines.
Package aggregations provides aggregation pipelines.
operators
Package operators provides aggregation operators.
Package operators provides aggregation operators.
operators/accumulators
Package accumulators provides aggregation accumulator operators.
Package accumulators provides aggregation accumulator operators.
stages
Package stages provides aggregation stages.
Package stages provides aggregation stages.
stages/projection
Package projection provides projection for aggregations.
Package projection provides projection for aggregations.

Jump to

Keyboard shortcuts

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