bsonkit

package
v0.3.7 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: MIT Imports: 16 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Alias2Type = map[string]bsontype.Type{}

Alias2Type is a map from BSON type aliases to BSON types.

View Source
var ErrValidationFailed = fmt.Errorf("validation failed")

ErrValidationFailed is returned when the value failed to validate against the schema.

View Source
var Missing = MissingType{}

Missing represents the absence of a value in a document.

View Source
var Number2Type = map[byte]bsontype.Type{}

Number2Type is a map from BSON type numbers to BSON types.

View Source
var PathEnd = "\x00"

PathEnd is returned by X if the end of the path has been reached.

View Source
var Type2Alias = map[bsontype.Type]string{
	bsontype.Double:           "double",
	bsontype.String:           "string",
	bsontype.EmbeddedDocument: "object",
	bsontype.Array:            "array",
	bsontype.Binary:           "binData",
	bsontype.Undefined:        "undefined",
	bsontype.ObjectID:         "objectId",
	bsontype.Boolean:          "bool",
	bsontype.DateTime:         "date",
	bsontype.Null:             "null",
	bsontype.Regex:            "regex",
	bsontype.DBPointer:        "dbPointer",
	bsontype.JavaScript:       "javascript",
	bsontype.Symbol:           "symbol",
	bsontype.CodeWithScope:    "javascriptWithScope",
	bsontype.Int32:            "int",
	bsontype.Timestamp:        "timestamp",
	bsontype.Int64:            "long",
	bsontype.Decimal128:       "decimal",
	bsontype.MinKey:           "minKey",
	bsontype.MaxKey:           "maxKey",
}

Type2Alias is a map from BSON types to their alias.

Functions

func Add added in v0.2.6

func Add(num, inc interface{}) interface{}

Add will add together two numerical values. It accepts and returns int32, int64, float64 and decimal128.

func All

func All(doc Doc, path string, compact, merge bool) (interface{}, bool)

All has the basic behaviour as Get but additionally collects values from embedded documents in arrays. It returns and array and true if values from multiple documents, haven been collected. Missing values are skipped and intermediary arrays flattened if compact is set to true. By enabling merge, a resulting array of embedded document may be merged to on array containing all values.

func Collect

func Collect(list List, path string, compact, merge, flatten, distinct bool) bson.A

Collect will get the value specified by path from each document and return a list of values. Different to Pick this function will also collect values from arrays of embedded documents. If compact is specified, Missing values are removed and intermediary arrays flattened. By enabling merge, a resulting array of embedded documents may be merged to on array containing all values. Flatten may flatten the resulting arrays per document to one array of values. Distinct may finally sort and remove duplicate values from the list.

func Compare

func Compare(lv, rv interface{}) int

Compare will compare two bson values and return their order according to the BSON type comparison order specification: https://docs.mongodb.com/manual/reference/bson-type-comparison-order.

func ConvertValue added in v0.2.6

func ConvertValue(v interface{}) (interface{}, error)

ConvertValue will convert the provided type to a standard type.

func Decode

func Decode(doc Doc, out interface{}) error

Decode will decode the specified document to an arbitrary value which may be a struct with bson tags in most cases.

func DecodeList

func DecodeList(list List, out interface{}) error

DecodeList will decode a list of documents to an arbitrary value.

func Get

func Get(doc Doc, path string) interface{}

Get returns the value in the document specified by path. It returns Missing if the value has not been found. Dots may be used to descend into nested documents e.g. "foo.bar.baz" and numbers may be used to descend into arrays e.g. "foo.2.bar".

func Increment

func Increment(doc Doc, path string, increment interface{}) (interface{}, error)

Increment will add the increment to the value at the location in the document specified by path and return the new value. If the value is missing, the increment is added to the document. The type of the field may be changed as part of the operation.

func IndexedPath added in v0.2.4

func IndexedPath(path string) bool

IndexedPath returns true if the specified path contains array indices.

func Mod added in v0.2.6

func Mod(num, div interface{}) interface{}

Mod will compute the modulo of the two values. It accepts and returns int32, in64, float64 and decimal128.

func Mul added in v0.2.6

func Mul(num, mul interface{}) interface{}

Mul will multiply the two numerical values. It accepts and returns int32, int64, float64 and decimal128.

func Multiply

func Multiply(doc Doc, path string, multiplier interface{}) (interface{}, error)

Multiply will multiply the multiplier with the value at the location in the document specified by path and return the new value. If the value is missing, a zero is added to the document. The type of the field may be changed as part of the operation.

func MustConvertValue added in v0.2.6

func MustConvertValue(v interface{}) interface{}

MustConvertValue will call ConvertValue and panic on errors.

func Now

func Now() primitive.Timestamp

