document

package
v1.85.2 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultCreatedAtField is the document field that is automatically added
	// by Service implementors. See Service.Create for more info.
	DefaultCreatedAtField = "CreatedAt"

	// DefaultUpdatedAtField is the document field that is automatically updated
	// by Service implementors. See Service.Update for more info.
	DefaultUpdatedAtField = "UpdatedAt"

	// LowerCreatedAtField is the document field that is automatically added
	// by Service implementors when using a marshaler that defaults to lower case,
	// either directly or indirectly through another Service.
	LowerCreatedAtField = "createdat"

	// LowerUpdatedAtField is the document field that is automatically updated
	// by Service implementors when using a marshaler that defaults to lower case,
	// either directly or indirectly through another Service.
	LowerUpdatedAtField = "updatedat"
)
View Source
const (
	// OpEqual evalates true if the value in the Filter and the value
	// stored are equal.
	OpEqual Op = "=="
	// OpGreaterThan evalates true if the value in the Filter
	// is greater than the value stored in the collection.
	OpGreaterThan = ">"
	// OpGreaterThanEqual evalates true if the value in the Filter
	// is greater than or equal to the value stored in the collection.
	OpGreaterThanEqual = ">="
	// OpLessThan evalates true if the value in the Filter
	// is smaller than the value stored in the collection.
	OpLessThan = "<"
	// OpLessThanEqual evalates true if the value in the Filter
	// is smaller than or equal to the value stored in the collection.
	OpLessThanEqual = "<="
)

Variables

View Source
var (
	// ErrNotFound is returned when the given document was not found in the store.
	ErrNotFound = errors.New("document not found")

	// ErrAlreadyExists is returned when the given document already exists.
	ErrAlreadyExists = errors.New("document already exists")

	// ErrPreconditionFailed is returned when a Precondition to Update
	// is not met by the underlying document.
	ErrPreconditionFailed = errors.New("document pre-condition was not met")

	// ErrPermissionDenied is returned when an operation is denied due to
	// permissions.
	ErrPermissionDenied = errors.New("access to document denied")
)

Functions

func ConsistentUpdate

func ConsistentUpdate(
	ctx context.Context, svc Service, ID string, doc interface{},
	retryStrategy retry.Strategy, callback func() ([]Update, []Precondition),
) error

ConsistentUpdate calls Update on the given service and tries to update the underlying document with the provided retry strategy and the callback function which gets called before attempting to update the document in storage. This can be used to scan the updated doc for any data that has been updated in the process of performing this operation and to update preconditions with the latest values.

The given doc value will be updated so it should be a valid value as defined by Service.Get.

func DerefCreateValue

func DerefCreateValue(data reflect.Value) (any, error)

DerefCreateValue dereferences data for a service.Create implementation until it finds a structure that can be used for Encode/Decode or returns an error if no such structure could be found.

func DerefUpdateValue

func DerefUpdateValue(data reflect.Value) (any, error)

DerefUpdateValue dereferences data until it finds a value that can be used by UpdateDefaultCreatedAtField and UpdateDefaultUpdatedAtField to update their updated at or created at fields.

func Encode

func Encode(m docmarshal.Marshaler, doc any, addCreatedAt bool) []byte

Encode encodes doc into a reversible format (via Decode) and returns the data in bytes.

func IsEncodeable

func IsEncodeable(doc any) bool

IsEncodeable returns true if doc is a structure that can be safely decoded via Decode.

func MatchFilter

func MatchFilter(proto map[string]any, f Filter) bool

MatchFilter returns true if proto satisfies the filter condition of f.

func MatchesAllFilters

func MatchesAllFilters(
	m docmarshal.Marshaler, proto map[string]any,
	filters []Filter,
) bool

MatchesAllFilters returns true if proto satisfies all of the give filters.

func SafeDecode

func SafeDecode(m docmarshal.Marshaler, rcv any, raw []byte) error

SafeDecode checks if the given interface would be decoded by Decode and decodes it or otherwise returns an error.

func UpdateCreatedAtField

func UpdateCreatedAtField(marshaler docmarshal.Marshaler, doc any) any

UpdateCreatedAtField calls UpdateCreatedAtFieldTime with time.Now. Deprecated: Use UpdateDefaultCreatedAtField.