Now will generate a locally monotonic timestamp.

func Order

func Order(l, r Doc, columns []Column, identity bool) int

Order will return the order of documents based on the specified columns.

func ParseIndex added in v0.2.0

func ParseIndex(str string) (int, bool)

ParseIndex will attempt to parse the provided string as an index.

func PathSegment added in v0.2.0

func PathSegment(path string) string

PathSegment will return the first segment of the path.

func PathSegmentReverse added in v0.2.3

func PathSegmentReverse(path string) string

PathSegmentReverse will return the last segment of the path.

func Pick

func Pick(list List, path string, compact bool) bson.A

Pick will get the value specified by path from each document and return a list of values. If compact is specified, Missing values are removed.

func Pop added in v0.2.0

func Pop(doc Doc, path string, last bool) (interface{}, error)

Pop will remove the first or last element from the array at the location in the document specified byt path and return the updated array. If the array is empty, the value is missing or not an array, it will do nothing and return Missing.

func Push added in v0.1.9

func Push(doc Doc, path string, value interface{}) (interface{}, error)

Push will add the value to the array at the location in the document specified by path and return the new value. If the value is missing, the value is added to a new array.

func Put

func Put(doc Doc, path string, value interface{}, prepend bool) (interface{}, error)

Put will store the value in the document at the location specified by path and return the previously stored value. It will automatically create document fields, array elements and embedded documents to fulfill the request. If prepends is set to true, new values are inserted at the beginning of the array or document. If the path contains a number e.g. "foo.1.bar" and no array exists at that levels, a document with the key "1" is created.

func ReducePath added in v0.2.3

func ReducePath(path string) string

ReducePath will reduce the path by one segment. It will return PathEnd if there are no more segments.

func ReducePathReverse added in v0.2.3

func ReducePathReverse(path string) string

ReducePathReverse will reduce the path by one segment from the back. It will return PathEnd if there are no more segments.

func Sort

func Sort(list List, columns []Column, identity bool)

Sort will sort the list of documents in-place based on the specified columns.

func Transfer

func Transfer(in, out interface{}) error

Transfer will transfer data from one type to another by marshalling the data and unmarshalling it again. This method is not very fast, but it ensures compatibility with custom types that implement the bson.Marshaller interface.

func Unset

func Unset(doc Doc, path string) interface{}

Unset will remove the value at the location in the document specified by path and return the previously stored value. If the path specifies an array element e.g. "foo.2" the element is nilled, but not removed from the array. This prevents unintentional effects through position shifts in the array.

Types

type Class

type Class int

Class is describes the class of one or more BSON types.

const (
	Null Class = iota
	Number
	String
	Document
	Array
	Binary
	ObjectID
	Boolean
	Date
	Timestamp
	Regex
)

The available BSON type classes.

func Inspect

func Inspect(v interface{}) (Class, bsontype.Type)

Inspect wil return the BSON type class and concrete type of the specified value.

type Column

type Column struct {
	Path    string
	Reverse bool
}

Column defines a column for ordering.

type Doc

type Doc = *bson.D

Doc is a full document that may contain fields, arrays and embedded documents. The pointer form is chosen to identify the document uniquely (pointer address).

func Clone

func Clone(doc Doc) Doc

Clone will clone the specified document. The returned document can be safely mutated without mutating the original document with one exception: the content of primitive.Binary values is not cloned and references the same byte slice as the original.

The function may panic if the doc is not obtained using Convert or Transform and contains unsupported types.

func Convert

func Convert(v interface{}) (Doc, error)

Convert will convert the provided value to a document. The value is expected to be a bson.M or bson.D composed of standard types.

func MustConvert added in v0.2.2

func MustConvert(v interface{}) Doc

MustConvert will call Convert and panic on errors.

func Transform

func Transform(v interface{}) (Doc, error)

Transform will transform an arbitrary value into a document composed of known primitives.

type Index

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

Index is a basic btree based index for documents. The index is not safe from concurrent access.

func NewIndex

func NewIndex(unique bool, columns []Column) *Index

NewIndex creates and returns a new index.

func (*Index) Add

func (i *Index) Add(doc Doc) bool

Add will add the document to index. May return false if the document has already been added to the index.

func (*Index) Build

func (i *Index) Build(list List) bool

Build will build the index from the specified list. It may return false if there was a unique constraint error when building the index. If an error is returned the index only has some documents added.

func (*Index) Clone

func (i *Index) Clone() *Index

Clone will clone the index. Mutating the new index will not mutate the original index.

func (*Index) Has

func (i *Index) Has(doc Doc) bool

Has returns whether the specified document has been added to the index.

func (*Index) List added in v0.1.5

func (i *Index) List() List