func UpdateDefaultCreatedAtField

func UpdateDefaultCreatedAtField(doc any, now time.Time, lowerCase bool) any

UpdateDefaultCreatedAtField updates the default CreatedAt field in the given document and the default UpdatedAt field. If lowerCase is false DefaultUpdatedAtField is used, otherwise LowerUpdatedAtField is used. If doc is not a map, a struct or a pointer to a struct, this method panics.

func UpdateDefaultUpdatedAtField

func UpdateDefaultUpdatedAtField(doc any, now time.Time, lowerCase bool) any

UpdateDefaultUpdatedAtField updates the default UpdatedAt field in the given document. If lowerCase is false DefaultUpdatedAtField is used, otherwise LowerUpdatedAtField is used. If doc is not a map, a struct or a pointer to a struct, this method panics.

func UpdateProto

func UpdateProto(m docmarshal.Marshaler, updates []Update,
	proto map[string]any, preconds ...Precondition) error

UpdateProto updates proto with the given slice of updates.

func UpdateUpdatedAtField

func UpdateUpdatedAtField(marshaler docmarshal.Marshaler, doc any) any

UpdateUpdatedAtField updates the default UpdatedAt field in the given document. Deprecated: Use UpdateDefaultUpdatedAtField.

Types

type BatchOp

type BatchOp struct {
	Type          BatchOpType
	ID            string
	Doc           any
	Updates       []Update
	Preconditions []Precondition
}

BatchOp is a single write of a batch. Doc is only read by BatchCreate and BatchSet; Updates and Preconditions only by BatchUpdate.

type BatchOpResult

type BatchOpResult struct {
	// Err is one of ErrAlreadyExists, ErrNotFound or
	// ErrPreconditionFailed when the operation was rejected by the
	// store, and nil when it was applied.
	Err error
}

BatchOpResult reports the outcome of the BatchOp at the same index.

type BatchOpType

type BatchOpType int

BatchOpType selects which write a BatchOp performs.

const (
	// BatchCreate mirrors Service.Create.
	BatchCreate BatchOpType = iota
	// BatchSet mirrors Service.Set.
	BatchSet
	// BatchUpdate mirrors Service.Update.
	BatchUpdate
	// BatchDelete mirrors Service.Delete.
	BatchDelete
)

type BatchWriter

type BatchWriter interface {
	// ApplyBatch applies every op to the same collection. Operations
	// rejected for document-level reasons (a Create over an existing
	// document, an Update whose preconditions fail) do not abort the
	// batch: their error is reported in the result at the same index
	// and the remaining ops are still applied. Any other failure aborts
	// the batch, leaves the store untouched, and is returned as the
	// call error.
	ApplyBatch(ctx context.Context, ops []BatchOp) ([]BatchOpResult, error)
}

BatchWriter is implemented by services that can apply several writes in a single atomic round trip.

type DroppableService

type DroppableService interface {
	Service

	// Drop deletes all records in a document.Service. Implementors must guarantee
	// that (1) this is done efficiently and (2) the service remains functional
	// after this operation succeeds.
	Drop(context.Context) error
}

DroppableService wraps a Service and provides a method to delete all records efficiently.

func NewInMemoryService

func NewInMemoryService() DroppableService

NewInMemoryService returns an instance of Service backed by an in-memory map.

func NewInMemoryServiceWithMarshaler

func NewInMemoryServiceWithMarshaler(m docmarshal.Marshaler) DroppableService

type Field

type Field struct {
	FieldPath []string
	Value     any
}

Field represents a document field.

type Filter

type Filter struct {
	Field
	Op
}

Filter is used to construct a filter predicate in a List operation.

func WithFilter

func WithFilter(
	in []Filter, fieldPath []string,
	value interface{}, op Op,
) []Filter

WithFilter returns an updated slice of filters with a filter built with fieldPath value and op.

func WithFilterProjectID

func WithFilterProjectID(
	in []Filter, projectID string,
) []Filter

WithFilterProjectID returns an updated slice of filters which now will include documents with projectID.

type Iterator

type Iterator interface {
	HasNext() bool
	NextTo(doc any) error
	io.Closer
}

Iterator is used to collect the the results obtained by List.

HasNext is used to check how many results are left in the iterator. When HasNext returns false, a call to NextTo will panic.