List will return an ascending list of all documents in the index.

func (*Index) Remove

func (i *Index) Remove(doc Doc) bool

Remove will remove a document from the index. May return false if the document has not yet been added to the index.

type List

type List = []Doc

List is consecutive list of documents.

func CloneList

func CloneList(list List) List

CloneList will clone a list of documents.

The function may panic if a doc is not obtained using Convert or Transform and contains unsupported types.

func ConvertList added in v0.2.0

func ConvertList(v interface{}) (List, error)

ConvertList will convert an array to a list. The value is expected to be an array of bson.M or bson.D elements composed of standard types.

func MustConvertList added in v0.2.2

func MustConvertList(v interface{}) List

MustConvertList will call ConvertList and panic on errors.

func Select

func Select(list List, limit int, selector func(Doc) (bool, bool)) List

Select will return a list of documents selected by the specified selector. Limit may be specified to break early if the list reached the limit.

func TransformList

func TransformList(v interface{}) (List, error)

TransformList will transform an arbitrary value info a list of documents composed of known primitives.

type MissingType

type MissingType struct{}

MissingType is the type of the Missing value.

type PathBuilder added in v0.2.4

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

PathBuilder is a memory efficient builder for paths.

func NewPathBuilder added in v0.2.4

func NewPathBuilder(buffer int) *PathBuilder

NewPathBuilder creates a new path builder with the provided allocated memory.

func (*PathBuilder) AddIndex added in v0.2.4

func (b *PathBuilder) AddIndex(idx int) int

AddIndex will add the specified index.

func (*PathBuilder) AddSegment added in v0.2.4

func (b *PathBuilder) AddSegment(seg string) int

AddSegment will add the specified segment.

func (*PathBuilder) String added in v0.2.4

func (b *PathBuilder) String() string

String will return the built path.

func (*PathBuilder) Truncate added in v0.2.4

func (b *PathBuilder) Truncate(len int)

Truncate will shrink the buffer to the provided length.

type PathNode added in v0.2.4

type PathNode map[string]interface{}

PathNode is a node of a path tree.

func NewPathNode added in v0.2.4

func NewPathNode() PathNode

NewPathNode will return a new path node.

func (PathNode) Append added in v0.2.4

func (n PathNode) Append(path string) PathNode

Append will traverse the path and append missing nodes.

func (PathNode) Load added in v0.2.4

func (n PathNode) Load() interface{}

Load will return the currently stored value.

func (PathNode) Lookup added in v0.2.4

func (n PathNode) Lookup(path string) (PathNode, string)

Lookup will traverse the path and return the last node. If the returned path is PathEnd the returned node is the final node.

func (PathNode) Recycle added in v0.2.4

func (n PathNode) Recycle()

Recycle will clear the node and its children.

func (PathNode) Store added in v0.2.4

func (n PathNode) Store(value interface{}) interface{}

Store will set the specified value and return the previous stored value.

type Schema added in v0.2.6

type Schema struct {
	// The schema document.
	Doc bson.D

	// The regex cache.
	Regexes map[string]*regexp.Regexp
}

Schema implements the JSON Schema validation algorithm. Specifically, it implements the following specifications:

- https://docs.mongodb.com/manual/reference/operator/query/jsonSchema - https://tools.ietf.org/html/draft-zyp-json-schema-04 - https://tools.ietf.org/html/draft-fge-json-schema-validation-00

Note: The Go regex engine ist not ECMA 262 compatible as required by the draft.

func NewSchema added in v0.2.6

func NewSchema(doc bson.D) *Schema

NewSchema will create and return a new schema from the provided document.

func (*Schema) Evaluate added in v0.2.6

func (s *Schema) Evaluate(value interface{}) error

Evaluate will evaluate the schema against the provided value. It returns ErrValidationFailed if the validation failed or another error if the schema is invalid or validation cannot be performed.

type Set

type Set struct {
	List  List
	Index map[Doc]int
}

Set is set of unique documents. The set is not safe from concurrent access.

func NewSet

func NewSet(list List) *Set

NewSet returns a new set from the specified list.

func (*Set) Add

func (s *Set) Add(doc Doc) bool

Add will add the document to set, if has not already been added. It may return false if the document has already been added.

func (*Set) Clone

func (s *Set) Clone() *Set

Clone will clone the set. Mutating the new set will not mutate the original set.

func (*Set) Remove

func (s *Set) Remove(doc Doc) bool

Remove will remove the document from the set. It may return false if the document has not been added to the set.

func (*Set) Replace

func (s *Set) Replace(d1, d2 Doc) bool

Replace will replace the first document with the second. It may return false if the first document has not been added and the second already has been added.

Jump to

Keyboard shortcuts

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