NextTo marshals the next document into the provided argument. It returns an error if marshaling fails. Once marshaled, the given document should not be re-used in the next call to NextTo otherwise map or slice fields could be overriden, depending on the implementation.

type ListIterator

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

ListIterator satisfies an Iterator with an inmemory list of documents.

func NewListIterator

func NewListIterator(m docmarshal.Marshaler, docs ...any) *ListIterator

ListIterator returns an iterator that iterates over docs. It will uson bson to encode and decode the data so it shouldn't be used by a document.Service that doesn't use the suite of Decode/Encode functions in this package.

func (*ListIterator) Close

func (l *ListIterator) Close() error

Close does nothing.

func (*ListIterator) Extend

func (l *ListIterator) Extend(filters []Filter, v []byte)

Extend extends this iterator if and only if the data chunk's structure satisfies all filters.

func (*ListIterator) HasNext

func (l *ListIterator) HasNext() bool

HasNext returns false if this Iterator is empty.

func (*ListIterator) NextTo

func (l *ListIterator) NextTo(doc any) error

NextTo decodes the next chunk of data into doc or returns an error if there was a decoding issue.

type Op

type Op string

Op represents a type of filter expression in a filter predicate.

type Precondition

type Precondition Field

Preconditions are optionally passed to Update to fail if the document state is not expected by the caller.

type Service

type Service interface {
	// Create creates the document with the given data.
	// It returns an error if a document with the same ID already exists.
	// The data argument can be a map with string keys, a struct, or a pointer
	// to a struct. The map keys or exported struct fields become the
	// fields of the document.
	//
	// Pointers and the empty any are permitted as
	// struct attributes or map values, and their elements processed recursively.
	//
	// DefaultCreatedAtField is automatically added and clients can consume it
	// by adding the corresponding property in the document structure.
	// Note that certain implementations might require special field tags.
	Create(ctx context.Context, ID string, doc any) error

	// Set creates a document with the given data or updates it if it already exists.
	//
	// DefaultUpdatedAtField is automatically updated and clients can consume it
	// by adding the corresponding property in the document structure.
	//
	// See Create for more details.
	Set(ctx context.Context, ID string, doc any) error

	// Update updates the document. The values at the given
	// field paths are replaced, but other fields of the stored document
	// are untouched.
	//
	// DefaultUpdatedAtField is automatically updated and clients can consume it
	// by adding the corresponding property in the document structure.
	Update(ctx context.Context, ID string,
		updates []Update, precond ...Precondition) error

	// Get retrieves the document. If the document does not exist,
	// it returns a ErrNotFound error.
	// Parameter doc is used to populate the document's fields.
	// It can be a pointer to a map[string]any or a pointer to a struct.
	Get(ctx context.Context, ID string, doc any) error

	// Delete deletes the document. If the document doesn't exist,
	// it does nothing and returns no error.
	Delete(ctx context.Context, ID string) error

	// The List operation returns a page of all documents in the collection.
	// To return a subset of the collection, you can provide a set of filters.
	List(ctx context.Context, filters []Filter) (Iterator, error)

	io.Closer
}

Service is the interface that encapsulates a document store service.

The following rules must be followed in order to guarantee compatiblity across implementations:

  • Document structures must not contain embedded public fields. This causes Update problems, as some implementations store the embedded fields as a nested field, whereas others store them using Go's internal representation.
  • Document structures must not attempt to rename fields with tags. Some implementations do not take tags, so Update operations, which use field names string literals, would work for some implementations but not others.

func RWSync

func RWSync(svc Service) Service

RWSync returns a mutual read/write exclusion document.Service. Create, Update, and Delete calls are serialized and will prevent Get and List to access the underlying documents while running but if there are no writes reads can run concurrently.

func Sync

func Sync(svc Service) Service

Sync returns a mutual exclusion document.Service. All calls are serialized preventing concurrent access to the given underlying Service.

func SyncWithLocker

func SyncWithLocker(svc Service, locker sync.Locker) Service

func WithPartition

func WithPartition(other Service, partition string) Service

WithPartition wraps a service and creates a partition with the given name. All the records created, stored, listed, etc. won't be seen by other partitions over the same Service, created by this function.

type Update

type Update Field

Update is used to indicate an update operation to a document field.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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